diff --git a/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/INSTALLER b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/METADATA b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..347f50c3e542f89c0f65e371c1607b32844b6d31 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/METADATA @@ -0,0 +1,56 @@ +Metadata-Version: 2.4 +Name: mypy +Version: 1.20.2 +Summary: Optional static typing for Python +Author-email: Jukka Lehtosalo +License-Expression: MIT +Project-URL: Homepage, https://www.mypy-lang.org/ +Project-URL: Documentation, https://mypy.readthedocs.io/en/stable/index.html +Project-URL: Repository, https://github.com/python/mypy +Project-URL: Changelog, https://github.com/python/mypy/blob/master/CHANGELOG.md +Project-URL: Issues, https://github.com/python/mypy/issues +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Software Development +Classifier: Typing :: Typed +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: mypy/typeshed/LICENSE +Requires-Dist: typing_extensions>=4.6.0; python_version < "3.15" +Requires-Dist: typing_extensions>=4.14.0; python_version >= "3.15" +Requires-Dist: mypy_extensions>=1.0.0 +Requires-Dist: pathspec>=1.0.0 +Requires-Dist: tomli>=1.1.0; python_version < "3.11" +Requires-Dist: librt>=0.8.0; platform_python_implementation != "PyPy" +Provides-Extra: dmypy +Requires-Dist: psutil>=4.0; extra == "dmypy" +Provides-Extra: mypyc +Requires-Dist: setuptools>=50; extra == "mypyc" +Provides-Extra: python2 +Provides-Extra: reports +Requires-Dist: lxml; extra == "reports" +Provides-Extra: install-types +Requires-Dist: pip; extra == "install-types" +Provides-Extra: faster-cache +Requires-Dist: orjson; extra == "faster-cache" +Provides-Extra: native-parser +Requires-Dist: ast-serialize<1.0.0,>=0.1.1; extra == "native-parser" +Dynamic: license-file + +Mypy -- Optional Static Typing for Python +========================================= + +Add type annotations to your Python programs, and use mypy to type +check them. Mypy is essentially a Python linter on steroids, and it +can catch many programming errors by analyzing your program, without +actually having to run it. Mypy has a powerful type system with +features such as type inference, gradual typing, generics and union +types. diff --git a/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/RECORD b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..1f14aea59ad94b8b4ed286372f27d323cf623bba --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/RECORD @@ -0,0 +1,1751 @@ +../../Scripts/dmypy.exe,sha256=8m9-45LJjmBe1badNKA4SJDVIRUeYB85CyPXgl2w8gY,108367 +../../Scripts/mypy.exe,sha256=-udwjXHXS4MiUafRWHrGOpqf8cvJWC-YL5BET9iG56M,108363 +../../Scripts/mypyc.exe,sha256=VoXZXVH7lICHcYU4LwKqTtlzt-SeuuhRsV1EmWS2AqU,108346 +../../Scripts/stubgen.exe,sha256=Q2Ib8EhhjOMkqDEvU0cxikQy9FDSHo58Jk2RUxSuPKc,108344 +../../Scripts/stubtest.exe,sha256=sd_WKoo9o0vLe-KBZYniLw6K6iOJY-Pbb0LAo_x3ATg,108345 +0aca9ce3d91742c5b361__mypyc.cp314-win_amd64.pyd,sha256=YCSII9VFhPRfzw3Y7Z6CrDO1STgD1PE2GaKPYXMl3No,19105792 +mypy-1.20.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +mypy-1.20.2.dist-info/METADATA,sha256=Jvm8hH-Guu4rwFicZM_y5L1EU-Ywk-UKU67wzxunfJg,2428 +mypy-1.20.2.dist-info/RECORD,, +mypy-1.20.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy-1.20.2.dist-info/WHEEL,sha256=jhxrRP3tdEfm7toB1X7dl5x6f0bu6Tve2cWwIdkbL8U,101 +mypy-1.20.2.dist-info/direct_url.json,sha256=kUJhAYWBUJHFeA4dWuzyVkqmFodZTtWS8hslocG19qE,71 +mypy-1.20.2.dist-info/entry_points.txt,sha256=DKRnGYlnjnz9_6jxYhHskdeZLwNC69R-ZPVxv3b9dpc,179 +mypy-1.20.2.dist-info/licenses/LICENSE,sha256=_fHNF_UOEwXtjP03RnMS0nqYRkjbpiLO9wVztVEuThs,12842 +mypy-1.20.2.dist-info/licenses/mypy/typeshed/LICENSE,sha256=KV-FOMlK5cMEMwHPfP8chS2ranhqjd7kceBhtA1eyr4,12657 +mypy-1.20.2.dist-info/top_level.txt,sha256=2PVTSlWteH8U4UMJ1XWOKLNMLYFRUzMlNvp0NaUVIHo,39 +mypy/__init__.cp314-win_amd64.pyd,sha256=tISpc1vaosVSoMVMlF7vIMczuoME7vAFhFDG0wCzWZY,10240 +mypy/__init__.py,sha256=4yp43qNAZZ0ViBpVn56Bc7MA4H2UMXe0WTVPdkODP6k,37 +mypy/__main__.py,sha256=F3MoYIPepYJOIKr7lWGCPsMX7PpWxuywYbqXZtKqXV8,1524 +mypy/__pycache__/__init__.cpython-314.pyc,, +mypy/__pycache__/__main__.cpython-314.pyc,, +mypy/__pycache__/api.cpython-314.pyc,, +mypy/__pycache__/applytype.cpython-314.pyc,, +mypy/__pycache__/argmap.cpython-314.pyc,, +mypy/__pycache__/binder.cpython-314.pyc,, +mypy/__pycache__/bogus_type.cpython-314.pyc,, +mypy/__pycache__/build.cpython-314.pyc,, +mypy/__pycache__/cache.cpython-314.pyc,, +mypy/__pycache__/checker.cpython-314.pyc,, +mypy/__pycache__/checker_shared.cpython-314.pyc,, +mypy/__pycache__/checker_state.cpython-314.pyc,, +mypy/__pycache__/checkexpr.cpython-314.pyc,, +mypy/__pycache__/checkmember.cpython-314.pyc,, +mypy/__pycache__/checkpattern.cpython-314.pyc,, +mypy/__pycache__/checkstrformat.cpython-314.pyc,, +mypy/__pycache__/config_parser.cpython-314.pyc,, +mypy/__pycache__/constant_fold.cpython-314.pyc,, +mypy/__pycache__/constraints.cpython-314.pyc,, +mypy/__pycache__/copytype.cpython-314.pyc,, +mypy/__pycache__/defaults.cpython-314.pyc,, +mypy/__pycache__/dmypy_os.cpython-314.pyc,, +mypy/__pycache__/dmypy_server.cpython-314.pyc,, +mypy/__pycache__/dmypy_util.cpython-314.pyc,, +mypy/__pycache__/erasetype.cpython-314.pyc,, +mypy/__pycache__/error_formatter.cpython-314.pyc,, +mypy/__pycache__/errorcodes.cpython-314.pyc,, +mypy/__pycache__/errors.cpython-314.pyc,, +mypy/__pycache__/evalexpr.cpython-314.pyc,, +mypy/__pycache__/expandtype.cpython-314.pyc,, +mypy/__pycache__/exportjson.cpython-314.pyc,, +mypy/__pycache__/exprtotype.cpython-314.pyc,, +mypy/__pycache__/fastparse.cpython-314.pyc,, +mypy/__pycache__/find_sources.cpython-314.pyc,, +mypy/__pycache__/fixup.cpython-314.pyc,, +mypy/__pycache__/freetree.cpython-314.pyc,, +mypy/__pycache__/fscache.cpython-314.pyc,, +mypy/__pycache__/fswatcher.cpython-314.pyc,, +mypy/__pycache__/gclogger.cpython-314.pyc,, +mypy/__pycache__/git.cpython-314.pyc,, +mypy/__pycache__/graph_utils.cpython-314.pyc,, +mypy/__pycache__/indirection.cpython-314.pyc,, +mypy/__pycache__/infer.cpython-314.pyc,, +mypy/__pycache__/inspections.cpython-314.pyc,, +mypy/__pycache__/ipc.cpython-314.pyc,, +mypy/__pycache__/join.cpython-314.pyc,, +mypy/__pycache__/literals.cpython-314.pyc,, +mypy/__pycache__/lookup.cpython-314.pyc,, +mypy/__pycache__/main.cpython-314.pyc,, +mypy/__pycache__/maptype.cpython-314.pyc,, +mypy/__pycache__/meet.cpython-314.pyc,, +mypy/__pycache__/memprofile.cpython-314.pyc,, +mypy/__pycache__/message_registry.cpython-314.pyc,, +mypy/__pycache__/messages.cpython-314.pyc,, +mypy/__pycache__/metastore.cpython-314.pyc,, +mypy/__pycache__/mixedtraverser.cpython-314.pyc,, +mypy/__pycache__/modulefinder.cpython-314.pyc,, +mypy/__pycache__/moduleinspect.cpython-314.pyc,, +mypy/__pycache__/mro.cpython-314.pyc,, +mypy/__pycache__/nativeparse.cpython-314.pyc,, +mypy/__pycache__/nodes.cpython-314.pyc,, +mypy/__pycache__/operators.cpython-314.pyc,, +mypy/__pycache__/options.cpython-314.pyc,, +mypy/__pycache__/parse.cpython-314.pyc,, +mypy/__pycache__/partially_defined.cpython-314.pyc,, +mypy/__pycache__/patterns.cpython-314.pyc,, +mypy/__pycache__/plugin.cpython-314.pyc,, +mypy/__pycache__/pyinfo.cpython-314.pyc,, +mypy/__pycache__/reachability.cpython-314.pyc,, +mypy/__pycache__/refinfo.cpython-314.pyc,, +mypy/__pycache__/renaming.cpython-314.pyc,, +mypy/__pycache__/report.cpython-314.pyc,, +mypy/__pycache__/scope.cpython-314.pyc,, +mypy/__pycache__/semanal.cpython-314.pyc,, +mypy/__pycache__/semanal_classprop.cpython-314.pyc,, +mypy/__pycache__/semanal_enum.cpython-314.pyc,, +mypy/__pycache__/semanal_infer.cpython-314.pyc,, +mypy/__pycache__/semanal_main.cpython-314.pyc,, +mypy/__pycache__/semanal_namedtuple.cpython-314.pyc,, +mypy/__pycache__/semanal_newtype.cpython-314.pyc,, +mypy/__pycache__/semanal_pass1.cpython-314.pyc,, +mypy/__pycache__/semanal_shared.cpython-314.pyc,, +mypy/__pycache__/semanal_typeargs.cpython-314.pyc,, +mypy/__pycache__/semanal_typeddict.cpython-314.pyc,, +mypy/__pycache__/sharedparse.cpython-314.pyc,, +mypy/__pycache__/solve.cpython-314.pyc,, +mypy/__pycache__/split_namespace.cpython-314.pyc,, +mypy/__pycache__/state.cpython-314.pyc,, +mypy/__pycache__/stats.cpython-314.pyc,, +mypy/__pycache__/strconv.cpython-314.pyc,, +mypy/__pycache__/stubdoc.cpython-314.pyc,, +mypy/__pycache__/stubgen.cpython-314.pyc,, +mypy/__pycache__/stubgenc.cpython-314.pyc,, +mypy/__pycache__/stubinfo.cpython-314.pyc,, +mypy/__pycache__/stubtest.cpython-314.pyc,, +mypy/__pycache__/stubutil.cpython-314.pyc,, +mypy/__pycache__/subtypes.cpython-314.pyc,, +mypy/__pycache__/suggestions.cpython-314.pyc,, +mypy/__pycache__/traverser.cpython-314.pyc,, +mypy/__pycache__/treetransform.cpython-314.pyc,, +mypy/__pycache__/tvar_scope.cpython-314.pyc,, +mypy/__pycache__/type_visitor.cpython-314.pyc,, +mypy/__pycache__/typeanal.cpython-314.pyc,, +mypy/__pycache__/typeops.cpython-314.pyc,, +mypy/__pycache__/types.cpython-314.pyc,, +mypy/__pycache__/types_utils.cpython-314.pyc,, +mypy/__pycache__/typestate.cpython-314.pyc,, +mypy/__pycache__/typetraverser.cpython-314.pyc,, +mypy/__pycache__/typevars.cpython-314.pyc,, +mypy/__pycache__/typevartuples.cpython-314.pyc,, +mypy/__pycache__/util.cpython-314.pyc,, +mypy/__pycache__/version.cpython-314.pyc,, +mypy/__pycache__/visitor.cpython-314.pyc,, +mypy/api.cp314-win_amd64.pyd,sha256=QdCgDC8yI9WreBgLELLCwPaosd5uLVPoLBnQ1w43bAQ,10240 +mypy/api.py,sha256=QlzdLRQb86I8d6p7Ph9HPxq1miRg_mrXl0UYDr9Vxsc,2949 +mypy/applytype.cp314-win_amd64.pyd,sha256=wleeW7G4LtVDQdkITbAz97t1OQgi_dsAZymrH9JpS58,10240 +mypy/applytype.py,sha256=MS5D8lbxsCAwVwoaRdd8Syh2_PddlnSlnx9tIA74Olk,12032 +mypy/argmap.cp314-win_amd64.pyd,sha256=jRn_JByuTuLi6piaq4LoTVEWOcDAgBDjwayKLNY4z7Y,10240 +mypy/argmap.py,sha256=05e1yn4g89hbXkPDMgUb6iKZfcAVmplMBbdKV0vL5gI,11416 +mypy/binder.cp314-win_amd64.pyd,sha256=LCqWPIi8R_Fp_MB4dpnB_6jcz9QLV3bVN_nuEwP2srs,10240 +mypy/binder.py,sha256=hH54Bn3DUqHaa0el76KcJwHAv-Xs7VIoddFhr3em7Xg,28610 +mypy/bogus_type.py,sha256=w3GrsWoj5FKbfEUsc87OVFO812HC9BvnWnSaV2T4u1c,816 +mypy/build.cp314-win_amd64.pyd,sha256=8RmZhqx4NNOG9NaVW_Gpu6AjA7d7SR0QPTKyzjTTY8U,10240 +mypy/build.py,sha256=5ABbHtNyahBOM03wQKisDloionskpTradQkGbENXpaE,193755 +mypy/build_worker/__init__.cp314-win_amd64.pyd,sha256=R4hrX-0uJblxocgASP6rMoEYSHUncw_BR857F36gt3k,10240 +mypy/build_worker/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/build_worker/__main__.py,sha256=v97-y5Te1hke8wIUJj4AtYyXRc6vKBimTz8vl2HUGAw,135 +mypy/build_worker/__pycache__/__init__.cpython-314.pyc,, +mypy/build_worker/__pycache__/__main__.cpython-314.pyc,, +mypy/build_worker/__pycache__/worker.cpython-314.pyc,, +mypy/build_worker/worker.cp314-win_amd64.pyd,sha256=l4Z8VqxwzzPbHsJBNmH6bsGYxOeKM5fyCiyQA4b3_BU,10240 +mypy/build_worker/worker.py,sha256=ss8bZabamRZxIWFIap4ybitcKx6Od2AtDpwrPbXNIZc,9272 +mypy/cache.cp314-win_amd64.pyd,sha256=yDFEu3k5C2NOY0RAef14K3lHhREb6_dBpTrl-oN8--w,10240 +mypy/cache.py,sha256=gphQeVLtG2mF0WjqlmiSdGQpQnsyeKhJWu3zKxjrdRM,19278 +mypy/checker.cp314-win_amd64.pyd,sha256=Zmv4u3Y9lofeEguOGAvCYLB_OwfIo8HwQ3KDSYKaJrI,10240 +mypy/checker.py,sha256=olknIUeqq2maiNP5_10SPXDPB5f4DK94etFmtECfVIs,430682 +mypy/checker_shared.cp314-win_amd64.pyd,sha256=G_aNwq4Dx8b_APGspLmGNHZJjTMs0mk2ssGSi1joYOU,10240 +mypy/checker_shared.py,sha256=YdeUPR4m0aBNBxNI55aqCJVUM_WQ-Zs7boRfqfNi7y0,10613 +mypy/checker_state.cp314-win_amd64.pyd,sha256=8so07UrLc95rqaotsa7KXtVm_IKNXYvmoPw65FatZfs,10240 +mypy/checker_state.py,sha256=JqVXZnHaqh0oWmLIWPZdLEct9lUCUe9gUFCTu8WT0hQ,858 +mypy/checkexpr.cp314-win_amd64.pyd,sha256=0hPVI9iabKu5I8Lsc_LhSedMUc31RPhvbi6A3aRWkKQ,10240 +mypy/checkexpr.py,sha256=HfrcO__WJtAcYKASi4uqUQmY__r1g4kkqXeKIxu5E3Y,303324 +mypy/checkmember.cp314-win_amd64.pyd,sha256=9TcnqaHmRboCU7SmmfAjiqYYCKI85_zI5UD16vjla84,10240 +mypy/checkmember.py,sha256=j5zPRGGz1odKJG1rGQ7QwazyW4zvsdVh0WWizS1DS1Q,64435 +mypy/checkpattern.cp314-win_amd64.pyd,sha256=iw67_WjhdtkwcVt0eT-XlZep2fH0umDAV4lV43Kt6f8,10240 +mypy/checkpattern.py,sha256=iP7rtUHnkvrOqiDYOBfunkplJHIJb9YhgL4rb2UQKAs,36820 +mypy/checkstrformat.cp314-win_amd64.pyd,sha256=J6GcI_5kGEfr_87QSuNwJZNnciTMop1IKZPwTWwDY6I,10240 +mypy/checkstrformat.py,sha256=eFxoYgS5IM73Hqzi-bUENJmbUe-Vo1PAbGo04AMjLF0,46015 +mypy/config_parser.cp314-win_amd64.pyd,sha256=73yl6wLWwGTddu1cW26HAvpW-F55sx1wXLPlxePjogo,10240 +mypy/config_parser.py,sha256=p4UjHSpaPgyAnGrXtF3-4QBt9Z2Bl5XYMpIYl2LDW-k,26326 +mypy/constant_fold.cp314-win_amd64.pyd,sha256=04HGphVtyjrF9KiRctf8AdFugAG3xVFkrI2s5lVFGVo,10240 +mypy/constant_fold.py,sha256=-s2aJ5GEIUPuzAP5Gh7b1lv6EOO-ILMKabTlC50ymeQ,6061 +mypy/constraints.cp314-win_amd64.pyd,sha256=2oAHekJRWvflYj8eBl0KYFq-QxJ6Ce9cw4FkBrD2SPc,10240 +mypy/constraints.py,sha256=1SP9ZeVOCowI2vmlHEG97VbZiPcY3nJP2pe20zlc2s8,79294 +mypy/copytype.cp314-win_amd64.pyd,sha256=xN9nx_Qhr_VTcKDNVlmIbJN2zHoN1GgznOPv5Rb-Maw,10240 +mypy/copytype.py,sha256=aDVQNWXI98-DyxvtB6inUaEO3B_IZCN9HIpUtmkZcdU,4448 +mypy/defaults.cp314-win_amd64.pyd,sha256=NUpt2tdt3kHAV3qGkMapcGA3broV26e3mi6OuWkAnUs,10240 +mypy/defaults.py,sha256=-M_v4prk46YcNEHGsSH_fuRci_noEE0T3S-CpIwTKg0,1666 +mypy/dmypy/__init__.cp314-win_amd64.pyd,sha256=2krnVnQT_Oftm0BAGCS4NoepteuWzmjtyb1XB_9EKvU,10240 +mypy/dmypy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/dmypy/__main__.py,sha256=u6ZYw52bfIJ11Oo88mzx7p4WD2WUo1-H9PRsT45eswU,128 +mypy/dmypy/__pycache__/__init__.cpython-314.pyc,, +mypy/dmypy/__pycache__/__main__.cpython-314.pyc,, +mypy/dmypy/__pycache__/client.cpython-314.pyc,, +mypy/dmypy/client.cp314-win_amd64.pyd,sha256=2c6k7hfF8YUOfVYrQ2Ynd8qBptHXR3-PXHpNOx9t3NI,10240 +mypy/dmypy/client.py,sha256=8LN2G1OWXWOzrWcA5LaSRhwmVtBCLgGdHdcOxtnVWzQ,24276 +mypy/dmypy_os.cp314-win_amd64.pyd,sha256=KMqYYQb7Nq1Kk8v3udOfvQHPFmbpaaqSgZnpyvVAFD4,10240 +mypy/dmypy_os.py,sha256=ON1h-kGywstKXeIYkBEuv6Tk-XammrZrDy1PhskETXs,1181 +mypy/dmypy_server.cp314-win_amd64.pyd,sha256=b46yUHEIBli4v98HT66qZDUWL6BGnzpkh9k9E8QQllk,10240 +mypy/dmypy_server.py,sha256=y9dw8OFJS__cAGH04icnvTimwW29qgMbLt7pRp2x3UQ,45611 +mypy/dmypy_util.cp314-win_amd64.pyd,sha256=7JK8GnqlR5HYuTnUW4Lgw0lr4hZ-fXt7H9OohZahRQc,10240 +mypy/dmypy_util.py,sha256=Qmmxof6Jdzy5zD6lX4-DF47dqAJNmoRmLYy_lJag9PY,3006 +mypy/erasetype.cp314-win_amd64.pyd,sha256=Z1oU5h6-tFJejPbPFzkBiDIC7OAxfR7D3ypdoqbHykA,10240 +mypy/erasetype.py,sha256=LI9br4FTWqK7ns-lcks4bnrTu31xR_3vPmfWuhFIyaU,11309 +mypy/error_formatter.cp314-win_amd64.pyd,sha256=PXPaePKgXW2yK-EWaDv0f_T0fIoT9ALqN7jWfq1oG3M,10240 +mypy/error_formatter.py,sha256=xBGtUNrEjzB-W6TZaSLLpwPH2XFGcjVk2tltaImNYxo,1165 +mypy/errorcodes.cp314-win_amd64.pyd,sha256=rvTju4wI2zm20IWO55gIBRQs8jUSJv63x6xT0M1kyNc,10240 +mypy/errorcodes.py,sha256=ydp7yz98G0lHqd6IVRV_hk05Rv7_t1qVfTSBFTUlyoc,11892 +mypy/errors.cp314-win_amd64.pyd,sha256=J4ZNcR5LUeiAz9OQst0K4Kfk0UJF50yldChyb0MO3Uo,10240 +mypy/errors.py,sha256=Uyua4SUD1hqOkLqCKJtUk7Rllk4unK-wOCZQeJEGEVk,57154 +mypy/evalexpr.cp314-win_amd64.pyd,sha256=FcqRCNEPWYjyhWTORXt1N5DjKgialxpDEt3WoyogPDs,10240 +mypy/evalexpr.py,sha256=Xhf7PqYRdp9IPQ8anGl-o6iyUYJB3oxG0j0UVUnSyCI,6764 +mypy/expandtype.cp314-win_amd64.pyd,sha256=3jCQr2I2GPmEOqMp2uiuxhk1dKrPDYiWtVAzSy-4GjE,10240 +mypy/expandtype.py,sha256=ch-DfjNd_E8yfE2Q5UplYHr0QirXPNSTdjHoXmQSBuM,29037 +mypy/exportjson.py,sha256=KVZ2fmZb6ZYaAJyG3WcsoBBdFrx1jCNsKxvVSXKaGq4,20250 +mypy/exprtotype.cp314-win_amd64.pyd,sha256=mXurnqq-JRPObbo1tOj7glElFmvFZsxHS85BslymdYY,10240 +mypy/exprtotype.py,sha256=-RJZodKL7whZ885BGGrQDNvTYByy9AXwHXaTfpdiKHw,10598 +mypy/fastparse.cp314-win_amd64.pyd,sha256=I90dsZyXLW_73VbEY0BnMp93F2olLB8z0YuGfs0YCKM,10240 +mypy/fastparse.py,sha256=u5qU6oEmJB_FiFhwo5tb8H0XQ42hIxMc0lxCSEzrVp8,87410 +mypy/find_sources.cp314-win_amd64.pyd,sha256=nkyCZucDVvyAj5XrCdpyCqdKozHkrzeb-d5jTFzNHww,10240 +mypy/find_sources.py,sha256=4Fqa1H1js009UUDVGpaW1BwT0Sm-hm7HzUUtxeEgiFY,9734 +mypy/fixup.cp314-win_amd64.pyd,sha256=VB37ZJqaK8hPVuMuTR8iYZaI61VQpQ1j1ymQ_14muU8,10240 +mypy/fixup.py,sha256=OCBOWLUaOv38M-7Lp_5CZ6lexfvp6D4-s_vfcy2TiM0,16600 +mypy/freetree.cp314-win_amd64.pyd,sha256=vLQntz8cfOVZY_sIOMyUqmJTllT1zXA1FVG21BUNaD4,10240 +mypy/freetree.py,sha256=yz4_ZUq8Ja89176nbDEAiBk-Et2nP74_KXyCcaW4inA,617 +mypy/fscache.cp314-win_amd64.pyd,sha256=-hNS8U7rkavvvjeGuBInwiXTfyG60q6-GaB_7iRVNmA,10240 +mypy/fscache.py,sha256=9YJBIKHPjk8Vzd9Yube6sXIzxrOdq-b2bG8kebzAUV0,11102 +mypy/fswatcher.cp314-win_amd64.pyd,sha256=_y54Rdtz7kNYJQLrVQ3rwSyDu7Elc-NBiz52lZ6ubrw,10240 +mypy/fswatcher.py,sha256=FSTEaV9NmgNZArX_A9Wox7wofa5vg9-GPgTEZWqx3yY,3985 +mypy/gclogger.cp314-win_amd64.pyd,sha256=pR-D8bKi-lOxLlEyXPlMNM6OcowN64SeMFk2ynYJXWE,10240 +mypy/gclogger.py,sha256=E-xdukA7h0ttgwFquruln_thKmREjbYA3dIkj8fYC-k,1639 +mypy/git.cp314-win_amd64.pyd,sha256=b0SEA6_GKUIYQ84DWMnZ6058vEJoe1mUMmBsWjG4rTY,10240 +mypy/git.py,sha256=FYdMg-3fTtikKjUwfFPXbWiNmpOIMG4rNgMAWIPBsLM,980 +mypy/graph_utils.cp314-win_amd64.pyd,sha256=ovEImSnOhge6t79Bn6AW1F-dZ1zk70PPrOz8LFGEdXE,10240 +mypy/graph_utils.py,sha256=WWjUg_g9DkwEL9xAHprtnkda7J3LWC-8gES-NNOS5XA,4983 +mypy/indirection.cp314-win_amd64.pyd,sha256=BEYR7xclWRDfSNIOBRGZnabrEqfTwgYifpBNvZSo7IQ,10240 +mypy/indirection.py,sha256=KkInogFEpns3MjtSQpVXgK64T7Dc5_4_0xb8qUhaopw,6432 +mypy/infer.cp314-win_amd64.pyd,sha256=yzCf0XtuugYu5J3dF0YN4he30j08jqwo7NGdP-lUq3E,10240 +mypy/infer.py,sha256=J8bcCjYFX7VZ4UjazbYC9SmAR2LA8eczsLvh1Ay14Yw,2538 +mypy/inspections.cp314-win_amd64.pyd,sha256=0bcVVwhgYh-7wrAgdkG4Q4fQrpjPi4lmiHQbfeejtGc,10240 +mypy/inspections.py,sha256=PWBbzmgERls2fKj5_5UGbBIr0xdsDUDn7adt5phMWak,23813 +mypy/ipc.cp314-win_amd64.pyd,sha256=QZThVN5sXSyfZehaUGULzAgyRKN7LRWc-mZoRgijr5w,10240 +mypy/ipc.py,sha256=pn5Z3TVEdFWJ0IyVRLQmkQe3ctn-qGvPtf3vQ3s5iAU,17139 +mypy/join.cp314-win_amd64.pyd,sha256=LBcG5owhHhr4jZ8WBI7XV8oDY_ykVGsEnM3tygIy8Fc,10240 +mypy/join.py,sha256=2o27_dKqCw8zv2wmWUqkFNAE4HG5BSvkKR4QFkTACLs,39575 +mypy/literals.cp314-win_amd64.pyd,sha256=tdYKOYlvCcUlix1rnipxREaXSBHT0tWDctEyuHw1p3c,10240 +mypy/literals.py,sha256=O6utOL4wLNztx8Lp1bg7ICQ58Sprh1_DYFdTGtUm36Y,9412 +mypy/lookup.cp314-win_amd64.pyd,sha256=AXbRqv-8vuuC7ktwjpL5zH3GsZvEuw9UgrVoCT1SJ3A,10240 +mypy/lookup.py,sha256=deiZ7pNVOYZiF0ShjGj47nOgmJ6AgREIdEbYrDdiGPk,2454 +mypy/main.cp314-win_amd64.pyd,sha256=BSB-OLCxsGwbyDn02k6XKqNh3Svv4-3g4a9-4abDxT4,10240 +mypy/main.py,sha256=94z8Vwa4EpgHNywMfouyWZ3GGinSh1N2kWqeRhsxHqA,64579 +mypy/maptype.cp314-win_amd64.pyd,sha256=KcFEz_ya8q9cTCIQb7HdrUoZIHTNIUay-brDNoa1NyA,10240 +mypy/maptype.py,sha256=USEg3N_4LCesekOVOLhwFoq65urhcR5CotSkprcJleU,4331 +mypy/meet.cp314-win_amd64.pyd,sha256=0kbn-9O4-vvbloZG-d71XwC4pCaMhmgYaqs1Mrp43_A,10240 +mypy/meet.py,sha256=Zt97DMWfZIpAaSNGEdVGEwjD2kLTnY4mSO39JaKmMQw,54063 +mypy/memprofile.cp314-win_amd64.pyd,sha256=jbX4W1SmiWtTLQsINEjYBX2mE1D4C0M5CofnOCweDUY,10240 +mypy/memprofile.py,sha256=Ar4FwaVBON42iT2OHHoj6_G5VL1YNnPAZU_cp4mgll8,4174 +mypy/message_registry.cp314-win_amd64.pyd,sha256=dk3oiKm_lBqBmc1apSDYXTLBsg3eyCV72gRrwZaZ4bU,10240 +mypy/message_registry.py,sha256=K4DTLVvT4K6TcT2rmg6AxCm5GInRag3c4AwF3WZlh3o,17320 +mypy/messages.cp314-win_amd64.pyd,sha256=0uek2lKd0QLrU99i-foYN_J0W12ooOXAFtA_1RMbMPg,10240 +mypy/messages.py,sha256=9TPr3XXaqa5QnuSHmftglX5M5WELOsEB4k5KwMhFJGc,137038 +mypy/metastore.cp314-win_amd64.pyd,sha256=e6c_jRQNLlkipHS8at0uF5ftxTiFMX3uxF0X5Dvd8ps,10240 +mypy/metastore.py,sha256=8934plg_MMhbyknKYG88jRmJROIGQQD3nlrO99I6k30,7339 +mypy/mixedtraverser.cp314-win_amd64.pyd,sha256=Ejr0rnC0RWwKWaxiC4lI4kpvd50nMbfCcQHRMsJaAE8,10240 +mypy/mixedtraverser.py,sha256=q0VwDWsSDmjkD4h0tBSWSj74WXkkXiBSXerSFeBiNzg,3852 +mypy/modulefinder.cp314-win_amd64.pyd,sha256=bbr5LPBVnx9UsjBOq5BNil_1X47-dEDcxZBazBv3EYI,10240 +mypy/modulefinder.py,sha256=abTHalmYq4MxEpVxzfuyF1rAIKT502eguO4hQpD_DuI,42875 +mypy/moduleinspect.cp314-win_amd64.pyd,sha256=Tz6NlCV46FEPFo6MylMZe9aPwu2oiWaROfQaGMR0t4I,10240 +mypy/moduleinspect.py,sha256=HCEI7yW61OkMNFqUqjuRB09HcTDpalcmtVBYjlWfxyo,6326 +mypy/mro.cp314-win_amd64.pyd,sha256=GQ0p-yt9MDErhuMfYjwjQkctc13UYb0QCmVr0UHMitU,10240 +mypy/mro.py,sha256=hSrgh1E8QhWpxpgTKe-Jt2OyjSyjIr8wDwpZoSLOf1g,2002 +mypy/nativeparse.cp314-win_amd64.pyd,sha256=94Fhh13MoL-AMEkvHcrrzb1VJqtr277bT_UexldHrpg,10240 +mypy/nativeparse.py,sha256=G7zkISdW3JgPyVBfmGeE9tZTQexnp_kvIrqEgnAEuHY,72662 +mypy/nodes.cp314-win_amd64.pyd,sha256=qrjQ513Sd1cc7qgK88BXZsxbooxFKs5Ma8dkkJSoLWs,10240 +mypy/nodes.py,sha256=JmEUCuALJTC_coi0CssawjCRi3XUKmCTvUW0Iw_bVIg,179975 +mypy/operators.cp314-win_amd64.pyd,sha256=S1Eh5HbMcStYCN5H2WDFnAsAuC5809ZV12UJuhFCcCg,10240 +mypy/operators.py,sha256=BHafr2ENZYPmUytEgKOYMS1GwPKFebWBs5pnk8pyZk8,2866 +mypy/options.cp314-win_amd64.pyd,sha256=Te1LYresdDJJ38nhvDWtpVCuJBcrtAceI1zZ18qiG7E,10240 +mypy/options.py,sha256=luzjO9dHrqoekP78_4agKrw_vK05G2bl0q1COf9i6WQ,27389 +mypy/parse.cp314-win_amd64.pyd,sha256=V8LEtVDSK-uPxxBEtyi0nvxs_gMulOFhSrYTuq2TEv4,10240 +mypy/parse.py,sha256=NmFWX6KHKYJN5KW9ckP5M0RwSv1MkS7cn4e8SGH1d8g,4996 +mypy/partially_defined.cp314-win_amd64.pyd,sha256=OmrCFIEIPV6u9RwIZFOqYmoaKz6o-6LpZOBrvwgjVRQ,10240 +mypy/partially_defined.py,sha256=FBqB9W4v27q6Mj9No5WNf5jjsUsEkTvyMKaTueI7quQ,26746 +mypy/patterns.cp314-win_amd64.pyd,sha256=_pjR2abjKud250-6nDqvUrNEai61-menG65H5Q9jGkU,10240 +mypy/patterns.py,sha256=epS_R9Fv5mnSAGsc6EtUxtmo34_DD1lJ5BevTdMn8Ak,4048 +mypy/plugin.cp314-win_amd64.pyd,sha256=STqV0V01TxsGq2WSDspPtYDgmS1HWZ2azDwlOFN97xU,10240 +mypy/plugin.py,sha256=yAcCukIWW2zflHpeiltIO6wKxXzoJr5s_cgfLep5Ngw,36250 +mypy/plugins/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/plugins/__pycache__/__init__.cpython-314.pyc,, +mypy/plugins/__pycache__/attrs.cpython-314.pyc,, +mypy/plugins/__pycache__/common.cpython-314.pyc,, +mypy/plugins/__pycache__/constants.cpython-314.pyc,, +mypy/plugins/__pycache__/ctypes.cpython-314.pyc,, +mypy/plugins/__pycache__/dataclasses.cpython-314.pyc,, +mypy/plugins/__pycache__/default.cpython-314.pyc,, +mypy/plugins/__pycache__/enums.cpython-314.pyc,, +mypy/plugins/__pycache__/functools.cpython-314.pyc,, +mypy/plugins/__pycache__/proper_plugin.cpython-314.pyc,, +mypy/plugins/__pycache__/singledispatch.cpython-314.pyc,, +mypy/plugins/attrs.cp314-win_amd64.pyd,sha256=xZKIEEkGMhN8L1i7FYL_e_caSmOhTQJsv2lGyVtCeWs,10240 +mypy/plugins/attrs.py,sha256=iMslFOlnQDVAhx9sYpj_yIDtKe_0uBXX0LcwREcEt30,46508 +mypy/plugins/common.cp314-win_amd64.pyd,sha256=6jXyGezukiFHoImKjqmiCw-07ogmbsz6TOMLE-Ogd8w,10240 +mypy/plugins/common.py,sha256=ikFQb2netqmmSW_72Ydz7j1TeUqG4teFuP1DnpOOLDY,14117 +mypy/plugins/constants.cp314-win_amd64.pyd,sha256=vFo-uwHl3d78LwAolUk4j5ArtZy5-JPmw2iHCjXQV3U,10240 +mypy/plugins/constants.py,sha256=EhWnIlkU1lHkF6CwlVqEitQE9dM9PfdZn35bHMI37jc,819 +mypy/plugins/ctypes.cp314-win_amd64.pyd,sha256=BVCQ1wVWv9cFJUA4DVykPAuaigLDx6dTkuY71lP6VvA,10240 +mypy/plugins/ctypes.py,sha256=uB84xNCEzCVfeKjC7FHy7dFF5o55V3L-Rve9OD3YoxM,10675 +mypy/plugins/dataclasses.cp314-win_amd64.pyd,sha256=-MnmxIB5a27ac0UO-Ri1bIHxRMHXW1tLciLx69K5gF4,10240 +mypy/plugins/dataclasses.py,sha256=W9IL9DM6m8vS1QSk19ErChLQtn3R3IMrJCHWlXj48lY,47255 +mypy/plugins/default.cp314-win_amd64.pyd,sha256=MfE3fFmASpJiL7I0Z4I8KkfHzhBxCxYuhvpoRfVIfc0,10240 +mypy/plugins/default.py,sha256=lzAE4nBuduJ7_hDRkRdFU0h1Y6lxXNi_heEosgzfDWE,24118 +mypy/plugins/enums.cp314-win_amd64.pyd,sha256=8tWMhLAtlMG47B9wToz0wIegqi_yNF-rwF3niSkvaYI,10240 +mypy/plugins/enums.py,sha256=XocRVf78mw3sOih8fVgjrhuEWfp1simmjKOyXbcdgZs,12110 +mypy/plugins/functools.cp314-win_amd64.pyd,sha256=VxuU-rG9HIEcwgVo0EfRthKC17cuODmhusSNBaZmdQg,10240 +mypy/plugins/functools.py,sha256=EcsCnQbhzfRBsePy3K7T3HNziDU5n84GLdAJb9ayX4s,15527 +mypy/plugins/proper_plugin.cp314-win_amd64.pyd,sha256=vwwX0o9GGY_NBlYMOKDQTdwWQaLi4rL9BxZAmjG3vh4,10240 +mypy/plugins/proper_plugin.py,sha256=HcrOREPKTWcvnA2BRW7m_-xxOQnnk4wU1Y3YKk9duoc,6574 +mypy/plugins/singledispatch.cp314-win_amd64.pyd,sha256=QX8HgCzEN94cJRbnTizohzSRDqLWH0rW-Ou1_ejwwgc,10240 +mypy/plugins/singledispatch.py,sha256=rEHOqk3DUvt4WUcI7ShnNJCg_QHj4kggEqDwPa8gcy4,8151 +mypy/py.typed,sha256=zlBhTdAQBRfJxeJXD-QnlXiZYsiAJYYkr3mbEsmwSac,64 +mypy/pyinfo.py,sha256=URtMQq4FxPkrPWB2jd8wQGDegZFoIvO8jM_AWTayOiY,3014 +mypy/reachability.cp314-win_amd64.pyd,sha256=kp7i6FjW70WankX_vLgEOd9--nNhDDgoSNtDUq-Lu4U,10240 +mypy/reachability.py,sha256=ti74QpP4fGo_2jqKdECU4lA2yUNtQKnoOF9X5gICviA,12977 +mypy/refinfo.cp314-win_amd64.pyd,sha256=ShIAj6cmCnPAWWyRPAaUXJ4Og1foO-wQo7EVQG2SYZU,10240 +mypy/refinfo.py,sha256=qaWKWtkgdlYQVxNucU3KG-4U2OsOBCSG8K8lqupc2S8,2784 +mypy/renaming.cp314-win_amd64.pyd,sha256=IXUfZRu-er6RGaTQCtQ1uz6Tt6qzVFnEJyVXkhSHc1M,10240 +mypy/renaming.py,sha256=-Ju3NKpUnJyvU8FSzZR-KgipUAIpRhrLiIVE2395NVo,20494 +mypy/report.cp314-win_amd64.pyd,sha256=vdSuKlT6aJHn1wO05K4fb_Nvxg3teewnYbcSk6nB9H4,10240 +mypy/report.py,sha256=885-LtqRZy2cawgZQ3Nw1NRL5hXSb-EAjCnmhjm2M3E,34700 +mypy/scope.cp314-win_amd64.pyd,sha256=P2WUV5EynAo9TQACcgM75ndbZq14XU9pRduDYrV8Rw4,10240 +mypy/scope.py,sha256=G9RJNrV_mJkkaNgWn5G4uNgJgNsMsA6ZBVGu7K7AGLI,4233 +mypy/semanal.cp314-win_amd64.pyd,sha256=cjH143SYu_uO86_aTgQLuLobMPLRMqGLbxn-NFjkVgc,10240 +mypy/semanal.py,sha256=7tHKS6ChLYfjvNmdFWdOyFZ-xo-zV6qoiOwJ0T2W408,361221 +mypy/semanal_classprop.cp314-win_amd64.pyd,sha256=4MqVpiW6Llw8ZUtyuOJrQzRAxDTfuuzEa_r6owFoods,10240 +mypy/semanal_classprop.py,sha256=81ClR1KA27TDEIl04vN3cpLPTVMEJphFiGp4n87kRjY,7673 +mypy/semanal_enum.cp314-win_amd64.pyd,sha256=OArncgp021mKk33070XyQiwOqnZ_jgTo_zK4B6q8Jy0,10240 +mypy/semanal_enum.py,sha256=NfHeW7rlHu0qzuXOOWFkCrITCHsNcMJxZDb58hNobCw,10197 +mypy/semanal_infer.cp314-win_amd64.pyd,sha256=_XWAC8xuQSjhr7IXbUJ2463Zm2P0mpf2li495ltnPgU,10240 +mypy/semanal_infer.py,sha256=ysch4tIEiwxefw_1LPSqB2wTyoJbnlOmCfO4Iq-_bC4,5350 +mypy/semanal_main.cp314-win_amd64.pyd,sha256=vnz45JGPwaZcab6wHFFXzFyqtidOnHEUBiQgNgqCXrY,10240 +mypy/semanal_main.py,sha256=B-1rINrKkpvt4J3iAk4ffPgMZWAH5kGpGx3yNMiGI6Q,21554 +mypy/semanal_namedtuple.cp314-win_amd64.pyd,sha256=RMy5lPa6Og3VdyoB7kxE3REetVjKGyPgcWT217PcMs8,10240 +mypy/semanal_namedtuple.py,sha256=aXCavynnPDXGStwD2nODpYOGYGCuZPfZjbZNp31RZGI,31368 +mypy/semanal_newtype.cp314-win_amd64.pyd,sha256=kfUsIKlt5SuuZCQrleGX0dYk1iQQM73QZO0pQBNFaXg,10240 +mypy/semanal_newtype.py,sha256=-kKdzbYvTuUpRqKMN9GpFSBqkKGZqFIDKf57pkoscUs,10576 +mypy/semanal_pass1.cp314-win_amd64.pyd,sha256=mpjfJ-6oC98n_DFptomEbp_N-9Ww0y84hec6Womouv4,10240 +mypy/semanal_pass1.py,sha256=6rhzEF6V7orOsgjYsnGHz8lqaG3TA-gr8QFA_ytihkc,5584 +mypy/semanal_shared.cp314-win_amd64.pyd,sha256=LWq77NaqA8qILYgC0mVkq4_qeZgeLiT_FttoMUnuB7c,10240 +mypy/semanal_shared.py,sha256=cw9UZAp1sPzXAmLuiIuTL_vK8lAx_Y8V4fW9iP515RI,15795 +mypy/semanal_typeargs.cp314-win_amd64.pyd,sha256=p0bmkDe-vBVzoU02P3fEzRM4yslr2GBw9CiLv3Tj34c,10240 +mypy/semanal_typeargs.py,sha256=Qw8UCzpRATUXSILVSLi8PvPqOzsTf5BiNV2RTorwlP4,13338 +mypy/semanal_typeddict.cp314-win_amd64.pyd,sha256=V_cKWZ3p1rxaT0EuvyDuGXDyZP3M8Zp1TPvV8mw274s,10240 +mypy/semanal_typeddict.py,sha256=P499w_SQXrTdw_4w_zvOW4YwlDxixKwQeB0yGfOncV4,26043 +mypy/server/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/server/__pycache__/__init__.cpython-314.pyc,, +mypy/server/__pycache__/astdiff.cpython-314.pyc,, +mypy/server/__pycache__/astmerge.cpython-314.pyc,, +mypy/server/__pycache__/aststrip.cpython-314.pyc,, +mypy/server/__pycache__/deps.cpython-314.pyc,, +mypy/server/__pycache__/mergecheck.cpython-314.pyc,, +mypy/server/__pycache__/objgraph.cpython-314.pyc,, +mypy/server/__pycache__/subexpr.cpython-314.pyc,, +mypy/server/__pycache__/target.cpython-314.pyc,, +mypy/server/__pycache__/trigger.cpython-314.pyc,, +mypy/server/__pycache__/update.cpython-314.pyc,, +mypy/server/astdiff.cp314-win_amd64.pyd,sha256=gtdpFL8_XPdBslRScB9KtXvQqgWIvQQBOVy0qNMc9pc,10240 +mypy/server/astdiff.py,sha256=gw6zjRsETX73Rb6ZGFKJZikEH7fK_TcJbxB0ep8M0DE,21362 +mypy/server/astmerge.cp314-win_amd64.pyd,sha256=VqZfirPHoUmpVgu04xhU81tfmUhImdjkjj5z-5RHqlM,10240 +mypy/server/astmerge.py,sha256=4_uLEbB2qQhdorpr8EwrGtBnVk5Dw8PhjEkuBlmHThw,20982 +mypy/server/aststrip.cp314-win_amd64.pyd,sha256=K6G_mmIedQNhjIQL7ndFQtYrmQtJ6hFrWVp1prOicao,10240 +mypy/server/aststrip.py,sha256=f8EY1kzRCUL_sR1SufJgwkbLC7A5IAOjwDRJE9Hhr2o,9789 +mypy/server/deps.cp314-win_amd64.pyd,sha256=QWDkRMl_YzuOalsv1vWAYDR-2rP3KxuImxvAPlvireU,10240 +mypy/server/deps.py,sha256=MJxOLZF08Ta9XgzBh982CVtknZ2DJ9QL928v36PBFiM,49683 +mypy/server/mergecheck.cp314-win_amd64.pyd,sha256=e44iIi5plCPDF7tVQ5MpoGNnkao7znQ5HeZbw2R8qjQ,10240 +mypy/server/mergecheck.py,sha256=yFpGbyK9JX_5VCB9V0Zz-b3o__PKmejRwgAL9LF0bUc,2757 +mypy/server/objgraph.cp314-win_amd64.pyd,sha256=m4FQFn3xeUJInlwtitwr-ppHlr6P5gUdd7R-VsnJ-_o,10240 +mypy/server/objgraph.py,sha256=l2otuEtyy6J67pfWgU17dg8LIWkDqP34YrBNjDrjytc,3230 +mypy/server/subexpr.cp314-win_amd64.pyd,sha256=n6f1s9IQ2fU28o5ydWWf-gXiPhmzXIj_izYvpAQuy8Y,10240 +mypy/server/subexpr.py,sha256=1BZiO7TmuOQBpwRN6t1DymbFowRSsguM_TQ-N-6nj28,5494 +mypy/server/target.cp314-win_amd64.pyd,sha256=qTEJb4k0c6OQnnZmqIibM0OZ4bm7cBbutfVS1ihHTEw,10240 +mypy/server/target.py,sha256=IbuK2qqtMvEPAof83BdgYJv6AGW2q_o4CQxC5TnB-Bg,273 +mypy/server/trigger.cp314-win_amd64.pyd,sha256=KITCqy1o1QRGf_xG-n-ScYg9Ip7E4Zgvw9w58B08niQ,10240 +mypy/server/trigger.py,sha256=qvo4tCLyrhI48oPTfDO_nWOVZfjMcYjoMdGgWsocEKg,793 +mypy/server/update.cp314-win_amd64.pyd,sha256=Mpp5QrVeXNNa2lBgbsY5wQTYaH3SR6wBDH1O1TWufmY,10240 +mypy/server/update.py,sha256=T8TmGRtc92uebhChVbeXFyyHpgF2scNWdp5ugF0xhIo,54315 +mypy/sharedparse.cp314-win_amd64.pyd,sha256=fluIPl7gDtXdtckuYRw24h19zXyVN-t7UjkDKYeK6DQ,10240 +mypy/sharedparse.py,sha256=tPLG0cUbBkZU7Pc37G80K5s24Fb8hkevp7qJIJBTplk,2146 +mypy/solve.cp314-win_amd64.pyd,sha256=IhjqxBjKpi2AcxrQMfPhIlGXj0fVk-jcXGmdaEW18kw,10240 +mypy/solve.py,sha256=yz2p2Mf1E4IZxpph5MSwWvT8D1yRoVdui2kCYHX8KWg,24530 +mypy/split_namespace.py,sha256=P67HianSrsMSZoeuS6F9swM5eK-B2fEBU3XJ6RFtYo0,1289 +mypy/state.cp314-win_amd64.pyd,sha256=CcMdtdLVZEVSLJNNHyvQ69FOroEhGdScEkUpXOkbz1I,10240 +mypy/state.py,sha256=yGfTdStRI9BJ3MpFvZS89uvVOLuqWxNy9DCY-SDHwcw,850 +mypy/stats.cp314-win_amd64.pyd,sha256=Z5ZFTKEDsJ5koIUP1jjh7K3ryux8mN5EFcWD1mb0Cnk,10240 +mypy/stats.py,sha256=661ysjBeZayvB16uK_bFr98KjqLamNm9BQpFO8iR9zA,16846 +mypy/strconv.cp314-win_amd64.pyd,sha256=guJZGCgRj7aHPjTL1ovCB57PQG0XCuoyb1B3YhTgtOc,10240 +mypy/strconv.py,sha256=dW3mTKd5wHuUswt0Af5KqmSfCeM7QRzIw73auzjjbsU,25969 +mypy/stubdoc.py,sha256=lrFgkX4kCMamVHbFwuARJziY21hSesBb-0LR5HIozAw,19328 +mypy/stubgen.cp314-win_amd64.pyd,sha256=wql9WTgUY13apMl9PR4jbkq23ogqc8jxxyqJtIIYPpo,10240 +mypy/stubgen.py,sha256=dGCPp5rLRcNi03rQLJ43s7LgnH23kwZZuI6IO52yGcY,78760 +mypy/stubgenc.py,sha256=4_TSpSPyCucpFqRTDdjnQn85dZOpchmeYr6o4NRQdR0,39265 +mypy/stubinfo.cp314-win_amd64.pyd,sha256=XWS7tLHLIG888YBn_LqeA2_M6ZFWhHS7ad3KxltdWFk,10240 +mypy/stubinfo.py,sha256=1RvGVmW0e1YwFRPNHtxjHuLTW7sdEiMAjyewVLEXy7o,11681 +mypy/stubtest.py,sha256=us8E7pDYor3s5jS1K5VO04-oKBxXY6SZGYXEFx1yiv0,103787 +mypy/stubutil.cp314-win_amd64.pyd,sha256=nLKErM32Sb5HnQKGzSwTmrJhccgK1c0YgsVAY58qk3M,10240 +mypy/stubutil.py,sha256=kX27FzBaIQlNVk6GO1oZEjsUsGFsjRN9leDDMnQ62F4,33495 +mypy/subtypes.cp314-win_amd64.pyd,sha256=5cDNS-Nzc4I9_bHzKgGvvcwAXBukfD4TooWY5rw7AuA,10240 +mypy/subtypes.py,sha256=CwQHZVVb2GEzhXGsjKsMy2rcriOdhB8sqa-OQj3Tsrg,100651 +mypy/suggestions.cp314-win_amd64.pyd,sha256=a71-RwIbbyOrgFaNJgHK_wtimpZjD74bDVw-W09MSq4,10240 +mypy/suggestions.py,sha256=UrxUFOwC1mG4DNTMY0RODTyvcQrZFKPYiYLquHwtVBY,39056 +mypy/test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/test/__pycache__/__init__.cpython-314.pyc,, +mypy/test/__pycache__/config.cpython-314.pyc,, +mypy/test/__pycache__/data.cpython-314.pyc,, +mypy/test/__pycache__/helpers.cpython-314.pyc,, +mypy/test/__pycache__/test_config_parser.cpython-314.pyc,, +mypy/test/__pycache__/test_diff_cache.cpython-314.pyc,, +mypy/test/__pycache__/test_find_sources.cpython-314.pyc,, +mypy/test/__pycache__/test_nativeparse.cpython-314.pyc,, +mypy/test/__pycache__/test_ref_info.cpython-314.pyc,, +mypy/test/__pycache__/testapi.cpython-314.pyc,, +mypy/test/__pycache__/testargs.cpython-314.pyc,, +mypy/test/__pycache__/testcheck.cpython-314.pyc,, +mypy/test/__pycache__/testcmdline.cpython-314.pyc,, +mypy/test/__pycache__/testconstraints.cpython-314.pyc,, +mypy/test/__pycache__/testdaemon.cpython-314.pyc,, +mypy/test/__pycache__/testdeps.cpython-314.pyc,, +mypy/test/__pycache__/testdiff.cpython-314.pyc,, +mypy/test/__pycache__/testerrorstream.cpython-314.pyc,, +mypy/test/__pycache__/testexportjson.cpython-314.pyc,, +mypy/test/__pycache__/testfinegrained.cpython-314.pyc,, +mypy/test/__pycache__/testfinegrainedcache.cpython-314.pyc,, +mypy/test/__pycache__/testformatter.cpython-314.pyc,, +mypy/test/__pycache__/testfscache.cpython-314.pyc,, +mypy/test/__pycache__/testgraph.cpython-314.pyc,, +mypy/test/__pycache__/testinfer.cpython-314.pyc,, +mypy/test/__pycache__/testipc.cpython-314.pyc,, +mypy/test/__pycache__/testmerge.cpython-314.pyc,, +mypy/test/__pycache__/testmodulefinder.cpython-314.pyc,, +mypy/test/__pycache__/testmypyc.cpython-314.pyc,, +mypy/test/__pycache__/testoutput.cpython-314.pyc,, +mypy/test/__pycache__/testparse.cpython-314.pyc,, +mypy/test/__pycache__/testpep561.cpython-314.pyc,, +mypy/test/__pycache__/testpythoneval.cpython-314.pyc,, +mypy/test/__pycache__/testreports.cpython-314.pyc,, +mypy/test/__pycache__/testsemanal.cpython-314.pyc,, +mypy/test/__pycache__/testsolve.cpython-314.pyc,, +mypy/test/__pycache__/teststubgen.cpython-314.pyc,, +mypy/test/__pycache__/teststubinfo.cpython-314.pyc,, +mypy/test/__pycache__/teststubtest.cpython-314.pyc,, +mypy/test/__pycache__/testsubtypes.cpython-314.pyc,, +mypy/test/__pycache__/testtransform.cpython-314.pyc,, +mypy/test/__pycache__/testtypegen.cpython-314.pyc,, +mypy/test/__pycache__/testtypes.cpython-314.pyc,, +mypy/test/__pycache__/testutil.cpython-314.pyc,, +mypy/test/__pycache__/typefixture.cpython-314.pyc,, +mypy/test/__pycache__/update_data.cpython-314.pyc,, +mypy/test/__pycache__/visitors.cpython-314.pyc,, +mypy/test/config.py,sha256=VEePvz7BHWcNCQS1qY5H-sOvCgNuIN2yY6zZmXbo9kU,1301 +mypy/test/data.py,sha256=kdCcRf7Em4y2WqA5jXgr6_SFS43Ga1G5Ywe2_nrXcIc,30791 +mypy/test/helpers.py,sha256=JUeqUJVp4vm6vOj7VAUHPyJ2dofe-WA7allgtuHw9hk,16992 +mypy/test/meta/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/test/meta/__pycache__/__init__.cpython-314.pyc,, +mypy/test/meta/__pycache__/_pytest.cpython-314.pyc,, +mypy/test/meta/__pycache__/test_diff_helper.cpython-314.pyc,, +mypy/test/meta/__pycache__/test_parse_data.cpython-314.pyc,, +mypy/test/meta/__pycache__/test_update_data.cpython-314.pyc,, +mypy/test/meta/_pytest.py,sha256=BHGoXuST1N2IqVBlWsJPAvBSxc0qVpALDjyLWVVvxPA,2276 +mypy/test/meta/test_diff_helper.py,sha256=ETTk0kyEvdKP_CMIKddY2sX6oSwTeUzEqNgDeBPLI6E,1692 +mypy/test/meta/test_parse_data.py,sha256=3sfb9tQbgaM_ioyzwJ8Wtn_i_ve17VLrv3PhYSOpSQs,1895 +mypy/test/meta/test_update_data.py,sha256=Ddg5vR2aRTshhcoi083FMvVBSM5K95ycBukxwLlVerU,4770 +mypy/test/test_config_parser.py,sha256=40D_aqRD6QCqJU4BsDBm_47b4X-Dnu05n36I2BY1lOU,4167 +mypy/test/test_diff_cache.py,sha256=wYtHiMzl4AzQSoZLDH6wW6vuM8NKqH58EKdozNefD2w,8601 +mypy/test/test_find_sources.py,sha256=X_YRHcS6F7sp2MC2YepatigrfxxShIA6q2zj6Yh0JfA,13693 +mypy/test/test_nativeparse.py,sha256=Wa-7XwK_v7_gZkSdv3ppUi6XhU_Gu3rOKYJ5MaNMED0,8609 +mypy/test/test_ref_info.py,sha256=MMbcYA8tX_kCgVhPdLX507vkzJsX13cN93u65h-30ls,1469 +mypy/test/testapi.py,sha256=Xinte9ICqFeoe9AUweIEKiHvjbgD8H_Xv6Leck_sUoA,1447 +mypy/test/testargs.py,sha256=QSkID7us5fc0YzJDoKrPldi9gdPI0QwQ7HOBl1bRl8s,3253 +mypy/test/testcheck.py,sha256=at5voKjwJ3Mwy5Fb-gffyWF9eUOdYsDOfe4dOlwklSM,14858 +mypy/test/testcmdline.py,sha256=PiVnlUbHd02V81ETs8zHBEOGLvAr6HcRC3lCsnmzp1Y,5081 +mypy/test/testconstraints.py,sha256=s3a2C6JcqTzzQeh2IFSKEXHF_OchhtmttX-TTmXYIJ8,5267 +mypy/test/testdaemon.py,sha256=9OACkimdIGIsqx7x7yhl78Zqwz-xpD860kCh0JcfbI0,4511 +mypy/test/testdeps.py,sha256=bYQ_g6sHA2VCWsrapenHOtZRkfBlsYg4PUH6Y5sNFVw,3236 +mypy/test/testdiff.py,sha256=VdM_0vp0NSOxlYifl0_ElvGEHhMoqsp6g9wWBfk5Rt4,2510 +mypy/test/testerrorstream.py,sha256=bEAw3kMIfSJNec8G2iR2VgcsvbupguGxhW71EZ_Cias,1441 +mypy/test/testexportjson.py,sha256=SVcIX9ov8_ZGI7SmtGEdYeswdpF4a4TJPQjgHy1PKFc,3983 +mypy/test/testfinegrained.py,sha256=V0B3PQI0WNMPigafrARqlzCyAzvBkkhwo7J082vkAo8,17820 +mypy/test/testfinegrainedcache.py,sha256=AocgzZWRs8dlNcaaKzwY3QSBwxbbdwi3xwq5qcH9XTI,580 +mypy/test/testformatter.py,sha256=QwuFdblCF28X2J6K43mSUw95pl_VRdwqrAfOkCQr1xM,2639 +mypy/test/testfscache.py,sha256=1QDTTg7Towo5GI31NIwamXiIhbpS8o1zVmYcRNzHwh8,4465 +mypy/test/testgraph.py,sha256=NI1Z1FaBeUcxuLBQL8cel2YliUCtMk8QdPWdkxXsjkY,5303 +mypy/test/testinfer.py,sha256=d3NV8bTBrNJbaY1aO_IiYfMBeiWIeZjgeyYeQVShQwA,13856 +mypy/test/testipc.py,sha256=pBz9DjZzPK_9l3EZVtrdzvUQr8aenIHCayatDi2YPuY,3966 +mypy/test/testmerge.py,sha256=8t54I0Yn8uaaBTXCdkjAikT0nKrj7M2nt_zbPC0y_Fo,8594 +mypy/test/testmodulefinder.py,sha256=T4bQKD0C6SQJsQdkXJ0ZqFKM47Bdaoqe8sUCeIoVp5U,13957 +mypy/test/testmypyc.py,sha256=qxqOJLOG1iOKlCt-_K3a5x_X1F0deY8Vb7ON3m2xVAI,869 +mypy/test/testoutput.py,sha256=YJqb5Utxrl2r18PMacgHr9jTd68I-1EUk2y8Pdp10zg,1980 +mypy/test/testparse.py,sha256=QDwxQj4wzq3EYpaNC1K7bJYnhJzDHaZaIntKxwhB67k,3834 +mypy/test/testpep561.py,sha256=hxowZEKsmA5bWLr4lFD1fxLF8aZmX47lf4Oncpe6LlY,6839 +mypy/test/testpythoneval.py,sha256=VrmzHfwenbJ7O0UeBO6WtXeWdhD3PYEBFEdO6ln7uIY,4586 +mypy/test/testreports.py,sha256=GOP5LgXn5r9ADErKNEsjyhzBcMInm_Qy_6QY9TEO9hI,1953 +mypy/test/testsemanal.py,sha256=qGir53aoBcCJhhURY-6NI2_I_YC6e-5yMMyiEKrL-pY,6975 +mypy/test/testsolve.py,sha256=e_2Yagxy7AsA4SkqwKVYXsjh1z5z6V9D5k2cMzwNdeU,10069 +mypy/test/teststubgen.py,sha256=haASr18XXBuGXMWq4PVrAYze4u2jQJqev2E-enwqSB8,60928 +mypy/test/teststubinfo.py,sha256=yx1VeSL53qh_MimncCq8gKT9tyD-84ZDeYLk_tOf214,1587 +mypy/test/teststubtest.py,sha256=vPZQhuxmMkDId23WlQRWpI3EGo5Mtlxgr_02CUpRrtQ,100706 +mypy/test/testsubtypes.py,sha256=UqehkYlJVgs-IsQa8XsZUgJqBawHgsDD78pguXKiWYo,12426 +mypy/test/testtransform.py,sha256=kg_-7Rl4tyVf5-Frs07_6fBBJ8DlG6a6CY_XgyNZeSc,2195 +mypy/test/testtypegen.py,sha256=tcvK_V2JXthKarGwIvOplp-m3Pp_3i_mHTSLV6OYhNA,3149 +mypy/test/testtypes.py,sha256=tKvqgMz4j0wn8nDYXZHzqgfJcqdSs5e7rSBd7Yh6jNY,64454 +mypy/test/testutil.py,sha256=HqmkgHC3TBnm7VUF5059l394PKLhS-YItLheKq8htLU,4233 +mypy/test/typefixture.py,sha256=-qWDr5Wxl8jURtrMVweDBNusUEuJb0nWg5r4iwwgX40,16014 +mypy/test/update_data.py,sha256=IOqTyP5RTOd2SUsj1faveoFKYc3q0i1kqP-_WBLVVmU,3685 +mypy/test/visitors.cp314-win_amd64.pyd,sha256=cRIRo4UBWcDkgVXzGZ_Kl5od-kraLpRx7lfXEvk7zAY,10240 +mypy/test/visitors.py,sha256=cfsPawFO9J2UnoeZGzkYbAbZcuZ8HRDc1FKGd9SV1E0,2089 +mypy/traverser.cp314-win_amd64.pyd,sha256=7Mo5MHF0nWk1h2f1mzKvKXkGMjMesjQEZ5xK6ECZ5L4,10240 +mypy/traverser.py,sha256=x6TYVDFBiAa6usETAxrE03WAns3uON3Cnu2zCBOEqRA,31313 +mypy/treetransform.cp314-win_amd64.pyd,sha256=jvQUm9aa6TA2taIUvvVR2cgBbVF9_JyzvKdkEbIy6V8,10240 +mypy/treetransform.py,sha256=OT9rMjZto4xJuZHfBq0cx2W1TvB-Rb04DspKvLHFepU,29360 +mypy/tvar_scope.cp314-win_amd64.pyd,sha256=47aiHViOl-ZlNeUM6k65yUhmlEAVw8Nx2HqePhiNwIk,10240 +mypy/tvar_scope.py,sha256=KrjzxZ_FMfmRAyb_mT5BlKlKadKzoSS4wkHXfjXgmkI,7356 +mypy/type_visitor.cp314-win_amd64.pyd,sha256=PyGDB-L6VKubrZPpIyHHkRmsZSlhbNjnTBqOd8DL3Nc,10240 +mypy/type_visitor.py,sha256=rfjJOstoCbI2ahlF9Hn8EZBoDcS4Cn-LvOuROHRQOic,19975 +mypy/typeanal.cp314-win_amd64.pyd,sha256=Lt1n95XPiYag-UKeevRlBtEOmSNJYZe3GZ7UAilKeco,10240 +mypy/typeanal.py,sha256=LfjMjHLxfMq-VGZmRSsS5pt-iT5WNaY2H-0ztW7HbM0,119559 +mypy/typeops.cp314-win_amd64.pyd,sha256=8Qrtzvm_M1sToCJ3u3Jsrs_oXhDQPeh-jGQh6_kHMWE,10240 +mypy/typeops.py,sha256=4W3kBRwtGs922R0IOhJUnvyXSkkNy10jqzIdqFfroQA,51180 +mypy/types.cp314-win_amd64.pyd,sha256=IywigBtJI3NuHOBZEK8NC007lE2opDPWlCet-XUKciY,10240 +mypy/types.py,sha256=j8Yx3uPHqjdR1CxPZRutTQldh51WxYsLowOSjggHzE0,159937 +mypy/types_utils.cp314-win_amd64.pyd,sha256=8ck-eybreBDlpfQx-yXxTtV0u_Jw1zjMt1W6Jc3-hSQ,10240 +mypy/types_utils.py,sha256=eqsCmSgcbyeIQGlJswM2IDCWejGEPsOCmdOZpa1bXjI,6216 +mypy/typeshed/LICENSE,sha256=KV-FOMlK5cMEMwHPfP8chS2ranhqjd7kceBhtA1eyr4,12657 +mypy/typeshed/stdlib/VERSIONS,sha256=PEsgFQAWjZl9toKVh62RCuAisUTrrlizbtvfja3zs9o,6442 +mypy/typeshed/stdlib/__future__.pyi,sha256=qIwWDmjaw3XCiulKYoKBQB_eJjLxweesUKwBdpkgQkU,915 +mypy/typeshed/stdlib/__main__.pyi,sha256=hcfHKThQRiibOXGnPeEUHunrtviMdorj0MtdnIwLtl8,53 +mypy/typeshed/stdlib/_ast.pyi,sha256=Hn23xk9t6_M5kuMZHkcgjAWeNcwktovuyMbMLjZbtEQ,3344 +mypy/typeshed/stdlib/_asyncio.pyi,sha256=7yPRcejEUZ1k1CbRFVgPyvx1EHoLqCokMRHiKG0Y0-s,4872 +mypy/typeshed/stdlib/_bisect.pyi,sha256=jndBnhfr-GmrZ4W11uW-L10_e7nv9nDd2uFlpQTUNpA,4854 +mypy/typeshed/stdlib/_blake2.pyi,sha256=_qavMws5SSi8fWHc3J4WsFll6N2SORWBegj7qQX5_u4,3542 +mypy/typeshed/stdlib/_bootlocale.pyi,sha256=vSVnoBvURsNzi7MPLR1b_wpuh-yySKzPValAwQ3OVT8,64 +mypy/typeshed/stdlib/_bz2.pyi,sha256=rFCr1AYojWvE59rRz5njFVK1m1vMC2wNmTm-F7nrx_E,678 +mypy/typeshed/stdlib/_codecs.pyi,sha256=ryICMIWdfKvRj4jRQTwniDw7bMOdhyCuduSX0nb6Z40,6721 +mypy/typeshed/stdlib/_collections_abc.pyi,sha256=b9lKh_z4afqI04pPZ1EcpPeUzGQ5tfC7SPIo4NmviXQ,3041 +mypy/typeshed/stdlib/_compat_pickle.pyi,sha256=3WH0XDg8YMQ_EzfT7cnBKrU5WjpXIRJ5aec8h0xrDbU,438 +mypy/typeshed/stdlib/_compression.pyi,sha256=qEdmEzjcfQ9rOKRLjVtkpPSfvNEViEc43FouPF3XAfA,1377 +mypy/typeshed/stdlib/_contextvars.pyi,sha256=CeOt4eddnDTydVq4R1qOE9J7n7hQN6Moo_vstCY0EfQ,2370 +mypy/typeshed/stdlib/_csv.pyi,sha256=AJt3gWebsJJwgTBsKC3aCwWKInuKZz00_5qNlKv4rKw,4041 +mypy/typeshed/stdlib/_ctypes.pyi,sha256=5NsU-2HxMfZSMJVZ5LpusBQHblRYcWsSU1HM2wFlJY8,17676 +mypy/typeshed/stdlib/_curses.pyi,sha256=jl9jHbBJlbuMfFvl_ho97IjmwPXo-JUl9iKJ9Nq13MM,16854 +mypy/typeshed/stdlib/_curses_panel.pyi,sha256=w1RxG64bD2C8OGi2sXQmVIrNRv3q9aB7XrfYMGCkPF0,757 +mypy/typeshed/stdlib/_dbm.pyi,sha256=QtTE7l0xah6cJnDhlnIYOiqwsK3UsNIj9xm0WM-uVnw,1775 +mypy/typeshed/stdlib/_decimal.pyi,sha256=mU59vCxZe6aFeK7eCfAfYUUTy87ox8yD4bbpw0S-9sU,2058 +mypy/typeshed/stdlib/_frozen_importlib.pyi,sha256=7r6dPA7W9aOIdRmf4jNDEpqbSQDbT4ITSVmb6qmZQWc,4679 +mypy/typeshed/stdlib/_frozen_importlib_external.pyi,sha256=nhmOFkagtckI1GvEBroRwCaxk2ECNFA_uXdzWIM1vMM,9607 +mypy/typeshed/stdlib/_gdbm.pyi,sha256=_xrxJzc3WMpbJSc5uzWb1v2-Q2rkyxRFtUg85Ze7r6g,1946 +mypy/typeshed/stdlib/_hashlib.pyi,sha256=Dwc-lt0zwAvmrJ_lvV58s7NKK85zmC19iXT2HkDaYsg,5593 +mypy/typeshed/stdlib/_heapq.pyi,sha256=SQZxb-0v3sujrUDvauFD1kgbQf9OuhRELp3J68-iC50,755 +mypy/typeshed/stdlib/_imp.pyi,sha256=yUAJduUklNqp7sHZ8mV-4MPnacchatn1xd4v23clNdc,1185 +mypy/typeshed/stdlib/_interpchannels.pyi,sha256=WvlfKacmFX89HoVOrEElyAmRsxotgbEiSAKKzUp4S1o,3204 +mypy/typeshed/stdlib/_interpqueues.pyi,sha256=0OTlJA5tszfEGyCralyqa1ZxyVdbd0jbDQLlqB7YeKg,866 +mypy/typeshed/stdlib/_interpreters.pyi,sha256=PR8fkrZPGLvMbTovssuuTn2j0SNhlLNQNUt0nx4eE8M,2654 +mypy/typeshed/stdlib/_io.pyi,sha256=rGC1-_e7nq2oiuFzIx7KOlIVF7626YoxZAFUl6RWoK4,13142 +mypy/typeshed/stdlib/_json.pyi,sha256=yhbNNpPlgcNr7UbLWYlJLRT_GJAs6cec5nR1Ze_lvDo,1532 +mypy/typeshed/stdlib/_locale.pyi,sha256=uK5szB547hvi-ZQ9mIhaQXhDKD5-oO1hWvXAhd2g4fk,3287 +mypy/typeshed/stdlib/_lsprof.pyi,sha256=SnrMRZ7reYUpO4aspszvPl08o-zfyIZwixON_SP97bU,1323 +mypy/typeshed/stdlib/_lzma.pyi,sha256=vhTkKz-psYRTdZS5z31HZ71LtUPiUs5jRnxti7w23VA,2090 +mypy/typeshed/stdlib/_markupbase.pyi,sha256=jXh5gaXQuqr2KmmACztGc8xDjWm48itq1NkaH1eupMA,730 +mypy/typeshed/stdlib/_msi.pyi,sha256=jm1bAk_feToRYsWSLcQknCl2T_X2XwGtTwDzzl32VJE,3652 +mypy/typeshed/stdlib/_multibytecodec.pyi,sha256=48jNSq3IH_FejpnGX0_qMinWaLFOVjox0b28466ywrU,1890 +mypy/typeshed/stdlib/_operator.pyi,sha256=uC0DFWn11LMIxHzILUz_RGv2Vy8QIrAdDEvcPSIwsso,4867 +mypy/typeshed/stdlib/_osx_support.pyi,sha256=3cwesRBNoUgiThjIsAiPNKoODAGoaRg9je4-A-QpOU8,1900 +mypy/typeshed/stdlib/_pickle.pyi,sha256=EiGJBPWfyp1VlFuXDsLX2tNAwNKpZc5oAsgdQnJUO2k,3295 +mypy/typeshed/stdlib/_posixsubprocess.pyi,sha256=sszb90KfUWD1Mnk8eJti8-O_PPr95u4vGJh4XSoyEUQ,1836 +mypy/typeshed/stdlib/_py_abc.pyi,sha256=yKisRv9tmwucBsWB1ILLo35NcNrZWwIkKRL6Pu8GH5s,397 +mypy/typeshed/stdlib/_pydecimal.pyi,sha256=wssuLOIKIuBbxUlyTcxx8ech_vGbA1A9EH9hqyHkG-4,995 +mypy/typeshed/stdlib/_queue.pyi,sha256=KX-GSZ_-tpD0mLw1WqfXW5WGCXaR7C10YwaZuexOUho,634 +mypy/typeshed/stdlib/_random.pyi,sha256=uOdUKAg2zvcoUlAwSYR5_1dc8Md0hsvJ6h7HGyvAeAU,571 +mypy/typeshed/stdlib/_sitebuiltins.pyi,sha256=Hw17bWzQybJdwlnQceJ8BMHzSuTYiAn65Ro7sZu5MoI,538 +mypy/typeshed/stdlib/_socket.pyi,sha256=WpkBcqyvVW2PQeYNbO4_yrb6n0FrG7o913IcJqK51HA,27852 +mypy/typeshed/stdlib/_sqlite3.pyi,sha256=WAqfvEdYY1Rcn0oByDEF_xh83BxJErT1FrKX7kSLkAE,10622 +mypy/typeshed/stdlib/_ssl.pyi,sha256=X9JlIuSp4SIFxu-Za5YoV0izW_T20Bp3vL-PTQRN8Nw,10060 +mypy/typeshed/stdlib/_stat.pyi,sha256=hUl5rnhbcV4UkNu4MASQinuAccNDU0MiHrdG8Bh_92Q,3441 +mypy/typeshed/stdlib/_struct.pyi,sha256=HwlQXLJV_jIckbuof-hIacm5RQpGsNyz6kO7L07MjQE,1196 +mypy/typeshed/stdlib/_thread.pyi,sha256=CNTZi_IhZAAZsGpsRckoiwVDeqjs0Vx2XeZ7DVo-wNA,4918 +mypy/typeshed/stdlib/_threading_local.pyi,sha256=vnzj6ILLO3h6_TkLIXlqQZmKnfRG6wxBfvA2IP1iHFE,880 +mypy/typeshed/stdlib/_tkinter.pyi,sha256=gquIfnhC8Y8aBbhZXmX8LdmV2-iGwekOlXyEX8Bavgg,5563 +mypy/typeshed/stdlib/_tracemalloc.pyi,sha256=bPNYXniUfh6u6NCEkkmpNDClCx7JD1EYRdl-87cY8ps,500 +mypy/typeshed/stdlib/_typeshed/__init__.pyi,sha256=XUzwRD9roAEluSa4y1Hxky4_nKno7DZuhjZUxYvUe78,13255 +mypy/typeshed/stdlib/_typeshed/_type_checker_internals.pyi,sha256=aS3E_CYU0Q1szNLqKjyGfub4-0rSBXK-znvd9FVVU08,4157 +mypy/typeshed/stdlib/_typeshed/dbapi.pyi,sha256=DbFvZC7aeSFuw_hopshe-nz6OL_btPB06zIoJ8O-9tA,1636 +mypy/typeshed/stdlib/_typeshed/importlib.pyi,sha256=iSR1SQrIgH39dZwu1o0M0qk8ZsxRUkn4DtG2_K5tO4o,727 +mypy/typeshed/stdlib/_typeshed/wsgi.pyi,sha256=qNH7QQT9Y_i8GxSoS2LUViFSmM4mH3-K5hxh7sGT5K4,1637 +mypy/typeshed/stdlib/_typeshed/xml.pyi,sha256=W4c9PcHw737FUoezcPAkfRuoMB--7Up7uKlZ0ShNIG0,499 +mypy/typeshed/stdlib/_warnings.pyi,sha256=fkbpcOeB7WnJshHYcNvXGB86qDMkDDtM52o_00I6Bzw,1569 +mypy/typeshed/stdlib/_weakref.pyi,sha256=UVIE-iE6GyVOBeCKC0CXABnd7t-PvxC8ZtrTV6IaI8M,643 +mypy/typeshed/stdlib/_weakrefset.pyi,sha256=_n_kXqzC0K_qb4uEtA6WUsgmHD70uCp6YuTUtZxfK3c,2345 +mypy/typeshed/stdlib/_winapi.pyi,sha256=sIvrVvBOiL3MXrrTL7XJRuaYNtgAWcefv9CpCdKDnDE,11325 +mypy/typeshed/stdlib/_zstd.pyi,sha256=ojiC5JC6u70gcWkD4PptHHnDzACxytrI8KOCoRZkOrI,3647 +mypy/typeshed/stdlib/abc.pyi,sha256=oFvki8FBAHlhrRRDXkoEBcYJVQzb9nnTUdU7kSd9wPA,2128 +mypy/typeshed/stdlib/aifc.pyi,sha256=j7qx4qEI_YH90FPfekf7fqRBDs2HXALqfv--MuXo0DQ,2986 +mypy/typeshed/stdlib/annotationlib.pyi,sha256=kiftU52i0S5cIqUf_xPiyl6SgnewDWt_0c942HhGsus,5435 +mypy/typeshed/stdlib/antigravity.pyi,sha256=AT_uMXdsZR3AL8NfPU7aH05CAQaYpiM7yv2pBm7F78k,123 +mypy/typeshed/stdlib/argparse.pyi,sha256=OX5_CaCtqUv-T_iv5NS1n5F9SDsXC7SADrcdZ9DyGvI,32065 +mypy/typeshed/stdlib/array.pyi,sha256=pMXARXYsQVcW4QHPexydiIOMMYr2qQAIfe8vBCxueVE,4741 +mypy/typeshed/stdlib/ast.pyi,sha256=O7dOu-BpucY17aIKFEiO0gQPAcwikmCTmb4HMsoni-8,77826 +mypy/typeshed/stdlib/asynchat.pyi,sha256=jFTiOSXClcmhNvWXQc9JdRD44AT5o9Cq7xSC2fbVC2k,787 +mypy/typeshed/stdlib/asyncio/__init__.pyi,sha256=KEWLcIiMBDio8lNUZpHu3wW0G9JlMc-HDjpYh0kL3Cc,44530 +mypy/typeshed/stdlib/asyncio/base_events.pyi,sha256=lPYGjH7Cr7gCH3-8xtOeUGJk4HtxvfaTZiq9WDKUfxs,20014 +mypy/typeshed/stdlib/asyncio/base_futures.pyi,sha256=Jy9MidrOMwCSy-ZkrbjLoKNNPcuVK9ASOX_RBLDAS3M,609 +mypy/typeshed/stdlib/asyncio/base_subprocess.pyi,sha256=CjBQyvXQcYWcmmVfWAq3z6ZY3MhXntxMh_xgtJhwKUQ,2680 +mypy/typeshed/stdlib/asyncio/base_tasks.pyi,sha256=1qMENIsXTar5-dVXn33qy8hpWzOtFOs_I-kf5I92dsI,404 +mypy/typeshed/stdlib/asyncio/constants.pyi,sha256=-Eu35n-kT7I8W9YNfoY1lXmrZKATdDBojxBOwMiPw6g,556 +mypy/typeshed/stdlib/asyncio/coroutines.pyi,sha256=yuB4AGXiDVOfPrJOL3aQaxUS6N1br9WD9zrNo18JRLs,2296 +mypy/typeshed/stdlib/asyncio/events.pyi,sha256=luf-9au-gOYMsTZhM6jOPvhWFOjBk99CxFKF-j5XFOA,25851 +mypy/typeshed/stdlib/asyncio/exceptions.pyi,sha256=livPkrVx3OkV5T5BXlmuiI0rQx-aRLCPkrkEOQlalh8,1163 +mypy/typeshed/stdlib/asyncio/format_helpers.pyi,sha256=2woQu8erzdP7jbY3DZcfWyOwEUjkKQbYIvGW5wwu59w,1353 +mypy/typeshed/stdlib/asyncio/futures.pyi,sha256=mcUrrMBgux4VvCIkAYEoXkiU5tb8hBrJsW0DJFcT7DM,721 +mypy/typeshed/stdlib/asyncio/graph.pyi,sha256=EMHKHA_90qYP4OB6lFtG2CGBtNKkefB-wzh8y1AR_WQ,1194 +mypy/typeshed/stdlib/asyncio/locks.pyi,sha256=QDXBtjjRszT62G52f6icc_qzozDPlr_qrVT7spcnj5E,3514 +mypy/typeshed/stdlib/asyncio/log.pyi,sha256=Ql97njxNKmNn76c8-vomSAM7P-V14o-17SOIgG47V-U,39 +mypy/typeshed/stdlib/asyncio/mixins.pyi,sha256=YqQRvFzqgxJ0BvStd6F56A4DaIEM3KvD4fDELKCYhco,215 +mypy/typeshed/stdlib/asyncio/proactor_events.pyi,sha256=vCZEY77LmyjcjJt_UgGuMqFSCG9BQmOTX-2aqArcYP8,2598 +mypy/typeshed/stdlib/asyncio/protocols.pyi,sha256=MV0bmW9iU_c5qw0vOdG9V7fvMA-RoB0PjxTRP7wIN-4,1927 +mypy/typeshed/stdlib/asyncio/queues.pyi,sha256=QFNRsudiTUFQ9eEVKvgQ4LKCGz7UxRFs3KEvsWqpW0s,1918 +mypy/typeshed/stdlib/asyncio/runners.pyi,sha256=xU7eEwtwajK_ATU37Bb9Y4B2QnIpdTwGFtdVeV6BRKo,1369 +mypy/typeshed/stdlib/asyncio/selector_events.pyi,sha256=99QJmKi-74k50L6pmkcfO9B716oIJt4uIU8g2nG6pCQ,315 +mypy/typeshed/stdlib/asyncio/sslproto.pyi,sha256=buih3k56xpku7kwDWaioIPO7ibOkN_d6df26ONKGDgo,6489 +mypy/typeshed/stdlib/asyncio/staggered.pyi,sha256=vtlD5Xfya4AEfvkwJmIL9zXXgRlsI8MmGOFitDK9h7g,341 +mypy/typeshed/stdlib/asyncio/streams.pyi,sha256=fTNtnQq_6s6ljW7B4xl-U4uO-zDTNsuS5zQi-ZJ61iw,6007 +mypy/typeshed/stdlib/asyncio/subprocess.pyi,sha256=7hdI_BmLWsvLtzz_mrabrGCibuHNHfbUlRyF2BB7MiE,9295 +mypy/typeshed/stdlib/asyncio/taskgroups.pyi,sha256=EREr5whbcIyL0gdD3nKDMLibfWSgKA0-wRxgqXDH1yg,1180 +mypy/typeshed/stdlib/asyncio/tasks.pyi,sha256=FUqGLtG9zWcz_vTwh7R1R5stGFfUEeG_0bvUDIySiYQ,17102 +mypy/typeshed/stdlib/asyncio/threads.pyi,sha256=mPM3TlwpYs5UUus7d-pob5vcrsehEp6Lp2a8JxwBbqk,330 +mypy/typeshed/stdlib/asyncio/timeouts.pyi,sha256=Py2VPr85sJCC48s63cQvCQQCVsk-T-9znyjQDaIs-o8,717 +mypy/typeshed/stdlib/asyncio/tools.pyi,sha256=zjh-ntujiZ_cIJIAgiFbV4R_CT_cYiOKF-mlP31PmMw,1489 +mypy/typeshed/stdlib/asyncio/transports.pyi,sha256=pzLqWKPGJmQyrtCoCMaK4hKVft-I-FwEmvNJe4rP08k,2390 +mypy/typeshed/stdlib/asyncio/trsock.pyi,sha256=hj0UMyDehb7QyWVpeauw2DVc-2X4Y2hi8_dqbJTGHqI,6096 +mypy/typeshed/stdlib/asyncio/unix_events.pyi,sha256=lv_QLe9gpKp7zJWB78MJL9p1hAeMNG0SVtB5EloIRcY,11341 +mypy/typeshed/stdlib/asyncio/windows_events.pyi,sha256=fL5j2FWLD1tixaAFnXOuFoveXgU--PktycxLPhCWAME,5397 +mypy/typeshed/stdlib/asyncio/windows_utils.pyi,sha256=muNyuM_00Nog2RVk6k46NCWwk7C761dbCNOe-HZIpI8,1955 +mypy/typeshed/stdlib/asyncore.pyi,sha256=xRANk6i8v5AshNfEgtRCInPWVEwL1NP40G7aRRqaaWs,3670 +mypy/typeshed/stdlib/atexit.pyi,sha256=YPzhxFxGPqJ1k5G-Iab8lqfJNum1kQ_UsmI84I_5zEk,398 +mypy/typeshed/stdlib/audioop.pyi,sha256=9k9vD1-ArGE3bl0iSGPn6Oh4-XOftsyuN5MbFi1W8xw,2122 +mypy/typeshed/stdlib/base64.pyi,sha256=wxttkEgPJROdDrk55N1uYnzCiTiqWZo54fDHJLKXS2I,2264 +mypy/typeshed/stdlib/bdb.pyi,sha256=b7zH0KfmVkWBje1oo3cwHw6VX2pvfONj300oua42YDs,5866 +mypy/typeshed/stdlib/binascii.pyi,sha256=tq0U58aXORL5lgMkufQHEcwVzYl0BUfJsXX8IR0AJFk,1822 +mypy/typeshed/stdlib/binhex.pyi,sha256=vyLQVbmIET6tr9sHDh-vewAJvpfCcaRIw3h9hRGs4xE,1274 +mypy/typeshed/stdlib/bisect.pyi,sha256=sQn9UUS0Cw5XZMEGcEj8Ka5VKPVobL43Pex_SagjXg8,67 +mypy/typeshed/stdlib/builtins.pyi,sha256=EDpa-vfBx0CwvgsMOkUzSMFAIlci5CdBN9wAdQCSWvE,92537 +mypy/typeshed/stdlib/bz2.pyi,sha256=xOkSxmwk1lYrayAxjpWi5dY5-WiUmeyE04eBmX5vxkw,4008 +mypy/typeshed/stdlib/cProfile.pyi,sha256=gnkhMSDZOdLpA3atsotilOXWNzqok4SXcsnvAKQH31E,1313 +mypy/typeshed/stdlib/calendar.pyi,sha256=Lmm4ZTTvJ9h1fZC-ofuty9BCv6BkENC7doe7TvuvAC0,7388 +mypy/typeshed/stdlib/cgi.pyi,sha256=0roTC0MUUXUS4xO7mhzY13Oa0GvlaD6UZF6UheEs6Qc,3810 +mypy/typeshed/stdlib/cgitb.pyi,sha256=l7aliv3yXrfw0MM15pXDdgeNpbIK1N1e84OjSEt2TFU,1394 +mypy/typeshed/stdlib/chunk.pyi,sha256=691YVfWjwx20ngjDSBGS5Pjs7IrLViQinuTBg8ddmX4,614 +mypy/typeshed/stdlib/cmath.pyi,sha256=i3ZCUsvAaek0Sebb5qYwgBxTatHzyq3f_f8Rs2MuGz8,1271 +mypy/typeshed/stdlib/cmd.pyi,sha256=Mbl8vjsuh_FXsT64NErKMK1FdPYlOdbC-jVLg7tiLoc,1783 +mypy/typeshed/stdlib/code.pyi,sha256=UnBJGRyi3C4lNtXYsC4wkMyAcF_k8FuM9aFq3uooSMc,2140 +mypy/typeshed/stdlib/codecs.pyi,sha256=oN6h8bIgdQhkPiGIO4ihlBWO_pQCiQ-HOczXZ3iJ2Jo,14124 +mypy/typeshed/stdlib/codeop.pyi,sha256=DAkqqHHsxirkzPomzRmpsL2dVW5FyhLdj27YTZ2jc7o,799 +mypy/typeshed/stdlib/collections/__init__.pyi,sha256=PtOWMNd56e-GBFAAv9mZUdZ_3qaSQkQMlJJze2BSUK8,23698 +mypy/typeshed/stdlib/collections/abc.pyi,sha256=kBiZAN0VPf8qpkInbjqKZRRe0PXrZ7jxNmCGs4o5UOc,79 +mypy/typeshed/stdlib/colorsys.pyi,sha256=o4IcMv2OA9R-5pwBWvEpW_kOzFsjZWtWZARpwMHTkv8,696 +mypy/typeshed/stdlib/compileall.pyi,sha256=eqS3LbYNS0f_aKhX5g-NPgTaMuF1PIzwxT_TdRm_q7A,2757 +mypy/typeshed/stdlib/compression/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/compression/_common/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/compression/_common/_streams.pyi,sha256=GbmwTLxClok7eRsWhgTX9884eLyPByx_7Czu1XKD9NA,1339 +mypy/typeshed/stdlib/compression/bz2.pyi,sha256=_Tb-V0PrToWQt38Y_XXS0FmJfRWIc2X5jnGeEwH7gmE,18 +mypy/typeshed/stdlib/compression/gzip.pyi,sha256=HRqVg9hDWsKJ83Ur28v1-WB7sLQzxADzxJPP7FTumec,19 +mypy/typeshed/stdlib/compression/lzma.pyi,sha256=nNMih_mDY-jxO3tY65zkpT9nT6r293X7fxwXk1SAJjU,19 +mypy/typeshed/stdlib/compression/zlib.pyi,sha256=UQc5WSd45ZWjhEc1Za5pOtEsoBi-kbrrOidCv7aguBw,19 +mypy/typeshed/stdlib/compression/zstd/__init__.pyi,sha256=8A6ZP2_83c7gq4Z0vwrgxKFBSgxJzIcM6wESC2zcnJc,3102 +mypy/typeshed/stdlib/compression/zstd/_zstdfile.pyi,sha256=Au10oAAxPlrl6EpSfsmse7s_5Tu9X-o0Y5kaL79txw4,3781 +mypy/typeshed/stdlib/concurrent/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/concurrent/futures/__init__.pyi,sha256=Ma8QgM22nhptstCwPahwrLn3yfYIokNZGBfVjRGvVnc,1765 +mypy/typeshed/stdlib/concurrent/futures/_base.pyi,sha256=cpRZfzzvOtgWhtlBGkCiTcps9InisdJIU_qJVDyfh2k,4346 +mypy/typeshed/stdlib/concurrent/futures/interpreter.pyi,sha256=6BNtvdAt0z5BDVO7YZPDepgTn9gV85C0FULjDKj9oOw,3053 +mypy/typeshed/stdlib/concurrent/futures/process.pyi,sha256=cBSyTr_2IMdujvLEIaJCWTzCrtJdQwcxj3nyYpqC_fM,8168 +mypy/typeshed/stdlib/concurrent/futures/thread.pyi,sha256=emnAXhk2GmHQoKx40vC3ihLDacCRzAAZssbT1OtX7CU,4738 +mypy/typeshed/stdlib/concurrent/interpreters/__init__.pyi,sha256=5E7AB0WNoIBkid5LhXlys78KudhHuHKve3dvKGLxbGE,2441 +mypy/typeshed/stdlib/concurrent/interpreters/_crossinterp.pyi,sha256=gIXVsaVcPvE6gAOlmSVCDFzmZ4pdssdmKQZufKikzNM,1257 +mypy/typeshed/stdlib/concurrent/interpreters/_queues.pyi,sha256=vHO4wi4vRMqtMw7GNdHTZXYe3v9FptKu2nhhDoIPSKE,2603 +mypy/typeshed/stdlib/configparser.pyi,sha256=8B8lFsXku9FCcxEgcfTofDajhOJoLjCaT8eg5ckPYX0,19610 +mypy/typeshed/stdlib/contextlib.pyi,sha256=U8yYhkL1nc14ci7FNWO2b3LuCXhVUGr12isDXSfLJR8,9523 +mypy/typeshed/stdlib/contextvars.pyi,sha256=dqUvNxlpq9-0XgvzzKlCz4kWsA7qWEEIXIn73jxpaf0,178 +mypy/typeshed/stdlib/copy.pyi,sha256=e0uVQHOXyuOSyeCibpPIDOjBiZhrc--BU1oYKJyosyQ,856 +mypy/typeshed/stdlib/copyreg.pyi,sha256=59YPSECQJ5ppsEmYJxcvb1NOac6UTAu5CqP3SMd6VL4,983 +mypy/typeshed/stdlib/crypt.pyi,sha256=OA9MXjgoTY0jyd4cn6ZypXL1TqHtOAA_udosFL0OldI,792 +mypy/typeshed/stdlib/csv.pyi,sha256=QoR9Mr8E9wHipM3ehLPHPb3ZWNmJqKFov1sRBGOdRjY,4535 +mypy/typeshed/stdlib/ctypes/__init__.pyi,sha256=xJlPx4xZNRV3NY77ERcNffCmfrPtMbWROapHSx670jg,11584 +mypy/typeshed/stdlib/ctypes/_endian.pyi,sha256=raioVluH0dlcLoayGs1jELpcBkPKmO7Wbwr2OcpZAUE,461 +mypy/typeshed/stdlib/ctypes/macholib/__init__.pyi,sha256=G8DxraRu5jEG-ve06msp9XoHqQwtnFEjVtCSLe7vaTw,50 +mypy/typeshed/stdlib/ctypes/macholib/dyld.pyi,sha256=K0ZDg1MB-_Y_n49CDgrEJytsEVOWgXgHN1THza5UQ9k,467 +mypy/typeshed/stdlib/ctypes/macholib/dylib.pyi,sha256=HVkz1Oyol9QCJcjdnwtkgW5iq-yFJwiQ-jZCAGzPjTU,326 +mypy/typeshed/stdlib/ctypes/macholib/framework.pyi,sha256=bWwjubZ_zKOiGqAlqByzonpxD4AJQemGiFIfS4emGm8,342 +mypy/typeshed/stdlib/ctypes/util.pyi,sha256=4dyWcDlzw6yUtBFC1j17JsnSzhJV8q94ZJfvo-07kng,222 +mypy/typeshed/stdlib/ctypes/wintypes.pyi,sha256=s59HOt-zLzzEeXbTeCSsB-wXiEBL-wxiy5Yff43agtc,6967 +mypy/typeshed/stdlib/curses/__init__.pyi,sha256=YM2Eo7wYTP_QgiElaBzMTWsWJFHsaHFznnp-9o8errs,1284 +mypy/typeshed/stdlib/curses/ascii.pyi,sha256=7xKdmHqbNJu7zXzLc36MKVuEsOoWmqDAFWrdDwVT6Zc,1465 +mypy/typeshed/stdlib/curses/has_key.pyi,sha256=1EoxgUM4xlB7ggY4Ru4eqnSa0Wn2mP7ylUE7p9V7Yc0,40 +mypy/typeshed/stdlib/curses/panel.pyi,sha256=tiz6sEiozlgKp3eC7goXP0irXp9PwWHSfWiMahWMRRs,28 +mypy/typeshed/stdlib/curses/textpad.pyi,sha256=2UsLwIhJh5iwWSN-1SJlzwvn--sJqh8zJYQ8pYCP8f8,422 +mypy/typeshed/stdlib/dataclasses.pyi,sha256=Cl6Lvi5YAzPZ0rcZjnDkOMAOHtHJdJeYRIjBF92HRsw,14451 +mypy/typeshed/stdlib/datetime.pyi,sha256=CiWGFuYlJcGsCDxyBUhYGbRDesevvX0V5Ndi3wol_cM,12256 +mypy/typeshed/stdlib/dbm/__init__.pyi,sha256=KZb9l0guolhsjOyfqZk1_r0-vdN8nt4a7ach5lOXe20,2143 +mypy/typeshed/stdlib/dbm/dumb.pyi,sha256=dsAfzLKJnXAW6xJMnw-47D-xdaiwuXwaQC_-c1If2ZE,1467 +mypy/typeshed/stdlib/dbm/gnu.pyi,sha256=QR25FB7f-Rxi5RzWWki9npyEF1JKu5A5RjOWDmR7T2U,20 +mypy/typeshed/stdlib/dbm/ndbm.pyi,sha256=dc0BCDY0QiGbHA0lcqZL4NqOfCES4htigqb4uM5UaSo,19 +mypy/typeshed/stdlib/dbm/sqlite3.pyi,sha256=v1uUMPBFIH7G34tYJ9HrcoYAt4E1zq8EWYGbVEbIQsQ,1228 +mypy/typeshed/stdlib/decimal.pyi,sha256=TVKrr33muv01oCyW1j1ZcMtkRMDYgmY03R8IUwTqs1Q,14077 +mypy/typeshed/stdlib/difflib.pyi,sha256=pv2JXhDbVzQF1UdfSrblMHZvHFMPcldu-FbRwtdJuJw,4512 +mypy/typeshed/stdlib/dis.pyi,sha256=GYfqrpaWw0vlhlhdY37xdw7mTqY_9h5uGa-qeRU8YVo,9643 +mypy/typeshed/stdlib/distutils/__init__.pyi,sha256=o-D0LAC_8LmRTahqNjjRUXycRSMyJ537NHeFaduZKVc,351 +mypy/typeshed/stdlib/distutils/_msvccompiler.pyi,sha256=HOTrNPKFYHGnaIggO2_-F2BTCF878cRQf-ge7Ng425k,437 +mypy/typeshed/stdlib/distutils/archive_util.pyi,sha256=E6T3Q7SSWW8UvxEkJlXbW_wr4UaY_ddLEb8MWFN0_KA,1040 +mypy/typeshed/stdlib/distutils/bcppcompiler.pyi,sha256=fge2cMbG4jp--o0I2zNcwykh24tJWZtk6leQgAH2NJw,78 +mypy/typeshed/stdlib/distutils/ccompiler.pyi,sha256=BCSgVAvfMJVh8EyX_HqNcggwpF_NEcTTnVournS-UUk,7358 +mypy/typeshed/stdlib/distutils/cmd.pyi,sha256=Dm_n741c6n7C-8bk3RBLOjW5hPPOy4FvRYpxuATINo4,11116 +mypy/typeshed/stdlib/distutils/command/__init__.pyi,sha256=AtZpmh1mhLqsWO11mGBB-CrtRWprrdDs6ylbXlXeTeQ,711 +mypy/typeshed/stdlib/distutils/command/bdist.pyi,sha256=YLLeluU6gqN_RNDL463SiE3aNQaNKDscuCC_Zm0bj3I,875 +mypy/typeshed/stdlib/distutils/command/bdist_dumb.pyi,sha256=tIuYyjsOwPpl1hSJK24tcjom5dTJ98id0ckXH4wN6ME,614 +mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi,sha256=GTn4n9D6tLwyQyuPtNH-hk1JL37l6Kkr3OHA3TMVv8o,1735 +mypy/typeshed/stdlib/distutils/command/bdist_packager.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/distutils/command/bdist_rpm.pyi,sha256=PeCQM0O6QWBoWD9se0GSzoLPwBf16HK5yANxdJ37qBs,1457 +mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi,sha256=wON2ucrSRQI8V1q2_wi8U4TW-GQpjUe_XRPvX4Z1lKw,646 +mypy/typeshed/stdlib/distutils/command/build.pyi,sha256=ufnjRjuH62Pb0e-cBDyvVEw67PFV4cOYv1_gP4MIkVE,1081 +mypy/typeshed/stdlib/distutils/command/build_clib.pyi,sha256=qR3q8TLdF63c0p33peUo284iEiLH9-2VLUJ2DleCpJA,918 +mypy/typeshed/stdlib/distutils/command/build_ext.pyi,sha256=a8kGtFnC6UtXGU7XOG80dfSd9G5zeD1fAQulKS7f1aI,1648 +mypy/typeshed/stdlib/distutils/command/build_py.pyi,sha256=omRTnXsWj7TFKmgC9IwhqGmC5Buh7ER9e3WdOB9l54A,1659 +mypy/typeshed/stdlib/distutils/command/build_scripts.pyi,sha256=Fv03MGtaBwwfdI66zTqJNPeD2BMAF98sdJnDRzBhLnM,703 +mypy/typeshed/stdlib/distutils/command/check.pyi,sha256=b_7HEEEs0Zr7lvIaDDg5yWeQBgoXInV-flLTTeg2KGw,1236 +mypy/typeshed/stdlib/distutils/command/clean.pyi,sha256=wagR3bxqh6UAXnvhsDf7qYQY_1jMTEP30QXuq6mJIoc,513 +mypy/typeshed/stdlib/distutils/command/config.pyi,sha256=d2h1OIMfkadYMGT96DPQEtL39QpLk-rCRjQRAGOGBFI,2781 +mypy/typeshed/stdlib/distutils/command/install.pyi,sha256=rFV8ukandp2i7iE23smdT8xL6jidpw3cY-HTSpzDMXo,2290 +mypy/typeshed/stdlib/distutils/command/install_data.pyi,sha256=09diiWpTZv5g5May_za9UEKw_m2fvwVbevMin63lxBs,558 +mypy/typeshed/stdlib/distutils/command/install_egg_info.pyi,sha256=pXV3L3dEjK0NnGiO7tyXgxIMzx5nwpu5v9OEF4jFyzk,532 +mypy/typeshed/stdlib/distutils/command/install_headers.pyi,sha256=2ZePm_2is9uIck2c7iIwLwJet7Ef6JopFVuHF6D6aGE,488 +mypy/typeshed/stdlib/distutils/command/install_lib.pyi,sha256=8hNzKDsNWLb_T9O0Kc75M4WuXpanTeJB-_CrFHebDnU,765 +mypy/typeshed/stdlib/distutils/command/install_scripts.pyi,sha256=lpExgrCH1wnyLS2S-bZwR12gqQTcHEffqWeezL51qu0,548 +mypy/typeshed/stdlib/distutils/command/register.pyi,sha256=P7m44QOal6qsDtw66FfA_amKyxLouynR7s5XtiBP6wE,697 +mypy/typeshed/stdlib/distutils/command/sdist.pyi,sha256=AxkvvnWR2K6xYmTKXqiDM7DUPaneriPiSgtJiYMG4O0,1517 +mypy/typeshed/stdlib/distutils/command/upload.pyi,sha256=re0EVwgTn6jWVMoOWTfsZStLXozX66LSiXokPEHM_74,511 +mypy/typeshed/stdlib/distutils/config.pyi,sha256=Bmpm5-txSuUYd92XnDnfpAevSl9bk5YfXO-I_wXC2QI,497 +mypy/typeshed/stdlib/distutils/core.pyi,sha256=oc3E79ctJ90TJsLmy88jM5XqkqmVyXNOxXYuDMOYy-E,1973 +mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi,sha256=A22lj-kl_06GMoQcl-M7yhWbmjzsTXml6KDjB3in5gM,586 +mypy/typeshed/stdlib/distutils/debug.pyi,sha256=xsHjfIMduqS9E5C28fFERqXr8Ss8y1GGO1rR9VR8vLs,51 +mypy/typeshed/stdlib/distutils/dep_util.pyi,sha256=G_1dehLB4Nq9vEmNKFqTasQtG-A8Ybpqxs1M2-GZwjI,647 +mypy/typeshed/stdlib/distutils/dir_util.pyi,sha256=pGJrASr0CVE9JqaQMcOhV9rkgsXUCI4qoFpyvF3UB18,875 +mypy/typeshed/stdlib/distutils/dist.pyi,sha256=_NHkVAtGXaru8FyZX8cmB0wy1WUN0uM1fpJdiPCKUBo,15218 +mypy/typeshed/stdlib/distutils/errors.pyi,sha256=l1W_FgoP9L-D-hEPFA2BzZuybjN0lV4WBXl0VJ-k7J8,852 +mypy/typeshed/stdlib/distutils/extension.pyi,sha256=KosWjLSvvyfdQTtOCu3fibblHyiFIXm8iHHWrWk916E,1236 +mypy/typeshed/stdlib/distutils/fancy_getopt.pyi,sha256=WmGW8EhQqL1yd6jPgBcCc9JFo9PMqIS8dvslu2IrWpE,1673 +mypy/typeshed/stdlib/distutils/file_util.pyi,sha256=zikh8dhZ0i8b2Pmw3-OtqqpS-w3gAF5GwN9GXEy1EbM,1323 +mypy/typeshed/stdlib/distutils/filelist.pyi,sha256=RiXyurPBQ_d4U0siqqxHk22qsUqAP2EZbX5LWA40lm0,2292 +mypy/typeshed/stdlib/distutils/log.pyi,sha256=8Fv8JYP-w6djwB7ad2fkWaABI-1xk1loqdEJOZiS_go,940 +mypy/typeshed/stdlib/distutils/msvccompiler.pyi,sha256=qQLr26msfhjz-omJutWcRHik3shLh1CIt7CDI3jBd3I,78 +mypy/typeshed/stdlib/distutils/spawn.pyi,sha256=o36CbAwOl3mVBnlyasqqYIBrYT-3v7fjYjyAyL4dFzk,317 +mypy/typeshed/stdlib/distutils/sysconfig.pyi,sha256=AIHwWAmZHKRcRC4ce6Ti9NWJJKu7P2x6b3xTjjOwPic,1210 +mypy/typeshed/stdlib/distutils/text_file.pyi,sha256=t-pGs6Li5ySUocSO0CEUoRYDUl2Uk-RhswWeECigR_Y,787 +mypy/typeshed/stdlib/distutils/unixccompiler.pyi,sha256=R3VKldSfFPIPPIhygeq0KEphtTp0gxUzLoOHd0QoWW8,79 +mypy/typeshed/stdlib/distutils/util.pyi,sha256=HJpxYeb-4XG_U5o4-GOUnAtUR776jsgUbs3a3Din2ZU,1736 +mypy/typeshed/stdlib/distutils/version.pyi,sha256=yIGp2uvie77qTBWlT2ffBGNXIKJmPfJLPzaE2zua1fc,1308 +mypy/typeshed/stdlib/doctest.pyi,sha256=ItHbQuL_dcVa4ZYZI9Iy96yv_g94X4qveq1GWGX5k0U,7932 +mypy/typeshed/stdlib/email/__init__.pyi,sha256=36My0D09zCOfT26GrMGtXQcX8V4Xp2o5KIuT4ZLRUwY,2769 +mypy/typeshed/stdlib/email/_header_value_parser.pyi,sha256=Qv50YMiDQCU_-oZv-n5M9iAiZ2ovhlgcMCI3Tn9pzQk,11936 +mypy/typeshed/stdlib/email/_policybase.pyi,sha256=swUeIOQDH3lf9NETZ3xa_21iW79bWP3WyDslKBuV5u8,3331 +mypy/typeshed/stdlib/email/base64mime.pyi,sha256=g98A7lvsErIaif8dVjP_LyoVFSXd6lNuJ_pOiTHudqs,559 +mypy/typeshed/stdlib/email/charset.pyi,sha256=K2kZQPiVXjmV9O1dRcRkIG-YkD6zRzimCJ6iy88z2KA,1713 +mypy/typeshed/stdlib/email/contentmanager.pyi,sha256=UwmeUcRuRTCDHXVEDzDASBN4lEtVG1A9BonNaMmv0b8,480 +mypy/typeshed/stdlib/email/encoders.pyi,sha256=dJc5t6R6TtZGffzRC_ji2O2KNj9n_fJHzkAnKWTbfcQ,293 +mypy/typeshed/stdlib/email/errors.pyi,sha256=YytDsUjPrDoI4fpZktf-mhKVCosZOedsS6pQfAFhDg4,1627 +mypy/typeshed/stdlib/email/feedparser.pyi,sha256=tCckWKeyn3VByGY8oWuHWJryiEMgrMI-ehJg0TaQeOI,978 +mypy/typeshed/stdlib/email/generator.pyi,sha256=rPe8JphvX-0-PtPiwWWPabik9A5DdyleteBCXSJi57g,2373 +mypy/typeshed/stdlib/email/header.pyi,sha256=qSEdPSMNtA22vkNbZ82enBddW0sZ6sq7GxBASj1-i6U,1332 +mypy/typeshed/stdlib/email/headerregistry.pyi,sha256=02TipcviVu8S0hwdnIYs8Bl3Xi80hOscPiU-_LmfIqU,6664 +mypy/typeshed/stdlib/email/iterators.pyi,sha256=Vou7LSsfU52ckW-lKx4i49KGi0rd54LctjXHimRblrc,648 +mypy/typeshed/stdlib/email/message.pyi,sha256=S0Rj-3C9_AylKvSJEAtTHPLQDEQmpwxN2AoHFpO0vBw,9210 +mypy/typeshed/stdlib/email/mime/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/email/mime/application.pyi,sha256=PkqCQXJMdIRSXBV14unvCnpQTuNcEQO23W8CJ8hhtAc,498 +mypy/typeshed/stdlib/email/mime/audio.pyi,sha256=hsnNC5xAaI2pvS7DYMr58Y46U-hv4MjAKUF0wXWnDfs,482 +mypy/typeshed/stdlib/email/mime/base.pyi,sha256=zMUOzyzRFw00inwMFYk-GG8ap-SM9dtp1GRTxjfAiWU,271 +mypy/typeshed/stdlib/email/mime/image.pyi,sha256=E3zejA7f_g0NY09tvTj8y1jzGQ0IPrhsKDAofd6ZObA,482 +mypy/typeshed/stdlib/email/mime/message.pyi,sha256=bsaprH4pzYNkTvgmycx-y5dLBHIk9jCgnnyiBtVZ0VA,313 +mypy/typeshed/stdlib/email/mime/multipart.pyi,sha256=F2NodkSKHx_3Vzad43ESWUF1LVYzGjpJGszm8NGsb-Q,504 +mypy/typeshed/stdlib/email/mime/nonmultipart.pyi,sha256=YW7_zxIBEwStGGAuw7nQEYYS7Yz_TMuTW4-ZIFpIpM4,108 +mypy/typeshed/stdlib/email/mime/text.pyi,sha256=wgYFMCXnpeiM7zp8gpxkLRLCh-7wrGuZUNvRqSHzbG8,298 +mypy/typeshed/stdlib/email/parser.pyi,sha256=Nf0GvqrZFcpD2sQzUTByKAtvevJVUdnAYSXs7-k-Qs0,1975 +mypy/typeshed/stdlib/email/policy.pyi,sha256=HIZ7t_nZivqGEuZouZg9OwehEOggKg6-it_wsrKda5s,2813 +mypy/typeshed/stdlib/email/quoprimime.pyi,sha256=bSFnFlSadE1pXHmqDzvAEnWwNyeWSLm-i21Kczwrt6A,835 +mypy/typeshed/stdlib/email/utils.pyi,sha256=ehSBF_IbXENAGCL-0WCokbKNI3Qap3q5j-sOF4MYn8s,2735 +mypy/typeshed/stdlib/encodings/__init__.pyi,sha256=LUuWxhvArWso6nBkQPJLAL_rbz3Bzd8-ydF4FWn_MJc,469 +mypy/typeshed/stdlib/encodings/aliases.pyi,sha256=NBl4ko1LeUclvHYI0p7ALF_qM5n2aJnXH5HXapTR95E,24 +mypy/typeshed/stdlib/encodings/ascii.pyi,sha256=JXS9tp2DG26Xrrhjf5-3JwR_6EK_qcZuK8WLcw_GCA8,1346 +mypy/typeshed/stdlib/encodings/base64_codec.pyi,sha256=BPqaBf4QojblNqNABf4bHmapZ9UJE0jlVB2C3depZ9I,1105 +mypy/typeshed/stdlib/encodings/big5.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/big5hkscs.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/bz2_codec.pyi,sha256=tpV7-M_UeQQDj6g3W2yDQz-rKjp2Ji_7A30aCc611t8,1099 +mypy/typeshed/stdlib/encodings/charmap.pyi,sha256=MrYgD5r621vymhH0pMTJOyoD9MBtf3GDmbnAG_7bhcA,1652 +mypy/typeshed/stdlib/encodings/cp037.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1006.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1026.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1125.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp1140.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1250.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1251.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1252.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1253.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1254.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1255.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1256.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1257.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp1258.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp273.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp424.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp437.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp500.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp720.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp737.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp775.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp850.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp852.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp855.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp856.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp857.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp858.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp860.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp861.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp862.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp863.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp864.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp865.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp866.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp869.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/cp874.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp875.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/cp932.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/cp949.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/cp950.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/euc_jis_2004.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/euc_jisx0213.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/euc_jp.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/euc_kr.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/gb18030.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/gb2312.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/gbk.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/hex_codec.pyi,sha256=6bEBV4unOUo8eopKjspIfrarAnyMTCccp71cZNX9usQ,1099 +mypy/typeshed/stdlib/encodings/hp_roman8.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/hz.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/idna.pyi,sha256=B9b4Xh5OeA3WSMD62Q-0i8N4OOBVjPsoAth6Zwjqpik,924 +mypy/typeshed/stdlib/encodings/iso2022_jp.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso2022_jp_1.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso2022_jp_2.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso2022_jp_2004.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso2022_jp_3.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso2022_jp_ext.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso2022_kr.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/iso8859_1.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_10.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_11.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_13.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_14.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_15.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_16.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_2.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_3.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_4.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_5.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_6.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_7.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_8.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/iso8859_9.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/johab.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/koi8_r.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/koi8_t.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/koi8_u.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/kz1048.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/latin_1.pyi,sha256=dGwLgYjYgcDVLAqJXzaOltDLDNgQNC-AkFvwfzgT2ls,1354 +mypy/typeshed/stdlib/encodings/mac_arabic.pyi,sha256=IuKRANFFOqIZW4rgRt7Uqnd2HxyegtYKuYOwVbRR9gY,733 +mypy/typeshed/stdlib/encodings/mac_croatian.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_cyrillic.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_farsi.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_greek.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_iceland.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_latin2.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_roman.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_romanian.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mac_turkish.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/mbcs.pyi,sha256=UiUp0WbMdEMZHIt8SnKjHg69ytiUNItKVAqF_DQMBGc,1091 +mypy/typeshed/stdlib/encodings/oem.pyi,sha256=N9CqMmApOhl7nSiLzjurOoNE2RLhmZNdP6HknNp_fm0,1087 +mypy/typeshed/stdlib/encodings/palmos.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/ptcp154.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/punycode.pyi,sha256=UkVSNYEFRPDcRIKMbI31RzSlUoE7zrV0CWXsXBHlne8,1593 +mypy/typeshed/stdlib/encodings/quopri_codec.pyi,sha256=vBA4qnjYHR5HgJtXe4fCziiPxHYkivKgS0kV-nppjX8,1105 +mypy/typeshed/stdlib/encodings/raw_unicode_escape.pyi,sha256=0fWozv5f1XYye3i6HZPnrrMUGqyqxJpDxq3KxJcsug0,1000 +mypy/typeshed/stdlib/encodings/rot_13.pyi,sha256=dU8Pz0tT7qe9xXipOvYcO6mcdPPXWvIIUJ7nsJVxkjQ,889 +mypy/typeshed/stdlib/encodings/shift_jis.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/shift_jis_2004.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/shift_jisx0213.pyi,sha256=lWSIa6c1POZybwhXwNOeTmw5ltJiFTiewyGFqrBU3-U,920 +mypy/typeshed/stdlib/encodings/tis_620.pyi,sha256=CGY8VLG2AMheowXmED0BuzUK5ByfDNUrJko2UJdFUb4,730 +mypy/typeshed/stdlib/encodings/undefined.pyi,sha256=kCUblX0Okd8hRsoTvKG6UvdQUbnLAbCr7z4MrfuhpU8,755 +mypy/typeshed/stdlib/encodings/unicode_escape.pyi,sha256=w981JOse_RTIukRgKiOqbCcktW5eaBUdyLNMoAIeWzA,992 +mypy/typeshed/stdlib/encodings/utf_16.pyi,sha256=SRka2t2ru2-Psn1H98shycpPpmxZhFn69wEFTXSuDck,761 +mypy/typeshed/stdlib/encodings/utf_16_be.pyi,sha256=k-ApL-tptz_Qby4BnAVsmUxfgzA2SDVcZBlgNdIyfes,1004 +mypy/typeshed/stdlib/encodings/utf_16_le.pyi,sha256=ShA30MIHkKSurNzu8CE0d1PxGrXqcO_JIpEshtIOALg,1004 +mypy/typeshed/stdlib/encodings/utf_32.pyi,sha256=PfqJtFEQglw65eSDJnvYofUWiQG-QZ9Z8RY3QHYr0yg,761 +mypy/typeshed/stdlib/encodings/utf_32_be.pyi,sha256=RF2NNlVWIYAzZ4kd97J5GaSYFm0uwiZeWMDdaWbXl0U,1004 +mypy/typeshed/stdlib/encodings/utf_32_le.pyi,sha256=wDx-GPbmCG3z_8VLu4Bm4VIcgBXXcxrmkyDt9-QW_0Y,1004 +mypy/typeshed/stdlib/encodings/utf_7.pyi,sha256=P-9LUl4xTXFeZofgd3n7OeR7euVOs5nM-zmMD_MJhf0,988 +mypy/typeshed/stdlib/encodings/utf_8.pyi,sha256=uENG0zdTfNG6D-Hwpjmtpsn937wGk9LcaXB05dqgKY4,988 +mypy/typeshed/stdlib/encodings/utf_8_sig.pyi,sha256=CAvKrplGLrXKmpdEW4-PjihiA5UICRtcD8YaJX5dhiM,1059 +mypy/typeshed/stdlib/encodings/uu_codec.pyi,sha256=Se3B9axmM6vAb3QORy3eL3ZXR9yrW96-3PhugTE0Ww0,1148 +mypy/typeshed/stdlib/encodings/zlib_codec.pyi,sha256=qVKqhqMfl5_AOj2gr6lfLi_KwOA3kotTpygyaGL6BZk,1101 +mypy/typeshed/stdlib/ensurepip/__init__.pyi,sha256=8tmoDM1Cy7ojGznNaYzp_-zzoTYP_FunKhPvKpsVU4I,264 +mypy/typeshed/stdlib/enum.pyi,sha256=CXcJRqgYi7a49ih39CfOjwrXhVbTf3X2ixiIpJ7sRRM,13512 +mypy/typeshed/stdlib/errno.pyi,sha256=9mBovztCB7JiBa_Vnqd8IcLEIY1SGQkoiXb0Ua6of_E,5522 +mypy/typeshed/stdlib/faulthandler.pyi,sha256=Z9827Vz1J1H-7Oe8RGn0n5-2GkScs32mV0J1pPZgeGc,957 +mypy/typeshed/stdlib/fcntl.pyi,sha256=_qHO3krIV030nllkmIUy9DZwPtus6ETGJ3XGXl02FUQ,5495 +mypy/typeshed/stdlib/filecmp.pyi,sha256=_8kalXH1bxz2bhbKjN37Axjbd-4VZ34Id3uW80IwHIE,2237 +mypy/typeshed/stdlib/fileinput.pyi,sha256=TeQEIAgfs7c22mjaZhDO16LSn1xcg4IxE22TC_tzSTQ,7378 +mypy/typeshed/stdlib/fnmatch.pyi,sha256=a4FS6DccPaFufmc4RaWyx6_YUwJn5EY1Y1dAWiDeN6Q,525 +mypy/typeshed/stdlib/formatter.pyi,sha256=PoCFa7jJ7efz-ZO-IJU73MK_O9t7mjbYwjxBaSppqpU,3711 +mypy/typeshed/stdlib/fractions.pyi,sha256=Ittk8E5Yt-PTbrhkgsoyQkJ9x2JvUo2E0qE7ja0UwsU,5879 +mypy/typeshed/stdlib/ftplib.pyi,sha256=8X5Bz9PymgF7APau-y2WV9wusJSurerkOvtqScuhs8c,6471 +mypy/typeshed/stdlib/functools.pyi,sha256=Ff9DT41crRL6n1DWN7o8Xr-HxVDeCJ4i4B4Y4RL9CSQ,9984 +mypy/typeshed/stdlib/gc.pyi,sha256=2oqPKzdagg0sTQiNweKlg_GblP1nKgln5SUxOyufW8Q,1153 +mypy/typeshed/stdlib/genericpath.pyi,sha256=z8Eq4qv3HvhYTk9WA69SzQ6n8-7eq59Kd0ROXfLkpHk,2384 +mypy/typeshed/stdlib/getopt.pyi,sha256=Gn-k7sstt-bKMRdLzdBORwZuWF12zbz53R4Lyp26NUk,909 +mypy/typeshed/stdlib/getpass.pyi,sha256=ftJHHXPw2nli4yEyEIaavmo2LKxaeuKthi4n0g1qS24,401 +mypy/typeshed/stdlib/gettext.pyi,sha256=z0oFjNUalU5YRjnAnPETfONgWcuMdgiB5eoBy2sk3_s,7574 +mypy/typeshed/stdlib/glob.pyi,sha256=nhNUCpB0XuONiJ7sX9hsRVPbcwo033QG5Dj7w3XR7bg,2201 +mypy/typeshed/stdlib/graphlib.pyi,sha256=3loMDkMk4j-vtp5dGRaOa_RNqyM3FUZCJhTJIyrplzE,917 +mypy/typeshed/stdlib/grp.pyi,sha256=2hJQL4kCKhQ-QBAa87oM83ldvW4WaOkWTlySGzB9VGg,702 +mypy/typeshed/stdlib/gzip.pyi,sha256=nRks2mwqCa2sb8Rw-hSzv4GGpd-z3LfLtGu-qyfamXk,5567 +mypy/typeshed/stdlib/hashlib.pyi,sha256=pJUJEmUpvp9MijK7Dlb4w5AVkzHv0dMR86x7s-vaaHM,2208 +mypy/typeshed/stdlib/heapq.pyi,sha256=pk3bixMpPG0XvHwoJ6Hb7TcF3ZNVawMts7TlV3AHIRo,949 +mypy/typeshed/stdlib/hmac.pyi,sha256=40bupGra_ng8jZ3ACrLf6chzc-vdo9YVWDBPddosgy0,1258 +mypy/typeshed/stdlib/html/__init__.pyi,sha256=TKNt2K9D-oAvCTmt9_EtgRndcpb--8rawxYFMPHTSC0,157 +mypy/typeshed/stdlib/html/entities.pyi,sha256=RC8NoJ_AMu5IUWVuSXkGvKD5O-6ZNShjHOL0NQgXNpo,236 +mypy/typeshed/stdlib/html/parser.pyi,sha256=WuDpXERSFK3XaJaDI4cIxkFl9Iudvifpm-JpBL2XbyU,2098 +mypy/typeshed/stdlib/http/__init__.pyi,sha256=QP08bjXK5harBEh319rMNwQmB3WrtFYMvSNPGs3CH0w,3030 +mypy/typeshed/stdlib/http/client.pyi,sha256=-t3te4k6kfKeucd8_snpxM3Op6n8O7R73r6ckd4NP6o,9790 +mypy/typeshed/stdlib/http/cookiejar.pyi,sha256=K1OKZM_u4Tf-NlITqc6DkMzi63EgJeLyyIrQ6ZEQI1w,6667 +mypy/typeshed/stdlib/http/cookies.pyi,sha256=rDnxuhD_248ig-SdmenZphkGueDCnQbwbKp4eF7yqKs,2298 +mypy/typeshed/stdlib/http/server.pyi,sha256=8aCsv0TBG8dfl_9vqf2BdcKDiVYuU2j9d_DRGhLNJ2A,5726 +mypy/typeshed/stdlib/imaplib.pyi,sha256=JV-fusQAQBWqKsyvu4ZaoQzQiUh4jT6GDEEtWy8jT-8,8949 +mypy/typeshed/stdlib/imghdr.pyi,sha256=syq6jKngvEHgcopZE0xDIZRok2gbjdCW4mT6DBPDNtI,541 +mypy/typeshed/stdlib/imp.pyi,sha256=EZyon6q6zcsDFy2qM0f5RQqyIGAnQ598mt85lWiTo54,2484 +mypy/typeshed/stdlib/importlib/__init__.pyi,sha256=s5reSVWSp1cZl-U2HSPsg5QXbM1zpY1IcHnnQsrWV5U,724 +mypy/typeshed/stdlib/importlib/_abc.pyi,sha256=CZnLlR8x_ckCsQ4W9qGS-iIv1CiYoOYma6n8aCVTBTM,858 +mypy/typeshed/stdlib/importlib/_bootstrap.pyi,sha256=qdoz8OV6L4bWxFlroAznM-KSVf0bYNCQeYTz-Uk1cUU,129 +mypy/typeshed/stdlib/importlib/_bootstrap_external.pyi,sha256=pfdzy0vceWdL5QBZyMak6yLi9ULR0xR3PgGQbO6M2BI,117 +mypy/typeshed/stdlib/importlib/abc.pyi,sha256=0THKS1Fkt8M1WFd-y-xCJrlK8Hjs_88wInME7eEn-TU,8119 +mypy/typeshed/stdlib/importlib/machinery.pyi,sha256=UsDZB7rAhKUwQw3ZRWHisxYl9VT6sI764eEIVCtzQ_Q,1503 +mypy/typeshed/stdlib/importlib/metadata/__init__.pyi,sha256=rRYAJosHlfIW29h3hvm3NiDXxRi-QwGJES2chNlGbns,10488 +mypy/typeshed/stdlib/importlib/metadata/_meta.pyi,sha256=dtApBQ2RiMU-m2Y1B_7yLfMRlLHEXVD1OACZdPKwGVw,2552 +mypy/typeshed/stdlib/importlib/metadata/diagnose.pyi,sha256=sf4qsMlUFHtdxkUxCQbo-hL0app08cWTq9c-z0HaHy4,59 +mypy/typeshed/stdlib/importlib/readers.pyi,sha256=7L8VwCKFo2l-XObbzjFIMRxy0WJEH3Zl2g6hB4rPskI,2737 +mypy/typeshed/stdlib/importlib/resources/__init__.pyi,sha256=juDRPr265zenEXFKtpTHr5RN2IrG7-Dvki77giGYjUE,2771 +mypy/typeshed/stdlib/importlib/resources/_common.pyi,sha256=5NPtrEBMicBxF4ozU69dVj7AtARLyl8Z1zsWSmkBlzU,1600 +mypy/typeshed/stdlib/importlib/resources/_functional.pyi,sha256=2WKLITIOtf0yZkrvsr9BcFB-Rn458TqFhmH7a_tUqzk,1597 +mypy/typeshed/stdlib/importlib/resources/abc.pyi,sha256=KYNT7Qe9NM9ym6H5xRUmiq9Xmr3spvOXZVaEiVQUZNk,2325 +mypy/typeshed/stdlib/importlib/resources/readers.pyi,sha256=L9ISdjyiVx8ppnP2bTSjbdd_dzvr1lY3_aRn6ZfitsM,398 +mypy/typeshed/stdlib/importlib/resources/simple.pyi,sha256=jXtnKAAwsnhFm1AsPBgbkXwCwMdhMEG0-Jh5fTgLsmY,2234 +mypy/typeshed/stdlib/importlib/simple.pyi,sha256=Px9D1mMPoXrh__Iy1JacqIN2AEUSTLHrV2fVGRRkTZI,354 +mypy/typeshed/stdlib/importlib/util.pyi,sha256=ufNdpvJwZjkC2rnGtIcvcCnCJB02lLj7rFpBhAzYxjE,2832 +mypy/typeshed/stdlib/inspect.pyi,sha256=OzruGvxWkCMRrcMkXh2kEIQM5e9PAl7Y39kPSvx4xPY,24080 +mypy/typeshed/stdlib/io.pyi,sha256=VVN4o6zv2BYaAAO9tHPKmAMx_-euN2qG6E8A5n02rzo,1944 +mypy/typeshed/stdlib/ipaddress.pyi,sha256=QsCpKNUg5SUfwsyQw-yuG7lw3fNGyIaIL48YXSBUiMo,8469 +mypy/typeshed/stdlib/itertools.pyi,sha256=QwLu8w3W9GM9KTcbz5canlUuLxnUx4TIpnedzzSaP40,14005 +mypy/typeshed/stdlib/json/__init__.pyi,sha256=XhcpH-7ynXInaWJyf2TG0DKKt3fC_1Owvn2s6E6aefY,2061 +mypy/typeshed/stdlib/json/decoder.pyi,sha256=XdU0nhYShlWZbSXpxGdsgurtM3S_l0C9mDYCV9Tfaik,1117 +mypy/typeshed/stdlib/json/encoder.pyi,sha256=f9FjO4Rjf_lLqLjPkusYRgCdrtG8hq7myq7p6_c3Bec,1323 +mypy/typeshed/stdlib/json/scanner.pyi,sha256=4UhE-14W8W3ciJpWohjD7YmE8NJb5W1z-csoM_de_oY,171 +mypy/typeshed/stdlib/json/tool.pyi,sha256=d4f22QGwpb1ZtDk-1Sn72ftvo4incC5E2JAikmjzfJI,24 +mypy/typeshed/stdlib/keyword.pyi,sha256=eCmwLAJJZkNZG5hADH8mPsiQVmSLO8FGKYctaFcmabo,434 +mypy/typeshed/stdlib/lib2to3/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/lib2to3/btm_matcher.pyi,sha256=zWMSDahNavhi40hkU1rK-3lPsSgvlsDJtwhQfqAlmSU,860 +mypy/typeshed/stdlib/lib2to3/fixer_base.pyi,sha256=NacQW1e6fooBSu5crrweMC0KKcBhXDQmsQbe11U3cj0,1692 +mypy/typeshed/stdlib/lib2to3/fixes/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/lib2to3/fixes/fix_apply.pyi,sha256=xMqbvuWy1ujOd9odCGJi3UpeSLmlYk6jNK9L5jydnAc,215 +mypy/typeshed/stdlib/lib2to3/fixes/fix_asserts.pyi,sha256=UI605ggRRcCzfho7-zYV7NelkKfOxP4pG9518pIgQJM,259 +mypy/typeshed/stdlib/lib2to3/fixes/fix_basestring.pyi,sha256=lY1h20fQ_HpI-54CXXjhRpazbh-I8PMasjxPau1iJjc,240 +mypy/typeshed/stdlib/lib2to3/fixes/fix_buffer.pyi,sha256=RysLZN7QX0ouBHx4bD5sRCTtV_p6GQlF-PKTFpePqHo,224 +mypy/typeshed/stdlib/lib2to3/fixes/fix_dict.pyi,sha256=qcbZRE3X7cFCwAQ-BH_0Nkxk0wEvS04tPUOfJbcae4c,424 +mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi,sha256=Df6KW8jrbtYWU_kWAqlY5FRLc8drkCgE8pmpp1S14Lo,415 +mypy/typeshed/stdlib/lib2to3/fixes/fix_exec.pyi,sha256=2qmp1Dmizd6ZgyeC8J5HvjLXpYBYT5oBBGCD9C7idWg,214 +mypy/typeshed/stdlib/lib2to3/fixes/fix_execfile.pyi,sha256=Ms7SLIU2e4kOB_ozEAs7Q5Oo86ka1k214dr8Iw_dQnc,218 +mypy/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi,sha256=gtX9wmo7ARiCUZdcYTFfmNsnbOXTudXM6yUzXf0Hui8,445 +mypy/typeshed/stdlib/lib2to3/fixes/fix_filter.pyi,sha256=J4qoUbRK8teogKnr91NZA17UlcWexU8YhcM8OCpYG60,280 +mypy/typeshed/stdlib/lib2to3/fixes/fix_funcattrs.pyi,sha256=2gPueWngu_FThhvFNXCbHzJzJfdez0m88wdfu_FBrCg,227 +mypy/typeshed/stdlib/lib2to3/fixes/fix_future.pyi,sha256=D2C_mtrnL2BZofMuWARTRX21Is6U1oKTUSy5T7-98d0,216 +mypy/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi,sha256=tredl7rFWBAEJs2ZPtiEd5jD0FP0Hyr7sQkwlms554A,225 +mypy/typeshed/stdlib/lib2to3/fixes/fix_has_key.pyi,sha256=oCI0xQcAIh4X8qW6ZF952bMpHCgp3lOJVFZLVwdTmDA,216 +mypy/typeshed/stdlib/lib2to3/fixes/fix_idioms.pyi,sha256=z73__dxQnDnXOmtl97XsDj0OcwwXVomz161RiJ-XmTY,459 +mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi,sha256=atLYbUa9wDEYsm8ImyHmmlfT6WVdiddPK0FUr0jtS8o,507 +mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi,sha256=cBkDJycNw0JcPQ3U63ODaqb2LNVW3MWbvxFD1v7SDmg,653 +mypy/typeshed/stdlib/lib2to3/fixes/fix_imports2.pyi,sha256=QDdVrRYdDeFHQ7d5qar8TK7derNWpJdMrwfUvMm2NTI,150 +mypy/typeshed/stdlib/lib2to3/fixes/fix_input.pyi,sha256=QYFs7CJ4jZZ-JwEVl1tjfFdPZsyACH9VfYoY2GWkW-I,269 +mypy/typeshed/stdlib/lib2to3/fixes/fix_intern.pyi,sha256=kmI0_JFByQJiRnumNO6lHjHpVZqdiw0Qs-vVFoix2nk,252 +mypy/typeshed/stdlib/lib2to3/fixes/fix_isinstance.pyi,sha256=LCDztGYxR0NBoLaNfU6kBxBUUG_VInMqccPxIQ3LOA8,228 +mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi,sha256=LMCpC8O9x9EmdL2QLy5QUHnCG3nMhx0hrW8KMsNgx60,245 +mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools_imports.pyi,sha256=RSOaZS-pyByKNWYwmD91NHE51PCNZp8BkoR7V8N4K3k,230 +mypy/typeshed/stdlib/lib2to3/fixes/fix_long.pyi,sha256=DFYBWAAkdgf09ftU0Hkdv7X3KPiJgHVf6URHpnyCyCQ,240 +mypy/typeshed/stdlib/lib2to3/fixes/fix_map.pyi,sha256=LPR5jxzCxakicFoFqCKGF1iM4wQbSM1ZfO-gl2OiwRc,274 +mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi,sha256=vr0_fJbfJEDXgt0RGMprEsR3Jwq934IHVOYitO-Yvbk,587 +mypy/typeshed/stdlib/lib2to3/fixes/fix_methodattrs.pyi,sha256=rCRrKsYEcXFsMLayDRnWG_X4tE7vHqxMGgOAbYM26pw,264 +mypy/typeshed/stdlib/lib2to3/fixes/fix_ne.pyi,sha256=za5_699UQ5u7gExpW0rFQWLoz0gBWiaL2bdM-Uk8XkE,217 +mypy/typeshed/stdlib/lib2to3/fixes/fix_next.pyi,sha256=4OdBIkvhFM1Ek3QWe9ACAUW2aqBE48SLKiY69RIG9YA,518 +mypy/typeshed/stdlib/lib2to3/fixes/fix_nonzero.pyi,sha256=BJ-vs3pK9DLUFfA-BjFExiPExmcDwyoNofwrY0ZPu4I,225 +mypy/typeshed/stdlib/lib2to3/fixes/fix_numliterals.pyi,sha256=DA_3aqN1HEiG2MaxlQYmmwGFX3UkxGoTlq2ipJskiTk,226 +mypy/typeshed/stdlib/lib2to3/fixes/fix_operator.pyi,sha256=Qph9PS3cZMsJBpxSnyqvdLXm4Wz6MRoM9OhIChvkBBw,312 +mypy/typeshed/stdlib/lib2to3/fixes/fix_paren.pyi,sha256=LHA6O3-Pc0iVRgFxTnk5SwdrhzD9ibtsb2xYVjxN5zw,223 +mypy/typeshed/stdlib/lib2to3/fixes/fix_print.pyi,sha256=PCnNJjkjn32OyMZDGt9I-tyuNF2rDeulcCHPaCdnN1Y,334 +mypy/typeshed/stdlib/lib2to3/fixes/fix_raise.pyi,sha256=kWLdHKgrCjNgWxy8_S8t1GLE_-RmCxzdV6EUDPGFRLA,215 +mypy/typeshed/stdlib/lib2to3/fixes/fix_raw_input.pyi,sha256=6JYhq6treAVEVMIJWogmw7a_7b7OQnGQCTdSTPaUhJM,226 +mypy/typeshed/stdlib/lib2to3/fixes/fix_reduce.pyi,sha256=gx_ts6bc5MOHO2RI_uK5WsH-ibfTHoqewnOq6bMCttI,264 +mypy/typeshed/stdlib/lib2to3/fixes/fix_reload.pyi,sha256=jDt5tEFPpe5bpW2_xX_K7g2mXZHBgD5daf1YLq1xrgk,252 +mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi,sha256=CE1ZA-tAamCMq6Gft9Kl9z15jtuAr6OBywN3fo5fAJ8,507 +mypy/typeshed/stdlib/lib2to3/fixes/fix_repr.pyi,sha256=91OLJrm0eK1k1FzpE4563_J_RnHfERocHeSrj6DE8qw,214 +mypy/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi,sha256=b-wHK26YV2c2R5cBOhIU63gf25JYqXbycta1zHqyrik,224 +mypy/typeshed/stdlib/lib2to3/fixes/fix_standarderror.pyi,sha256=RQP7prg227V7Lm5grhrzD7MHg3ApogLcb5SlgyR7DzI,223 +mypy/typeshed/stdlib/lib2to3/fixes/fix_sys_exc.pyi,sha256=izheZTCqKPd-Fl2aZWzhhcFOtdMIY4F_lVqtOmcdtng,250 +mypy/typeshed/stdlib/lib2to3/fixes/fix_throw.pyi,sha256=Ayft1UP88mwxNDsP3KXuyEUfacJ9myhP07vP3lXHL28,223 +mypy/typeshed/stdlib/lib2to3/fixes/fix_tuple_params.pyi,sha256=YIZEizRdrqqcuJwK6XW87OUSUQHo9aSMdkGMJls1nHk,451 +mypy/typeshed/stdlib/lib2to3/fixes/fix_types.pyi,sha256=p3quhtHggwMg-KDc2dmO8c9oTT6SOZLTG1feVPqXuVw,215 +mypy/typeshed/stdlib/lib2to3/fixes/fix_unicode.pyi,sha256=AVUm0QE0OxwwXgZLWITXQBHrp3WFQGyQo1kPN8tF6io,369 +mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi,sha256=RMEF00r8pC3wq6PgHKTg52_Iwo8azKPRs5oGKmKAJAA,556 +mypy/typeshed/stdlib/lib2to3/fixes/fix_ws_comma.pyi,sha256=7WECM-TvzSNknzhW7fy7Q1RAAwLNsncFNP_ujjHKPZA,304 +mypy/typeshed/stdlib/lib2to3/fixes/fix_xrange.pyi,sha256=IE05vQKlmMkk9tPbvH-I3FOfSNd-XP1XLvdBX8K0Rb8,726 +mypy/typeshed/stdlib/lib2to3/fixes/fix_xreadlines.pyi,sha256=aXv8cGy3hLrtZerMtHLAiNQaSAQQGke3C6WJR-8A_Ok,228 +mypy/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi,sha256=Qw4i-Jn3A2LoG-jSpHJ8BoUSHk38iegK1FyxtUqngD8,274 +mypy/typeshed/stdlib/lib2to3/main.pyi,sha256=MgUWnovV8WODrjmnR55Xgej8tjBSg3p9gOK1GRbVkJs,1532 +mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi,sha256=J1r7O6-RC55RX9XuIU4QcT8sm-7ySY0eowiibNJz0kE,287 +mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi,sha256=PNvewWFDcgWCmmEwYEKtBrKrHkukMZqkryr6WauQZ1w,1067 +mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi,sha256=dG17yFsbtkiDsvKCyWRZvc0zmaCLF83m_naTZzUziRU,682 +mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi,sha256=TtrXnXJiXUTSBXIP_3hJUoKM2h_rSNg5aTqQcL5tZIc,151 +mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi,sha256=dSjInOriPq4H6YhXCvsW0lUeCZKMV81mYmYc9ZbEh4Y,1133 +mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi,sha256=suHtbvS7x64S7z70EMaFdw-ZJgu8_w7t0WwRvq1AzBo,2273 +mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi,sha256=9kLlQlmffvLgVeS7cQC-OGDuzwKmP92YOOfqmaIDRUM,1418 +mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi,sha256=mdjbHoIgTIFWGaGKpky1FqxpY6Ugih514SvAlNUT-8k,1972 +mypy/typeshed/stdlib/lib2to3/pygram.pyi,sha256=cMDHpJNWgsy0aJVrG2e2uBDq9DbXd30htXQBMjAO_pA,2253 +mypy/typeshed/stdlib/lib2to3/pytree.pyi,sha256=RowzuYJKhSUKX32E6Vrf_SHu9HS8ezr97-vQ-x2MFWY,4185 +mypy/typeshed/stdlib/lib2to3/refactor.pyi,sha256=vhGguYDE5gxdbUxG_LKxVPZ9KhkbryDjRT_hK7FSZ1U,3946 +mypy/typeshed/stdlib/linecache.pyi,sha256=HKDzUJPKyFXBXceGeeoYpMhxXIYapQBj9D2DyQrJ2R8,852 +mypy/typeshed/stdlib/locale.pyi,sha256=fQYiQf-xr8d02FmoEbMECafNv43Hhu0wJK9fZaT9m8s,4934 +mypy/typeshed/stdlib/logging/__init__.pyi,sha256=yTdkVuimp1L1s0C5mVCgfpR96sx1FI0ZCnfM7iw_F2k,21288 +mypy/typeshed/stdlib/logging/config.pyi,sha256=hJxN2Oieqxij9A3m6jYuNJOYlccveJkiynIwhkJVvtA,6323 +mypy/typeshed/stdlib/logging/handlers.pyi,sha256=-tE5aQIqfaG3oNqT8O-bymyKzzMUlI8DFPs8QNueB8k,9192 +mypy/typeshed/stdlib/lzma.pyi,sha256=jW_lZJbwFU3LyHV4jqCm32diG1Qk1G0-2cDFHgJVJdk,4926 +mypy/typeshed/stdlib/mailbox.pyi,sha256=A59sq_iCF1kyKxZhioUeusZkVLfYfTyBnifwvinYGP8,10779 +mypy/typeshed/stdlib/mailcap.pyi,sha256=h3wCqy9SD2DA8-aB5k7vW17ShyhlL-AZV6iYKpRTyP4,388 +mypy/typeshed/stdlib/marshal.pyi,sha256=LqlTQDvNSGJGSKNjSQ832j-3opQFkcaeMVuy2v4RWM0,1605 +mypy/typeshed/stdlib/math.pyi,sha256=pBs28qdJCrqf9GbUFnZpWE3SRQDjnnobRt1z3fXNMS8,6156 +mypy/typeshed/stdlib/mimetypes.pyi,sha256=xW5fMdXLqWZ28W24kOXRvKJFBLtB0Dw_xGrvha4nI7w,2128 +mypy/typeshed/stdlib/mmap.pyi,sha256=O5U2etvBYdYDq1agg3iH2587jMQQkZ4CwLWMK71t1kY,5692 +mypy/typeshed/stdlib/modulefinder.pyi,sha256=IbgQdklMWj-I-DZL4ceI5KzniZ1cNuwdBPLE5ZnD12k,3399 +mypy/typeshed/stdlib/msilib/__init__.pyi,sha256=AMuAaoRE_erzIsqazBOn53UVl2Ss8wIoFX-zgr_YP2Q,5854 +mypy/typeshed/stdlib/msilib/schema.pyi,sha256=2V7cxsSreXKr3UnBQVIgpUEVjXS1gbBGUXsggjFUltM,2173 +mypy/typeshed/stdlib/msilib/sequence.pyi,sha256=6MlkmUtknHyQU535LP_PPXGY5_QCxJo910--XfE0KwM,429 +mypy/typeshed/stdlib/msilib/text.pyi,sha256=1I58yqiApA7hjFdzhrhsw6D8WlVfH8JJtB1b4NkMNL8,216 +mypy/typeshed/stdlib/msvcrt.pyi,sha256=tWT8Hx0Ogy2Fwv_Gt3dVjub0ibtMcXLYoiGPLGiI4MQ,1196 +mypy/typeshed/stdlib/multiprocessing/__init__.pyi,sha256=KafkEHitV2NmXHJS956RawcoMZhXV6_mZ-io0ZpMSv4,3132 +mypy/typeshed/stdlib/multiprocessing/connection.pyi,sha256=QHxUSmeTedOmVlXk_Nn9rvls0rpyZL3XMSujfYuCPtU,3723 +mypy/typeshed/stdlib/multiprocessing/context.pyi,sha256=FCFuO3lfuMSzOeYuBJZJ3K1-PrS9yN5GrPM59i2isWc,8578 +mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi,sha256=RxtDm0qYAruvxpGO-ijjlP_OUNeaTeE0vsb7mlxbKsc,2353 +mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi,sha256=WNsr78HeHz67VG14qLrc6xUkFNQkKt18jw95amhFBQg,1282 +mypy/typeshed/stdlib/multiprocessing/forkserver.pyi,sha256=FDzUWLVRjUsyDrOT1h7mvZD_JIbGf4mPnK6OEN3WwYM,1873 +mypy/typeshed/stdlib/multiprocessing/heap.pyi,sha256=HTI4VlqHvZBggg775D8DsGkkDCTLsda4zbRqHvGCeL0,1084 +mypy/typeshed/stdlib/multiprocessing/managers.pyi,sha256=UaOACGizOaw5DViNPKJ0v9axvYrCQpYD0KKYZeDVdv0,17215 +mypy/typeshed/stdlib/multiprocessing/pool.pyi,sha256=szTwi4UNMQZ37pSC3MMQuHTDs4MLs8AjEOGM5r9wDG0,3938 +mypy/typeshed/stdlib/multiprocessing/popen_fork.pyi,sha256=RHaJE_47OeQykmnXjxeT52Q7FlxznFVaknStQxZJlP8,810 +mypy/typeshed/stdlib/multiprocessing/popen_forkserver.pyi,sha256=-f851cHQEbM_L9oXaw6PrUHI6bKAVasRR17OirOSd60,353 +mypy/typeshed/stdlib/multiprocessing/popen_spawn_posix.pyi,sha256=kuKZmJxw4id8R5dTTp-B7E-5qDWTSexAOkCqStEMoKo,524 +mypy/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi,sha256=ZyXdPF2y4wvcgveiWOouv9Y9P9gnhn7D4XXpD9WF46Q,773 +mypy/typeshed/stdlib/multiprocessing/process.pyi,sha256=k2Zxt_FkjkRG7wFGlGhK6-WDXgDITeF8pIplbaxrRDk,1266 +mypy/typeshed/stdlib/multiprocessing/queues.pyi,sha256=1VGowyM1s1VDJenHK76rdleZfDGAubiic2px79Gqcjw,1949 +mypy/typeshed/stdlib/multiprocessing/reduction.pyi,sha256=y_Iw8A3Tla4xBI233K--zseyG-SsXyVWyjLD2Gvqigw,3270 +mypy/typeshed/stdlib/multiprocessing/resource_sharer.pyi,sha256=d9OjiE5L4aC3-u2-WC7csArCtkqs_IMOhhOVMEi6UjY,420 +mypy/typeshed/stdlib/multiprocessing/resource_tracker.pyi,sha256=zGYELoHtbABO37k1BWl3_LgSXHnFiBnIUj1fciE8Jb8,695 +mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi,sha256=JRimnBHWs_TwG96aTh2FnuVIGc9gtUjieRe4ZYJeFSA,1500 +mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi,sha256=_srRMuFu7Qgx_T8pCxJnmioDglYGQWoMsIyhd4OFOJk,5254 +mypy/typeshed/stdlib/multiprocessing/spawn.pyi,sha256=oy8FZLtca2ZmZ1OXzvU-kFGSLioeCghBO1iaqLwfy8c,904 +mypy/typeshed/stdlib/multiprocessing/synchronize.pyi,sha256=yxldGzmsmfSGGUYEqalcUUAYKb0U0JHKuaATm87JigE,2525 +mypy/typeshed/stdlib/multiprocessing/util.pyi,sha256=1H7c1aqVS6BpLXB7MCmHxUp53seiuD3O4McMk2Xbq5U,3090 +mypy/typeshed/stdlib/netrc.pyi,sha256=tvfrFw9uqNzt6Xt_fJVlbF2uXIoJy7YXEAOzveB8AEo,745 +mypy/typeshed/stdlib/nis.pyi,sha256=jnKh2Xj3mroOTpZpm-C7BYPVe5M18UAIVeh66AFGyw0,293 +mypy/typeshed/stdlib/nntplib.pyi,sha256=FYFknQ33uku7s3vEFrIPxHlEVA0KY82-a7L66EgPCK0,4279 +mypy/typeshed/stdlib/nt.pyi,sha256=FNIRcLSoTrcRDA2NIYrHiACEr3r3WgkyDwNhSujOlsc,3407 +mypy/typeshed/stdlib/ntpath.pyi,sha256=c_WZ6Pg1gmoyTxjZV5X1HasYC7znrU_9WY5_hYDg5N4,3049 +mypy/typeshed/stdlib/nturl2path.pyi,sha256=MeWnFTlqhvq6m2QsnYDaX_oGiUga6swI7bn_RjP6epE,412 +mypy/typeshed/stdlib/numbers.pyi,sha256=Jhh3FjInAcY76uLHr0aS4zbHOVyydjDR0sGvD8ddnK0,7546 +mypy/typeshed/stdlib/opcode.pyi,sha256=OYD0--bYWa-eZl2IFKBhbwI_nVsz1nmgM9nWzyIJe6k,1119 +mypy/typeshed/stdlib/operator.pyi,sha256=7l31EfbCCMDMwLWVNn7M7Jgt2WYX2IzenDxtAnkgjv8,4927 +mypy/typeshed/stdlib/optparse.pyi,sha256=bpx4WTvY-c8mRkjiF3FgjPzU4T4aoF5zlTtLzf2MwSU,13191 +mypy/typeshed/stdlib/os/__init__.pyi,sha256=rtWD_qwmcyQY8o-oA4K7oOs6Qw3QrYOGiV_GbhybXr8,57934 +mypy/typeshed/stdlib/os/path.pyi,sha256=G76tJbvlG1_kzFd8gnCqS4Mht3gPzlC1ihIBqzurxDM,186 +mypy/typeshed/stdlib/ossaudiodev.pyi,sha256=mjHFd2y8BrdeToNwDIUX3YJtRHBgs9vaGo32sQP9uPI,4409 +mypy/typeshed/stdlib/parser.pyi,sha256=qESTvpCIEl06MJlFOeGt6pVTgqDvrwINj3Haj_g26DE,1100 +mypy/typeshed/stdlib/pathlib/__init__.pyi,sha256=GrZmCnXWQSXVlaBuI24ZRXwTXMnMN0JCyAmtrujfqwU,14683 +mypy/typeshed/stdlib/pathlib/types.pyi,sha256=zNj89KIAok7fdN8Lvm8ujgUnRKS5nZFJsIiSon5LEIY,333 +mypy/typeshed/stdlib/pdb.pyi,sha256=hdT_FYHrX43STqMRgikB79-Z5MT25-IfOjzYODToC7Q,11118 +mypy/typeshed/stdlib/pickle.pyi,sha256=CwfRBnwjHRKgLtvZaxfQ7JW1gROeTM7shtLCfqI6gqM,5306 +mypy/typeshed/stdlib/pickletools.pyi,sha256=Avlw2PygqsaMj4zcx-b2jWXzMFFbz96NC82jefeYsYM,4232 +mypy/typeshed/stdlib/pipes.pyi,sha256=FvE1GTA5YU-JHBIO-mCAIfrAARL7g2Ck0HmgJ765gNc,502 +mypy/typeshed/stdlib/pkgutil.pyi,sha256=ApsHouaT21XnCdXiW4WVG_ck5eDv2vqt8RWS2zpnlGI,2591 +mypy/typeshed/stdlib/platform.pyi,sha256=-YjPVuiCJWNL8W4d1S6ceclr8vW-L04i--1--NqosLs,4109 +mypy/typeshed/stdlib/plistlib.pyi,sha256=YSN2FLch6L7BEJrNR-LpZPlNZQy6qBWBQYmwh-c7I4Y,2746 +mypy/typeshed/stdlib/poplib.pyi,sha256=a-MhQrCHvKvvLACrGalHGM4OTN7dMl8UJJDcjNLjiYo,3122 +mypy/typeshed/stdlib/posix.pyi,sha256=gwKe-gvg6-QOeRCIIpMZmYhmpCybxGGeh54J6qS232I,14052 +mypy/typeshed/stdlib/posixpath.pyi,sha256=dJIklN8TxPNn_5Y-CSL6w5I3IEn5gQXGBXljc_CdhPs,4744 +mypy/typeshed/stdlib/pprint.pyi,sha256=dZlYga82u0YmsP_K_V6INIkqTdZhskEsFBp79l5Qrlk,4835 +mypy/typeshed/stdlib/profile.pyi,sha256=VENI6_XB1JcY18Kn3bY2Sm02efBuCFMG_beiLlpZOQY,1416 +mypy/typeshed/stdlib/pstats.pyi,sha256=cKqAT2Hf7DCOx9b5QKFWZSZ1enS70UdDcHVWWD3SAK8,3074 +mypy/typeshed/stdlib/pty.pyi,sha256=A0mqxGnMi5mqKwFeDbkRUC4bDbga0X9TovCDfbMLZt8,1072 +mypy/typeshed/stdlib/pwd.pyi,sha256=rXA9jXtUOJeQ5D06dv5C8twQxrOatqmQrlg1SZFfxUU,905 +mypy/typeshed/stdlib/py_compile.pyi,sha256=pRlpK44H98D9tnHGi5C0eDgOX68dk_82SizC7voWnH4,894 +mypy/typeshed/stdlib/pyclbr.pyi,sha256=xZ2POHrJZT7xe7eaueO6wxdgpFFkdf1BePdF0PuSbqc,2284 +mypy/typeshed/stdlib/pydoc.pyi,sha256=GuA5LMlVvyseqR5UGQUT0JIUSi6XFcOVN-l7ib26Bfc,14303 +mypy/typeshed/stdlib/pydoc_data/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/pydoc_data/module_docs.pyi,sha256=N40eJTBi8loXiVb-QlmiobAaZQYbDkQEs1WO6rUacks,61 +mypy/typeshed/stdlib/pydoc_data/topics.pyi,sha256=gqCAY10yIjRcrCCE8hqoUVs5o5cE0NgOOft9X-wg3AE,56 +mypy/typeshed/stdlib/pyexpat/__init__.pyi,sha256=uT9PYCwa1oRrxNkdndQoI2tx9MWdcduw8l3faku9STA,3887 +mypy/typeshed/stdlib/pyexpat/errors.pyi,sha256=XA5Ik0oagDYSTmleaMQFSTqkcfMN_1xGwP19va6xeH8,2357 +mypy/typeshed/stdlib/pyexpat/model.pyi,sha256=WLYMeiykYnU6gpN35DItiUEjTPby-vu0DKAZ4afGefU,291 +mypy/typeshed/stdlib/queue.pyi,sha256=_Zq4o820Qh_giAIlnV7hnA9Ox1ws0dRjdGwWVFOUmFE,1910 +mypy/typeshed/stdlib/quopri.pyi,sha256=a-dyP2A0w_xQm3D2KXIZzDA99FPX15Kaq297GJTnK1o,669 +mypy/typeshed/stdlib/random.pyi,sha256=4v-VQZ69AZ8x0vGKKSa82EnIaeyJ5_M2RN6KRSQFdS0,5214 +mypy/typeshed/stdlib/re.pyi,sha256=A3Er_MgsvnAX2T7YTLDGpIrc_bzIxp9P_cR79ThHWhM,12139 +mypy/typeshed/stdlib/readline.pyi,sha256=JoE2nbK4Fv-UIDbo7lgTp_38524hDx8kRRpL5Qhuo5M,1988 +mypy/typeshed/stdlib/reprlib.pyi,sha256=usKrUhRcCNeOVdYy3S6I8njRORXIQ9rXrGme00uGJd4,1986 +mypy/typeshed/stdlib/resource.pyi,sha256=OAlIxkLvLkdxOWk3nmG7kh0GPvPUPgU3HV8wkGx8Fkc,2972 +mypy/typeshed/stdlib/rlcompleter.pyi,sha256=FtTt0Z1sNrWz6EMCyowIRAq8tzAeTpee6rUVJ5b-Tsw,322 +mypy/typeshed/stdlib/runpy.pyi,sha256=hrHtuhkdU-vJb7E6trWXD-ITI33AOQT_HH5CEsURVdQ,811 +mypy/typeshed/stdlib/sched.pyi,sha256=iIT6hC0Nzz47CUBmzSoBlamexV9s5KRD0--vXuumJRk,1521 +mypy/typeshed/stdlib/secrets.pyi,sha256=IrwNYsRo8gkFA4FkqJSPKwYqcAgDnGcgrm3Pu6Y4Yxs,660 +mypy/typeshed/stdlib/select.pyi,sha256=xOhnY8bIZgqUpVX-w4RxXgMpKnNsGCQSDnoiHYLMLWc,5805 +mypy/typeshed/stdlib/selectors.pyi,sha256=2rN66ItZthqaO9SCb6Ix9ImpLfGkdn2-hYk9SexRGt4,2927 +mypy/typeshed/stdlib/shelve.pyi,sha256=iXAfiiZL63IYPfUdIS4g2pMfx6thq4K6NqQ2WfcY6ZE,2343 +mypy/typeshed/stdlib/shlex.pyi,sha256=CNq7RB3jlgSD8lpZVEb42Coh3pfeOpd6tjp3XCVXptQ,2191 +mypy/typeshed/stdlib/shutil.pyi,sha256=TjwVseRzVNWxQgerDoEBwtOWkr5F5nY5GMTPeyovNbU,8362 +mypy/typeshed/stdlib/signal.pyi,sha256=YDVZyjuYVKTZOK7Mvb1LcVyMIqkqDdfyGf_iRPtjED4,6094 +mypy/typeshed/stdlib/site.pyi,sha256=lDIaRFWoJkNeGfPKavcrMtvia4akAMWMR5BIDlDYvx0,1547 +mypy/typeshed/stdlib/smtpd.pyi,sha256=_DHsDMkG8iT4uDal27Ub0-kssEC73bncY-A8f_E_IEE,3082 +mypy/typeshed/stdlib/smtplib.pyi,sha256=OADEHJ4wKdstbcknWtEFw_jaJ0Nmm3aHW8v7nIPaJCY,7523 +mypy/typeshed/stdlib/sndhdr.pyi,sha256=4boTiWWf2o3VW6QhITP8JNEePP734AlxyMeU1cn74CM,353 +mypy/typeshed/stdlib/socket.pyi,sha256=3oEyyJMejbeWsXrfFFI-d_JEmIcpgt2PzLQTnnokh2w,46182 +mypy/typeshed/stdlib/socketserver.pyi,sha256=gPN47U1Kh7UPFxuvK-you8aRwvHbtzgvMVnt9xBQM1A,6991 +mypy/typeshed/stdlib/spwd.pyi,sha256=hyZQp0XfNGpN05cq8qpIenyS2sUm6_H3odOvSyxacKo,1299 +mypy/typeshed/stdlib/sqlite3/__init__.pyi,sha256=gTSYC8b30HiRXBg-yOyB4iySbwpY42lb3ygc-WOWM9E,22071 +mypy/typeshed/stdlib/sqlite3/dbapi2.pyi,sha256=5_auPrbYUGLd6BirR7xmDFUr_Ibdm7ZTAeZ3meU5KEQ,11438 +mypy/typeshed/stdlib/sqlite3/dump.pyi,sha256=kKrQ2CozgG8GoIXMDMNiMJz__B7tzZ0VQb2jzkH6p5g,90 +mypy/typeshed/stdlib/sre_compile.pyi,sha256=WUWnQmaYMB5XB6H9i6VAU-pVrqKb9FqeKYneO99QGak,401 +mypy/typeshed/stdlib/sre_constants.pyi,sha256=XTz8_VeEEAXJSnMdUviQINrLMOXclnaJbzKifN_zjuU,4781 +mypy/typeshed/stdlib/sre_parse.pyi,sha256=AsBSS835EPpGxhpKlo8Ce2Z_t_cwOB7CNwKmR494On0,3906 +mypy/typeshed/stdlib/ssl.pyi,sha256=lRy9m6ekUYu_CRw_S2SgRvdOXO1noZR2T9tVneBjzPQ,22938 +mypy/typeshed/stdlib/stat.pyi,sha256=YbUbmHZzGlieVnKK7uvAjRwv784LjinmOWsnmu05FJM,3354 +mypy/typeshed/stdlib/statistics.pyi,sha256=b40i4KdsQ8NiKI6F4BFqAwuOUsTOdPpy3mdlGzrT6Lo,5916 +mypy/typeshed/stdlib/string/__init__.pyi,sha256=aRIqf-qZi4mc_N7u3HAALMWpXttjU48A6a0bcbPLuoY,3095 +mypy/typeshed/stdlib/string/templatelib.pyi,sha256=b2lwTPVujnkpNrmHIfwe1cz_NFhUJPpaM5UbLPWIAzs,1324 +mypy/typeshed/stdlib/stringprep.pyi,sha256=53l-7SuzjSdXnCCb5lHYSHxNWQNBXLQzbL8DX4usXYs,985 +mypy/typeshed/stdlib/struct.pyi,sha256=7xjDbX-Sh1C_E0rFZ-Z0DnwF6P27v088eMM03kL2R2g,155 +mypy/typeshed/stdlib/subprocess.pyi,sha256=Bysl_cmplt39Hog8xlEquwiYK2Fc6h5j5kShndAqj1Q,73103 +mypy/typeshed/stdlib/sunau.pyi,sha256=qTvLbam1UgmqH9Hr0mLgIFZ3jQqxSvBceIOq5QcnwMU,2991 +mypy/typeshed/stdlib/symbol.pyi,sha256=ADRkN_rhRV_foCYktb0NHR7jm7h_N4XOHo9VPWF1lFM,2144 +mypy/typeshed/stdlib/symtable.pyi,sha256=cisakBNhFUXqj4qVY5DPVHYhCQne9EXG0xvPFMZY0SI,3095 +mypy/typeshed/stdlib/sys/__init__.pyi,sha256=OYe28JBiW5YJNApqSVC_LcCI4KJw0VEJ2jgA3ynxD6c,17286 +mypy/typeshed/stdlib/sys/_monitoring.pyi,sha256=Q1m7PiECYw6GsBMriYApV4ZuNWwzG2az8sW3JptGryM,2116 +mypy/typeshed/stdlib/sysconfig.pyi,sha256=lyZJxIlFWYJ38V_GlzJH5ZZphKd1G89adNl-ryWdMzQ,2075 +mypy/typeshed/stdlib/syslog.pyi,sha256=i76lh_ehgdU2LU7fJ964HDXiDXL64_BSAdR1F7j-rhg,1597 +mypy/typeshed/stdlib/tabnanny.pyi,sha256=qBHW9MY44U92xKdFbYgrSXljglOVtAY0GYTa41BHwbE,514 +mypy/typeshed/stdlib/tarfile.pyi,sha256=ByPxvJLZoWhP025Jq031LgDhwgUUz8WhFIzTo24Zpl0,29540 +mypy/typeshed/stdlib/telnetlib.pyi,sha256=Sh0M5cJCI6WicuEAhDCsDXYxejYsMcZMcLsu0lo0diY,3640 +mypy/typeshed/stdlib/tempfile.pyi,sha256=cbw3xYs5wg6rbl0YvaAfvTzkn3oPsOpbHlWp1f0gHIo,16591 +mypy/typeshed/stdlib/termios.pyi,sha256=z-dQ4Pz1e7IBBVKQx4GraNjNrHC4OI8vAZU4-FYM4TY,8171 +mypy/typeshed/stdlib/textwrap.pyi,sha256=6eEGWUkmDRU_-fA-aOIWWse9-1GIq8T89S4Vaf9aJ7Y,3233 +mypy/typeshed/stdlib/this.pyi,sha256=qeiwAiqbPK8iEcH4W--jUM_ickhZFNnx8cEvTqVPvCY,25 +mypy/typeshed/stdlib/threading.pyi,sha256=W89e0e_bdAeJUfA_MNFK-ICT3j5Rvq_Ob7-wqh3BlBY,6878 +mypy/typeshed/stdlib/time.pyi,sha256=Ngd1mFfkGzY5yPk5C-XWeCoTFttFXpptgpGiyy4yFa8,4317 +mypy/typeshed/stdlib/timeit.pyi,sha256=bF-Gp00o3l1_ccA1EvQoauAJ1lZOLhq8TON2G5-UhBo,1344 +mypy/typeshed/stdlib/tkinter/__init__.pyi,sha256=aGRd3Pe-B1VmomI38V9_0GE_vhv7uAbE2nv2SwFYaMA,163233 +mypy/typeshed/stdlib/tkinter/colorchooser.pyi,sha256=WigYRTIs27oyuwzPwhvndb3z8DkuLuZngd2MsKM3DNA,360 +mypy/typeshed/stdlib/tkinter/commondialog.pyi,sha256=jJRmyjdOxTouujFvS2YtOg0qh1ngKyHQKPc0dnoumhw,468 +mypy/typeshed/stdlib/tkinter/constants.pyi,sha256=sP9hOZSnvBITqJRCmpigGDJqwP_1GoOAOZ2eQH0blkY,1853 +mypy/typeshed/stdlib/tkinter/dialog.pyi,sha256=oEV2mFaVp0ESk_8nFJOuKGlXWG4u5MAYVcRLedjoZik,324 +mypy/typeshed/stdlib/tkinter/dnd.pyi,sha256=hltw1-itHapOgnqlBgcmOgzV1XGMlu6CEsHjwwtqFYE,774 +mypy/typeshed/stdlib/tkinter/filedialog.pyi,sha256=1TUWUWpUtYN7aPDM7ANHPEDIW9tQoTfmY0m9rJhpdI0,5176 +mypy/typeshed/stdlib/tkinter/font.pyi,sha256=raU_THjHyDL6A61VUGyBR1RtojyWuQhhgArYqQ3E-hw,4606 +mypy/typeshed/stdlib/tkinter/messagebox.pyi,sha256=u_s-BST--wes-h8D1d1uSSj-9s-S6hRfJYcwZSHL9Bg,2742 +mypy/typeshed/stdlib/tkinter/scrolledtext.pyi,sha256=Hp_LlFfwVwR3W4iDZKthreGUofPbIbiOkjl1O-HEL9o,302 +mypy/typeshed/stdlib/tkinter/simpledialog.pyi,sha256=ZZxYKT7uNQ7t1FJ4RqlXX5BCJg9Zcs93e3uFRqt-bSU,1596 +mypy/typeshed/stdlib/tkinter/tix.pyi,sha256=c2OTQkpGaZtIUARkX1drGDhFwdl9ffl52ZNiGvkt39Y,14375 +mypy/typeshed/stdlib/tkinter/ttk.pyi,sha256=lkosHUk5zhrJab7NvdZ00qCXP7d3avNg4aXzX5LGkRs,54053 +mypy/typeshed/stdlib/token.pyi,sha256=45u8j2PqFfchSf-9MPcS-Ep7nL_EKb1jSalRa1qr3Mo,3343 +mypy/typeshed/stdlib/tokenize.pyi,sha256=pB0iu_RYKwen5_ZtDW--R7aKiwH8JprdTQsJzKRCAGY,5445 +mypy/typeshed/stdlib/tomllib.pyi,sha256=v4XWpK6XmcXUQ8R3tQSmQBwtbOuBssM0Z5ZDjhYVIcM,937 +mypy/typeshed/stdlib/trace.pyi,sha256=cwRpCtKhsA0IdW7O8OgQJ3l03k-7f7EwrYTj3jQwrko,3605 +mypy/typeshed/stdlib/traceback.pyi,sha256=MSmYqikk5aEGvXjxZEL-9WtQ378lmgmGuRpfiyryf9k,11677 +mypy/typeshed/stdlib/tracemalloc.pyi,sha256=ifAatgAvsKZq2B4JBSCcdhgHy4d22FIVUMEyNO3sN4I,4581 +mypy/typeshed/stdlib/tty.pyi,sha256=fwxTycZe6nGL5DBdXGhiCcgA0yAlqF9hXIUKHmDkTWQ,871 +mypy/typeshed/stdlib/turtle.pyi,sha256=oixZtSAwes43tubfJp3oAF5bmVNebZIhBRhNva1y_tc,25277 +mypy/typeshed/stdlib/types.pyi,sha256=eew2fvipkTE8RmqTx3p2cJGiE8A2UtgXaTevFo7-oQ0,26443 +mypy/typeshed/stdlib/typing.pyi,sha256=AzTvVltVDrEUuHZu2BXS5eLKhnw6QXNuQXGeO97Ixt0,42646 +mypy/typeshed/stdlib/typing_extensions.pyi,sha256=Os4QFp5rNjqa9gt6tieuY0xJq51joHjF86ohGa6OlUE,23359 +mypy/typeshed/stdlib/unicodedata.pyi,sha256=UdeHUdLrKlVMWZ1bttS8npUWtPcpDjt3PzS3y36SAZA,2589 +mypy/typeshed/stdlib/unittest/__init__.pyi,sha256=ARla4cG9E5nWe7hRFzZ82kH10g_awzGp55lY16IU6xA,1848 +mypy/typeshed/stdlib/unittest/_log.pyi,sha256=QnmSKoFS_D1bcRLqFAvfJinXn2-0-DjyBSqH_92vr4g,912 +mypy/typeshed/stdlib/unittest/async_case.pyi,sha256=owQLuLwHxWCY6UDv1wI6eVDGUi9xOKk5l_IWVCvGpXI,850 +mypy/typeshed/stdlib/unittest/case.pyi,sha256=fuVLYJh6s5nsGmSWhiWMWElSsOk3wFc1wl4e2T5hk1A,14468 +mypy/typeshed/stdlib/unittest/loader.pyi,sha256=tr-lR3NHul7QaC61k-MPUJnn5RRfqEbZZXri3qUnxes,3332 +mypy/typeshed/stdlib/unittest/main.pyi,sha256=rd2LDQ54q_gIamVlYfLBT97SE6-IYSknHgEpCcn1Xdw,2767 +mypy/typeshed/stdlib/unittest/mock.pyi,sha256=Wt8aijXORBPX7PyvVceX6JuyH_Jef0qJ8i8QaoF1ung,20327 +mypy/typeshed/stdlib/unittest/result.pyi,sha256=HX5DXqQaIentVCiFufZh-tHpSfliUUGDjb1X8iAnk_8,2050 +mypy/typeshed/stdlib/unittest/runner.pyi,sha256=kKBdpnU1ahX_Uky1uL4C-DnkglLC1QkLUL1Eq6XfslU,3502 +mypy/typeshed/stdlib/unittest/signals.pyi,sha256=6rqsVHXOvSPHSkeF_vYPf5sUaLgqqFSmFihkaDqPhSw,488 +mypy/typeshed/stdlib/unittest/suite.pyi,sha256=FhS30BvL4niz3gI5Acnp2TX449CNPs2avEUEqGt14mo,1047 +mypy/typeshed/stdlib/unittest/util.pyi,sha256=or4A8A8A-AzIJWs-74Ofhm-TaEd29zUYzlnIRhwg-dA,1656 +mypy/typeshed/stdlib/urllib/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/urllib/error.pyi,sha256=UqUqcqbz8FPtlixaJP0Gp3ecUc6MpPJaYOPydkGRQN4,978 +mypy/typeshed/stdlib/urllib/parse.pyi,sha256=Y7xJVpKJHohxE6bPifub48wXO8bJAwYA08lTtNAovzM,6544 +mypy/typeshed/stdlib/urllib/request.pyi,sha256=PYWa5-pItt_y2KWxAAO0HmwqlXjpKk5-aRNiTk_3gcw,20041 +mypy/typeshed/stdlib/urllib/response.pyi,sha256=HTnWMkkVuowLoNdtuZ99Spdymx4NLcJTSG-BdcIrkzk,2002 +mypy/typeshed/stdlib/urllib/robotparser.pyi,sha256=sA7npNj2rB3b_aFOhXqGlQNh-G7kGmyYaZ3wz__N96o,683 +mypy/typeshed/stdlib/uu.pyi,sha256=yMt5ZRAepWSra-qWti133ZGibCtrJXkMZg5kKJe-MdM,431 +mypy/typeshed/stdlib/uuid.pyi,sha256=aqeMSWDDQ0aKOl8Y-cOT7e5OmfSgymoI4gEjy467v8k,3109 +mypy/typeshed/stdlib/venv/__init__.pyi,sha256=GLWFpMESaRETXfoH7IXs67daBAmbJG0aIfDHMU5Nx24,2951 +mypy/typeshed/stdlib/warnings.pyi,sha256=AztB0gbwUylgZH2A-T7FA3X_uOeUWwpjDLaDJOe9cQ0,4238 +mypy/typeshed/stdlib/wave.pyi,sha256=bbbWyMa3ag475svSkm6idBLX6cOdN60IINkp-JSZhww,3492 +mypy/typeshed/stdlib/weakref.pyi,sha256=ic0GBe2EkvHbsXXSgpyCY5Cx339sMv21AejZsOrvNXs,8475 +mypy/typeshed/stdlib/webbrowser.pyi,sha256=CURvTjznP2Tvs8sT8_hFAsEKOBXGsr2IYHki02fSBmE,3040 +mypy/typeshed/stdlib/winreg.pyi,sha256=Iu8TKxlLIEaYP8WJuTS7RZMAgcKUVOhqnv123BsUS7M,5567 +mypy/typeshed/stdlib/winsound.pyi,sha256=I4ogNevxTWqwIqNRIeg5WXvcm_aQDAyI6VKXqMG13xw,1259 +mypy/typeshed/stdlib/wsgiref/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/wsgiref/handlers.pyi,sha256=d4qMJ3ZNLNAnDk1I___l8nIUK9uxDol-bXsjtc9BsX0,3068 +mypy/typeshed/stdlib/wsgiref/headers.pyi,sha256=hwXvKMQQHbjmcdsvFZgJ3LeIdNLcmRUDf7IrT94ZCCo,1050 +mypy/typeshed/stdlib/wsgiref/simple_server.pyi,sha256=CGpqJaFTlao6-hnkzCqHv4sHcDQfpBGT0sIueL5jhMQ,1426 +mypy/typeshed/stdlib/wsgiref/types.pyi,sha256=89NSSgpDnuOWMCuBprU210FsnnMh3V6TPmT26md1aYc,1264 +mypy/typeshed/stdlib/wsgiref/util.pyi,sha256=NxqrfAJ7JBdP4BuWs90xyfdSCfnywSXYi80uCXRt21Q,1060 +mypy/typeshed/stdlib/wsgiref/validate.pyi,sha256=NCpbRPP9fTt21peGNlXLgegq6U1yZaeAxFO-SUfBlng,1737 +mypy/typeshed/stdlib/xdrlib.pyi,sha256=wxJVHCfO5rju29ihBF96XgK3dj5b-LbsVGeotGgp15k,2368 +mypy/typeshed/stdlib/xml/__init__.pyi,sha256=m6b7OtCfk4VfTktwgMovrcUyjhCV0671jAktSJMbdwE,249 +mypy/typeshed/stdlib/xml/dom/NodeFilter.pyi,sha256=W8h9o8Jp1CsxU7O3ciu-6GelYeoJQoVuy8jeUs6xRIs,735 +mypy/typeshed/stdlib/xml/dom/__init__.pyi,sha256=4P-wzCUKUSkybVJieQlmIt338OwpdO0Q_kUnlDDZ4Fc,2548 +mypy/typeshed/stdlib/xml/dom/domreg.pyi,sha256=LNRgIl78O0eH3m7E5GFqG0BKQ0JSsHxTBnwr5KznZvI,418 +mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi,sha256=ClpimZ5otjEESOeunAAT1KoM9d2FvbdJ7a8wCOqWowE,6487 +mypy/typeshed/stdlib/xml/dom/minicompat.pyi,sha256=IgywKLWtKGaXnNA5ZzsAd-VsXUKAgjVIzjPQCpklUFc,716 +mypy/typeshed/stdlib/xml/dom/minidom.pyi,sha256=rxqF7PasZaBH6vugDxx_jR7pEkxhTkWIyUlaV6W7iGs,28674 +mypy/typeshed/stdlib/xml/dom/pulldom.pyi,sha256=nlFB0Lbj0kzV7_F0teVTMTykZ3y_-ZmPQ4dL2cMEWHs,4844 +mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi,sha256=qQK35MzE_YE2hNt90AhQE5jq0jd2bnVTLiGKO0GtEgk,2952 +mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi,sha256=8G_tDfXrvOGm9g3LTVIKnH8JfB1ZzJGcUfVTOA4N-WY,1176 +mypy/typeshed/stdlib/xml/etree/ElementPath.pyi,sha256=TiZrEPQInm35MiIMWr94B77iftOXmBMNvM1WxiwKLYc,2035 +mypy/typeshed/stdlib/xml/etree/ElementTree.pyi,sha256=NWA4O8oUjXfzZfbdEl3J4BMr-9LmSWmWx-eFW5QlVWo,15176 +mypy/typeshed/stdlib/xml/etree/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/xml/etree/cElementTree.pyi,sha256=iYR7ebpdB3g9zfBvICnV1VzvQktMya-Dh6lX4C9u4Uo,36 +mypy/typeshed/stdlib/xml/parsers/__init__.pyi,sha256=PS75lzF6CFuo_xdO83zK-IOQrnoJQ3FkUoMSOMdwWJM,39 +mypy/typeshed/stdlib/xml/parsers/expat/__init__.pyi,sha256=8pm3z3heMEx09A84UjPVQw3lb9cH6X-UK86skDsfEfk,189 +mypy/typeshed/stdlib/xml/parsers/expat/errors.pyi,sha256=mH9YRZuV4quzksDMLEmxiisAFgNhMOhl8p07ZzlS2XE,29 +mypy/typeshed/stdlib/xml/parsers/expat/model.pyi,sha256=M7GVdd-AxOh6oGw6zfONEATLMsxAIYW2y9kROXnn-Zg,28 +mypy/typeshed/stdlib/xml/sax/__init__.pyi,sha256=7TU3Ez8RjqR041xvpGy6eEBajytpO2W8C7L7AxVOwB8,1616 +mypy/typeshed/stdlib/xml/sax/_exceptions.pyi,sha256=Q41LNt4ARdDs5ynBIAGP-YapjU08m5Kah2ZD939fO9c,804 +mypy/typeshed/stdlib/xml/sax/expatreader.pyi,sha256=D77gx2ZCLo4OI11kXiKHUHwidxAv61UfPUI5k3JqFVg,3800 +mypy/typeshed/stdlib/xml/sax/handler.pyi,sha256=rYfSg3SBNou6cpoO7sBwcP6T-kHClkCwzj0QDZW57Zw,4528 +mypy/typeshed/stdlib/xml/sax/saxutils.pyi,sha256=j-yIPACE-yvjnStAguxaR_HLfJN_Hq8KOLVd8DBGJzo,3804 +mypy/typeshed/stdlib/xml/sax/xmlreader.pyi,sha256=cGP-i2OzR9bUSuZct5ijA8bjWUApxdPVopuJ4yerDlU,4348 +mypy/typeshed/stdlib/xmlrpc/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stdlib/xmlrpc/client.pyi,sha256=dIN8JqkYO713oZIdUjdPddwe8-M1Na7v54d4zRR0FdQ,12035 +mypy/typeshed/stdlib/xmlrpc/server.pyi,sha256=OF2v_1XAjRYtbMLb_akHJrkXUKHX27cfzmrX7sfgm7E,6231 +mypy/typeshed/stdlib/xxlimited.pyi,sha256=SCWnX8bML0Kky9tWb8sMQSCrafe7gj7ZA_xhltk9Lik,491 +mypy/typeshed/stdlib/zipapp.pyi,sha256=gOkFhcdfGpy6PIboXe45wODMw-94YtC1ypUTCxBxTfU,553 +mypy/typeshed/stdlib/zipfile/__init__.pyi,sha256=0bIQh6JP0UqbBFhcFhP6MlpkVwVYV06yeEUguByZT9A,12968 +mypy/typeshed/stdlib/zipfile/_path/__init__.pyi,sha256=V0KUH4awNAvD4rMNVdhMyGnntWdR8udpDXMp9gkBKrY,3074 +mypy/typeshed/stdlib/zipfile/_path/glob.pyi,sha256=7w_87VMRxyV1KnR7WaXktZtPbi0ZS8ibd9w0qsLxksc,943 +mypy/typeshed/stdlib/zipimport.pyi,sha256=SM9xql-crUor4aP7fFefFvGITxf0MpQPV3dNfTv9hVA,2677 +mypy/typeshed/stdlib/zlib.pyi,sha256=DIoGakJlb3pOGe_aAbSfPpLfaJq1HhdBCL1FbEijqcE,2395 +mypy/typeshed/stdlib/zoneinfo/__init__.pyi,sha256=qM_vgqSETLRL7D6D5upCnmwbnE_Pk_96i0RDnHjWYS8,1326 +mypy/typeshed/stdlib/zoneinfo/_common.pyi,sha256=QdqQFkqe8f-PN05bSbHLW90qfEqgdVLbIsKiPbW4lno,462 +mypy/typeshed/stdlib/zoneinfo/_tzpath.pyi,sha256=C5ve2ashiiq2Jm0EtWEdJDtcdxNc-_Ewff8I56pFfZE,524 +mypy/typeshed/stubs/librt/librt/__init__.pyi,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy/typeshed/stubs/librt/librt/base64.pyi,sha256=eg1QM7rzBPf0M6vRyeufBzPEs5IVIdi0Ibz8ZBI75m8,180 +mypy/typeshed/stubs/librt/librt/internal.pyi,sha256=_PYEoUfpIUrfy9BYwR6E2KeYR5PIasX1J9xjItL8e0s,850 +mypy/typeshed/stubs/librt/librt/strings.pyi,sha256=TZp9sDx-XJ9oCsjRKHtcd6xDm9YslTS9UsnulnZJrXI,1780 +mypy/typeshed/stubs/librt/librt/time.pyi,sha256=cUxvWAIFy4V5dF4bBxljjyBdQDA9dMIEXiEO0kXV2I0,25 +mypy/typeshed/stubs/librt/librt/vecs.pyi,sha256=5bFw_RT-Q7DKxTZGUlPph6qeORj8-DKPozAEOIZWBlU,678 +mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi,sha256=tYCX8TT53K59k-CGWcO0BBH6e04ysgytc6f9LiPDGws,9072 +mypy/typestate.cp314-win_amd64.pyd,sha256=Vh3JvgNy5sAEr_x5OJB8-Uii3HVi9Rv2ojzEJQwqnwQ,10240 +mypy/typestate.py,sha256=8jPWL2ahTWfehNT6WWlVFPC86RFZ152FM7nqq6PeG2A,15958 +mypy/typetraverser.cp314-win_amd64.pyd,sha256=DdmCZpD-mO8J780XsK6yqp3Ksmiw44mW_XxZZwGQDNk,10240 +mypy/typetraverser.py,sha256=eswFxl-86t2d9nukXA00-e8kwWsl8UY4wKudQdCDS3c,4456 +mypy/typevars.cp314-win_amd64.pyd,sha256=9uUqObLGgxAa6CrUH_yA3mGBWwdRBfo0dCH-hsDV7hw,10240 +mypy/typevars.py,sha256=8qw5kAfCaKm5hkk5Ze08HH9yMzsTSZOjBenjydTw5OA,2996 +mypy/typevartuples.cp314-win_amd64.pyd,sha256=t762eW9CLL3V62JaUDP5TujCXbSNa2eW9IRB4mUPTSU,10240 +mypy/typevartuples.py,sha256=jo6F1pu39vcaohI38BbkVhgtmvSy-2aoA3H8WYXzfJI,1058 +mypy/util.cp314-win_amd64.pyd,sha256=uom-_j0SuWCnMOrYCe_FySS6yo8SvKissOi7FRrDg-4,10240 +mypy/util.py,sha256=MjiXTD_BzN02H6xRdx1XhQDMsgdHQ6OhSVEkcFu9zq8,33125 +mypy/version.py,sha256=7WAGL73uwneMeTnPmico6R65EQhKPhmDe0X7Xd0XeqM,24 +mypy/visitor.cp314-win_amd64.pyd,sha256=UDCcL2aGuGeWmbsnMNiZ3KTBO41SxEyHLnS8PE2g7D0,10240 +mypy/visitor.py,sha256=reus_vNJ7I4PNWh1JNRO7-IVxdfbfXbMe4AsGV06C3c,18785 +mypy/xml/mypy-html.css,sha256=-e3IQLmSIuw_RVP8BzyIIsgGg-eOsefWawOg2b3H2KY,1409 +mypy/xml/mypy-html.xslt,sha256=19QUoO3-8HArENuzA1n5sgTiIuUHQEl1YuFy9pJCd3M,3824 +mypy/xml/mypy-txt.xslt,sha256=r94I7UBJQRb-QVytQdPlpRVi4R1AZ49vgf1HN-DPp4k,4686 +mypy/xml/mypy.xsd,sha256=RQw6a6mG9eTaXDT5p2xxLX8rRhfDUyCMCeyDrmLIhdE,2173 +mypyc/__init__.cp314-win_amd64.pyd,sha256=BU-gDnutp4_HiPlZ5W8F6a30K9VnbhGa5cTUlbSwRv8,10240 +mypyc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/__main__.py,sha256=19Zu2Z6FDpgBZU4_L47hAfYuQS9nvmYgiTr9X0m8c4s,1928 +mypyc/__pycache__/__init__.cpython-314.pyc,, +mypyc/__pycache__/__main__.cpython-314.pyc,, +mypyc/__pycache__/annotate.cpython-314.pyc,, +mypyc/__pycache__/build.cpython-314.pyc,, +mypyc/__pycache__/build_setup.cpython-314.pyc,, +mypyc/__pycache__/common.cpython-314.pyc,, +mypyc/__pycache__/crash.cpython-314.pyc,, +mypyc/__pycache__/errors.cpython-314.pyc,, +mypyc/__pycache__/namegen.cpython-314.pyc,, +mypyc/__pycache__/options.cpython-314.pyc,, +mypyc/__pycache__/rt_subtype.cpython-314.pyc,, +mypyc/__pycache__/sametype.cpython-314.pyc,, +mypyc/__pycache__/subtype.cpython-314.pyc,, +mypyc/analysis/__init__.cp314-win_amd64.pyd,sha256=fPb5PWHrxQWSGIMPhYWtwmbTL8KC2qHIXM6hJSZRpos,10240 +mypyc/analysis/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/analysis/__pycache__/__init__.cpython-314.pyc,, +mypyc/analysis/__pycache__/attrdefined.cpython-314.pyc,, +mypyc/analysis/__pycache__/blockfreq.cpython-314.pyc,, +mypyc/analysis/__pycache__/capsule_deps.cpython-314.pyc,, +mypyc/analysis/__pycache__/dataflow.cpython-314.pyc,, +mypyc/analysis/__pycache__/ircheck.cpython-314.pyc,, +mypyc/analysis/__pycache__/selfleaks.cpython-314.pyc,, +mypyc/analysis/attrdefined.cp314-win_amd64.pyd,sha256=0-2ZWHu1M13szksWr6TZcyg7O11GmHN3zt2wCQmU_l0,10240 +mypyc/analysis/attrdefined.py,sha256=6GizEEEnsA_pMmDkBQoxEVFd0beZ-WmbO3alJWUmZZo,15419 +mypyc/analysis/blockfreq.cp314-win_amd64.pyd,sha256=DnBmvhBVRAtMOJ2Sim9NvOO8_Ir3_Z_8weWNj7ev43Y,10240 +mypyc/analysis/blockfreq.py,sha256=CjdVRFXgRdsuksk6e11cqbsFdj4e1z_8GHvvnY_Pgb8,1004 +mypyc/analysis/capsule_deps.cp314-win_amd64.pyd,sha256=qPB8iC_L0GUS2ue1y80os7mMgaj-K2OFUBE47AUxlbA,10240 +mypyc/analysis/capsule_deps.py,sha256=yiyc9sR8M9YqxgvPOt2UzyNExID4p4KvV3zj_LDZOXk,3026 +mypyc/analysis/dataflow.cp314-win_amd64.pyd,sha256=6FzbnEC5xjdhe4CVwKi7diRyt1zcLorKDiBQQpJkYZs,10240 +mypyc/analysis/dataflow.py,sha256=knLglTPySxNfObLRMUXrnHP8_jZSPpc4Go1SZVyKYxo,20011 +mypyc/analysis/ircheck.cp314-win_amd64.pyd,sha256=FYM381O9_6hGr9B_bS8-2d7KQTy10xwvNirXn4QJs0Y,10240 +mypyc/analysis/ircheck.py,sha256=vKEnpVGYYQt3ATGhe9Wietm7-XNcHxrFoeJ_S7EWdM8,15810 +mypyc/analysis/selfleaks.cp314-win_amd64.pyd,sha256=Zn4v-VxftPEkooPDqy2r09ONNOixi-X-MAuceIlPN8Q,10240 +mypyc/analysis/selfleaks.py,sha256=GsSBCBl-Fxqg7n7TCV6MTj-rHDZ0cgTn9UzXiX9hArE,6173 +mypyc/annotate.cp314-win_amd64.pyd,sha256=NfvClFoBHQfLHkbSxkNTcOGaA__yCogwaxN3o3WCqvk,10240 +mypyc/annotate.py,sha256=XANWJWaGzXkyUn5J1jlnSj8y4OFucH3PUWwfjtMNfU8,17993 +mypyc/build.cp314-win_amd64.pyd,sha256=7lVbcFlIj4ozJ6tQCBGAXZJSnX6D7UHE7Dz-IIZGKJg,10240 +mypyc/build.py,sha256=L6LH_ryZdwKCbVMmZg0SrIJlOfsF00_AANcl7EIo-SY,31474 +mypyc/build_setup.py,sha256=rbgoioeFLbyK_KNuLYwwd9snN3kDDFv-Qa3QC8NzHgw,2653 +mypyc/codegen/__init__.cp314-win_amd64.pyd,sha256=QRn9nrr86QZqtCf--luVDBNE9I82joo_RLH7jh8-Wdo,10240 +mypyc/codegen/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/codegen/__pycache__/__init__.cpython-314.pyc,, +mypyc/codegen/__pycache__/cstring.cpython-314.pyc,, +mypyc/codegen/__pycache__/emit.cpython-314.pyc,, +mypyc/codegen/__pycache__/emitclass.cpython-314.pyc,, +mypyc/codegen/__pycache__/emitfunc.cpython-314.pyc,, +mypyc/codegen/__pycache__/emitmodule.cpython-314.pyc,, +mypyc/codegen/__pycache__/emitwrapper.cpython-314.pyc,, +mypyc/codegen/__pycache__/literals.cpython-314.pyc,, +mypyc/codegen/cstring.cp314-win_amd64.pyd,sha256=RSnZG2Cgk81m0oul1iPPu8bdGo7_kUpSH_72PIlf5Mw,10240 +mypyc/codegen/cstring.py,sha256=yB_SJmahDpTC7Xq3vlCstPZhhyLpRzEy9yHBwdqdIa4,2004 +mypyc/codegen/emit.cp314-win_amd64.pyd,sha256=-MOtIVsXrHLpMUsKJdtvA99hxLzCy4Ah5FgAZ_EeKf8,10240 +mypyc/codegen/emit.py,sha256=jobXvG1e8ilUR80tonwrDISOseM2Og5Y3LzgTfrZTa8,58255 +mypyc/codegen/emitclass.cp314-win_amd64.pyd,sha256=XgM0TApzwdkxYWAR1pD6xfBCX1-Ox6AX9qQ3a3A8Dgo,10240 +mypyc/codegen/emitclass.py,sha256=JMtbxdPbF_JA_7Vi244X_Z_gkshCn07ztuPEy4zMTm8,51670 +mypyc/codegen/emitfunc.cp314-win_amd64.pyd,sha256=JacJeaw2bEwjk7CPLkPCufAIpbo0kgd_ArF36c5Orvo,10240 +mypyc/codegen/emitfunc.py,sha256=rClZn2ddp7_6RbQI9movAXIdCkQmPu2S7twTmiocj1Y,38208 +mypyc/codegen/emitmodule.cp314-win_amd64.pyd,sha256=IURfjSe1YRrGXThjGoFNX2YckzIme4vQ08SkkKvsIUs,10240 +mypyc/codegen/emitmodule.py,sha256=yaWs_S3-diEOprte1muJkxmWKLSh-HHrf7yuuS_P6X4,62790 +mypyc/codegen/emitwrapper.cp314-win_amd64.pyd,sha256=ByAg7rK5V1I9u5fSKdVwLWfGl0mI_cp8c2Ee91wUo9k,10240 +mypyc/codegen/emitwrapper.py,sha256=18d3XwiTPwnc4-Ql68I5JxwLVEI2gfzuFn6MTm8GRME,37886 +mypyc/codegen/literals.cp314-win_amd64.pyd,sha256=5jZ4drEsSxMCq0FOaPf5uJYAbZ6Cs0_yfapEMYF4Mpc,10240 +mypyc/codegen/literals.py,sha256=ZTD77KLDI_B6TfJs1HSatKa5DUMVzbeJs66lXuA8lGY,10602 +mypyc/common.cp314-win_amd64.pyd,sha256=P-0qRRrLqdqN7I19xFASk2O5935sk9Xq1OSi4-FY6RY,10240 +mypyc/common.py,sha256=csTeTjoc3kIjnkbmG1wK29xUHeT2BEJ9ihSMPnuTYvc,5131 +mypyc/crash.cp314-win_amd64.pyd,sha256=8t7h418p2Xuy2aCuBIZo_g-QR9mga-F4FhY9331It7g,10240 +mypyc/crash.py,sha256=ULZHLQqJqSK8oFBsoDvr1eOCLAIoe2lwkVCDi-f9eww,953 +mypyc/errors.cp314-win_amd64.pyd,sha256=eHLPJ1cfIoDXx5fp0WnAeIt4SLU8M3X2sOkOhoha6MA,10240 +mypyc/errors.py,sha256=sUkIPSWQtn4dksR52iCGMwTEmW8CZGiIdggWJzPYNRk,1104 +mypyc/ir/__init__.cp314-win_amd64.pyd,sha256=-3rSxLFCLRkuP_NLjeLckYg6nlWapbBhS5Rkwl5atQc,10240 +mypyc/ir/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/ir/__pycache__/__init__.cpython-314.pyc,, +mypyc/ir/__pycache__/class_ir.cpython-314.pyc,, +mypyc/ir/__pycache__/deps.cpython-314.pyc,, +mypyc/ir/__pycache__/func_ir.cpython-314.pyc,, +mypyc/ir/__pycache__/module_ir.cpython-314.pyc,, +mypyc/ir/__pycache__/ops.cpython-314.pyc,, +mypyc/ir/__pycache__/pprint.cpython-314.pyc,, +mypyc/ir/__pycache__/rtypes.cpython-314.pyc,, +mypyc/ir/class_ir.cp314-win_amd64.pyd,sha256=r5s7MMlYSkCbP8HmG4mU4Gckm36NXHKxxcjDY7meBoM,10240 +mypyc/ir/class_ir.py,sha256=fb0BEd46LQ1-_pECqso1XJbAQfwr4K4xW6YuE1E7zrg,24168 +mypyc/ir/deps.cp314-win_amd64.pyd,sha256=-7b3fc98F3SiVpbVtBEJBWzsj33qBdXfKropnxZIU3w,10240 +mypyc/ir/deps.py,sha256=iAOPw_oD2i5MgmZSZUM7DPGOjv0DvGGnT6bvlSMmLL8,1877 +mypyc/ir/func_ir.cp314-win_amd64.pyd,sha256=tbG38dQsaorsqP_gVbU4J0-kZXAacO6dV1kLzeGcgt0,10240 +mypyc/ir/func_ir.py,sha256=ERRu35X1ZWirhIhqbhswpN9cv1-q7ZgWWU7QkPVPf2g,15944 +mypyc/ir/module_ir.cp314-win_amd64.pyd,sha256=vjsbE6yTNGCTdkyJ637VwvnUwSack8pIe1tpDoFSXac,10240 +mypyc/ir/module_ir.py,sha256=nAr2VjXu5zDPO5189iZTj-DT2aWqei4vHd7y6C4qwTI,4517 +mypyc/ir/ops.cp314-win_amd64.pyd,sha256=bWycUeuI6QugVd0xJXa-msMBJIqYVPiF_0sFnu6Pe7c,10240 +mypyc/ir/ops.py,sha256=na-hk3pCi2eiEvQAt_3aw9_MESbRnpvhjjMQmOYSyi0,62481 +mypyc/ir/pprint.cp314-win_amd64.pyd,sha256=gJsNy7WtnwPAGBLyHgwJALCM_xfjkpGBjxkmveZnrio,10240 +mypyc/ir/pprint.py,sha256=yngmVjQYWb0frc_JdP32i7ZTUph07n6kOQMRMRTf8oo,18668 +mypyc/ir/rtypes.cp314-win_amd64.pyd,sha256=I4dk9IZagNpkMoXzCoVqemj9ULV4kfGceU0acoXzGeU,10240 +mypyc/ir/rtypes.py,sha256=JNRslpTAg2cWUCoBUoTTTY8dQhhIosKJrb0l-x7M7aI,46940 +mypyc/irbuild/__init__.cp314-win_amd64.pyd,sha256=1C-Z4ujM_oVSTvb8jciWzfX-akPEeC0uTFgBdXa6-wM,10240 +mypyc/irbuild/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/irbuild/__pycache__/__init__.cpython-314.pyc,, +mypyc/irbuild/__pycache__/ast_helpers.cpython-314.pyc,, +mypyc/irbuild/__pycache__/builder.cpython-314.pyc,, +mypyc/irbuild/__pycache__/callable_class.cpython-314.pyc,, +mypyc/irbuild/__pycache__/classdef.cpython-314.pyc,, +mypyc/irbuild/__pycache__/constant_fold.cpython-314.pyc,, +mypyc/irbuild/__pycache__/context.cpython-314.pyc,, +mypyc/irbuild/__pycache__/env_class.cpython-314.pyc,, +mypyc/irbuild/__pycache__/expression.cpython-314.pyc,, +mypyc/irbuild/__pycache__/for_helpers.cpython-314.pyc,, +mypyc/irbuild/__pycache__/format_str_tokenizer.cpython-314.pyc,, +mypyc/irbuild/__pycache__/function.cpython-314.pyc,, +mypyc/irbuild/__pycache__/generator.cpython-314.pyc,, +mypyc/irbuild/__pycache__/ll_builder.cpython-314.pyc,, +mypyc/irbuild/__pycache__/main.cpython-314.pyc,, +mypyc/irbuild/__pycache__/mapper.cpython-314.pyc,, +mypyc/irbuild/__pycache__/match.cpython-314.pyc,, +mypyc/irbuild/__pycache__/missingtypevisitor.cpython-314.pyc,, +mypyc/irbuild/__pycache__/nonlocalcontrol.cpython-314.pyc,, +mypyc/irbuild/__pycache__/prebuildvisitor.cpython-314.pyc,, +mypyc/irbuild/__pycache__/prepare.cpython-314.pyc,, +mypyc/irbuild/__pycache__/specialize.cpython-314.pyc,, +mypyc/irbuild/__pycache__/statement.cpython-314.pyc,, +mypyc/irbuild/__pycache__/targets.cpython-314.pyc,, +mypyc/irbuild/__pycache__/util.cpython-314.pyc,, +mypyc/irbuild/__pycache__/vec.cpython-314.pyc,, +mypyc/irbuild/__pycache__/visitor.cpython-314.pyc,, +mypyc/irbuild/__pycache__/vtable.cpython-314.pyc,, +mypyc/irbuild/ast_helpers.cp314-win_amd64.pyd,sha256=SrPZDQiRD9gQikkP8yUuNp37mVWBPa5FQ1Zyv_YXT1Q,10240 +mypyc/irbuild/ast_helpers.py,sha256=aM2zAHB_ZsumV6OWOSnl7StCjhzlLnOUjlXbr63aR4Y,4339 +mypyc/irbuild/builder.cp314-win_amd64.pyd,sha256=l5vVlihVk6mfoI3Oe3JI-vXUZUzGntN8Pt2tqbG7bso,10240 +mypyc/irbuild/builder.py,sha256=jCUDjnnB8Pi_No-RJ9GRqOPAtS4tXNtxBZ2jkj5GWCg,71361 +mypyc/irbuild/callable_class.cp314-win_amd64.pyd,sha256=x7poYGzv5e6KsgiCyNF2Omg5nrbl35qJkrodW5HMPxw,10240 +mypyc/irbuild/callable_class.py,sha256=TLQxOrZL-UR_NaYYUYyiJWqmZLg1kV0TLWCvKxmLatc,10378 +mypyc/irbuild/classdef.cp314-win_amd64.pyd,sha256=gVbV1JUQkYU7-IfYv6SSb0rf6lXS-_OHr0k-aZzkVRI,10240 +mypyc/irbuild/classdef.py,sha256=5JlX4z-0-Rxvrx7EVgiA7jHBqSOxPdG1dwqe6cjVvaQ,38980 +mypyc/irbuild/constant_fold.cp314-win_amd64.pyd,sha256=WXeTaB4vohwlXpzfeJklPyLewkrB_wctZYYuwzVaqxk,10240 +mypyc/irbuild/constant_fold.py,sha256=7qIVEJSgabHIQ37ydZq2wearPFtwn_ztRy3670RhMw0,3335 +mypyc/irbuild/context.cp314-win_amd64.pyd,sha256=bNjd4VYxyJ1G5f71DKhbJ6m6gPlxcjG16qupU0ABStg,10240 +mypyc/irbuild/context.py,sha256=Z1hJYqzIocihndm_rcNZ50uNtFq6GcIdCYh462jT64E,7858 +mypyc/irbuild/env_class.cp314-win_amd64.pyd,sha256=3kql5JxrqXeK-DCwkIpgXzvDqru-jGrh_HcBzKVk7rA,10240 +mypyc/irbuild/env_class.py,sha256=R0i7Fxvzm9zDIK4w_ZBC9V2JOpG-GodPF3fhtt1EJ8I,13034 +mypyc/irbuild/expression.cp314-win_amd64.pyd,sha256=Lc-bC_21gTJauNoz0kNlVovCkH5A1IfC_d2HueulTDg,10240 +mypyc/irbuild/expression.py,sha256=Q-GN14QvP4qzo_UVFASKU07USksQON8hi5B4fJEbvFQ,48353 +mypyc/irbuild/for_helpers.cp314-win_amd64.pyd,sha256=JF3_KRbpgaDxAgRO-qOrQOCX5owG82fnDc_Rxpc0SYE,10240 +mypyc/irbuild/for_helpers.py,sha256=dskqoNgteL_bTIPo6WNOUHkYASLJUv93rF6CdEJol2U,52539 +mypyc/irbuild/format_str_tokenizer.cp314-win_amd64.pyd,sha256=8JGY6s7gM-StuNvfSIGoeDqd8Lf1Kx2-Dh0RkGSJQ64,10240 +mypyc/irbuild/format_str_tokenizer.py,sha256=SI8tBdKISJZ7u8uqr67YCOvv1V05Nz_cGAKvGjka0zc,9491 +mypyc/irbuild/function.cp314-win_amd64.pyd,sha256=NQzxpKb8SL11xTShy7MDj_-u9mbXAHoo2bDW6-x0xXg,10240 +mypyc/irbuild/function.py,sha256=Li5AnagBqBXLX-E9wPXwNEynmG-pXB1qlER7G7Sm8q0,50088 +mypyc/irbuild/generator.cp314-win_amd64.pyd,sha256=-TG4r3nmnPlG2XBkdzv6kBdTC4IJdWqAU2I6jezsEoc,10240 +mypyc/irbuild/generator.py,sha256=srx_C-ZyzHKa_7PHM-qE5NNsVAo15SvYbJfQ265tyb0,17139 +mypyc/irbuild/ll_builder.cp314-win_amd64.pyd,sha256=pIHCMKBRxpOdxcuBiY_QUPNIYdjBxy_WAUDlGdpX4zc,10240 +mypyc/irbuild/ll_builder.py,sha256=rtLMVRMf1Oil5yA-1QTqpeFRuSGANs_KG77gN3tt0CE,126260 +mypyc/irbuild/main.cp314-win_amd64.pyd,sha256=oEKcdwXCjyH7_kugipP3pBB02bokcLeOBxaY4IOuG2Y,10240 +mypyc/irbuild/main.py,sha256=AXVfML8txMS7qavazawaIJq2RrLD_8PLrMScItonBXY,5438 +mypyc/irbuild/mapper.cp314-win_amd64.pyd,sha256=ruVN7_HZQF6BMzs5ZOThERUC2K5mIJuV12TBH-ImAhI,10240 +mypyc/irbuild/mapper.py,sha256=KFLyJxngqkaPpeGE-TBGt1RxRr_htcONi-bSI5NQeto,9861 +mypyc/irbuild/match.cp314-win_amd64.pyd,sha256=xjFlRSkDN01cxgjUZCkcHCXFSzlE2LoGQzyMscait20,10240 +mypyc/irbuild/match.py,sha256=c-HbpkpZUgVS-ULCgVHRlCkp9efSzAfOEMCwayn8beA,12420 +mypyc/irbuild/missingtypevisitor.cp314-win_amd64.pyd,sha256=SYDroe68XuDK8PNsmRyXZzMURuoBmm69BUpCWEyg1oY,10240 +mypyc/irbuild/missingtypevisitor.py,sha256=awXMMkRhXZq0AnbSGKfUzs9Lx526gFvDuiYaKjeqAq4,699 +mypyc/irbuild/nonlocalcontrol.cp314-win_amd64.pyd,sha256=zCU7D72fBmUgf2Vta9z1au1PlywO8xp-RG3wKJ4isrY,10240 +mypyc/irbuild/nonlocalcontrol.py,sha256=3Afxmw21hnY2EeOdDCgSmVElV4qNGM1o8b5FGO6FVck,8035 +mypyc/irbuild/prebuildvisitor.cp314-win_amd64.pyd,sha256=2gj_NTgHMTFP_lYwbY4uulE_T_kXNUur5d_1l_6Wcjk,10240 +mypyc/irbuild/prebuildvisitor.py,sha256=JCbt7jv8_vR5LRtkhixhtA0KKbXKuS4fG02pvvBXeCM,12085 +mypyc/irbuild/prepare.cp314-win_amd64.pyd,sha256=QNlQupX0EaZWAMhGNeUwIr8lJJSeiQ0LLfF5BE1Vj2w,10240 +mypyc/irbuild/prepare.py,sha256=oOl9GsYAklOXG6dTAIu8g1afdHfvrYSbsos5p5-ozWs,35992 +mypyc/irbuild/specialize.cp314-win_amd64.pyd,sha256=xTWI3wUO28I6vLCZ_9xZEXB0p1KQYQYRkEDanEl6qKQ,10240 +mypyc/irbuild/specialize.py,sha256=j11nSFUlcCvTUU7gFt0-xQpNJxsweDcHrGnKoOR7rfg,56112 +mypyc/irbuild/statement.cp314-win_amd64.pyd,sha256=qAA4MerD5Nhzd1ZpkD7nPrCuBbBM0u_-wXJQr0_eTI8,10240 +mypyc/irbuild/statement.py,sha256=CoWJYC7extK7SZXUZERMaOb5vcc11dLDw7BFUrqGrm0,53212 +mypyc/irbuild/targets.cp314-win_amd64.pyd,sha256=mNKqI13--GrJGY7NLne5qcx5jMykHlHLqHVHJMCe7Xs,10240 +mypyc/irbuild/targets.py,sha256=r12ynPhUaTmIgnmV5c5eNbWJbqf2_L12RtW_PIQXhq8,2313 +mypyc/irbuild/util.cp314-win_amd64.pyd,sha256=P5QKbMK6G_4FfZ_AZYqcATPM863Q1hSVJf4TJEgrqn4,10240 +mypyc/irbuild/util.py,sha256=PF1wZAzRKo8eF1rSNR-zwefph-6TPf-HTx8z03i-MDE,10094 +mypyc/irbuild/vec.cp314-win_amd64.pyd,sha256=nnYCqOPDYnV0wV7RKRTsbR-3GRZ_-0RJCltHvVc61vo,10240 +mypyc/irbuild/vec.py,sha256=tNbM_s23ZVx9RxiyVboKbjhJa7Qytd_uzHDCVAKvgmM,17774 +mypyc/irbuild/visitor.cp314-win_amd64.pyd,sha256=mGPN1jxjolTLwNcfb9MGhCFuv6Fcnz1t_OXtRH0VLIk,10240 +mypyc/irbuild/visitor.py,sha256=u9q8PNSuoltkukmZkhegjCqIfQ2XIsst-Q72hd8uTOY,13305 +mypyc/irbuild/vtable.cp314-win_amd64.pyd,sha256=yG5Hd0HussrlS5388y6opYAIgt0MjDkEJXmJQaC0zcs,10240 +mypyc/irbuild/vtable.py,sha256=7OZtwAaX90up3daQb793uVlqA3q2l6WUgTAeKwrbfAI,3333 +mypyc/lib-rt/CPy.h,sha256=LwzpGVowkZSEpoScf8mtsTA71-Jx68TtWlK8v3sFSU8,37907 +mypyc/lib-rt/__pycache__/build_setup.cpython-314.pyc,, +mypyc/lib-rt/base64/arch/avx/codec.c,sha256=urTWLTPI5DOFUKQEM1eptpEgACXA0PK9oXCNZMzd0o4,1691 +mypyc/lib-rt/base64/arch/avx/enc_loop_asm.c,sha256=5x7KgCny9gCuv0Oo50lNCo2LDt-tPOYg3t5vyTaW-kY,9314 +mypyc/lib-rt/base64/arch/avx2/codec.c,sha256=3HbccwvMmDoP_QS-B6YzXIOgY51vp7FDe9m838Kv5tk,1398 +mypyc/lib-rt/base64/arch/avx2/dec_loop.c,sha256=hq_yeFr9wrlOXrU4lPUQ--xpW1D0_m6FJkenA1Yt-fE,3229 +mypyc/lib-rt/base64/arch/avx2/dec_reshuffle.c,sha256=_qr6r3_QSicmOgl8tNMjoSX9UAR0tLY2QTk6dpwDt3Q,1304 +mypyc/lib-rt/base64/arch/avx2/enc_loop.c,sha256=-dydoBxKt1X_sTVpSYKZJlR8sfIeYLUJOzv_6HD60XM,2293 +mypyc/lib-rt/base64/arch/avx2/enc_loop_asm.c,sha256=LseS09A_syLXv0C4n5C_loPIGg3B0sjOZZ5UVZ3D-po,10453 +mypyc/lib-rt/base64/arch/avx2/enc_reshuffle.c,sha256=CWOGlvQQEsOXzCjkA5KV5EYlgAyXqyMthfD09qQbJ8w,2714 +mypyc/lib-rt/base64/arch/avx2/enc_translate.c,sha256=ZbxW4tT0V5uZEOqiium6CtRnXaYK1gd-JdG-P77RRSM,1251 +mypyc/lib-rt/base64/arch/avx512/codec.c,sha256=8244HSPoAsilcDbpbI2pvPJMuqO746VNUb5wGsAbUI8,1139 +mypyc/lib-rt/base64/arch/avx512/enc_loop.c,sha256=c264nxVYfl3m72ArgsHGol9-FQW4e4yipzTm1yoSMW8,1506 +mypyc/lib-rt/base64/arch/avx512/enc_reshuffle_translate.c,sha256=lESfOAK6yVviMyCwAQrnpWQJdxds0m109czGSbxeuRw,2277 +mypyc/lib-rt/base64/arch/generic/32/dec_loop.c,sha256=XCo00web4l5L98dDc_4ZPjdwRhwJYJJyv6zTg2ia3kM,2218 +mypyc/lib-rt/base64/arch/generic/32/enc_loop.c,sha256=8WMMHEf-xmo5f6Z7DY5JVaSvAaf80pziA9vm--GvYj0,1932 +mypyc/lib-rt/base64/arch/generic/64/enc_loop.c,sha256=6jBEKBphrKK0f3a4ZUg4pY1YXvEnVW5yvJcXtoMAOyE,2128 +mypyc/lib-rt/base64/arch/generic/codec.c,sha256=7yiK4he-nAvRAMS3RF2bkL3Q0k19OusjyAjcuLniSAM,790 +mypyc/lib-rt/base64/arch/generic/dec_head.c,sha256=XG7_4Z7O5zIWkYbyhiCuyGz8kQOT1P3hd73WJDuGSsk,791 +mypyc/lib-rt/base64/arch/generic/dec_tail.c,sha256=l4QXLn3bJYYhPJzTz2Hi1OuISw0svJAsgLkMllTCX6s,1774 +mypyc/lib-rt/base64/arch/generic/enc_head.c,sha256=gY1NrRIVDBKz1krrqbmBFQCXvW7TsISu6SP2h0Ty1W4,585 +mypyc/lib-rt/base64/arch/generic/enc_tail.c,sha256=oIaNxx1iv54RB_sjfCt9y3iwcKeYVDrXmQdj28RT6sc,637 +mypyc/lib-rt/base64/arch/neon32/codec.c,sha256=OSnQicSBOazJecWFtqLAJswxO4XFQ_6zXUEyYyDzlwo,1984 +mypyc/lib-rt/base64/arch/neon32/dec_loop.c,sha256=RP9UALT25-0h9y0ZZT-UfcUPGPnRAdrCY7DFT_qQwtY,2906 +mypyc/lib-rt/base64/arch/neon32/enc_loop.c,sha256=9OFz_fJlYxFHOEWSqftSE7D1lrK2wYXW0XswNcZ1K1U,4655 +mypyc/lib-rt/base64/arch/neon32/enc_reshuffle.c,sha256=1KiwN8mbkMlHGt1Vdh9ZqFCxmPSGbFeirZF1r_KNr6o,982 +mypyc/lib-rt/base64/arch/neon32/enc_translate.c,sha256=6p36hJofziya1lgosMW2X7Q8Hp6pU01-DJmWsj_iNQw,2116 +mypyc/lib-rt/base64/arch/neon64/codec.c,sha256=iPS0ePONE6VHjSAPcna41Dy3adhNnbp_tOhv78fJfx0,2190 +mypyc/lib-rt/base64/arch/neon64/dec_loop.c,sha256=QDwhq_CvCMo6p1JMjNW5S8-Z5woMVDxMeExeZXxO_qA,5263 +mypyc/lib-rt/base64/arch/neon64/enc_loop.c,sha256=blYyAtfGMaOj1jhqaeHbBxRvyXRbJEzXsmv2S5aIL-4,1857 +mypyc/lib-rt/base64/arch/neon64/enc_loop_asm.c,sha256=1EyqW3h__LuKAXbvQjSL7JZolvzoiEVdcgDXwDMalwU,5617 +mypyc/lib-rt/base64/arch/neon64/enc_reshuffle.c,sha256=re6811Zr3Tzd98VPMWfeTD6gi4LTznykA9QIqTxoEpc,988 +mypyc/lib-rt/base64/arch/sse41/codec.c,sha256=FZ5gJbgm_89_eK10ELRqskzCDerJDjlxoegiu2zb-kk,1456 +mypyc/lib-rt/base64/arch/sse42/codec.c,sha256=OkPETkcPsuWC3uqz3aNJ3dIrnlOSlwaucfJUe8Mkzng,1456 +mypyc/lib-rt/base64/arch/ssse3/codec.c,sha256=p6vpLANpGMSQriymltKOkGOBQwoeuCDJCpymNSs1MR8,1540 +mypyc/lib-rt/base64/arch/ssse3/dec_loop.c,sha256=ijGEu4Sqie-yqQe6SBIsJUCYht___loZE-QWh97LOJk,6891 +mypyc/lib-rt/base64/arch/ssse3/dec_reshuffle.c,sha256=1he_eNgNRnjYzq8ggN_UQhm3iu6EMrfWEILfJ_PVDII,1118 +mypyc/lib-rt/base64/arch/ssse3/enc_loop.c,sha256=j04w3bGmfUhJfG1lfa5Q7L_R2NztzS96A-r_veHeTLg,1549 +mypyc/lib-rt/base64/arch/ssse3/enc_loop_asm.c,sha256=x8xD-nt8hZbrL40GvwAZHTchbCfBENgW_sBZ_AB3New,9310 +mypyc/lib-rt/base64/arch/ssse3/enc_reshuffle.c,sha256=PmfzUCjYt32d6GfeI-Y7yhISywFON1k63kT34PqRZAI,1514 +mypyc/lib-rt/base64/arch/ssse3/enc_translate.c,sha256=MubLb6H3NQxyBjDnqFednwREHp9BSpGr_uk_riGL62k,1171 +mypyc/lib-rt/base64/codec_choose.c,sha256=bc_oLC_HVv4jNnXKuJ3clxJZHpa8uCDxR_gnri7zg3w,7590 +mypyc/lib-rt/base64/codecs.h,sha256=UJ-aFppCj4u4NoCv9WJtqeBWXYMF_JY8Jg8p1PoerUo,1188 +mypyc/lib-rt/base64/config.h,sha256=1ObCnDkVHLBW8jezBLG-VEtKuxMrnp4RmE3HxTD7Ej8,600 +mypyc/lib-rt/base64/env.h,sha256=7BFrEAjO7eymj4U3t-GHkDb3CgDlRTvFOqQLl_ERWvQ,2453 +mypyc/lib-rt/base64/lib.c,sha256=Wsr16GjZknZVF19smY382ZXxbZb94JcL28jkFB0G_Wo,3270 +mypyc/lib-rt/base64/lib_openmp.c,sha256=5UyZ_yWMjmyY3Lgr8CTAPnSNB7BgJDq-SowgsWKFaxo,4457 +mypyc/lib-rt/base64/libbase64.h,sha256=NTBKkl1S6J7OGEqOAQiHIwEuNcS9CFC8HM7t4y7YRnY,4789 +mypyc/lib-rt/base64/librt_base64.c,sha256=QNMU-YdCSPGSj99tZgm7iFhtSPil9polk5c8yfUgJKY,11681 +mypyc/lib-rt/base64/librt_base64.h,sha256=UsANYtfzM__3EwnZPaHPCCsYQ4RoZj71brWXH8tCQS8,1754 +mypyc/lib-rt/base64/tables/table_dec_32bit.h,sha256=huHBM0bQhO-qaY4VKQXZd_sPGr-hGuLoCQAsBYULbo0,25258 +mypyc/lib-rt/base64/tables/table_enc_12bit.h,sha256=d5pGp6iJjmRvuy53oS9QDQ_om9Ra4Y9BqnKTyRDA8mE,74858 +mypyc/lib-rt/base64/tables/tables.c,sha256=8EMu3og65__OzaHO_lbIk8ZMtdXyHqe4j7VpLRfPggY,2051 +mypyc/lib-rt/base64/tables/tables.h,sha256=Vnp9YLfiaFlKzM3JWSi3FJFG53rdzrMluwz1XqSRSvI,704 +mypyc/lib-rt/build_setup.py,sha256=rbgoioeFLbyK_KNuLYwwd9snN3kDDFv-Qa3QC8NzHgw,2653 +mypyc/lib-rt/bytearray_extra_ops.c,sha256=8psEK_k3gCa8MOdhYBEw9PN2AET8AiFvf9Ay9wxdOFc,122 +mypyc/lib-rt/bytearray_extra_ops.h,sha256=FaaMRumr8tfrFry10gy-4sI58KmzPYrOHAwL2D8PcJA,182 +mypyc/lib-rt/bytes_extra_ops.c,sha256=C4QRQH0hoXdwIrr5sY9CRWZmt07nTldOvXwmXNfpszg,1531 +mypyc/lib-rt/bytes_extra_ops.h,sha256=reksqOE75L9aGqtAucfUh7E2eRmxdSX_DGLlLTvCBQ4,896 +mypyc/lib-rt/bytes_ops.c,sha256=O7F_GJUvJe0MW2KSI9Ogc5YpadNzkFCP8qVdnlQsVIc,7018 +mypyc/lib-rt/byteswriter_extra_ops.c,sha256=Fgg3mVx8IbvYZKCyiAibCQkORPxh8pwtB3xtNIVN9ms,1377 +mypyc/lib-rt/byteswriter_extra_ops.h,sha256=q8SYxozwj2D83ECkiiHm7awEd2UkZqZX-lMJ58KhsDc,9460 +mypyc/lib-rt/dict_ops.c,sha256=C9xc53PPthOZzu9ZlrbHk72zLrmOt1WQe50pQUscx1g,12310 +mypyc/lib-rt/exc_ops.c,sha256=4Uw3Yf99IsGhUa7lFREBokqVUxUd49qqpIXd54DLrU0,8337 +mypyc/lib-rt/float_ops.c,sha256=MdcyrPHS44ct8ELfLnGEuUXveD7Kiy4onTYSSHwKCiU,6326 +mypyc/lib-rt/function_wrapper.c,sha256=gmi5h5HuzscLXUumCa7BlGvolbebYth3uy46AqS5QU4,8723 +mypyc/lib-rt/generic_ops.c,sha256=yTHiCG4diW9B5a407M-5wQlIEqiCFs_eKVCMavHC1Zs,2419 +mypyc/lib-rt/getargs.c,sha256=EAGGVcJKuNWvZ4r_Lfy5hUviqZKObokXADyuRR-R8lU,15769 +mypyc/lib-rt/getargsfast.c,sha256=NEVdecCZduWjuBZlQK30d4jO-_a8kxPFFmzTIIwOxrs,18808 +mypyc/lib-rt/init.c,sha256=R6y6CoucAaMijQfTftiD5cqfjJWNT-VqKsg89GM7-Ko,807 +mypyc/lib-rt/int_ops.c,sha256=ijRFnrtdhgV1czE3b8vNiAkDPbRAunQP2FUdRZMmr6k,21587 +mypyc/lib-rt/internal/librt_internal.c,sha256=VgfyevQ0a2AIVbX5pjd_YR50ySRw7FC4Poepu4mQbQU,31116 +mypyc/lib-rt/internal/librt_internal.h,sha256=3z33EzjYalaS_AURAlLcDrKJkn56nnHunGMwfcBx5CA,5202 +mypyc/lib-rt/list_ops.c,sha256=Aso05zNE2Pb1LhhZ2rJh96fncH9ov2FznugXemPKPyc,11625 +mypyc/lib-rt/misc_ops.c,sha256=-lVvAh7zgwWXlrBgAXsC95tjXvdi22k5bH5Bjg-dXRc,52384 +mypyc/lib-rt/module_shim.tmpl,sha256=HciO4-fZWZ4de_Xjb1P3n20ajJuab5tt5INgt5Pab7g,670 +mypyc/lib-rt/module_shim_no_gil_multiphase.tmpl,sha256=dEyyzaG6xmIgCOyWNX7qC4YjhgSHc_5_6yNG-WbUKUo,1205 +mypyc/lib-rt/mypyc_util.h,sha256=PN32V6x4hpip7ifMWoUc6zC0eVzcmeBuLv2Eg5KqgDc,6103 +mypyc/lib-rt/pythoncapi_compat.h,sha256=TF6SIFdR6KYE_FlWc-2JL8GcZGpsdf_LoQSEj0ua0_o,70628 +mypyc/lib-rt/pythonsupport.c,sha256=xPeVp4cOPw3zd60Gh1xLFSIb7CILMCWb8pZVtsoNa0c,5252 +mypyc/lib-rt/pythonsupport.h,sha256=Au9MSk0mfPBOkOr3hQ1kyfmmqAU2Tq45jv_SEPWVcuI,10320 +mypyc/lib-rt/set_ops.c,sha256=-fImDML6Aobq7-NCbb28O19g6C2YyHkGJ6NF1gueHJM,351 +mypyc/lib-rt/static_data.c,sha256=VFK_GRXuRIiBWO4sqcazKITjoAESHnKwhToNrFa-yqM,2651 +mypyc/lib-rt/static_data.h,sha256=ih4pBQlopFRhUdj8R8TUGAKrS7ckNNZtcX7wxa9cKw4,1569 +mypyc/lib-rt/str_extra_ops.c,sha256=CSxw5KMIPiDLWaz1Ezbr2AqNQiszTKtwHDiyO5nMXSw,147 +mypyc/lib-rt/str_extra_ops.h,sha256=lfWF7LgHyvDKlUJszbjiGPDIpEHUVWum6QFXZXyxM5k,865 +mypyc/lib-rt/str_ops.c,sha256=4eVj_n35JzuhQBx3q2gM2IcNkKOOw2YFycEmmm7VfrU,26284 +mypyc/lib-rt/strings/librt_strings.c,sha256=66K-kzGHU2zrBivNGRmeszABl4TikQ0mlsVVO1eu7-8,39842 +mypyc/lib-rt/strings/librt_strings.h,sha256=XkeeqKEWIY_WbAR6DC_7UQVqgY1jq727iLGj_v3MgQ0,4285 +mypyc/lib-rt/strings/librt_strings_common.h,sha256=Bp6pxoZlfKTOjSyQXtC6tioyQJDVdG-Z_Rfg66_jkcQ,11644 +mypyc/lib-rt/stringwriter_extra_ops.c,sha256=AcMzbrJWbGOs9-u0LFePXV0b6g4lBTTi5ukjc3uYmhg,390 +mypyc/lib-rt/stringwriter_extra_ops.h,sha256=TrpFPWYrSwG6rL2Q9UADsDF16ywrgKE0U887Utiq7eE,2200 +mypyc/lib-rt/time/librt_time.c,sha256=pCgP5XfC2JYGFfNDZLMNnhYgN4HMnJpIDwlmhDm-CFs,3843 +mypyc/lib-rt/time/librt_time.h,sha256=IlttzlxyKB4WnkyXPQky-BS4kClS83cPAKgZOLirxHs,1773 +mypyc/lib-rt/tuple_ops.c,sha256=Fe7Tj8ZVF6HTVrflq9um-rDCduF-M846sJ1TYbpX4p0,1956 +mypyc/lib-rt/vecs/librt_vecs.c,sha256=pAm4ZSRHKWx85rhH3F8JC1cGBNj6YizWXoSiQsF3Ngk,32578 +mypyc/lib-rt/vecs/librt_vecs.h,sha256=31OXD3qo8Lxy9CJROH7Fg5WO63jw3HqI1gTyioipuhc,25801 +mypyc/lib-rt/vecs/vec_bool.c,sha256=ehJc_Bqr9aPe4HTodZvLFCEjGUnh8CgF8c6Fv1AOmlo,550 +mypyc/lib-rt/vecs/vec_float.c,sha256=lsEZVaESGcqW0TdPBxm24_0h6NTMqrpZ8KCePh2QpRk,565 +mypyc/lib-rt/vecs/vec_i16.c,sha256=tUgRuDiETfx728SHvDOs_9LM3fWfhXPrvfToP4Pt2iw,540 +mypyc/lib-rt/vecs/vec_i32.c,sha256=87yOpNOs7-lWl1CKkHWTqUiMIqUGXp_3vEHBAjZt6AY,540 +mypyc/lib-rt/vecs/vec_i64.c,sha256=ycHcMxNCU-fLtyKG0yh5xkRIMVz_89rka0hK7XmEETQ,540 +mypyc/lib-rt/vecs/vec_nested.c,sha256=RyCfLHRsyW6jAb2QH1mz3EolRJmqwVfEbHxuVodmruI,15911 +mypyc/lib-rt/vecs/vec_t.c,sha256=g8Ox19H9M323Oss-KbXMvrpMvkIxwmy124IEO0Hc8qQ,14945 +mypyc/lib-rt/vecs/vec_template.c,sha256=2y-5VB5hd46tiQ2t_O_2LGlop9nbqfOWvtbAYAqY5uU,12055 +mypyc/lib-rt/vecs/vec_u8.c,sha256=OVzKEpLmEj7Nn4QVMKtbh3mPhLbUb5TB0QAGimqYa8k,527 +mypyc/lib-rt/vecs/vecs_internal.h,sha256=92eiZe_4rq00xg00kl-MDL2d4PE7oktsgL403uZCrRg,220 +mypyc/lib-rt/vecs_extra_ops.c,sha256=O0j9Lfs_7q5_S51O35Y3bx1s0dEHzzsKd6qAQoDYcGE,299 +mypyc/lib-rt/vecs_extra_ops.h,sha256=iWowopsv3jvqZNqXvnwLtvvNXyvFog5fmvHik0yawAU,323 +mypyc/lower/__init__.cp314-win_amd64.pyd,sha256=Hzcux7o3rseOFUrT2DXVmtT55hOC7rnrzn8oBhV9B3Y,10240 +mypyc/lower/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/lower/__pycache__/__init__.cpython-314.pyc,, +mypyc/lower/__pycache__/int_ops.cpython-314.pyc,, +mypyc/lower/__pycache__/list_ops.cpython-314.pyc,, +mypyc/lower/__pycache__/misc_ops.cpython-314.pyc,, +mypyc/lower/__pycache__/registry.cpython-314.pyc,, +mypyc/lower/int_ops.cp314-win_amd64.pyd,sha256=bc1lQkNlLBC-JWsENSWsYhZiCXpe_wXfWeGFoIXJr2w,10240 +mypyc/lower/int_ops.py,sha256=3YiQ1qc5cjNJwp_Xm_8tztYcBcKvxr1_1YPmCqACOnY,4777 +mypyc/lower/list_ops.cp314-win_amd64.pyd,sha256=Rfpa20NOIvALWabLmJtB2q3fNRuO_sbHqNtFuZQg8_c,10240 +mypyc/lower/list_ops.py,sha256=OZP8EEVq-IpEUm8lBnQqKNB3BvJDu3ILJtbm5_dgJyc,2522 +mypyc/lower/misc_ops.cp314-win_amd64.pyd,sha256=RxNUdhvG2DYtJHmmoUHE2G7vdALkhzIGzy0-363xjzw,10240 +mypyc/lower/misc_ops.py,sha256=Nw5HXBjMmaCePpDQ54xiN9xlr8Tl5VsXl-Yo6znAeag,920 +mypyc/lower/registry.cp314-win_amd64.pyd,sha256=D0UTjc0lIoY-REeu4LBrEp5q5kCW4gkRZE1xuKLPPx4,10240 +mypyc/lower/registry.py,sha256=wbO1g9rZ0XldFPjNTVln6gxcZbH1fMcXLX03JftNEOE,844 +mypyc/namegen.cp314-win_amd64.pyd,sha256=d_z6-zgMoIuDlxG7rrP-zc0_DsX49DJfrBBYMjzzx_0,10240 +mypyc/namegen.py,sha256=c5p7yxxUyWqJRNqKmkVCR1xW0u45LbIrqTPnR0n-I64,4934 +mypyc/options.cp314-win_amd64.pyd,sha256=4_MCkuV7UXQntPTDQxdUpRDqRmQlHiFMu30HsnxD_j0,10240 +mypyc/options.py,sha256=nK8E1Ze1C8r8a0m9349UOWWhQxGPrJXgcUJWvjSl-Rc,3890 +mypyc/primitives/__init__.cp314-win_amd64.pyd,sha256=Co8Ih2Nlg5XOHhrYdnuXgqKbDVbGijGJk72o4RZvyyI,10240 +mypyc/primitives/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/primitives/__pycache__/__init__.cpython-314.pyc,, +mypyc/primitives/__pycache__/bytearray_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/bytes_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/dict_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/exc_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/float_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/generic_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/int_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/librt_strings_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/librt_time_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/librt_vecs_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/list_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/misc_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/registry.cpython-314.pyc,, +mypyc/primitives/__pycache__/set_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/str_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/tuple_ops.cpython-314.pyc,, +mypyc/primitives/__pycache__/weakref_ops.cpython-314.pyc,, +mypyc/primitives/bytearray_ops.cp314-win_amd64.pyd,sha256=Pw6eiz2yqzjy0euNX35y7PBHjYUdsiht39O_aCAJNDM,10240 +mypyc/primitives/bytearray_ops.py,sha256=_OZZkKJzFZHHYbn2A2muMrCc3vzRvVDcMXdVfxQWvBs,1387 +mypyc/primitives/bytes_ops.cp314-win_amd64.pyd,sha256=hDrFNK7LKC3hqc7dh8SRiLVsWQRGs29hql_TgN_CPng,10240 +mypyc/primitives/bytes_ops.py,sha256=Z08QDrqLaZS8F0uFrlAOGTX3QP8widaODeB4PUnauFw,4936 +mypyc/primitives/dict_ops.cp314-win_amd64.pyd,sha256=AmlaSn-SX1KmRKvNZJ5GjEDQyMvtYaRORgzOLuY4ODw,10240 +mypyc/primitives/dict_ops.py,sha256=PWEAZVXfGavfGGGA8kyVCwkD3-vR7Qrks13NACVF4wI,8825 +mypyc/primitives/exc_ops.cp314-win_amd64.pyd,sha256=Cnps-3p65GrvpHTdocZJJDQqhtWEPz5Zqee9WYIf0Gg,10240 +mypyc/primitives/exc_ops.py,sha256=JMmg41FKPOwGFxNWwIhSFDCqwD7GaItxPmWeDajNMQE,3650 +mypyc/primitives/float_ops.cp314-win_amd64.pyd,sha256=eVOkQZPinEC-ApfCXnseHXXnaZUPDSr8hRcgbbNY7YU,10240 +mypyc/primitives/float_ops.py,sha256=uWZfhN6ixM46o-Ryu9nRSLN-zopol8cnudIrnSRRf7I,4090 +mypyc/primitives/generic_ops.cp314-win_amd64.pyd,sha256=ik1U0g2-1QPsVd9c1fTtdYg2JMNfm2a56-fnRQprRRU,10240 +mypyc/primitives/generic_ops.py,sha256=PkAUT1YlfpwbeDkMNNLTwc01eCqmLPv3-kU0ZtwwWsA,11749 +mypyc/primitives/int_ops.cp314-win_amd64.pyd,sha256=Fcbvzy_0F4qREZWunwY41bK7espxoAjNgEPOCpsck88,10240 +mypyc/primitives/int_ops.py,sha256=53jqguUtyvAECGdm45ZZw4CvbJNh9XS8SS3s34LyRoA,10566 +mypyc/primitives/librt_strings_ops.cp314-win_amd64.pyd,sha256=ZKCCfvkdH1X5URRUeOtqD7Fb6xAAiqEyabMMVPgORkA,10240 +mypyc/primitives/librt_strings_ops.py,sha256=kwQlcx84KbQ9DarEGMoZY8gziaxnwgZYnmmLGnfsrAA,12903 +mypyc/primitives/librt_time_ops.cp314-win_amd64.pyd,sha256=rxmU7UvpeIG2V-LC2qmqLEivxqKviG1IQ9TW13aGOlU,10240 +mypyc/primitives/librt_time_ops.py,sha256=sywnuBEdxQRaf7_5WKdSapQa5re7BeJlUfttxnyQL4k,405 +mypyc/primitives/librt_vecs_ops.cp314-win_amd64.pyd,sha256=aIDpCyQqvlhk8Bxr_A91qa1GZNnSOVIuJy46-Cg7f90,10240 +mypyc/primitives/librt_vecs_ops.py,sha256=n67p6dP3ct6iovw-VFG2RMnbsBFCMp7MQ9h2K1OoA6c,487 +mypyc/primitives/list_ops.cp314-win_amd64.pyd,sha256=gii7FxxFu6LbuHp9_kygRuTmLsylMm6nouc9lT0zkYE,10240 +mypyc/primitives/list_ops.py,sha256=auDy4fR5yf-wGRpho0elbaZ5WPQMe9S-s6sxRcM3XVs,9121 +mypyc/primitives/misc_ops.cp314-win_amd64.pyd,sha256=Mm9JnEUoarI_B-1z76hOCDlg8C9DyeBlL3st6ch67tM,10240 +mypyc/primitives/misc_ops.py,sha256=Y3vXitX4T4e77X3pOoSueWJ6F6BjEk6x7S4s3IB3tqo,17949 +mypyc/primitives/registry.cp314-win_amd64.pyd,sha256=VdmF1MmHIlgR6PNc9B3Xaz21GOmt1wPnxiyNfCf5Huc,10240 +mypyc/primitives/registry.py,sha256=VkAhMsGIDbq8K_9Sf_PRh9prLlIW2BmeCIKBIoXT4KA,13239 +mypyc/primitives/set_ops.cp314-win_amd64.pyd,sha256=6zyB01NVtHwpPicdgGJrtJ3NIfkMSvjpFls2cL-kM-s,10240 +mypyc/primitives/set_ops.py,sha256=dgy_6M2ZuQglEYlf-AX1YNQPgaYK9uKQ9Vr3svMf768,3795 +mypyc/primitives/str_ops.cp314-win_amd64.pyd,sha256=O9iocu7MMIvBthwCPgZSr1yW3q7nrBN0EzVAVkw-yss,10240 +mypyc/primitives/str_ops.py,sha256=vDI3h9OB7KQZ0mNOSt1oFhRx-T7fqxwYZwTlS2RY6II,15715 +mypyc/primitives/tuple_ops.cp314-win_amd64.pyd,sha256=XBFt7sKWw1dIJVkBv2QcZFvbOcBpttmLYhAjvLpDe0M,10240 +mypyc/primitives/tuple_ops.py,sha256=PeDVdwZkvOxvnnOP_iUi4c-rzPiF4LqaUqv5yu98-lQ,3752 +mypyc/primitives/weakref_ops.cp314-win_amd64.pyd,sha256=gvWt6oWDxoxuSvzgW6J0Sn0AzcHrfZezBGCSAYmIuLE,10240 +mypyc/primitives/weakref_ops.py,sha256=jfh4j2yO5OAFKXsSQeJKPIKWl3j3mYnyDpjwgj9mUHI,1160 +mypyc/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/rt_subtype.cp314-win_amd64.pyd,sha256=MSc0Vq6iRktK3X-w3_P7EQjpfe7V6khptCu7hC_xyi0,10240 +mypyc/rt_subtype.py,sha256=G1fE7PptSRl4z3AoifqNmmVCKthir2z3dw4EtDy1SVw,2743 +mypyc/sametype.cp314-win_amd64.pyd,sha256=nEwG0XElHkMUKzK-ny0hEPEDMWS0UQuyBSN1XOsSWzU,10240 +mypyc/sametype.py,sha256=CpcY2ck5NYPOM6pjyg73LxrgWOcYqgIRiLP0W78efpM,2608 +mypyc/subtype.cp314-win_amd64.pyd,sha256=0dUXjD1r-_KZbcUv5_3yMtVa0FHhU1zfLdiA1q3IUzU,10240 +mypyc/subtype.py,sha256=Aa_w1kbRWYCb8rxUwwVfWp7UCs40uMNpWliDUsD_frY,3354 +mypyc/test/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/test/__pycache__/__init__.cpython-314.pyc,, +mypyc/test/__pycache__/config.cpython-314.pyc,, +mypyc/test/__pycache__/librt_cache.cpython-314.pyc,, +mypyc/test/__pycache__/test_alwaysdefined.cpython-314.pyc,, +mypyc/test/__pycache__/test_analysis.cpython-314.pyc,, +mypyc/test/__pycache__/test_annotate.cpython-314.pyc,, +mypyc/test/__pycache__/test_capsule_deps.cpython-314.pyc,, +mypyc/test/__pycache__/test_cheader.cpython-314.pyc,, +mypyc/test/__pycache__/test_commandline.cpython-314.pyc,, +mypyc/test/__pycache__/test_emit.cpython-314.pyc,, +mypyc/test/__pycache__/test_emitclass.cpython-314.pyc,, +mypyc/test/__pycache__/test_emitfunc.cpython-314.pyc,, +mypyc/test/__pycache__/test_emitwrapper.cpython-314.pyc,, +mypyc/test/__pycache__/test_exceptions.cpython-314.pyc,, +mypyc/test/__pycache__/test_external.cpython-314.pyc,, +mypyc/test/__pycache__/test_irbuild.cpython-314.pyc,, +mypyc/test/__pycache__/test_ircheck.cpython-314.pyc,, +mypyc/test/__pycache__/test_literals.cpython-314.pyc,, +mypyc/test/__pycache__/test_lowering.cpython-314.pyc,, +mypyc/test/__pycache__/test_misc.cpython-314.pyc,, +mypyc/test/__pycache__/test_namegen.cpython-314.pyc,, +mypyc/test/__pycache__/test_optimizations.cpython-314.pyc,, +mypyc/test/__pycache__/test_pprint.cpython-314.pyc,, +mypyc/test/__pycache__/test_rarray.cpython-314.pyc,, +mypyc/test/__pycache__/test_refcount.cpython-314.pyc,, +mypyc/test/__pycache__/test_run.cpython-314.pyc,, +mypyc/test/__pycache__/test_serialization.cpython-314.pyc,, +mypyc/test/__pycache__/test_statement.cpython-314.pyc,, +mypyc/test/__pycache__/test_struct.cpython-314.pyc,, +mypyc/test/__pycache__/test_tuplename.cpython-314.pyc,, +mypyc/test/__pycache__/test_typeops.cpython-314.pyc,, +mypyc/test/__pycache__/testutil.cpython-314.pyc,, +mypyc/test/config.py,sha256=ZnruYrojiT_ZG4RrYzoESoNTiZY1bWuk0SQ2CFZHTQA,406 +mypyc/test/librt_cache.py,sha256=nvsUhe0_g5zZowzv7ELrIQH3oto1Z4SE6KRZsdDdThM,8596 +mypyc/test/test_alwaysdefined.py,sha256=NtJx8cYeU9wblyglViCc1Ww0yRyoEhElW1HV9-7i_ok,1528 +mypyc/test/test_analysis.py,sha256=8TetLNYto3iO3KCjEhYKOMvPkOc6Hr5tVbEqdo8G8zk,3265 +mypyc/test/test_annotate.py,sha256=WgWtYrPHQHu8PVhbHkk4GuG9Xf_r63Vu5adBkkzRPfo,2600 +mypyc/test/test_capsule_deps.py,sha256=FWkA3NPXT8xrJil8hZQgXzgQVqsWgfaAwfbuDZMarSs,2002 +mypyc/test/test_cheader.py,sha256=65ScI-JGu_v6HlKZsFbesJYmW4Wh3p1ltfp_zmteEi4,2974 +mypyc/test/test_commandline.py,sha256=ULYaN9gmgBXwnGUVYIui_x8Ybny3Wy5KKHpuJaeXxFs,2823 +mypyc/test/test_emit.py,sha256=XHCqiTDTt3KTQiSLMdF8DtjDo_7CLQodwOHlN5GhZvo,6519 +mypyc/test/test_emitclass.py,sha256=DE9sG9K-05LjbDvT6CWidDJB-onab7O0t8l2GVhjYlM,1228 +mypyc/test/test_emitfunc.py,sha256=35g_frZXo6Ps7oQqRiUTj2qTzbC0dm2hlRoMPaVQf-Q,39997 +mypyc/test/test_emitwrapper.py,sha256=C2cI4tJlpv-S4XOE1NIGG5-hUsm0YLVngNBzIN9yZL8,2219 +mypyc/test/test_exceptions.py,sha256=xKKMry9EcV6Msjnv3x_BIaXOoD1Y0VCZFqHKtCHxXcY,2145 +mypyc/test/test_external.py,sha256=KcgwW_a7L8btyPmo88YaFNQ8v_ODcpr4OtiS2aLaleA,4029 +mypyc/test/test_irbuild.py,sha256=wUI10odXsb-6HFxyUNG1XOphRQehtr5xUPrxiucq8Vo,3074 +mypyc/test/test_ircheck.py,sha256=OS5yZipy-bOCW9zCePk-b8x-xn2eK5yle_aoH6CrSiI,6891 +mypyc/test/test_literals.py,sha256=VospqX81-sNRhInwnnwC81Kzk9z1hr7UsnIDjC1NXhs,3325 +mypyc/test/test_lowering.py,sha256=8jllO0-mIwbdcJXxFgpj4XUsy8XiZgfeYJddkya5f5U,2473 +mypyc/test/test_misc.py,sha256=ncl-npJh2z8deAaNK30lq7LH3R7FCabiEhD_VwClwfI,740 +mypyc/test/test_namegen.py,sha256=GZaE_OGUApOf-RzJKe-5XlVHL5-rwoINEhPotCuwx5Q,2720 +mypyc/test/test_optimizations.py,sha256=lutkoLAqF3K_prJoXByFGHVykB8VhY1SQcyiYRuXmgg,2318 +mypyc/test/test_pprint.py,sha256=6kfSLDyEvNXPGmdbvDojM4wEdWFoi-6Oh23AHOjx-v4,1281 +mypyc/test/test_rarray.py,sha256=eVIfBeR2t6F-16QXznpycEN5DkRGYAvR-hNbkIkaRPw,1488 +mypyc/test/test_refcount.py,sha256=PSfI4Nsetl6O5uw9JnjAfyHMDcD9U3qtLnsoHJgrnZY,2058 +mypyc/test/test_run.py,sha256=qhaPJu7Jq_NXCqdjZcfWeWKaG3uJFBDEEPYtqqXRPVg,19669 +mypyc/test/test_serialization.py,sha256=DEEW4smq3Exp_4yJnfldsFcGEWmVq-uGH3oCEOx0GU0,3881 +mypyc/test/test_statement.py,sha256=27jPSZCbXVWLZKv7WwrPpaqTkDhF2bR7potVW7vrT2M,5515 +mypyc/test/test_struct.py,sha256=EEfu868uSm1wJmwowq1S_g1wInUaURX8tIhoPqGzs8w,3903 +mypyc/test/test_tuplename.py,sha256=P03_NcIw1n-g4vFOig_aKX5RgLqoBkO3xh7M2Zzerkg,1044 +mypyc/test/test_typeops.py,sha256=FQvUfsjTKL_eIPbBxcchG6zrsVJvgWpb5U316NrvFCw,3935 +mypyc/test/testutil.py,sha256=1PAHAhDQYg9npFSxLHRcbsB1zJembWsDwRdXfwZDrLQ,10252 +mypyc/transform/__init__.cp314-win_amd64.pyd,sha256=NtvJjilP3-CJTG9J3drcdBLtaSOQ3bjSSpH-ogC47rE,10240 +mypyc/transform/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypyc/transform/__pycache__/__init__.cpython-314.pyc,, +mypyc/transform/__pycache__/copy_propagation.cpython-314.pyc,, +mypyc/transform/__pycache__/exceptions.cpython-314.pyc,, +mypyc/transform/__pycache__/flag_elimination.cpython-314.pyc,, +mypyc/transform/__pycache__/ir_transform.cpython-314.pyc,, +mypyc/transform/__pycache__/log_trace.cpython-314.pyc,, +mypyc/transform/__pycache__/lower.cpython-314.pyc,, +mypyc/transform/__pycache__/refcount.cpython-314.pyc,, +mypyc/transform/__pycache__/spill.cpython-314.pyc,, +mypyc/transform/__pycache__/uninit.cpython-314.pyc,, +mypyc/transform/copy_propagation.cp314-win_amd64.pyd,sha256=HdbnJ71DwETSSzoRtuus2p4xNMQB8AJsTGXQcw7wdC0,10240 +mypyc/transform/copy_propagation.py,sha256=JrbL3Y-qPlcSGyWI2_jBO-UezHDrMf2pIII9wRu6fJI,3435 +mypyc/transform/exceptions.cp314-win_amd64.pyd,sha256=S3GRI6umtTitXw1RXoFuVsgIFm9xAz41MSk-nDRNJHk,10240 +mypyc/transform/exceptions.py,sha256=-62uaOPEZBlXbtJNVxI_bnRY3G9HmhR5Rjlx52XT3Wo,6797 +mypyc/transform/flag_elimination.cp314-win_amd64.pyd,sha256=oYicPSvvCrxUpnGDSCOvbOFYy-O7a9rj2N3wjFvLknM,10240 +mypyc/transform/flag_elimination.py,sha256=84M5VUt57iEj-yJR02XVeJsV-nviYO5YoqiDuOK0kxI,3531 +mypyc/transform/ir_transform.cp314-win_amd64.pyd,sha256=ZO0mi4dgJuz6L7WUD8JpgfQtuOtzkaQJATRTunEtWoY,10240 +mypyc/transform/ir_transform.py,sha256=WXHXZgKacp3ujajD0jlgps-WeVG36fEeY5O9gFVjKUU,11693 +mypyc/transform/log_trace.cp314-win_amd64.pyd,sha256=dxH6Dkt9Pdw0Du0FuX3bXcMjJoYlCrZ0AwgqG0LccCY,10240 +mypyc/transform/log_trace.py,sha256=_vLi9moWRpRqi5w85dLZt7Olg0n0HCPwh_NJMu0gX_E,5374 +mypyc/transform/lower.cp314-win_amd64.pyd,sha256=9DyJbWRJNUREmr--4BhMq06lg7TUJ53zAhlSvnfybEI,10240 +mypyc/transform/lower.py,sha256=LfFFCqN5_XoISoHoAHDggVTo9E45eeBiRnIQzJWWHAg,1344 +mypyc/transform/refcount.cp314-win_amd64.pyd,sha256=V1mGQBokl4SQ3wlPI7qJvTtjESSCGOW56WQp0mvCS0c,10240 +mypyc/transform/refcount.py,sha256=iW00ioXptnZe_CK9yBXe1dIajeHqweo3LNlKqHVMobQ,10109 +mypyc/transform/spill.cp314-win_amd64.pyd,sha256=8I7qyADwHo1IvHeQ-KhmELh05Fzlzr9h0ETTmoP7ij4,10240 +mypyc/transform/spill.py,sha256=dO7W2tChyzpb3E_Ut4RD510SIrvAu-mVM45_kR13JLk,4185 +mypyc/transform/uninit.cp314-win_amd64.pyd,sha256=iS8XT8wgsGNMJXboHcPAidaqj4vFBK0egc_ZhewKsBo,10240 +mypyc/transform/uninit.py,sha256=oY72iJXKDkWwYT4NsEHMZH_u1TpcFKp2EhsmkTwFje0,7307 diff --git a/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/REQUESTED b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/WHEEL b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..a2596f35678bd8c16829de6f09aac682f013ad1f --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: false +Tag: cp314-cp314-win_amd64 + diff --git a/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/direct_url.json b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..b0b565014f974fc49d412aced7f2288e3f8544fe --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///D:/bld/mypy-split_1776801208905/work"} \ No newline at end of file diff --git a/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/entry_points.txt b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..0ece8370b20afd5c124c69bf2a956da90f7e4573 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/entry_points.txt @@ -0,0 +1,6 @@ +[console_scripts] +dmypy = mypy.dmypy.client:console_entry +mypy = mypy.__main__:console_entry +mypyc = mypyc.__main__:main +stubgen = mypy.stubgen:main +stubtest = mypy.stubtest:main diff --git a/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/top_level.txt b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..50589689b1823f95fe723f5b4f9c53de79063c03 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy-1.20.2.dist-info/top_level.txt @@ -0,0 +1,3 @@ +0aca9ce3d91742c5b361__mypyc +mypy +mypyc diff --git a/micromamba_root/Lib/site-packages/mypy/__init__.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/__init__.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..0f6dd08aefafcc9a9bd989c681c9e779ad135b2c Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/__init__.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/__init__.py b/micromamba_root/Lib/site-packages/mypy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fa4000266849d05c68ee9559bbe1126a8493c4f9 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/__init__.py @@ -0,0 +1 @@ +# This page intentionally left blank diff --git a/micromamba_root/Lib/site-packages/mypy/__main__.py b/micromamba_root/Lib/site-packages/mypy/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb4d61f44658cc78424c440efb5e03a600e1aa08 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/__main__.py @@ -0,0 +1,50 @@ +"""Mypy type checker command line tool.""" + +from __future__ import annotations + +import os +import sys +import traceback + +from mypy.main import main, process_options +from mypy.util import FancyFormatter + + +def console_entry() -> None: + try: + main() + sys.stdout.flush() + sys.stderr.flush() + except BrokenPipeError: + # Python flushes standard streams on exit; redirect remaining output + # to devnull to avoid another BrokenPipeError at shutdown + devnull = os.open(os.devnull, os.O_WRONLY) + os.dup2(devnull, sys.stdout.fileno()) + sys.exit(2) + except KeyboardInterrupt: + _, options = process_options(args=sys.argv[1:]) + if options.show_traceback: + sys.stdout.write(traceback.format_exc()) + formatter = FancyFormatter(sys.stdout, sys.stderr, False) + msg = "Interrupted\n" + sys.stdout.write(formatter.style(msg, color="red", bold=True)) + sys.stdout.flush() + sys.stderr.flush() + sys.exit(2) + except Exception as e: + # Try reporting any uncaught error canonically, otherwise just flush the traceback. + try: + import mypy.errors + + _, options = process_options(args=sys.argv[1:]) + mypy.errors.report_internal_error(e, None, 0, None, options) + except Exception: + pass + sys.stdout.write(traceback.format_exc()) + sys.stdout.flush() + sys.stderr.flush() + sys.exit(2) + + +if __name__ == "__main__": + console_entry() diff --git a/micromamba_root/Lib/site-packages/mypy/error_formatter.py b/micromamba_root/Lib/site-packages/mypy/error_formatter.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb962e4641fed59468eaa09e147111c63e03837 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/error_formatter.py @@ -0,0 +1,39 @@ +"""Defines the different custom formats in which mypy can output.""" + +import json +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from mypy.errors import MypyError + + +class ErrorFormatter(ABC): + """Base class to define how errors are formatted before being printed.""" + + @abstractmethod + def report_error(self, error: "MypyError") -> str: + raise NotImplementedError + + +class JSONFormatter(ErrorFormatter): + """Formatter for basic JSON output format.""" + + def report_error(self, error: "MypyError") -> str: + """Prints out the errors as simple, static JSON lines.""" + return json.dumps( + { + "file": error.file_path, + "line": error.line, + "column": error.column, + "end_line": error.end_line, + "end_column": error.end_column, + "message": error.message, + "hint": None if len(error.hints) == 0 else "\n".join(error.hints), + "code": error.errorcode, + "severity": error.severity, + } + ) + + +OUTPUT_CHOICES = {"json": JSONFormatter()} diff --git a/micromamba_root/Lib/site-packages/mypy/evalexpr.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/evalexpr.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..0f740b5751a363f74710e9017816b900133b8839 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/evalexpr.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/evalexpr.py b/micromamba_root/Lib/site-packages/mypy/evalexpr.py new file mode 100644 index 0000000000000000000000000000000000000000..f46e5c23c3e43f79899791e173d4ad9bf999daa9 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/evalexpr.py @@ -0,0 +1,211 @@ +""" + +Evaluate an expression. + +Used by stubtest; in a separate file because things break if we don't +put it in a mypyc-compiled file. + +""" + +import ast +from typing import Final + +import mypy.nodes +from mypy.visitor import ExpressionVisitor + +UNKNOWN = object() + + +class _NodeEvaluator(ExpressionVisitor[object]): + def visit_int_expr(self, o: mypy.nodes.IntExpr) -> int: + return o.value + + def visit_str_expr(self, o: mypy.nodes.StrExpr) -> str: + return o.value + + def visit_bytes_expr(self, o: mypy.nodes.BytesExpr) -> object: + # The value of a BytesExpr is a string created from the repr() + # of the bytes object. Get the original bytes back. + try: + return ast.literal_eval(f"b'{o.value}'") + except SyntaxError: + return ast.literal_eval(f'b"{o.value}"') + + def visit_float_expr(self, o: mypy.nodes.FloatExpr) -> float: + return o.value + + def visit_complex_expr(self, o: mypy.nodes.ComplexExpr) -> object: + return o.value + + def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr) -> object: + return Ellipsis + + def visit_star_expr(self, o: mypy.nodes.StarExpr) -> object: + return UNKNOWN + + def visit_name_expr(self, o: mypy.nodes.NameExpr) -> object: + if o.name == "True": + return True + elif o.name == "False": + return False + elif o.name == "None": + return None + # TODO: Handle more names by figuring out a way to hook into the + # symbol table. + return UNKNOWN + + def visit_member_expr(self, o: mypy.nodes.MemberExpr) -> object: + return UNKNOWN + + def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr) -> object: + return UNKNOWN + + def visit_yield_expr(self, o: mypy.nodes.YieldExpr) -> object: + return UNKNOWN + + def visit_call_expr(self, o: mypy.nodes.CallExpr) -> object: + return UNKNOWN + + def visit_op_expr(self, o: mypy.nodes.OpExpr) -> object: + return UNKNOWN + + def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr) -> object: + return UNKNOWN + + def visit_cast_expr(self, o: mypy.nodes.CastExpr) -> object: + return o.expr.accept(self) + + def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr) -> object: + return UNKNOWN + + def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr) -> object: + return o.expr.accept(self) + + def visit_reveal_expr(self, o: mypy.nodes.RevealExpr) -> object: + return UNKNOWN + + def visit_super_expr(self, o: mypy.nodes.SuperExpr) -> object: + return UNKNOWN + + def visit_unary_expr(self, o: mypy.nodes.UnaryExpr) -> object: + operand = o.expr.accept(self) + if operand is UNKNOWN: + return UNKNOWN + if o.op == "-": + if isinstance(operand, (int, float, complex)): + return -operand + elif o.op == "+": + if isinstance(operand, (int, float, complex)): + return +operand + elif o.op == "~": + if isinstance(operand, int): + return ~operand + elif o.op == "not": + if isinstance(operand, (bool, int, float, str, bytes)): + return not operand + return UNKNOWN + + def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr) -> object: + return o.value.accept(self) + + def visit_list_expr(self, o: mypy.nodes.ListExpr) -> object: + items = [item.accept(self) for item in o.items] + if all(item is not UNKNOWN for item in items): + return items + return UNKNOWN + + def visit_dict_expr(self, o: mypy.nodes.DictExpr) -> object: + items = [ + (UNKNOWN if key is None else key.accept(self), value.accept(self)) + for key, value in o.items + ] + if all(key is not UNKNOWN and value is not None for key, value in items): + return dict(items) + return UNKNOWN + + def visit_tuple_expr(self, o: mypy.nodes.TupleExpr) -> object: + items = [item.accept(self) for item in o.items] + if all(item is not UNKNOWN for item in items): + return tuple(items) + return UNKNOWN + + def visit_set_expr(self, o: mypy.nodes.SetExpr) -> object: + items = [item.accept(self) for item in o.items] + if all(item is not UNKNOWN for item in items): + return set(items) + return UNKNOWN + + def visit_index_expr(self, o: mypy.nodes.IndexExpr) -> object: + return UNKNOWN + + def visit_type_application(self, o: mypy.nodes.TypeApplication) -> object: + return UNKNOWN + + def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr) -> object: + return UNKNOWN + + def visit_list_comprehension(self, o: mypy.nodes.ListComprehension) -> object: + return UNKNOWN + + def visit_set_comprehension(self, o: mypy.nodes.SetComprehension) -> object: + return UNKNOWN + + def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension) -> object: + return UNKNOWN + + def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr) -> object: + return UNKNOWN + + def visit_slice_expr(self, o: mypy.nodes.SliceExpr) -> object: + return UNKNOWN + + def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr) -> object: + return UNKNOWN + + def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr) -> object: + return UNKNOWN + + def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr) -> object: + return UNKNOWN + + def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr) -> object: + return UNKNOWN + + def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr) -> object: + return UNKNOWN + + def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr) -> object: + return UNKNOWN + + def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr) -> object: + return UNKNOWN + + def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr) -> object: + return UNKNOWN + + def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr) -> object: + return UNKNOWN + + def visit__promote_expr(self, o: mypy.nodes.PromoteExpr) -> object: + return UNKNOWN + + def visit_await_expr(self, o: mypy.nodes.AwaitExpr) -> object: + return UNKNOWN + + def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr) -> object: + return UNKNOWN + + def visit_temp_node(self, o: mypy.nodes.TempNode) -> object: + return UNKNOWN + + +_evaluator: Final = _NodeEvaluator() + + +def evaluate_expression(expr: mypy.nodes.Expression) -> object: + """Evaluate an expression at runtime. + + Return the result of the expression, or UNKNOWN if the expression cannot be + evaluated. + """ + return expr.accept(_evaluator) diff --git a/micromamba_root/Lib/site-packages/mypy/expandtype.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/expandtype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..8602768428c753e96af5b8ae951baeb3f95797e5 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/expandtype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/expandtype.py b/micromamba_root/Lib/site-packages/mypy/expandtype.py new file mode 100644 index 0000000000000000000000000000000000000000..5790b717172acafe218f45882aaa010ef62be236 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/expandtype.py @@ -0,0 +1,662 @@ +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from typing import Final, TypeVar, cast, overload + +from mypy.nodes import ARG_STAR, ArgKind, FakeInfo, Var +from mypy.state import state +from mypy.types import ( + ANY_STRATEGY, + AnyType, + BoolTypeQuery, + CallableType, + DeletedType, + ErasedType, + FunctionLike, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecFlavor, + ParamSpecType, + PartialType, + ProperType, + TrivialSyntheticTypeTranslator, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + flatten_nested_unions, + get_proper_type, + split_with_prefix_and_suffix, +) +from mypy.typevartuples import split_with_instance + +# Solving the import cycle: +import mypy.type_visitor # ruff: isort: skip + +# WARNING: these functions should never (directly or indirectly) depend on +# is_subtype(), meet_types(), join_types() etc. +# TODO: add a static dependency test for this. + + +@overload +def expand_type(typ: CallableType, env: Mapping[TypeVarId, Type]) -> CallableType: ... + + +@overload +def expand_type(typ: ProperType, env: Mapping[TypeVarId, Type]) -> ProperType: ... + + +@overload +def expand_type(typ: Type, env: Mapping[TypeVarId, Type]) -> Type: ... + + +def expand_type(typ: Type, env: Mapping[TypeVarId, Type]) -> Type: + """Substitute any type variable references in a type given by a type + environment. + """ + return typ.accept(ExpandTypeVisitor(env)) + + +@overload +def expand_type_by_instance(typ: CallableType, instance: Instance) -> CallableType: ... + + +@overload +def expand_type_by_instance(typ: ProperType, instance: Instance) -> ProperType: ... + + +@overload +def expand_type_by_instance(typ: Type, instance: Instance) -> Type: ... + + +def expand_type_by_instance(typ: Type, instance: Instance) -> Type: + """Substitute type variables in type using values from an Instance. + Type variables are considered to be bound by the class declaration.""" + if not instance.args and not instance.type.has_type_var_tuple_type: + return typ + else: + variables: dict[TypeVarId, Type] = {} + if instance.type.has_type_var_tuple_type: + assert instance.type.type_var_tuple_prefix is not None + assert instance.type.type_var_tuple_suffix is not None + + args_prefix, args_middle, args_suffix = split_with_instance(instance) + tvars_prefix, tvars_middle, tvars_suffix = split_with_prefix_and_suffix( + tuple(instance.type.defn.type_vars), + instance.type.type_var_tuple_prefix, + instance.type.type_var_tuple_suffix, + ) + tvar = tvars_middle[0] + assert isinstance(tvar, TypeVarTupleType) + variables = {tvar.id: TupleType(list(args_middle), tvar.tuple_fallback)} + instance_args = args_prefix + args_suffix + tvars = tvars_prefix + tvars_suffix + else: + tvars = tuple(instance.type.defn.type_vars) + instance_args = instance.args + + for binder, arg in zip(tvars, instance_args): + assert isinstance(binder, TypeVarLikeType) + variables[binder.id] = arg + + return expand_type(typ, variables) + + +F = TypeVar("F", bound=FunctionLike) + + +def freshen_function_type_vars(callee: F) -> F: + """Substitute fresh type variables for generic function type variables.""" + if isinstance(callee, CallableType): + if not callee.is_generic(): + return callee + tvs = [] + tvmap: dict[TypeVarId, Type] = {} + for v in callee.variables: + tv = v.new_unification_variable(v) + tvs.append(tv) + tvmap[v.id] = tv + fresh = expand_type(callee, tvmap).copy_modified(variables=tvs) + return cast(F, fresh) + else: + assert isinstance(callee, Overloaded) + fresh_overload = Overloaded([freshen_function_type_vars(item) for item in callee.items]) + return cast(F, fresh_overload) + + +class HasGenericCallable(BoolTypeQuery): + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_callable_type(self, t: CallableType) -> bool: + return t.is_generic() or super().visit_callable_type(t) + + +# Share a singleton since this is performance sensitive +has_generic_callable: Final = HasGenericCallable() + + +T = TypeVar("T", bound=Type) + + +def freshen_all_functions_type_vars(t: T) -> T: + result: Type + has_generic_callable.reset() + if not t.accept(has_generic_callable): + return t # Fast path to avoid expensive freshening + else: + result = t.accept(FreshenCallableVisitor()) + assert isinstance(result, type(t)) + return result + + +class FreshenCallableVisitor(mypy.type_visitor.TypeTranslator): + def visit_callable_type(self, t: CallableType) -> Type: + result = super().visit_callable_type(t) + assert isinstance(result, ProperType) and isinstance(result, CallableType) + return freshen_function_type_vars(result) + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + # Same as for ExpandTypeVisitor + return t.copy_modified(args=[arg.accept(self) for arg in t.args]) + + +class ExpandTypeVisitor(TrivialSyntheticTypeTranslator): + """Visitor that substitutes type variables with values.""" + + variables: Mapping[TypeVarId, Type] # TypeVar id -> TypeVar value + + def __init__(self, variables: Mapping[TypeVarId, Type]) -> None: + super().__init__() + self.variables = variables + self.recursive_tvar_guard: dict[TypeVarId, Type | None] | None = None + + def visit_unbound_type(self, t: UnboundType) -> Type: + return t + + def visit_any(self, t: AnyType) -> Type: + return t + + def visit_none_type(self, t: NoneType) -> Type: + return t + + def visit_uninhabited_type(self, t: UninhabitedType) -> Type: + return t + + def visit_deleted_type(self, t: DeletedType) -> Type: + return t + + def visit_erased_type(self, t: ErasedType) -> Type: + # This may happen during type inference if some function argument + # type is a generic callable, and its erased form will appear in inferred + # constraints, then solver may check subtyping between them, which will trigger + # unify_generic_callables(), this is why we can get here. Another example is + # when inferring type of lambda in generic context, the lambda body contains + # a generic method in generic class. + return t + + def visit_instance(self, t: Instance) -> Type: + if len(t.args) == 0: + return t + + args = self.expand_type_tuple_with_unpack(t.args) + + if isinstance(t.type, FakeInfo): + # The type checker expands function definitions and bodies + # if they depend on constrained type variables but the body + # might contain a tuple type comment (e.g., # type: (int, float)), + # in which case 't.type' is not yet available. + # + # See: https://github.com/python/mypy/issues/16649 + return t.copy_modified(args=args) + + if t.type.fullname == "builtins.tuple": + # Normalize Tuple[*Tuple[X, ...], ...] -> Tuple[X, ...] + arg = args[0] + if isinstance(arg, UnpackType): + unpacked = get_proper_type(arg.type) + if isinstance(unpacked, Instance): + # TODO: this and similar asserts below may be unsafe because get_proper_type() + # may be called during semantic analysis before all invalid types are removed. + assert unpacked.type.fullname == "builtins.tuple" + args = list(unpacked.args) + return t.copy_modified(args=args) + + def visit_type_var(self, t: TypeVarType) -> Type: + # Normally upper bounds can't contain other type variables, the only exception is + # special type variable Self`0 <: C[T, S], where C is the class where Self is used. + if t.id.is_self(): + t = t.copy_modified(upper_bound=t.upper_bound.accept(self)) + repl = self.variables.get(t.id, t) + if isinstance(repl, ProperType) and isinstance(repl, Instance): + # TODO: do we really need to do this? + # If I try to remove this special-casing ~40 tests fail on reveal_type(). + return repl.copy_modified(last_known_value=None) + if isinstance(repl, TypeVarType) and repl.has_default(): + if self.recursive_tvar_guard is None: + self.recursive_tvar_guard = {} + if (tvar_id := repl.id) in self.recursive_tvar_guard: + return self.recursive_tvar_guard[tvar_id] or repl + self.recursive_tvar_guard[tvar_id] = None + repl.default = repl.default.accept(self) + expanded = repl.accept(self) # Note: `expanded is repl` may be true. + repl = repl if isinstance(expanded, TypeVarType) else expanded + self.recursive_tvar_guard[tvar_id] = repl + return repl + + def visit_param_spec(self, t: ParamSpecType) -> Type: + # Set prefix to something empty, so we don't duplicate it below. + repl = self.variables.get(t.id, t.copy_modified(prefix=Parameters([], [], []))) + if isinstance(repl, ParamSpecType): + return repl.copy_modified( + flavor=t.flavor, + prefix=t.prefix.copy_modified( + arg_types=self.expand_types(t.prefix.arg_types) + repl.prefix.arg_types, + arg_kinds=t.prefix.arg_kinds + repl.prefix.arg_kinds, + arg_names=t.prefix.arg_names + repl.prefix.arg_names, + ), + ) + elif isinstance(repl, Parameters): + assert isinstance(t.upper_bound, ProperType) and isinstance(t.upper_bound, Instance) + if t.flavor == ParamSpecFlavor.BARE: + return Parameters( + self.expand_types(t.prefix.arg_types) + repl.arg_types, + t.prefix.arg_kinds + repl.arg_kinds, + t.prefix.arg_names + repl.arg_names, + variables=[*t.prefix.variables, *repl.variables], + imprecise_arg_kinds=repl.imprecise_arg_kinds, + ) + elif t.flavor == ParamSpecFlavor.ARGS: + assert all(k.is_positional() for k in t.prefix.arg_kinds) + return self._possible_callable_varargs( + repl, list(t.prefix.arg_types), t.upper_bound + ) + else: + assert t.flavor == ParamSpecFlavor.KWARGS + return self._possible_callable_kwargs(repl, t.upper_bound) + else: + # We could encode Any as trivial parameters etc., but it would be too verbose. + # TODO: assert this is a trivial type, like Any, Never, or object. + return repl + + @classmethod + def _possible_callable_varargs( + cls, repl: Parameters, required_prefix: list[Type], tuple_type: Instance + ) -> ProperType: + """Given a callable, extract all parameters that can be passed as `*args`. + + This builds a union of all (possibly variadic) tuples representing all possible + argument sequences that can be passed positionally. Each such tuple starts with + all required (pos-only without a default) arguments, followed by some prefix + of other arguments that can be passed positionally. + """ + required_posargs = required_prefix + if repl.variables: + # We will tear the callable apart, do not leak type variables + return tuple_type + optional_posargs: list[Type] = [] + for kind, name, type in zip(repl.arg_kinds, repl.arg_names, repl.arg_types): + if kind == ArgKind.ARG_POS and name is None: + if optional_posargs: + # May happen following Unpack expansion without kinds correction + required_posargs += optional_posargs + optional_posargs = [] + required_posargs.append(type) + elif kind.is_positional(): + optional_posargs.append(type) + elif kind == ArgKind.ARG_STAR: + if isinstance(type, UnpackType): + optional_posargs.append(type) + else: + optional_posargs.append(UnpackType(Instance(tuple_type.type, [type]))) + break + return UnionType.make_union( + [ + TupleType(required_posargs + optional_posargs[:i], fallback=tuple_type) + for i in range(len(optional_posargs) + 1) + ] + ) + + @classmethod + def _possible_callable_kwargs(cls, repl: Parameters, dict_type: Instance) -> ProperType: + """Given a callable, extract all parameters that can be passed as `**kwargs`. + + If the function only accepts **kwargs, this will be a `dict[str, KwargsValueType]`. + Otherwise, this will be a `TypedDict` containing all explicit args and ignoring + `**kwargs` (until PEP 728 `extra_items` is supported). TypedDict entries will + be required iff the corresponding argument is kw-only and has no default. + """ + if repl.variables: + # We will tear the callable apart, do not leak type variables + return dict_type + kwargs = {} + required_names = set() + extra_items: Type = UninhabitedType() + for kind, name, type in zip(repl.arg_kinds, repl.arg_names, repl.arg_types): + if kind == ArgKind.ARG_NAMED and name is not None: + kwargs[name] = type + required_names.add(name) + elif kind == ArgKind.ARG_STAR2: + # Unpack[TypedDict] is normalized early, it isn't stored as Unpack + extra_items = type + elif not kind.is_star() and name is not None: + kwargs[name] = type + if not kwargs: + return Instance(dict_type.type, [dict_type.args[0], extra_items]) + # TODO: when PEP 728 is implemented, pass extra_items below. + return TypedDictType(kwargs, required_names, set(), fallback=dict_type) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type: + # Sometimes solver may need to expand a type variable with (a copy of) itself + # (usually together with other TypeVars, but it is hard to filter out TypeVarTuples). + repl = self.variables.get(t.id, t) + if isinstance(repl, TypeVarTupleType): + return repl + elif isinstance(repl, ProperType) and isinstance(repl, (AnyType, UninhabitedType)): + # Some failed inference scenarios will try to set all type variables to Never. + # Instead of being picky and require all the callers to wrap them, + # do this here instead. + # Note: most cases when this happens are handled in expand unpack below, but + # in rare cases (e.g. ParamSpec containing Unpack star args) it may be skipped. + return t.tuple_fallback.copy_modified(args=[repl]) + raise NotImplementedError + + def visit_unpack_type(self, t: UnpackType) -> Type: + # It is impossible to reasonably implement visit_unpack_type, because + # unpacking inherently expands to something more like a list of types. + # + # Relevant sections that can call unpack should call expand_unpack() + # instead. + # However, if the item is a variadic tuple, we can simply carry it over. + # In particular, if we expand A[*tuple[T, ...]] with substitutions {T: str}, + # it is hard to assert this without getting proper type. Another important + # example is non-normalized types when called from semanal.py. + return UnpackType(t.type.accept(self)) + + def expand_unpack(self, t: UnpackType) -> list[Type]: + assert isinstance(t.type, TypeVarTupleType) + repl = get_proper_type(self.variables.get(t.type.id, t.type)) + if isinstance(repl, UnpackType): + repl = get_proper_type(repl.type) + if isinstance(repl, TupleType): + return repl.items + elif ( + isinstance(repl, Instance) + and repl.type.fullname == "builtins.tuple" + or isinstance(repl, TypeVarTupleType) + ): + return [UnpackType(typ=repl)] + elif isinstance(repl, (AnyType, UninhabitedType)): + # Replace *Ts = Any with *Ts = *tuple[Any, ...] and same for Never. + # These types may appear here as a result of user error or failed inference. + return [UnpackType(t.type.tuple_fallback.copy_modified(args=[repl]))] + else: + raise RuntimeError(f"Invalid type replacement to expand: {repl}") + + def visit_parameters(self, t: Parameters) -> Type: + return t.copy_modified(arg_types=self.expand_types(t.arg_types)) + + def interpolate_args_for_unpack(self, t: CallableType, var_arg: UnpackType) -> list[Type]: + star_index = t.arg_kinds.index(ARG_STAR) + prefix = self.expand_types(t.arg_types[:star_index]) + suffix = self.expand_types(t.arg_types[star_index + 1 :]) + + var_arg_type = get_proper_type(var_arg.type) + new_unpack: Type + if isinstance(var_arg_type, TupleType): + # We have something like Unpack[Tuple[Unpack[Ts], X1, X2]] + expanded_tuple = var_arg_type.accept(self) + assert isinstance(expanded_tuple, ProperType) and isinstance(expanded_tuple, TupleType) + expanded_items = expanded_tuple.items + fallback = var_arg_type.partial_fallback + new_unpack = UnpackType(TupleType(expanded_items, fallback)) + elif isinstance(var_arg_type, TypeVarTupleType): + # We have plain Unpack[Ts] + fallback = var_arg_type.tuple_fallback + expanded_items = self.expand_unpack(var_arg) + new_unpack = UnpackType(TupleType(expanded_items, fallback)) + # Since get_proper_type() may be called in semanal.py before callable + # normalization happens, we need to also handle non-normal cases here. + elif isinstance(var_arg_type, Instance): + # we have something like Unpack[Tuple[Any, ...]] + new_unpack = UnpackType(var_arg.type.accept(self)) + else: + # We have invalid type in Unpack. This can happen when expanding aliases + # to Callable[[*Invalid], Ret] + new_unpack = AnyType(TypeOfAny.from_error, line=var_arg.line, column=var_arg.column) + return prefix + [new_unpack] + suffix + + def visit_callable_type(self, t: CallableType) -> CallableType: + param_spec = t.param_spec() + if param_spec is not None: + repl = self.variables.get(param_spec.id) + # If a ParamSpec in a callable type is substituted with a + # callable type, we can't use normal substitution logic, + # since ParamSpec is actually split into two components + # *P.args and **P.kwargs in the original type. Instead, we + # must expand both of them with all the argument types, + # kinds and names in the replacement. The return type in + # the replacement is ignored. + if isinstance(repl, Parameters): + # We need to expand both the types in the prefix and the ParamSpec itself + expanded = t.copy_modified( + arg_types=self.expand_types(t.arg_types[:-2]) + repl.arg_types, + arg_kinds=t.arg_kinds[:-2] + repl.arg_kinds, + arg_names=t.arg_names[:-2] + repl.arg_names, + ret_type=t.ret_type.accept(self), + type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None), + type_is=(t.type_is.accept(self) if t.type_is is not None else None), + imprecise_arg_kinds=(t.imprecise_arg_kinds or repl.imprecise_arg_kinds), + variables=[*repl.variables, *t.variables], + ) + var_arg = expanded.var_arg() + if var_arg is not None and isinstance(var_arg.typ, UnpackType): + # Sometimes we get new unpacks after expanding ParamSpec. + expanded.normalize_trivial_unpack() + return expanded + elif isinstance(repl, ParamSpecType): + # We're substituting one ParamSpec for another; this can mean that the prefix + # changes, e.g. substitute Concatenate[int, P] in place of Q. + prefix = repl.prefix + clean_repl = repl.copy_modified(prefix=Parameters([], [], [])) + return t.copy_modified( + arg_types=self.expand_types(t.arg_types[:-2]) + + prefix.arg_types + + [ + clean_repl.with_flavor(ParamSpecFlavor.ARGS), + clean_repl.with_flavor(ParamSpecFlavor.KWARGS), + ], + arg_kinds=t.arg_kinds[:-2] + prefix.arg_kinds + t.arg_kinds[-2:], + arg_names=t.arg_names[:-2] + prefix.arg_names + t.arg_names[-2:], + ret_type=t.ret_type.accept(self), + from_concatenate=t.from_concatenate or bool(repl.prefix.arg_types), + imprecise_arg_kinds=(t.imprecise_arg_kinds or prefix.imprecise_arg_kinds), + ) + + var_arg = t.var_arg() + needs_normalization = False + if var_arg is not None and isinstance(var_arg.typ, UnpackType): + needs_normalization = True + arg_types = self.interpolate_args_for_unpack(t, var_arg.typ) + else: + arg_types = self.expand_types(t.arg_types) + expanded = t.copy_modified( + arg_types=arg_types, + ret_type=t.ret_type.accept(self), + type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None), + type_is=(t.type_is.accept(self) if t.type_is is not None else None), + ) + if needs_normalization: + return expanded.with_normalized_var_args() + return expanded + + def visit_overloaded(self, t: Overloaded) -> Type: + items: list[CallableType] = [] + for item in t.items: + new_item = item.accept(self) + assert isinstance(new_item, ProperType) + assert isinstance(new_item, CallableType) + items.append(new_item) + return Overloaded(items) + + def expand_type_list_with_unpack(self, typs: list[Type]) -> list[Type]: + """Expands a list of types that has an unpack.""" + items: list[Type] = [] + for item in typs: + if isinstance(item, UnpackType) and isinstance(item.type, TypeVarTupleType): + items.extend(self.expand_unpack(item)) + else: + items.append(item.accept(self)) + return items + + def expand_type_tuple_with_unpack(self, typs: tuple[Type, ...]) -> list[Type]: + """Expands a tuple of types that has an unpack.""" + # Micro-optimization: Specialized variant of expand_type_list_with_unpack + items: list[Type] = [] + for item in typs: + if isinstance(item, UnpackType) and isinstance(item.type, TypeVarTupleType): + items.extend(self.expand_unpack(item)) + else: + items.append(item.accept(self)) + return items + + def visit_tuple_type(self, t: TupleType) -> Type: + items = self.expand_type_list_with_unpack(t.items) + if len(items) == 1: + # Normalize Tuple[*Tuple[X, ...]] -> Tuple[X, ...] + item = items[0] + if isinstance(item, UnpackType): + unpacked = get_proper_type(item.type) + if isinstance(unpacked, Instance): + # expand_type() may be called during semantic analysis, before invalid unpacks are fixed. + if unpacked.type.fullname != "builtins.tuple": + return t.partial_fallback.accept(self) + if t.partial_fallback.type.fullname != "builtins.tuple": + # If it is a subtype (like named tuple) we need to preserve it, + # this essentially mimics the logic in tuple_fallback(). + return t.partial_fallback.accept(self) + return unpacked + fallback = t.partial_fallback.accept(self) + assert isinstance(fallback, ProperType) and isinstance(fallback, Instance) + return t.copy_modified(items=items, fallback=fallback) + + def visit_typeddict_type(self, t: TypedDictType) -> Type: + if cached := self.get_cached(t): + return cached + fallback = t.fallback.accept(self) + assert isinstance(fallback, ProperType) and isinstance(fallback, Instance) + result = t.copy_modified(item_types=self.expand_types(t.items.values()), fallback=fallback) + self.set_cached(t, result) + return result + + def visit_literal_type(self, t: LiteralType) -> Type: + # TODO: Verify this implementation is correct + return t + + def visit_union_type(self, t: UnionType) -> Type: + # Use cache to avoid O(n**2) or worse expansion of types during translation + # (only for large unions, since caching adds overhead) + use_cache = len(t.items) > 3 + if use_cache and (cached := self.get_cached(t)): + return cached + + expanded = self.expand_types(t.items) + # After substituting for type variables in t.items, some resulting types + # might be subtypes of others, however calling make_simplified_union() + # can cause recursion, so we just remove strict duplicates. + simplified = UnionType.make_union( + remove_trivial(flatten_nested_unions(expanded)), t.line, t.column + ) + # This call to get_proper_type() is unfortunate but is required to preserve + # the invariant that ProperType will stay ProperType after applying expand_type(), + # otherwise a single item union of a type alias will break it. Note this should not + # cause infinite recursion since pathological aliases like A = Union[A, B] are + # banned at the semantic analysis level. + result = get_proper_type(simplified) + + if use_cache: + self.set_cached(t, result) + return result + + def visit_partial_type(self, t: PartialType) -> Type: + return t + + def visit_type_type(self, t: TypeType) -> Type: + # TODO: Verify that the new item type is valid (instance or + # union of instances or Any). Sadly we can't report errors + # here yet. + item = t.item.accept(self) + return TypeType.make_normalized(item, is_type_form=t.is_type_form) + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + # Target of the type alias cannot contain type variables (not bound by the type + # alias itself), so we just expand the arguments. + if len(t.args) == 0: + return t + args = self.expand_type_list_with_unpack(t.args) + # TODO: normalize if target is Tuple, and args are [*tuple[X, ...]]? + return t.copy_modified(args=args) + + def expand_types(self, types: Iterable[Type]) -> list[Type]: + a: list[Type] = [] + for t in types: + a.append(t.accept(self)) + return a + + +@overload +def expand_self_type(var: Var, typ: ProperType, replacement: ProperType) -> ProperType: ... + + +@overload +def expand_self_type(var: Var, typ: Type, replacement: Type) -> Type: ... + + +def expand_self_type(var: Var, typ: Type, replacement: Type) -> Type: + """Expand appearances of Self type in a variable type.""" + if var.info.self_type is not None and not var.is_property: + return expand_type(typ, {var.info.self_type.id: replacement}) + return typ + + +def remove_trivial(types: Iterable[Type]) -> list[Type]: + """Make trivial simplifications on a list of types without calling is_subtype(). + + This makes following simplifications: + * Remove bottom types (taking into account strict optional setting) + * Remove everything else if there is an `object` + * Remove strict duplicate types + """ + removed_none = False + new_types = [] + all_types = set() + for t in types: + p_t = get_proper_type(t) + if isinstance(p_t, UninhabitedType): + continue + if isinstance(p_t, NoneType) and not state.strict_optional: + removed_none = True + continue + if isinstance(p_t, Instance) and p_t.type.fullname == "builtins.object": + return [p_t] + if p_t not in all_types: + new_types.append(t) + all_types.add(p_t) + if new_types: + return new_types + if removed_none: + return [NoneType()] + return [UninhabitedType()] diff --git a/micromamba_root/Lib/site-packages/mypy/exportjson.py b/micromamba_root/Lib/site-packages/mypy/exportjson.py new file mode 100644 index 0000000000000000000000000000000000000000..c08f0f9f2911824ffa0a7fca65b73a4a296b8abb --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/exportjson.py @@ -0,0 +1,612 @@ +"""Tool to convert binary mypy cache files (.ff) to JSON (.ff.json). + +Usage: + python -m mypy.exportjson .mypy_cache/.../my_module.data.ff + +The idea is to make caches introspectable once we've switched to a binary +cache format and removed support for the older JSON cache format. + +This is primarily to support existing use cases that need to inspect +cache files, and to support debugging mypy caching issues. This means that +this doesn't necessarily need to be kept 1:1 up to date with changes in the +binary cache format (to simplify maintenance -- we don't want this to slow +down mypy development). +""" + +import argparse +import json +import sys +from typing import Any, TypeAlias as _TypeAlias + +from librt.internal import ReadBuffer, cache_version + +from mypy.cache import CACHE_VERSION, CacheMeta +from mypy.nodes import ( + FUNCBASE_FLAGS, + FUNCDEF_FLAGS, + VAR_FLAGS, + ClassDef, + DataclassTransformSpec, + Decorator, + FuncDef, + MypyFile, + OverloadedFuncDef, + OverloadPart, + ParamSpecExpr, + SymbolNode, + SymbolTable, + SymbolTableNode, + TypeAlias, + TypeInfo, + TypeVarExpr, + TypeVarTupleExpr, + Var, + get_flags, + node_kinds, +) +from mypy.types import ( + NOT_READY, + AnyType, + CallableType, + ExtraAttrs, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + get_proper_type, +) + +Json: _TypeAlias = dict[str, Any] | str + + +class Config: + def __init__(self, *, implicit_names: bool = True) -> None: + self.implicit_names = implicit_names + + +def convert_binary_cache_to_json(data: bytes, *, implicit_names: bool = True) -> Json: + tree = MypyFile.read(ReadBuffer(data)) + return convert_mypy_file_to_json(tree, Config(implicit_names=implicit_names)) + + +def convert_mypy_file_to_json(self: MypyFile, cfg: Config) -> Json: + return { + ".class": "MypyFile", + "_fullname": self._fullname, + "names": convert_symbol_table(self.names, cfg), + "is_stub": self.is_stub, + "path": self.path, + "is_partial_stub_package": self.is_partial_stub_package, + "future_import_flags": sorted(self.future_import_flags), + } + + +def convert_symbol_table(self: SymbolTable, cfg: Config) -> Json: + data: dict[str, Any] = {".class": "SymbolTable"} + for key, value in self.items(): + # Skip __builtins__: it's a reference to the builtins + # module that gets added to every module by + # SemanticAnalyzerPass2.visit_file(), but it shouldn't be + # accessed by users of the module. + if key == "__builtins__" or value.no_serialize: + continue + if not cfg.implicit_names and key in { + "__spec__", + "__package__", + "__file__", + "__doc__", + "__annotations__", + "__name__", + }: + continue + data[key] = convert_symbol_table_node(value, cfg) + return data + + +def convert_symbol_table_node(self: SymbolTableNode, cfg: Config) -> Json: + data: dict[str, Any] = {".class": "SymbolTableNode", "kind": node_kinds[self.kind]} + if self.module_hidden: + data["module_hidden"] = True + if not self.module_public: + data["module_public"] = False + if self.implicit: + data["implicit"] = True + if self.plugin_generated: + data["plugin_generated"] = True + if self.cross_ref: + data["cross_ref"] = self.cross_ref + elif self.node is not None: + data["node"] = convert_symbol_node(self.node, cfg) + return data + + +def convert_symbol_node(self: SymbolNode, cfg: Config) -> Json: + if isinstance(self, FuncDef): + return convert_func_def(self) + elif isinstance(self, OverloadedFuncDef): + return convert_overloaded_func_def(self) + elif isinstance(self, Decorator): + return convert_decorator(self) + elif isinstance(self, Var): + return convert_var(self) + elif isinstance(self, TypeInfo): + return convert_type_info(self, cfg) + elif isinstance(self, TypeAlias): + return convert_type_alias(self) + elif isinstance(self, TypeVarExpr): + return convert_type_var_expr(self) + elif isinstance(self, ParamSpecExpr): + return convert_param_spec_expr(self) + elif isinstance(self, TypeVarTupleExpr): + return convert_type_var_tuple_expr(self) + return {"ERROR": f"{type(self)!r} unrecognized"} + + +def convert_func_def(self: FuncDef) -> Json: + return { + ".class": "FuncDef", + "name": self._name, + "fullname": self._fullname, + "arg_names": self.arg_names, + "arg_kinds": [int(x.value) for x in self.arg_kinds], + "type": None if self.type is None else convert_type(self.type), + "flags": get_flags(self, FUNCDEF_FLAGS), + "abstract_status": self.abstract_status, + # TODO: Do we need expanded, original_def? + "dataclass_transform_spec": ( + None + if self.dataclass_transform_spec is None + else convert_dataclass_transform_spec(self.dataclass_transform_spec) + ), + "deprecated": self.deprecated, + "original_first_arg": self.original_first_arg, + } + + +def convert_dataclass_transform_spec(self: DataclassTransformSpec) -> Json: + return { + "eq_default": self.eq_default, + "order_default": self.order_default, + "kw_only_default": self.kw_only_default, + "frozen_default": self.frozen_default, + "field_specifiers": list(self.field_specifiers), + } + + +def convert_overloaded_func_def(self: OverloadedFuncDef) -> Json: + return { + ".class": "OverloadedFuncDef", + "items": [convert_overload_part(i) for i in self.items], + "type": None if self.type is None else convert_type(self.type), + "fullname": self._fullname, + "impl": None if self.impl is None else convert_overload_part(self.impl), + "flags": get_flags(self, FUNCBASE_FLAGS), + "deprecated": self.deprecated, + "setter_index": self.setter_index, + } + + +def convert_overload_part(self: OverloadPart) -> Json: + if isinstance(self, FuncDef): + return convert_func_def(self) + else: + return convert_decorator(self) + + +def convert_decorator(self: Decorator) -> Json: + return { + ".class": "Decorator", + "func": convert_func_def(self.func), + "var": convert_var(self.var), + "is_overload": self.is_overload, + } + + +def convert_var(self: Var) -> Json: + data: dict[str, Any] = { + ".class": "Var", + "name": self._name, + "fullname": self._fullname, + "type": None if self.type is None else convert_type(self.type), + "setter_type": None if self.setter_type is None else convert_type(self.setter_type), + "flags": get_flags(self, VAR_FLAGS), + } + if self.final_value is not None: + data["final_value"] = self.final_value + return data + + +def convert_type_info(self: TypeInfo, cfg: Config) -> Json: + data = { + ".class": "TypeInfo", + "module_name": self.module_name, + "fullname": self.fullname, + "names": convert_symbol_table(self.names, cfg), + "defn": convert_class_def(self.defn), + "abstract_attributes": self.abstract_attributes, + "type_vars": self.type_vars, + "has_param_spec_type": self.has_param_spec_type, + "bases": [convert_type(b) for b in self.bases], + "mro": self._mro_refs, + "_promote": [convert_type(p) for p in self._promote], + "alt_promote": None if self.alt_promote is None else convert_type(self.alt_promote), + "declared_metaclass": ( + None if self.declared_metaclass is None else convert_type(self.declared_metaclass) + ), + "metaclass_type": ( + None if self.metaclass_type is None else convert_type(self.metaclass_type) + ), + "tuple_type": None if self.tuple_type is None else convert_type(self.tuple_type), + "typeddict_type": ( + None if self.typeddict_type is None else convert_typeddict_type(self.typeddict_type) + ), + "flags": get_flags(self, TypeInfo.FLAGS), + "metadata": self.metadata, + "slots": sorted(self.slots) if self.slots is not None else None, + "deletable_attributes": self.deletable_attributes, + "self_type": convert_type(self.self_type) if self.self_type is not None else None, + "dataclass_transform_spec": ( + convert_dataclass_transform_spec(self.dataclass_transform_spec) + if self.dataclass_transform_spec is not None + else None + ), + "deprecated": self.deprecated, + } + return data + + +def convert_class_def(self: ClassDef) -> Json: + return { + ".class": "ClassDef", + "name": self.name, + "fullname": self.fullname, + "type_vars": [convert_type(v) for v in self.type_vars], + } + + +def convert_type_alias(self: TypeAlias) -> Json: + data: Json = { + ".class": "TypeAlias", + "fullname": self._fullname, + "module": self.module, + "target": convert_type(self.target), + "alias_tvars": [convert_type(v) for v in self.alias_tvars], + "no_args": self.no_args, + "normalized": self.normalized, + "python_3_12_type_alias": self.python_3_12_type_alias, + } + return data + + +def convert_type_var_expr(self: TypeVarExpr) -> Json: + return { + ".class": "TypeVarExpr", + "name": self._name, + "fullname": self._fullname, + "values": [convert_type(t) for t in self.values], + "upper_bound": convert_type(self.upper_bound), + "default": convert_type(self.default), + "variance": self.variance, + } + + +def convert_param_spec_expr(self: ParamSpecExpr) -> Json: + return { + ".class": "ParamSpecExpr", + "name": self._name, + "fullname": self._fullname, + "upper_bound": convert_type(self.upper_bound), + "default": convert_type(self.default), + "variance": self.variance, + } + + +def convert_type_var_tuple_expr(self: TypeVarTupleExpr) -> Json: + return { + ".class": "TypeVarTupleExpr", + "name": self._name, + "fullname": self._fullname, + "upper_bound": convert_type(self.upper_bound), + "tuple_fallback": convert_type(self.tuple_fallback), + "default": convert_type(self.default), + "variance": self.variance, + } + + +def convert_type(typ: Type) -> Json: + if type(typ) is TypeAliasType: + return convert_type_alias_type(typ) + typ = get_proper_type(typ) + if isinstance(typ, Instance): + return convert_instance(typ) + elif isinstance(typ, AnyType): + return convert_any_type(typ) + elif isinstance(typ, NoneType): + return convert_none_type(typ) + elif isinstance(typ, UnionType): + return convert_union_type(typ) + elif isinstance(typ, TupleType): + return convert_tuple_type(typ) + elif isinstance(typ, CallableType): + return convert_callable_type(typ) + elif isinstance(typ, Overloaded): + return convert_overloaded(typ) + elif isinstance(typ, LiteralType): + return convert_literal_type(typ) + elif isinstance(typ, TypeVarType): + return convert_type_var_type(typ) + elif isinstance(typ, TypeType): + return convert_type_type(typ) + elif isinstance(typ, UninhabitedType): + return convert_uninhabited_type(typ) + elif isinstance(typ, UnpackType): + return convert_unpack_type(typ) + elif isinstance(typ, ParamSpecType): + return convert_param_spec_type(typ) + elif isinstance(typ, TypeVarTupleType): + return convert_type_var_tuple_type(typ) + elif isinstance(typ, Parameters): + return convert_parameters(typ) + elif isinstance(typ, TypedDictType): + return convert_typeddict_type(typ) + elif isinstance(typ, UnboundType): + return convert_unbound_type(typ) + return {"ERROR": f"{type(typ)!r} unrecognized"} + + +def convert_instance(self: Instance) -> Json: + ready = self.type is not NOT_READY + if not self.args and not self.last_known_value and not self.extra_attrs: + if ready: + return self.type.fullname + elif self.type_ref: + return self.type_ref + + data: dict[str, Any] = { + ".class": "Instance", + "type_ref": self.type.fullname if ready else self.type_ref, + "args": [convert_type(arg) for arg in self.args], + } + if self.last_known_value is not None: + data["last_known_value"] = convert_type(self.last_known_value) + data["extra_attrs"] = convert_extra_attrs(self.extra_attrs) if self.extra_attrs else None + return data + + +def convert_extra_attrs(self: ExtraAttrs) -> Json: + return { + ".class": "ExtraAttrs", + "attrs": {k: convert_type(v) for k, v in self.attrs.items()}, + "immutable": sorted(self.immutable), + "mod_name": self.mod_name, + } + + +def convert_type_alias_type(self: TypeAliasType) -> Json: + data: Json = { + ".class": "TypeAliasType", + "type_ref": self.type_ref, + "args": [convert_type(arg) for arg in self.args], + } + return data + + +def convert_any_type(self: AnyType) -> Json: + return { + ".class": "AnyType", + "type_of_any": self.type_of_any, + "source_any": convert_type(self.source_any) if self.source_any is not None else None, + "missing_import_name": self.missing_import_name, + } + + +def convert_none_type(self: NoneType) -> Json: + return {".class": "NoneType"} + + +def convert_union_type(self: UnionType) -> Json: + return { + ".class": "UnionType", + "items": [convert_type(t) for t in self.items], + "uses_pep604_syntax": self.uses_pep604_syntax, + } + + +def convert_tuple_type(self: TupleType) -> Json: + return { + ".class": "TupleType", + "items": [convert_type(t) for t in self.items], + "partial_fallback": convert_type(self.partial_fallback), + "implicit": self.implicit, + } + + +def convert_literal_type(self: LiteralType) -> Json: + return {".class": "LiteralType", "value": self.value, "fallback": convert_type(self.fallback)} + + +def convert_type_var_type(self: TypeVarType) -> Json: + assert not self.id.is_meta_var() + return { + ".class": "TypeVarType", + "name": self.name, + "fullname": self.fullname, + "id": self.id.raw_id, + "namespace": self.id.namespace, + "values": [convert_type(v) for v in self.values], + "upper_bound": convert_type(self.upper_bound), + "default": convert_type(self.default), + "variance": self.variance, + } + + +def convert_callable_type(self: CallableType) -> Json: + return { + ".class": "CallableType", + "arg_types": [convert_type(t) for t in self.arg_types], + "arg_kinds": [int(x.value) for x in self.arg_kinds], + "arg_names": self.arg_names, + "ret_type": convert_type(self.ret_type), + "fallback": convert_type(self.fallback), + "name": self.name, + # We don't serialize the definition (only used for error messages). + "variables": [convert_type(v) for v in self.variables], + "is_ellipsis_args": self.is_ellipsis_args, + "implicit": self.implicit, + "is_bound": self.is_bound, + "type_guard": convert_type(self.type_guard) if self.type_guard is not None else None, + "type_is": convert_type(self.type_is) if self.type_is is not None else None, + "from_concatenate": self.from_concatenate, + "imprecise_arg_kinds": self.imprecise_arg_kinds, + "unpack_kwargs": self.unpack_kwargs, + } + + +def convert_overloaded(self: Overloaded) -> Json: + return {".class": "Overloaded", "items": [convert_type(t) for t in self.items]} + + +def convert_type_type(self: TypeType) -> Json: + return {".class": "TypeType", "item": convert_type(self.item)} + + +def convert_uninhabited_type(self: UninhabitedType) -> Json: + return {".class": "UninhabitedType"} + + +def convert_unpack_type(self: UnpackType) -> Json: + return {".class": "UnpackType", "type": convert_type(self.type)} + + +def convert_param_spec_type(self: ParamSpecType) -> Json: + assert not self.id.is_meta_var() + return { + ".class": "ParamSpecType", + "name": self.name, + "fullname": self.fullname, + "id": self.id.raw_id, + "namespace": self.id.namespace, + "flavor": self.flavor, + "upper_bound": convert_type(self.upper_bound), + "default": convert_type(self.default), + "prefix": convert_type(self.prefix), + } + + +def convert_type_var_tuple_type(self: TypeVarTupleType) -> Json: + assert not self.id.is_meta_var() + return { + ".class": "TypeVarTupleType", + "name": self.name, + "fullname": self.fullname, + "id": self.id.raw_id, + "namespace": self.id.namespace, + "upper_bound": convert_type(self.upper_bound), + "tuple_fallback": convert_type(self.tuple_fallback), + "default": convert_type(self.default), + "min_len": self.min_len, + } + + +def convert_parameters(self: Parameters) -> Json: + return { + ".class": "Parameters", + "arg_types": [convert_type(t) for t in self.arg_types], + "arg_kinds": [int(x.value) for x in self.arg_kinds], + "arg_names": self.arg_names, + "variables": [convert_type(tv) for tv in self.variables], + "imprecise_arg_kinds": self.imprecise_arg_kinds, + } + + +def convert_typeddict_type(self: TypedDictType) -> Json: + return { + ".class": "TypedDictType", + "items": [[n, convert_type(t)] for (n, t) in self.items.items()], + "required_keys": sorted(self.required_keys), + "readonly_keys": sorted(self.readonly_keys), + "fallback": convert_type(self.fallback), + } + + +def convert_unbound_type(self: UnboundType) -> Json: + return { + ".class": "UnboundType", + "name": self.name, + "args": [convert_type(a) for a in self.args], + "expr": self.original_str_expr, + "expr_fallback": self.original_str_fallback, + } + + +def convert_binary_cache_meta_to_json(data: bytes, data_file: str) -> Json: + assert ( + data[0] == cache_version() and data[1] == CACHE_VERSION + ), "Cache file created by an incompatible mypy version" + meta = CacheMeta.read(ReadBuffer(data[2:]), data_file) + assert meta is not None, f"Error reading meta cache file associated with {data_file}" + return { + "id": meta.id, + "path": meta.path, + "mtime": meta.mtime, + "size": meta.size, + "hash": meta.hash, + "data_mtime": meta.data_mtime, + "dependencies": meta.dependencies, + "suppressed": meta.suppressed, + "options": meta.options, + "dep_prios": meta.dep_prios, + "dep_lines": meta.dep_lines, + "dep_hashes": [dep.hex() for dep in meta.dep_hashes], + "interface_hash": meta.interface_hash.hex(), + "version_id": meta.version_id, + "ignore_all": meta.ignore_all, + "plugin_data": meta.plugin_data, + } + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Convert binary cache files to JSON. " + "Create files in the same directory with extra .json extension." + ) + parser.add_argument( + "path", nargs="+", help="mypy cache data file to convert (.data.ff extension)" + ) + args = parser.parse_args() + fnams: list[str] = args.path + for fnam in fnams: + if fnam.endswith(".data.ff"): + is_data = True + elif fnam.endswith(".meta.ff"): + is_data = False + else: + sys.exit(f"error: Expected .data.ff or .meta.ff extension, but got {fnam}") + with open(fnam, "rb") as f: + data = f.read() + if is_data: + json_data = convert_binary_cache_to_json(data) + else: + data_file = fnam.removesuffix(".meta.ff") + ".data.ff" + json_data = convert_binary_cache_meta_to_json(data, data_file) + new_fnam = fnam + ".json" + with open(new_fnam, "w") as f: + json.dump(json_data, f) + print(f"{fnam} -> {new_fnam}") + + +if __name__ == "__main__": + main() diff --git a/micromamba_root/Lib/site-packages/mypy/exprtotype.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/exprtotype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..21911c9f92452926eebccd2daf3982a4a06307f4 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/exprtotype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/exprtotype.py b/micromamba_root/Lib/site-packages/mypy/exprtotype.py new file mode 100644 index 0000000000000000000000000000000000000000..ae36fc8adde09560e04d2e516a277d804906a77c --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/exprtotype.py @@ -0,0 +1,289 @@ +"""Translate an Expression to a Type value.""" + +from __future__ import annotations + +from collections.abc import Callable + +from mypy.fastparse import parse_type_string +from mypy.nodes import ( + MISSING_FALLBACK, + BytesExpr, + CallExpr, + ComplexExpr, + Context, + DictExpr, + EllipsisExpr, + Expression, + FloatExpr, + IndexExpr, + IntExpr, + ListExpr, + MemberExpr, + NameExpr, + OpExpr, + RefExpr, + StarExpr, + StrExpr, + SymbolTableNode, + TupleExpr, + UnaryExpr, + get_member_expr_fullname, +) +from mypy.options import Options +from mypy.types import ( + ANNOTATED_TYPE_NAMES, + AnyType, + CallableArgument, + EllipsisType, + Instance, + ProperType, + RawExpressionType, + Type, + TypedDictType, + TypeList, + TypeOfAny, + UnboundType, + UnionType, + UnpackType, +) + + +class TypeTranslationError(Exception): + """Exception raised when an expression is not valid as a type.""" + + +def _extract_argument_name(expr: Expression) -> str | None: + if isinstance(expr, NameExpr) and expr.name == "None": + return None + elif isinstance(expr, StrExpr): + return expr.value + else: + raise TypeTranslationError() + + +def expr_to_unanalyzed_type( + expr: Expression, + options: Options, + allow_new_syntax: bool = False, + _parent: Expression | None = None, + allow_unpack: bool = False, + lookup_qualified: Callable[[str, Context], SymbolTableNode | None] | None = None, +) -> ProperType: + """Translate an expression to the corresponding type. + + The result is not semantically analyzed. It can be UnboundType or TypeList. + Raise TypeTranslationError if the expression cannot represent a type. + + If lookup_qualified is not provided, the expression is expected to be semantically + analyzed. + + If allow_new_syntax is True, allow all type syntax independent of the target + Python version (used in stubs). + + # TODO: a lot of code here is duplicated in fastparse.py, refactor this. + """ + # The `parent` parameter is used in recursive calls to provide context for + # understanding whether an CallableArgument is ok. + name: str | None = None + if isinstance(expr, NameExpr): + name = expr.name + if name == "True": + return RawExpressionType(True, "builtins.bool", line=expr.line, column=expr.column) + elif name == "False": + return RawExpressionType(False, "builtins.bool", line=expr.line, column=expr.column) + else: + return UnboundType(name, line=expr.line, column=expr.column) + elif isinstance(expr, MemberExpr): + fullname = get_member_expr_fullname(expr) + if fullname: + return UnboundType(fullname, line=expr.line, column=expr.column) + else: + raise TypeTranslationError() + elif isinstance(expr, IndexExpr): + base = expr_to_unanalyzed_type( + expr.base, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified + ) + if isinstance(base, UnboundType): + if base.args: + raise TypeTranslationError() + if isinstance(expr.index, TupleExpr): + args = expr.index.items + else: + args = [expr.index] + + if isinstance(expr.base, RefExpr): + # Check if the type is Annotated[...]. For this we need the fullname, + # which must be looked up if the expression hasn't been semantically analyzed. + base_fullname = None + if lookup_qualified is not None: + sym = lookup_qualified(base.name, expr) + if sym and sym.node: + base_fullname = sym.node.fullname + else: + base_fullname = expr.base.fullname + + if base_fullname is not None and base_fullname in ANNOTATED_TYPE_NAMES: + # TODO: this is not the optimal solution as we are basically getting rid + # of the Annotation definition and only returning the type information, + # losing all the annotations. + return expr_to_unanalyzed_type( + args[0], options, allow_new_syntax, expr, lookup_qualified=lookup_qualified + ) + base.args = tuple( + expr_to_unanalyzed_type( + arg, + options, + allow_new_syntax, + expr, + allow_unpack=True, + lookup_qualified=lookup_qualified, + ) + for arg in args + ) + if not base.args: + base.empty_tuple_index = True + return base + else: + raise TypeTranslationError() + elif ( + isinstance(expr, OpExpr) + and expr.op == "|" + and ((options.python_version >= (3, 10)) or allow_new_syntax) + ): + return UnionType( + [ + expr_to_unanalyzed_type( + expr.left, options, allow_new_syntax, lookup_qualified=lookup_qualified + ), + expr_to_unanalyzed_type( + expr.right, options, allow_new_syntax, lookup_qualified=lookup_qualified + ), + ], + uses_pep604_syntax=True, + ) + elif isinstance(expr, CallExpr) and isinstance(_parent, ListExpr): + c = expr.callee + names = [] + # Go through the dotted member expr chain to get the full arg + # constructor name to look up + while True: + if isinstance(c, NameExpr): + names.append(c.name) + break + elif isinstance(c, MemberExpr): + names.append(c.name) + c = c.expr + else: + raise TypeTranslationError() + arg_const = ".".join(reversed(names)) + + # Go through the constructor args to get its name and type. + name = None + default_type = AnyType(TypeOfAny.unannotated) + typ: Type = default_type + for i, arg in enumerate(expr.args): + if expr.arg_names[i] is not None: + if expr.arg_names[i] == "name": + if name is not None: + # Two names + raise TypeTranslationError() + name = _extract_argument_name(arg) + continue + elif expr.arg_names[i] == "type": + if typ is not default_type: + # Two types + raise TypeTranslationError() + typ = expr_to_unanalyzed_type( + arg, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified + ) + continue + else: + raise TypeTranslationError() + elif i == 0: + typ = expr_to_unanalyzed_type( + arg, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified + ) + elif i == 1: + name = _extract_argument_name(arg) + else: + raise TypeTranslationError() + return CallableArgument(typ, name, arg_const, expr.line, expr.column) + elif isinstance(expr, ListExpr): + return TypeList( + [ + expr_to_unanalyzed_type( + t, + options, + allow_new_syntax, + expr, + allow_unpack=True, + lookup_qualified=lookup_qualified, + ) + for t in expr.items + ], + line=expr.line, + column=expr.column, + ) + elif isinstance(expr, StrExpr): + return parse_type_string(expr.value, "builtins.str", expr.line, expr.column) + elif isinstance(expr, BytesExpr): + return parse_type_string(expr.value, "builtins.bytes", expr.line, expr.column) + elif isinstance(expr, UnaryExpr): + typ = expr_to_unanalyzed_type( + expr.expr, options, allow_new_syntax, lookup_qualified=lookup_qualified + ) + if isinstance(typ, RawExpressionType): + if isinstance(typ.literal_value, int): + if expr.op == "-": + typ.literal_value *= -1 + return typ + elif expr.op == "+": + return typ + raise TypeTranslationError() + elif isinstance(expr, IntExpr): + return RawExpressionType(expr.value, "builtins.int", line=expr.line, column=expr.column) + elif isinstance(expr, FloatExpr): + # Floats are not valid parameters for RawExpressionType , so we just + # pass in 'None' for now. We'll report the appropriate error at a later stage. + return RawExpressionType(None, "builtins.float", line=expr.line, column=expr.column) + elif isinstance(expr, ComplexExpr): + # Same thing as above with complex numbers. + return RawExpressionType(None, "builtins.complex", line=expr.line, column=expr.column) + elif isinstance(expr, EllipsisExpr): + return EllipsisType(expr.line) + elif allow_unpack and isinstance(expr, StarExpr): + return UnpackType( + expr_to_unanalyzed_type( + expr.expr, options, allow_new_syntax, lookup_qualified=lookup_qualified + ), + from_star_syntax=True, + ) + elif isinstance(expr, DictExpr): + if not expr.items: + raise TypeTranslationError() + items: dict[str, Type] = {} + extra_items_from = [] + for item_name, value in expr.items: + if not isinstance(item_name, StrExpr): + if item_name is None: + extra_items_from.append( + expr_to_unanalyzed_type( + value, + options, + allow_new_syntax, + expr, + lookup_qualified=lookup_qualified, + ) + ) + continue + raise TypeTranslationError() + items[item_name.value] = expr_to_unanalyzed_type( + value, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified + ) + result = TypedDictType( + items, set(), set(), Instance(MISSING_FALLBACK, ()), expr.line, expr.column + ) + result.extra_items_from = extra_items_from + return result + else: + raise TypeTranslationError() diff --git a/micromamba_root/Lib/site-packages/mypy/fastparse.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/fastparse.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..3438cdc5d3e1f74e5031889bce995e7dc650a76e Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/fastparse.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/fastparse.py b/micromamba_root/Lib/site-packages/mypy/fastparse.py new file mode 100644 index 0000000000000000000000000000000000000000..e85b8fffaf9e970710589890cc59a2d17b042640 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/fastparse.py @@ -0,0 +1,2256 @@ +from __future__ import annotations + +import re +import sys +import warnings +from collections.abc import Callable, Sequence +from typing import Any, Final, Literal, TypeVar, cast, overload + +from mypy import defaults, errorcodes as codes, message_registry +from mypy.errors import Errors +from mypy.message_registry import ErrorMessage +from mypy.nodes import ( + ARG_NAMED, + ARG_NAMED_OPT, + ARG_OPT, + ARG_POS, + ARG_STAR, + ARG_STAR2, + MISSING_FALLBACK, + PARAM_SPEC_KIND, + TYPE_VAR_KIND, + TYPE_VAR_TUPLE_KIND, + ArgKind, + Argument, + AssertStmt, + AssignmentExpr, + AssignmentStmt, + AwaitExpr, + Block, + BreakStmt, + BytesExpr, + CallExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + ContinueStmt, + Decorator, + DelStmt, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + Expression, + ExpressionStmt, + FloatExpr, + ForStmt, + FuncDef, + GeneratorExpr, + GlobalDecl, + IfStmt, + Import, + ImportAll, + ImportBase, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MatchStmt, + MemberExpr, + MypyFile, + NameExpr, + Node, + NonlocalDecl, + OperatorAssignmentStmt, + OpExpr, + OverloadedFuncDef, + OverloadPart, + PassStmt, + RaiseStmt, + RefExpr, + ReturnStmt, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + Statement, + StrExpr, + SuperExpr, + TemplateStrExpr, + TempNode, + TryStmt, + TupleExpr, + TypeAliasStmt, + TypeParam, + UnaryExpr, + Var, + WhileStmt, + WithStmt, + YieldExpr, + YieldFromExpr, + check_param_names, +) +from mypy.options import Options +from mypy.patterns import ( + AsPattern, + ClassPattern, + MappingPattern, + OrPattern, + SequencePattern, + SingletonPattern, + StarredPattern, + ValuePattern, +) +from mypy.reachability import infer_reachability_of_if_statement, mark_block_unreachable +from mypy.sharedparse import argument_elide_name, special_function_elide_names +from mypy.traverser import TraverserVisitor +from mypy.types import ( + AnyType, + CallableArgument, + CallableType, + EllipsisType, + Instance, + ProperType, + RawExpressionType, + TupleType, + Type, + TypedDictType, + TypeList, + TypeOfAny, + UnboundType, + UnionType, + UnpackType, +) +from mypy.util import bytes_to_human_readable_repr, unnamed_function + +# pull this into a final variable to make mypyc be quiet about the +# the default argument warning +PY_MINOR_VERSION: Final = sys.version_info[1] + +import ast as ast3 +from ast import AST, Attribute, Call, FunctionType, Name, Starred, UAdd, UnaryOp, USub + + +def ast3_parse( + source: str | bytes, filename: str, mode: str, feature_version: int = PY_MINOR_VERSION +) -> AST: + # Ignore warnings that look like: + # :1: SyntaxWarning: invalid escape sequence '\.' + # because `source` could be anything, including literals like r'(re\.match)' + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + return ast3.parse( + source, + filename, + mode, + type_comments=True, # This works the magic + feature_version=feature_version, + ) + + +AstNode = ast3.expr | ast3.stmt | ast3.pattern | ast3.ExceptHandler + +if sys.version_info >= (3, 11): + TryStar = ast3.TryStar +else: + TryStar = Any + +if sys.version_info >= (3, 12): + ast_TypeAlias = ast3.TypeAlias + ast_ParamSpec = ast3.ParamSpec + ast_TypeVar = ast3.TypeVar + ast_TypeVarTuple = ast3.TypeVarTuple +else: + ast_TypeAlias = Any + ast_ParamSpec = Any + ast_TypeVar = Any + ast_TypeVarTuple = Any + +if sys.version_info >= (3, 14): + ast_TemplateStr = ast3.TemplateStr + ast_Interpolation = ast3.Interpolation +else: + ast_TemplateStr = Any + ast_Interpolation = Any + +N = TypeVar("N", bound=Node) + +# There is no way to create reasonable fallbacks at this stage, +# they must be patched later. +_dummy_fallback: Final = Instance(MISSING_FALLBACK, [], -1) + +TYPE_IGNORE_PATTERN: Final = re.compile(r"[^#]*#\s*type:\s*ignore\s*(.*)") + + +def parse( + source: str | bytes, + fnam: str, + module: str | None, + errors: Errors, + options: Options | None = None, +) -> MypyFile: + """Parse a source file, without doing any semantic analysis. + + Return the parse tree. If errors is not provided, raise ParseError + on failure. Otherwise, use the errors object to report parse errors. + """ + ignore_errors = (options is not None and options.ignore_errors) or ( + fnam in errors.ignored_files + ) + # If errors are ignored, we can drop many function bodies to speed up type checking. + strip_function_bodies = ignore_errors and (options is None or not options.preserve_asts) + + if options is None: + options = Options() + errors.set_file(fnam, module, options=options) + is_stub_file = fnam.endswith(".pyi") + if is_stub_file: + feature_version = defaults.PYTHON3_VERSION[1] + if options.python_version[0] == 3 and options.python_version[1] > feature_version: + feature_version = options.python_version[1] + else: + assert options.python_version[0] >= 3 + feature_version = options.python_version[1] + try: + # Disable + # - deprecation warnings for 'invalid escape sequence' (Python 3.11 and below) + # - syntax warnings for 'invalid escape sequence' (3.12+) and 'return in finally' (3.14+) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=SyntaxWarning) + ast = ast3_parse(source, fnam, "exec", feature_version=feature_version) + + tree = ASTConverter( + options=options, + is_stub=is_stub_file, + errors=errors, + strip_function_bodies=strip_function_bodies, + path=fnam, + ).visit(ast) + + except RecursionError as e: + # For very complex expressions it is possible to hit recursion limit + # before reaching a leaf node. + # Should reject at top level instead at bottom, since bottom would already + # be at the threshold of the recursion limit, and may fail again later. + # E.G. x1+x2+x3+...+xn -> BinOp(left=BinOp(left=BinOp(left=... + try: + # But to prove that is the cause of this particular recursion error, + # try to walk the tree using builtin visitor + ast3.NodeVisitor().visit(ast) + except RecursionError: + errors.report( + -1, -1, "Source expression too complex to parse", blocker=False, code=codes.MISC + ) + + tree = MypyFile([], [], False, {}) + + else: + # re-raise original recursion error if it *can* be unparsed, + # maybe this is some other issue that shouldn't be silenced/misdirected + raise e + + except SyntaxError as e: + message = e.msg + if feature_version > sys.version_info.minor and message.startswith("invalid syntax"): + python_version_str = f"{options.python_version[0]}.{options.python_version[1]}" + message += f"; you likely need to run mypy using Python {python_version_str} or newer" + errors.report( + e.lineno if e.lineno is not None else -1, + e.offset, + re.sub( + r"^(\s*\w)", lambda m: m.group(1).upper(), message + ), # Standardizing error message + blocker=True, + code=codes.SYNTAX, + ) + tree = MypyFile([], [], False, {}) + + assert isinstance(tree, MypyFile) + return tree + + +def parse_type_ignore_tag(tag: str | None) -> list[str] | None: + """Parse optional "[code, ...]" tag after "# type: ignore". + + Return: + * [] if no tag was found (ignore all errors) + * list of ignored error codes if a tag was found + * None if the tag was invalid. + """ + if not tag or tag.strip() == "" or tag.strip().startswith("#"): + # No tag -- ignore all errors. + return [] + m = re.match(r"\s*\[([^]#]*)\]\s*(#.*)?$", tag) + if m is None: + # Invalid "# type: ignore" comment. + return None + return [stripped_code for code in m.group(1).split(",") if (stripped_code := code.strip())] + + +def parse_type_comment( + type_comment: str, line: int, column: int, errors: Errors | None +) -> tuple[list[str] | None, ProperType | None]: + """Parse type portion of a type comment (+ optional type ignore). + + Return (ignore info, parsed type). + """ + try: + typ = ast3_parse(type_comment, "", "eval") + except SyntaxError: + if errors is not None: + stripped_type = type_comment.split("#", 2)[0].strip() + err_msg = message_registry.TYPE_COMMENT_SYNTAX_ERROR_VALUE.format(stripped_type) + errors.report(line, column, err_msg.value, blocker=True, code=err_msg.code) + return None, None + else: + raise + else: + extra_ignore = TYPE_IGNORE_PATTERN.match(type_comment) + if extra_ignore: + tag: str | None = extra_ignore.group(1) + ignored: list[str] | None = parse_type_ignore_tag(tag) + if ignored is None: + if errors is not None: + errors.report( + line, column, message_registry.INVALID_TYPE_IGNORE.value, code=codes.SYNTAX + ) + else: + raise SyntaxError + else: + ignored = None + assert isinstance(typ, ast3.Expression) + converted = TypeConverter( + errors, line=line, override_column=column, is_evaluated=False + ).visit(typ.body) + return ignored, converted + + +def parse_type_string( + expr_string: str, expr_fallback_name: str, line: int, column: int +) -> ProperType: + """Parses a type that was originally present inside of an explicit string. + + For example, suppose we have the type `Foo["blah"]`. We should parse the + string expression "blah" using this function. + """ + try: + _, node = parse_type_comment(f"({expr_string})", line=line, column=column, errors=None) + if isinstance(node, (UnboundType, UnionType)) and node.original_str_expr is None: + node.original_str_expr = expr_string + node.original_str_fallback = expr_fallback_name + return node + else: + return RawExpressionType(expr_string, expr_fallback_name, line, column) + except (SyntaxError, ValueError): + # Note: the parser will raise a `ValueError` instead of a SyntaxError if + # the string happens to contain things like \x00. + return RawExpressionType(expr_string, expr_fallback_name, line, column) + + +def is_no_type_check_decorator(expr: ast3.expr) -> bool: + if isinstance(expr, Name): + return expr.id == "no_type_check" + elif isinstance(expr, Attribute): + if isinstance(expr.value, Name): + return expr.value.id == "typing" and expr.attr == "no_type_check" + return False + + +def find_disallowed_expression_in_annotation_scope(expr: ast3.expr | None) -> ast3.expr | None: + if expr is None: + return None + for node in ast3.walk(expr): + if isinstance(node, (ast3.Yield, ast3.YieldFrom, ast3.NamedExpr, ast3.Await)): + return node + return None + + +class ASTConverter: + def __init__( + self, + options: Options, + is_stub: bool, + errors: Errors, + *, + strip_function_bodies: bool, + path: str, + ) -> None: + # 'C' for class, 'D' for function signature, 'F' for function, 'L' for lambda + self.class_and_function_stack: list[Literal["C", "D", "F", "L"]] = [] + self.imports: list[ImportBase] = [] + + self.options = options + self.is_stub = is_stub + self.errors = errors + self.strip_function_bodies = strip_function_bodies + self.path = path + + self.type_ignores: dict[int, list[str]] = {} + self.uses_template_strings = False + + # Cache of visit_X methods keyed by type of visited object + self.visitor_cache: dict[type, Callable[[AST | None], Any]] = {} + + def note(self, msg: str, line: int, column: int) -> None: + self.errors.report(line, column, msg, severity="note", code=codes.SYNTAX) + + def fail(self, msg: ErrorMessage, line: int, column: int, blocker: bool) -> None: + if blocker or not self.options.ignore_errors: + # Make sure self.errors reflects any type ignores that we have parsed + self.errors.set_file_ignored_lines( + self.path, self.type_ignores, self.options.ignore_errors + ) + self.errors.report(line, column, msg.value, blocker=blocker, code=msg.code) + + def fail_merge_overload(self, node: IfStmt) -> None: + self.fail( + message_registry.FAILED_TO_MERGE_OVERLOADS, + line=node.line, + column=node.column, + blocker=False, + ) + + def visit(self, node: AST | None) -> Any: + if node is None: + return None + typeobj = type(node) + visitor = self.visitor_cache.get(typeobj) + if visitor is None: + method = "visit_" + node.__class__.__name__ + visitor = getattr(self, method) + self.visitor_cache[typeobj] = visitor + + return visitor(node) + + def set_line(self, node: N, n: AstNode) -> N: + node.line = n.lineno + node.column = n.col_offset + node.end_line = n.end_lineno + node.end_column = n.end_col_offset + + return node + + def translate_opt_expr_list(self, l: Sequence[AST | None]) -> list[Expression | None]: + res: list[Expression | None] = [] + for e in l: + exp = self.visit(e) + res.append(exp) + return res + + def translate_expr_list(self, l: Sequence[AST]) -> list[Expression]: + return cast(list[Expression], self.translate_opt_expr_list(l)) + + def get_lineno(self, node: ast3.expr | ast3.stmt) -> int: + if ( + isinstance(node, (ast3.AsyncFunctionDef, ast3.ClassDef, ast3.FunctionDef)) + and node.decorator_list + ): + return node.decorator_list[0].lineno + return node.lineno + + def translate_stmt_list( + self, + stmts: Sequence[ast3.stmt], + *, + ismodule: bool = False, + can_strip: bool = False, + is_coroutine: bool = False, + ) -> list[Statement]: + # A "# type: ignore" comment before the first statement of a module + # ignores the whole module: + if ( + ismodule + and stmts + and self.type_ignores + and (first := min(self.type_ignores)) < self.get_lineno(stmts[0]) + ): + ignores = self.type_ignores.pop(first) + if ignores: + joined_ignores = ", ".join(ignores) + self.fail( + message_registry.TYPE_IGNORE_WITH_ERRCODE_ON_MODULE.format(joined_ignores), + line=first, + column=0, + blocker=False, + ) + block = Block(self.fix_function_overloads(self.translate_stmt_list(stmts))) + self.set_block_lines(block, stmts) + mark_block_unreachable(block) + return [block] + + stack = self.class_and_function_stack + # Fast case for stripping function bodies + if ( + can_strip + and self.strip_function_bodies + and len(stack) == 1 + and stack[0] == "F" + and not is_coroutine + ): + return [] + + res: list[Statement] = [] + for stmt in stmts: + node = self.visit(stmt) + res.append(node) + + # Slow case for stripping function bodies + if can_strip and self.strip_function_bodies: + if stack[-2:] == ["C", "F"]: + if is_possible_trivial_body(res): + can_strip = False + else: + # We only strip method bodies if they don't assign to an attribute, as + # this may define an attribute which has an externally visible effect. + visitor = FindAttributeAssign() + for s in res: + s.accept(visitor) + if visitor.found: + can_strip = False + break + + if can_strip and stack[-1] == "F" and is_coroutine: + # Yields inside an async function affect the return type and should not + # be stripped. + yield_visitor = FindYield() + for s in res: + s.accept(yield_visitor) + if yield_visitor.found: + can_strip = False + break + + if can_strip: + return [] + return res + + def translate_type_comment( + self, n: ast3.stmt | ast3.arg, type_comment: str | None + ) -> ProperType | None: + if type_comment is None: + return None + else: + lineno = n.lineno + extra_ignore, typ = parse_type_comment(type_comment, lineno, n.col_offset, self.errors) + if extra_ignore is not None: + self.type_ignores[lineno] = extra_ignore + return typ + + op_map: Final[dict[type[AST], str]] = { + ast3.Add: "+", + ast3.Sub: "-", + ast3.Mult: "*", + ast3.MatMult: "@", + ast3.Div: "/", + ast3.Mod: "%", + ast3.Pow: "**", + ast3.LShift: "<<", + ast3.RShift: ">>", + ast3.BitOr: "|", + ast3.BitXor: "^", + ast3.BitAnd: "&", + ast3.FloorDiv: "//", + } + + def from_operator(self, op: ast3.operator) -> str: + op_name = ASTConverter.op_map.get(type(op)) + if op_name is None: + raise RuntimeError("Unknown operator " + str(type(op))) + else: + return op_name + + comp_op_map: Final[dict[type[AST], str]] = { + ast3.Gt: ">", + ast3.Lt: "<", + ast3.Eq: "==", + ast3.GtE: ">=", + ast3.LtE: "<=", + ast3.NotEq: "!=", + ast3.Is: "is", + ast3.IsNot: "is not", + ast3.In: "in", + ast3.NotIn: "not in", # codespell:ignore notin + } + + def from_comp_operator(self, op: ast3.cmpop) -> str: + op_name = ASTConverter.comp_op_map.get(type(op)) + if op_name is None: + raise RuntimeError("Unknown comparison operator " + str(type(op))) + else: + return op_name + + def set_block_lines(self, b: Block, stmts: Sequence[ast3.stmt]) -> None: + first, last = stmts[0], stmts[-1] + b.line = first.lineno + b.column = first.col_offset + b.end_line = last.end_lineno + b.end_column = last.end_col_offset + if not b.body: + return + new_first = b.body[0] + if isinstance(new_first, (Decorator, OverloadedFuncDef)): + # Decorated function lines are different between Python versions. + # copy the normalization we do for them to block first lines. + b.line = new_first.line + b.column = new_first.column + + def as_block(self, stmts: list[ast3.stmt]) -> Block | None: + b = None + if stmts: + b = Block(self.fix_function_overloads(self.translate_stmt_list(stmts))) + self.set_block_lines(b, stmts) + return b + + def as_required_block( + self, stmts: list[ast3.stmt], *, can_strip: bool = False, is_coroutine: bool = False + ) -> Block: + assert stmts # must be non-empty + b = Block( + self.fix_function_overloads( + self.translate_stmt_list(stmts, can_strip=can_strip, is_coroutine=is_coroutine) + ) + ) + self.set_block_lines(b, stmts) + return b + + def fix_function_overloads(self, stmts: list[Statement]) -> list[Statement]: + ret: list[Statement] = [] + current_overload: list[OverloadPart] = [] + current_overload_name: str | None = None + last_unconditional_func_def: str | None = None + last_if_stmt: IfStmt | None = None + last_if_overload: Decorator | FuncDef | OverloadedFuncDef | None = None + last_if_stmt_overload_name: str | None = None + last_if_unknown_truth_value: IfStmt | None = None + skipped_if_stmts: list[IfStmt] = [] + for stmt in stmts: + if_overload_name: str | None = None + if_block_with_overload: Block | None = None + if_unknown_truth_value: IfStmt | None = None + if isinstance(stmt, IfStmt): + # Check IfStmt block to determine if function overloads can be merged + if_overload_name = self._check_ifstmt_for_overloads(stmt, current_overload_name) + if if_overload_name is not None: + if_block_with_overload, if_unknown_truth_value = ( + self._get_executable_if_block_with_overloads(stmt) + ) + + if ( + current_overload_name is not None + and isinstance(stmt, (Decorator, FuncDef)) + and stmt.name == current_overload_name + ): + if last_if_stmt is not None: + skipped_if_stmts.append(last_if_stmt) + if last_if_overload is not None: + # Last stmt was an IfStmt with same overload name + # Add overloads to current_overload + if isinstance(last_if_overload, OverloadedFuncDef): + current_overload.extend(last_if_overload.items) + else: + current_overload.append(last_if_overload) + last_if_stmt, last_if_overload = None, None + if last_if_unknown_truth_value: + self.fail_merge_overload(last_if_unknown_truth_value) + last_if_unknown_truth_value = None + current_overload.append(stmt) + if isinstance(stmt, FuncDef): + # This is, strictly speaking, wrong: there might be a decorated + # implementation. However, it only affects the error message we show: + # ideally it's "already defined", but "implementation must come last" + # is also reasonable. + # TODO: can we get rid of this completely and just always emit + # "implementation must come last" instead? + last_unconditional_func_def = stmt.name + elif ( + current_overload_name is not None + and isinstance(stmt, IfStmt) + and if_overload_name == current_overload_name + and last_unconditional_func_def != current_overload_name + ): + # IfStmt only contains stmts relevant to current_overload. + # Check if stmts are reachable and add them to current_overload, + # otherwise skip IfStmt to allow subsequent overload + # or function definitions. + skipped_if_stmts.append(stmt) + if if_block_with_overload is None: + if if_unknown_truth_value is not None: + self.fail_merge_overload(if_unknown_truth_value) + continue + if last_if_overload is not None: + # Last stmt was an IfStmt with same overload name + # Add overloads to current_overload + if isinstance(last_if_overload, OverloadedFuncDef): + current_overload.extend(last_if_overload.items) + else: + current_overload.append(last_if_overload) + last_if_stmt, last_if_overload = None, None + if isinstance(if_block_with_overload.body[-1], OverloadedFuncDef): + skipped_if_stmts.extend(cast(list[IfStmt], if_block_with_overload.body[:-1])) + current_overload.extend(if_block_with_overload.body[-1].items) + else: + current_overload.append( + cast(Decorator | FuncDef, if_block_with_overload.body[0]) + ) + else: + if last_if_stmt is not None: + ret.append(last_if_stmt) + last_if_stmt_overload_name = current_overload_name + last_if_stmt, last_if_overload = None, None + last_if_unknown_truth_value = None + + if current_overload and current_overload_name == last_if_stmt_overload_name: + # Remove last stmt (IfStmt) from ret if the overload names matched + # Only happens if no executable block had been found in IfStmt + popped = ret.pop() + assert isinstance(popped, IfStmt) + skipped_if_stmts.append(popped) + if current_overload and skipped_if_stmts: + # Add bare IfStmt (without overloads) to ret + # Required for mypy to be able to still check conditions + for if_stmt in skipped_if_stmts: + self._strip_contents_from_if_stmt(if_stmt) + ret.append(if_stmt) + skipped_if_stmts = [] + if len(current_overload) == 1: + ret.append(current_overload[0]) + elif len(current_overload) > 1: + ret.append(OverloadedFuncDef(current_overload)) + + # If we have multiple decorated functions named "_" next to each, we want to treat + # them as a series of regular FuncDefs instead of one OverloadedFuncDef because + # most of mypy/mypyc assumes that all the functions in an OverloadedFuncDef are + # related, but multiple underscore functions next to each other aren't necessarily + # related + last_unconditional_func_def = None + if isinstance(stmt, Decorator) and not unnamed_function(stmt.name): + current_overload = [stmt] + current_overload_name = stmt.name + elif isinstance(stmt, IfStmt) and if_overload_name is not None: + current_overload = [] + current_overload_name = if_overload_name + last_if_stmt = stmt + last_if_stmt_overload_name = None + if if_block_with_overload is not None: + skipped_if_stmts.extend( + cast(list[IfStmt], if_block_with_overload.body[:-1]) + ) + last_if_overload = cast( + Decorator | FuncDef | OverloadedFuncDef, + if_block_with_overload.body[-1], + ) + last_if_unknown_truth_value = if_unknown_truth_value + else: + current_overload = [] + current_overload_name = None + ret.append(stmt) + + if current_overload and skipped_if_stmts: + # Add bare IfStmt (without overloads) to ret + # Required for mypy to be able to still check conditions + for if_stmt in skipped_if_stmts: + self._strip_contents_from_if_stmt(if_stmt) + ret.append(if_stmt) + if len(current_overload) == 1: + ret.append(current_overload[0]) + elif len(current_overload) > 1: + ret.append(OverloadedFuncDef(current_overload)) + elif last_if_overload is not None: + ret.append(last_if_overload) + elif last_if_stmt is not None: + ret.append(last_if_stmt) + return ret + + def _check_ifstmt_for_overloads( + self, stmt: IfStmt, current_overload_name: str | None = None + ) -> str | None: + """Check if IfStmt contains only overloads with the same name. + Return overload_name if found, None otherwise. + """ + # Check that block only contains a single Decorator, FuncDef, or OverloadedFuncDef. + # Multiple overloads have already been merged as OverloadedFuncDef. + if not ( + len(stmt.body[0].body) == 1 + and ( + isinstance(stmt.body[0].body[0], (Decorator, OverloadedFuncDef)) + or current_overload_name is not None + and isinstance(stmt.body[0].body[0], FuncDef) + ) + or len(stmt.body[0].body) > 1 + and isinstance(stmt.body[0].body[-1], OverloadedFuncDef) + and all(self._is_stripped_if_stmt(if_stmt) for if_stmt in stmt.body[0].body[:-1]) + ): + return None + + overload_name = cast(Decorator | FuncDef | OverloadedFuncDef, stmt.body[0].body[-1]).name + if stmt.else_body is None: + return overload_name + + if len(stmt.else_body.body) == 1: + # For elif: else_body contains an IfStmt itself -> do a recursive check. + if ( + isinstance(stmt.else_body.body[0], (Decorator, FuncDef, OverloadedFuncDef)) + and stmt.else_body.body[0].name == overload_name + ): + return overload_name + if ( + isinstance(stmt.else_body.body[0], IfStmt) + and self._check_ifstmt_for_overloads(stmt.else_body.body[0], current_overload_name) + == overload_name + ): + return overload_name + + return None + + def _get_executable_if_block_with_overloads( + self, stmt: IfStmt + ) -> tuple[Block | None, IfStmt | None]: + """Return block from IfStmt that will get executed. + + Return + 0 -> A block if sure that alternative blocks are unreachable. + 1 -> An IfStmt if the reachability of it can't be inferred, + i.e. the truth value is unknown. + """ + infer_reachability_of_if_statement(stmt, self.options) + if stmt.else_body is None and stmt.body[0].is_unreachable is True: + # always False condition with no else + return None, None + if ( + stmt.else_body is None + or stmt.body[0].is_unreachable is False + and stmt.else_body.is_unreachable is False + ): + # The truth value is unknown, thus not conclusive + return None, stmt + if stmt.else_body.is_unreachable is True: + # else_body will be set unreachable if condition is always True + return stmt.body[0], None + if stmt.body[0].is_unreachable is True: + # body will be set unreachable if condition is always False + # else_body can contain an IfStmt itself (for elif) -> do a recursive check + if isinstance(stmt.else_body.body[0], IfStmt): + return self._get_executable_if_block_with_overloads(stmt.else_body.body[0]) + return stmt.else_body, None + return None, stmt + + def _strip_contents_from_if_stmt(self, stmt: IfStmt) -> None: + """Remove contents from IfStmt. + + Needed to still be able to check the conditions after the contents + have been merged with the surrounding function overloads. + """ + if len(stmt.body) == 1: + stmt.body[0].body = [] + if stmt.else_body and len(stmt.else_body.body) == 1: + if isinstance(stmt.else_body.body[0], IfStmt): + self._strip_contents_from_if_stmt(stmt.else_body.body[0]) + else: + stmt.else_body.body = [] + + def _is_stripped_if_stmt(self, stmt: Statement) -> bool: + """Check stmt to make sure it is a stripped IfStmt. + + See also: _strip_contents_from_if_stmt + """ + if not isinstance(stmt, IfStmt): + return False + + if not (len(stmt.body) == 1 and len(stmt.body[0].body) == 0): + # Body not empty + return False + + if not stmt.else_body or len(stmt.else_body.body) == 0: + # No or empty else_body + return True + + # For elif, IfStmt are stored recursively in else_body + return self._is_stripped_if_stmt(stmt.else_body.body[0]) + + def translate_module_id(self, id: str) -> str: + """Return the actual, internal module id for a source text id.""" + if id == self.options.custom_typing_module: + return "typing" + return id + + def visit_Module(self, mod: ast3.Module) -> MypyFile: + self.type_ignores = {} + self.uses_template_strings = False + for ti in mod.type_ignores: + parsed = parse_type_ignore_tag(ti.tag) + if parsed is not None: + self.type_ignores[ti.lineno] = parsed + else: + self.fail(message_registry.INVALID_TYPE_IGNORE, ti.lineno, -1, blocker=False) + + body = self.fix_function_overloads(self.translate_stmt_list(mod.body, ismodule=True)) + + ret = MypyFile(body, self.imports, False, ignored_lines=self.type_ignores) + ret.is_stub = self.is_stub + ret.path = self.path + ret.uses_template_strings = self.uses_template_strings + return ret + + # --- stmt --- + # FunctionDef(identifier name, arguments args, + # stmt* body, expr* decorator_list, expr? returns, string? type_comment) + # arguments = (arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults, + # arg? kwarg, expr* defaults) + def visit_FunctionDef(self, n: ast3.FunctionDef) -> FuncDef | Decorator: + return self.do_func_def(n) + + # AsyncFunctionDef(identifier name, arguments args, + # stmt* body, expr* decorator_list, expr? returns, string? type_comment) + def visit_AsyncFunctionDef(self, n: ast3.AsyncFunctionDef) -> FuncDef | Decorator: + return self.do_func_def(n, is_coroutine=True) + + def do_func_def( + self, n: ast3.FunctionDef | ast3.AsyncFunctionDef, is_coroutine: bool = False + ) -> FuncDef | Decorator: + """Helper shared between visit_FunctionDef and visit_AsyncFunctionDef.""" + self.class_and_function_stack.append("D") + no_type_check = bool( + n.decorator_list and any(is_no_type_check_decorator(d) for d in n.decorator_list) + ) + + lineno = n.lineno + args = self.transform_args(n.args, lineno, no_type_check=no_type_check) + if self.options.pos_only_special_methods and special_function_elide_names(n.name): + for arg in args: + arg.pos_only = True + + arg_kinds = [arg.kind for arg in args] + arg_names = [None if arg.pos_only else arg.variable.name for arg in args] + # Type parameters, if using new syntax for generics (PEP 695) + explicit_type_params: list[TypeParam] | None = None + + arg_types: list[Type | None] = [] + if no_type_check: + arg_types = [None] * len(args) + return_type = None + elif n.type_comment is not None: + try: + func_type_ast = ast3_parse(n.type_comment, "", "func_type") + assert isinstance(func_type_ast, FunctionType) + # for ellipsis arg + if ( + len(func_type_ast.argtypes) == 1 + and isinstance(func_type_ast.argtypes[0], ast3.Constant) + and func_type_ast.argtypes[0].value is Ellipsis + ): + if n.returns: + # PEP 484 disallows both type annotations and type comments + self.fail( + message_registry.DUPLICATE_TYPE_SIGNATURES, + lineno, + n.col_offset, + blocker=False, + ) + arg_types = [ + ( + a.type_annotation + if a.type_annotation is not None + else AnyType(TypeOfAny.unannotated) + ) + for a in args + ] + else: + # PEP 484 disallows both type annotations and type comments + if n.returns or any(a.type_annotation is not None for a in args): + self.fail( + message_registry.DUPLICATE_TYPE_SIGNATURES, + lineno, + n.col_offset, + blocker=False, + ) + translated_args: list[Type] = TypeConverter( + self.errors, line=lineno, override_column=n.col_offset + ).translate_expr_list(func_type_ast.argtypes) + # Use a cast to work around `list` invariance + arg_types = cast(list[Type | None], translated_args) + return_type = TypeConverter(self.errors, line=lineno).visit(func_type_ast.returns) + + # add implicit self type + in_method_scope = self.class_and_function_stack[-2:] == ["C", "D"] + if in_method_scope and len(arg_types) < len(args): + arg_types.insert(0, AnyType(TypeOfAny.special_form)) + except SyntaxError: + stripped_type = n.type_comment.split("#", 2)[0].strip() + err_msg = message_registry.TYPE_COMMENT_SYNTAX_ERROR_VALUE.format(stripped_type) + self.fail(err_msg, lineno, n.col_offset, blocker=False) + if n.type_comment and n.type_comment[0] not in ["(", "#"]: + self.note( + "Suggestion: wrap argument types in parentheses", lineno, n.col_offset + ) + arg_types = [AnyType(TypeOfAny.from_error)] * len(args) + return_type = AnyType(TypeOfAny.from_error) + else: + if sys.version_info >= (3, 12) and n.type_params: + explicit_type_params = self.translate_type_params(n.type_params) + + arg_types = [a.type_annotation for a in args] + return_type = TypeConverter( + self.errors, line=n.returns.lineno if n.returns else lineno + ).visit(n.returns) + + for arg, arg_type in zip(args, arg_types): + self.set_type_optional(arg_type, arg.initializer) + + func_type = None + if any(arg_types) or return_type: + if len(arg_types) != 1 and any(isinstance(t, EllipsisType) for t in arg_types): + self.fail( + message_registry.ELLIPSIS_WITH_OTHER_TYPEPARAMS, + lineno, + n.col_offset, + blocker=False, + ) + elif len(arg_types) > len(arg_kinds): + self.fail( + message_registry.TYPE_SIGNATURE_TOO_MANY_PARAMS, + lineno, + n.col_offset, + blocker=False, + ) + elif len(arg_types) < len(arg_kinds): + self.fail( + message_registry.TYPE_SIGNATURE_TOO_FEW_PARAMS, + lineno, + n.col_offset, + blocker=False, + ) + else: + func_type = CallableType( + [a if a is not None else AnyType(TypeOfAny.unannotated) for a in arg_types], + arg_kinds, + arg_names, + return_type if return_type is not None else AnyType(TypeOfAny.unannotated), + _dummy_fallback, + ) + + # End position is always the same. + end_line = n.end_lineno + end_column = n.end_col_offset + + self.class_and_function_stack.pop() + self.class_and_function_stack.append("F") + body = self.as_required_block(n.body, can_strip=True, is_coroutine=is_coroutine) + func_def = FuncDef(n.name, args, body, func_type, explicit_type_params) + if isinstance(func_def.type, CallableType): + # semanal.py does some in-place modifications we want to avoid + func_def.unanalyzed_type = func_def.type.copy_modified() + if is_coroutine: + func_def.is_coroutine = True + if func_type is not None: + func_type.definition = func_def + func_type.set_line(lineno) + + if n.decorator_list: + var = Var(func_def.name) + var.is_ready = False + var.set_line(lineno) + + func_def.is_decorated = True + self.set_line(func_def, n) + + deco = Decorator(func_def, self.translate_expr_list(n.decorator_list), var) + first = n.decorator_list[0] + deco.set_line(first.lineno, first.col_offset, end_line, end_column) + retval: FuncDef | Decorator = deco + else: + self.set_line(func_def, n) + retval = func_def + if self.options.include_docstrings: + func_def.docstring = ast3.get_docstring(n, clean=False) + self.class_and_function_stack.pop() + return retval + + def set_type_optional(self, type: Type | None, initializer: Expression | None) -> None: + if not self.options.implicit_optional: + return + # Indicate that type should be wrapped in an Optional if arg is initialized to None. + optional = isinstance(initializer, NameExpr) and initializer.name == "None" + if isinstance(type, UnboundType): + type.optional = optional + + def transform_args( + self, args: ast3.arguments, line: int, no_type_check: bool = False + ) -> list[Argument]: + new_args = [] + names: list[ast3.arg] = [] + posonlyargs = args.posonlyargs + args_args = posonlyargs + args.args + args_defaults = args.defaults + num_no_defaults = len(args_args) - len(args_defaults) + # positional arguments without defaults + for i, a in enumerate(args_args[:num_no_defaults]): + pos_only = i < len(posonlyargs) + new_args.append(self.make_argument(a, None, ARG_POS, no_type_check, pos_only)) + names.append(a) + + # positional arguments with defaults + for i, (a, d) in enumerate(zip(args_args[num_no_defaults:], args_defaults)): + pos_only = num_no_defaults + i < len(posonlyargs) + new_args.append(self.make_argument(a, d, ARG_OPT, no_type_check, pos_only)) + names.append(a) + + # *arg + if args.vararg is not None: + new_args.append(self.make_argument(args.vararg, None, ARG_STAR, no_type_check)) + names.append(args.vararg) + + # keyword-only arguments with defaults + for a, kd in zip(args.kwonlyargs, args.kw_defaults): + new_args.append( + self.make_argument( + a, kd, ARG_NAMED if kd is None else ARG_NAMED_OPT, no_type_check + ) + ) + names.append(a) + + # **kwarg + if args.kwarg is not None: + new_args.append(self.make_argument(args.kwarg, None, ARG_STAR2, no_type_check)) + names.append(args.kwarg) + + check_param_names([arg.variable.name for arg in new_args], names, self.fail_arg) + + return new_args + + def make_argument( + self, + arg: ast3.arg, + default: ast3.expr | None, + kind: ArgKind, + no_type_check: bool, + pos_only: bool = False, + ) -> Argument: + if no_type_check: + arg_type = None + else: + annotation = arg.annotation + type_comment = arg.type_comment + if annotation is not None and type_comment is not None: + self.fail( + message_registry.DUPLICATE_TYPE_SIGNATURES, + arg.lineno, + arg.col_offset, + blocker=False, + ) + arg_type = None + if annotation is not None: + arg_type = TypeConverter(self.errors, line=arg.lineno).visit(annotation) + else: + arg_type = self.translate_type_comment(arg, type_comment) + if argument_elide_name(arg.arg): + pos_only = True + + var = Var(arg.arg, arg_type) + var.is_inferred = False + var.is_argument = True + argument = Argument(var, arg_type, self.visit(default), kind, pos_only) + argument.set_line(arg.lineno, arg.col_offset, arg.end_lineno, arg.end_col_offset) + return argument + + def fail_arg(self, msg: str, arg: ast3.arg) -> None: + self.fail(ErrorMessage(msg), arg.lineno, arg.col_offset, blocker=True) + + # ClassDef(identifier name, + # expr* bases, + # keyword* keywords, + # stmt* body, + # expr* decorator_list) + def visit_ClassDef(self, n: ast3.ClassDef) -> ClassDef: + self.class_and_function_stack.append("C") + keywords = [(kw.arg, self.visit(kw.value)) for kw in n.keywords if kw.arg] + + # Type parameters, if using new syntax for generics (PEP 695) + explicit_type_params: list[TypeParam] | None = None + + if sys.version_info >= (3, 12) and n.type_params: + explicit_type_params = self.translate_type_params(n.type_params) + + cdef = ClassDef( + n.name, + self.as_required_block(n.body), + None, + self.translate_expr_list(n.bases), + metaclass=dict(keywords).get("metaclass"), + keywords=keywords, + type_args=explicit_type_params, + ) + cdef.decorators = self.translate_expr_list(n.decorator_list) + self.set_line(cdef, n) + + if self.options.include_docstrings: + cdef.docstring = ast3.get_docstring(n, clean=False) + cdef.column = n.col_offset + cdef.end_line = n.end_lineno + cdef.end_column = n.end_col_offset + self.class_and_function_stack.pop() + return cdef + + def validate_type_param(self, type_param: ast_TypeVar) -> None: + incorrect_expr = find_disallowed_expression_in_annotation_scope(type_param.bound) + if incorrect_expr is None: + return + if isinstance(incorrect_expr, (ast3.Yield, ast3.YieldFrom)): + self.fail( + message_registry.TYPE_VAR_YIELD_EXPRESSION_IN_BOUND, + type_param.lineno, + type_param.col_offset, + blocker=True, + ) + if isinstance(incorrect_expr, ast3.NamedExpr): + self.fail( + message_registry.TYPE_VAR_NAMED_EXPRESSION_IN_BOUND, + type_param.lineno, + type_param.col_offset, + blocker=True, + ) + if isinstance(incorrect_expr, ast3.Await): + self.fail( + message_registry.TYPE_VAR_AWAIT_EXPRESSION_IN_BOUND, + type_param.lineno, + type_param.col_offset, + blocker=True, + ) + + def translate_type_params(self, type_params: list[Any]) -> list[TypeParam]: + explicit_type_params = [] + for p in type_params: + bound: Type | None = None + values: list[Type] = [] + default: Type | None = None + if sys.version_info >= (3, 13): + default = TypeConverter(self.errors, line=p.lineno).visit(p.default_value) + if isinstance(p, ast_ParamSpec): # type: ignore[misc] + explicit_type_params.append(TypeParam(p.name, PARAM_SPEC_KIND, None, [], default)) + elif isinstance(p, ast_TypeVarTuple): # type: ignore[misc] + explicit_type_params.append( + TypeParam(p.name, TYPE_VAR_TUPLE_KIND, None, [], default) + ) + else: + if isinstance(p.bound, ast3.Tuple): + if len(p.bound.elts) < 2: + self.fail( + message_registry.TYPE_VAR_TOO_FEW_CONSTRAINED_TYPES, + p.lineno, + p.col_offset, + blocker=False, + ) + else: + conv = TypeConverter(self.errors, line=p.lineno) + values = [conv.visit(t) for t in p.bound.elts] + elif p.bound is not None: + self.validate_type_param(p) + bound = TypeConverter(self.errors, line=p.lineno).visit(p.bound) + explicit_type_params.append( + TypeParam(p.name, TYPE_VAR_KIND, bound, values, default) + ) + return explicit_type_params + + # Return(expr? value) + def visit_Return(self, n: ast3.Return) -> ReturnStmt: + node = ReturnStmt(self.visit(n.value)) + return self.set_line(node, n) + + # Delete(expr* targets) + def visit_Delete(self, n: ast3.Delete) -> DelStmt: + if len(n.targets) > 1: + tup = TupleExpr(self.translate_expr_list(n.targets)) + tup.set_line(n.lineno) + node = DelStmt(tup) + else: + node = DelStmt(self.visit(n.targets[0])) + return self.set_line(node, n) + + # Assign(expr* targets, expr? value, string? type_comment, expr? annotation) + def visit_Assign(self, n: ast3.Assign) -> AssignmentStmt: + lvalues = self.translate_expr_list(n.targets) + rvalue = self.visit(n.value) + typ = self.translate_type_comment(n, n.type_comment) + s = AssignmentStmt(lvalues, rvalue, type=typ, new_syntax=False) + return self.set_line(s, n) + + # AnnAssign(expr target, expr annotation, expr? value, int simple) + def visit_AnnAssign(self, n: ast3.AnnAssign) -> AssignmentStmt: + line = n.lineno + if n.value is None: # always allow 'x: int' + rvalue: Expression = TempNode(AnyType(TypeOfAny.special_form), no_rhs=True) + self.set_line(rvalue, n) + else: + rvalue = self.visit(n.value) + typ = TypeConverter(self.errors, line=line).visit(n.annotation) + assert typ is not None + typ.column = n.annotation.col_offset + s = AssignmentStmt([self.visit(n.target)], rvalue, type=typ, new_syntax=True) + return self.set_line(s, n) + + # AugAssign(expr target, operator op, expr value) + def visit_AugAssign(self, n: ast3.AugAssign) -> OperatorAssignmentStmt: + s = OperatorAssignmentStmt( + self.from_operator(n.op), self.visit(n.target), self.visit(n.value) + ) + return self.set_line(s, n) + + # For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment) + def visit_For(self, n: ast3.For) -> ForStmt: + target_type = self.translate_type_comment(n, n.type_comment) + node = ForStmt( + self.visit(n.target), + self.visit(n.iter), + self.as_required_block(n.body), + self.as_block(n.orelse), + target_type, + ) + return self.set_line(node, n) + + # AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment) + def visit_AsyncFor(self, n: ast3.AsyncFor) -> ForStmt: + target_type = self.translate_type_comment(n, n.type_comment) + node = ForStmt( + self.visit(n.target), + self.visit(n.iter), + self.as_required_block(n.body), + self.as_block(n.orelse), + target_type, + ) + node.is_async = True + return self.set_line(node, n) + + # While(expr test, stmt* body, stmt* orelse) + def visit_While(self, n: ast3.While) -> WhileStmt: + node = WhileStmt( + self.visit(n.test), self.as_required_block(n.body), self.as_block(n.orelse) + ) + return self.set_line(node, n) + + # If(expr test, stmt* body, stmt* orelse) + def visit_If(self, n: ast3.If) -> IfStmt: + node = IfStmt( + [self.visit(n.test)], [self.as_required_block(n.body)], self.as_block(n.orelse) + ) + return self.set_line(node, n) + + # With(withitem* items, stmt* body, string? type_comment) + def visit_With(self, n: ast3.With) -> WithStmt: + target_type = self.translate_type_comment(n, n.type_comment) + node = WithStmt( + [self.visit(i.context_expr) for i in n.items], + [self.visit(i.optional_vars) for i in n.items], + self.as_required_block(n.body), + target_type, + ) + return self.set_line(node, n) + + # AsyncWith(withitem* items, stmt* body, string? type_comment) + def visit_AsyncWith(self, n: ast3.AsyncWith) -> WithStmt: + target_type = self.translate_type_comment(n, n.type_comment) + s = WithStmt( + [self.visit(i.context_expr) for i in n.items], + [self.visit(i.optional_vars) for i in n.items], + self.as_required_block(n.body), + target_type, + ) + s.is_async = True + return self.set_line(s, n) + + # Raise(expr? exc, expr? cause) + def visit_Raise(self, n: ast3.Raise) -> RaiseStmt: + node = RaiseStmt(self.visit(n.exc), self.visit(n.cause)) + return self.set_line(node, n) + + # Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody) + def visit_Try(self, n: ast3.Try) -> TryStmt: + vs = [ + self.set_line(NameExpr(h.name), h) if h.name is not None else None for h in n.handlers + ] + types = [self.visit(h.type) for h in n.handlers] + handlers = [self.as_required_block(h.body) for h in n.handlers] + + node = TryStmt( + self.as_required_block(n.body), + vs, + types, + handlers, + self.as_block(n.orelse), + self.as_block(n.finalbody), + ) + return self.set_line(node, n) + + def visit_TryStar(self, n: TryStar) -> TryStmt: + vs = [ + self.set_line(NameExpr(h.name), h) if h.name is not None else None for h in n.handlers + ] + types = [self.visit(h.type) for h in n.handlers] + handlers = [self.as_required_block(h.body) for h in n.handlers] + + node = TryStmt( + self.as_required_block(n.body), + vs, + types, + handlers, + self.as_block(n.orelse), + self.as_block(n.finalbody), + ) + node.is_star = True + return self.set_line(node, n) + + # Assert(expr test, expr? msg) + def visit_Assert(self, n: ast3.Assert) -> AssertStmt: + node = AssertStmt(self.visit(n.test), self.visit(n.msg)) + return self.set_line(node, n) + + # Import(alias* names) + def visit_Import(self, n: ast3.Import) -> Import: + names: list[tuple[str, str | None]] = [] + for alias in n.names: + name = self.translate_module_id(alias.name) + asname = alias.asname + if asname is None and name != alias.name: + # if the module name has been translated (and it's not already + # an explicit import-as), make it an implicit import-as the + # original name + asname = alias.name + names.append((name, asname)) + i = Import(names) + self.imports.append(i) + return self.set_line(i, n) + + # ImportFrom(identifier? module, alias* names, int? level) + def visit_ImportFrom(self, n: ast3.ImportFrom) -> ImportBase: + assert n.level is not None + if len(n.names) == 1 and n.names[0].name == "*": + mod = n.module if n.module is not None else "" + i: ImportBase = ImportAll(mod, n.level) + else: + i = ImportFrom( + self.translate_module_id(n.module) if n.module is not None else "", + n.level, + [(a.name, a.asname) for a in n.names], + ) + self.imports.append(i) + return self.set_line(i, n) + + # Global(identifier* names) + def visit_Global(self, n: ast3.Global) -> GlobalDecl: + g = GlobalDecl(n.names) + return self.set_line(g, n) + + # Nonlocal(identifier* names) + def visit_Nonlocal(self, n: ast3.Nonlocal) -> NonlocalDecl: + d = NonlocalDecl(n.names) + return self.set_line(d, n) + + # Expr(expr value) + def visit_Expr(self, n: ast3.Expr) -> ExpressionStmt: + value = self.visit(n.value) + node = ExpressionStmt(value) + return self.set_line(node, n) + + # Pass + def visit_Pass(self, n: ast3.Pass) -> PassStmt: + s = PassStmt() + return self.set_line(s, n) + + # Break + def visit_Break(self, n: ast3.Break) -> BreakStmt: + s = BreakStmt() + return self.set_line(s, n) + + # Continue + def visit_Continue(self, n: ast3.Continue) -> ContinueStmt: + s = ContinueStmt() + return self.set_line(s, n) + + # --- expr --- + + def visit_NamedExpr(self, n: ast3.NamedExpr) -> AssignmentExpr: + s = AssignmentExpr(self.visit(n.target), self.visit(n.value)) + return self.set_line(s, n) + + # BoolOp(boolop op, expr* values) + def visit_BoolOp(self, n: ast3.BoolOp) -> OpExpr: + # mypy translates (1 and 2 and 3) as (1 and (2 and 3)) + assert len(n.values) >= 2 + op_node = n.op + if isinstance(op_node, ast3.And): + op = "and" + elif isinstance(op_node, ast3.Or): + op = "or" + else: + raise RuntimeError("unknown BoolOp " + str(type(n))) + + # potentially inefficient! + return self.group(op, self.translate_expr_list(n.values), n) + + def group(self, op: str, vals: list[Expression], n: ast3.expr) -> OpExpr: + if len(vals) == 2: + e = OpExpr(op, vals[0], vals[1]) + else: + e = OpExpr(op, vals[0], self.group(op, vals[1:], n)) + return self.set_line(e, n) + + # BinOp(expr left, operator op, expr right) + def visit_BinOp(self, n: ast3.BinOp) -> OpExpr: + op = self.from_operator(n.op) + + if op is None: + raise RuntimeError("cannot translate BinOp " + str(type(n.op))) + + e = OpExpr(op, self.visit(n.left), self.visit(n.right)) + return self.set_line(e, n) + + # UnaryOp(unaryop op, expr operand) + def visit_UnaryOp(self, n: ast3.UnaryOp) -> UnaryExpr: + op = None + if isinstance(n.op, ast3.Invert): + op = "~" + elif isinstance(n.op, ast3.Not): + op = "not" + elif isinstance(n.op, ast3.UAdd): + op = "+" + elif isinstance(n.op, ast3.USub): + op = "-" + + if op is None: + raise RuntimeError("cannot translate UnaryOp " + str(type(n.op))) + + e = UnaryExpr(op, self.visit(n.operand)) + return self.set_line(e, n) + + # Lambda(arguments args, expr body) + def visit_Lambda(self, n: ast3.Lambda) -> LambdaExpr: + body = ast3.Return(n.body) + body.lineno = n.body.lineno + body.col_offset = n.body.col_offset + + self.class_and_function_stack.append("L") + e = LambdaExpr(self.transform_args(n.args, n.lineno), self.as_required_block([body])) + self.class_and_function_stack.pop() + e.set_line(n.lineno, n.col_offset) # Overrides set_line -- can't use self.set_line + return e + + # IfExp(expr test, expr body, expr orelse) + def visit_IfExp(self, n: ast3.IfExp) -> ConditionalExpr: + e = ConditionalExpr(self.visit(n.test), self.visit(n.body), self.visit(n.orelse)) + return self.set_line(e, n) + + # Dict(expr* keys, expr* values) + def visit_Dict(self, n: ast3.Dict) -> DictExpr: + e = DictExpr( + list(zip(self.translate_opt_expr_list(n.keys), self.translate_expr_list(n.values))) + ) + return self.set_line(e, n) + + # Set(expr* elts) + def visit_Set(self, n: ast3.Set) -> SetExpr: + e = SetExpr(self.translate_expr_list(n.elts)) + return self.set_line(e, n) + + # ListComp(expr elt, comprehension* generators) + def visit_ListComp(self, n: ast3.ListComp) -> ListComprehension: + e = ListComprehension(self.visit_GeneratorExp(cast(ast3.GeneratorExp, n))) + return self.set_line(e, n) + + # SetComp(expr elt, comprehension* generators) + def visit_SetComp(self, n: ast3.SetComp) -> SetComprehension: + e = SetComprehension(self.visit_GeneratorExp(cast(ast3.GeneratorExp, n))) + return self.set_line(e, n) + + # DictComp(expr key, expr value, comprehension* generators) + def visit_DictComp(self, n: ast3.DictComp) -> DictionaryComprehension: + targets = [self.visit(c.target) for c in n.generators] + iters = [self.visit(c.iter) for c in n.generators] + ifs_list = [self.translate_expr_list(c.ifs) for c in n.generators] + is_async = [bool(c.is_async) for c in n.generators] + e = DictionaryComprehension( + self.visit(n.key), self.visit(n.value), targets, iters, ifs_list, is_async + ) + return self.set_line(e, n) + + # GeneratorExp(expr elt, comprehension* generators) + def visit_GeneratorExp(self, n: ast3.GeneratorExp) -> GeneratorExpr: + targets = [self.visit(c.target) for c in n.generators] + iters = [self.visit(c.iter) for c in n.generators] + ifs_list = [self.translate_expr_list(c.ifs) for c in n.generators] + is_async = [bool(c.is_async) for c in n.generators] + e = GeneratorExpr(self.visit(n.elt), targets, iters, ifs_list, is_async) + return self.set_line(e, n) + + # Await(expr value) + def visit_Await(self, n: ast3.Await) -> AwaitExpr: + v = self.visit(n.value) + e = AwaitExpr(v) + return self.set_line(e, n) + + # Yield(expr? value) + def visit_Yield(self, n: ast3.Yield) -> YieldExpr: + e = YieldExpr(self.visit(n.value)) + return self.set_line(e, n) + + # YieldFrom(expr value) + def visit_YieldFrom(self, n: ast3.YieldFrom) -> YieldFromExpr: + e = YieldFromExpr(self.visit(n.value)) + return self.set_line(e, n) + + # Compare(expr left, cmpop* ops, expr* comparators) + def visit_Compare(self, n: ast3.Compare) -> ComparisonExpr: + operators = [self.from_comp_operator(o) for o in n.ops] + operands = self.translate_expr_list([n.left] + n.comparators) + e = ComparisonExpr(operators, operands) + return self.set_line(e, n) + + # Call(expr func, expr* args, keyword* keywords) + # keyword = (identifier? arg, expr value) + def visit_Call(self, n: Call) -> CallExpr: + args = n.args + keywords = n.keywords + keyword_names = [k.arg for k in keywords] + arg_types = self.translate_expr_list( + [a.value if isinstance(a, Starred) else a for a in args] + [k.value for k in keywords] + ) + arg_kinds = [ARG_STAR if type(a) is Starred else ARG_POS for a in args] + [ + ARG_STAR2 if arg is None else ARG_NAMED for arg in keyword_names + ] + e = CallExpr( + self.visit(n.func), + arg_types, + arg_kinds, + cast("list[str | None]", [None] * len(args)) + keyword_names, + ) + return self.set_line(e, n) + + # Constant(object value) + def visit_Constant(self, n: ast3.Constant) -> Any: + val = n.value + e: Any = None + if val is None: + e = NameExpr("None") + elif isinstance(val, str): + e = StrExpr(val) + elif isinstance(val, bytes): + e = BytesExpr(bytes_to_human_readable_repr(val)) + elif isinstance(val, bool): # Must check before int! + e = NameExpr(str(val)) + elif isinstance(val, int): + e = IntExpr(val) + elif isinstance(val, float): + e = FloatExpr(val) + elif isinstance(val, complex): + e = ComplexExpr(val) + elif val is Ellipsis: + e = EllipsisExpr() + else: + raise RuntimeError("Constant not implemented for " + str(type(val))) + return self.set_line(e, n) + + # JoinedStr(expr* values) + def visit_JoinedStr(self, n: ast3.JoinedStr) -> Expression: + # Each of n.values is a str or FormattedValue; we just concatenate + # them all using ''.join. + empty_string = StrExpr("") + empty_string.set_line(n.lineno, n.col_offset) + strs_to_join = ListExpr(self.translate_expr_list(n.values)) + strs_to_join.set_line(empty_string) + # Don't make unnecessary join call if there is only one str to join + if len(strs_to_join.items) == 1: + return self.set_line(strs_to_join.items[0], n) + elif len(strs_to_join.items) > 1: + last = strs_to_join.items[-1] + if isinstance(last, StrExpr) and last.value == "": + # 3.12 can add an empty literal at the end. Delete it for consistency + # between Python versions. + del strs_to_join.items[-1:] + join_method = MemberExpr(empty_string, "join") + join_method.set_line(empty_string) + result_expression = CallExpr(join_method, [strs_to_join], [ARG_POS], [None]) + return self.set_line(result_expression, n) + + # FormattedValue(expr value) + def visit_FormattedValue(self, n: ast3.FormattedValue) -> Expression: + # A FormattedValue is a component of a JoinedStr, or it can exist + # on its own. We translate them to individual '{}'.format(value) + # calls. Format specifier and conversion information is passed along + # to allow mypyc to support f-strings with format specifiers and conversions. + val_exp = self.visit(n.value) + val_exp.set_line(n.lineno, n.col_offset) + conv_str = "" if n.conversion < 0 else "!" + chr(n.conversion) + format_string = StrExpr("{" + conv_str + ":{}}") + format_spec_exp = self.visit(n.format_spec) if n.format_spec is not None else StrExpr("") + format_string.set_line(n.lineno, n.col_offset) + format_method = MemberExpr(format_string, "format") + format_method.set_line(format_string) + result_expression = CallExpr( + format_method, [val_exp, format_spec_exp], [ARG_POS, ARG_POS], [None, None] + ) + return self.set_line(result_expression, n) + + # TemplateStr(expr* values) + def visit_TemplateStr(self, n: ast_TemplateStr) -> TemplateStrExpr: + self.uses_template_strings = True + items: list[Expression | tuple[Expression, str, str | None, Expression | None]] = [] + for value in n.values: + if isinstance(value, ast_Interpolation): # type: ignore[misc] + val_expr = self.visit(value.value) + val_expr.set_line(value.lineno, value.col_offset) + conversion = None if value.conversion < 0 else chr(value.conversion) + format_spec = ( + self.visit(value.format_spec) if value.format_spec is not None else None + ) + items.append((val_expr, value.str, conversion, format_spec)) + else: + items.append(self.visit(value)) + e = TemplateStrExpr(items) + return self.set_line(e, n) + + # Attribute(expr value, identifier attr, expr_context ctx) + def visit_Attribute(self, n: Attribute) -> MemberExpr | SuperExpr: + value = n.value + member_expr = MemberExpr(self.visit(value), n.attr) + obj = member_expr.expr + if ( + isinstance(obj, CallExpr) + and isinstance(obj.callee, NameExpr) + and obj.callee.name == "super" + ): + e: MemberExpr | SuperExpr = SuperExpr(member_expr.name, obj) + else: + e = member_expr + return self.set_line(e, n) + + # Subscript(expr value, slice slice, expr_context ctx) + def visit_Subscript(self, n: ast3.Subscript) -> IndexExpr: + e = IndexExpr(self.visit(n.value), self.visit(n.slice)) + return self.set_line(e, n) + + # Starred(expr value, expr_context ctx) + def visit_Starred(self, n: Starred) -> StarExpr: + e = StarExpr(self.visit(n.value)) + return self.set_line(e, n) + + # Name(identifier id, expr_context ctx) + def visit_Name(self, n: Name) -> NameExpr: + e = NameExpr(n.id) + return self.set_line(e, n) + + # List(expr* elts, expr_context ctx) + def visit_List(self, n: ast3.List) -> ListExpr | TupleExpr: + expr_list: list[Expression] = [self.visit(e) for e in n.elts] + if isinstance(n.ctx, ast3.Store): + # [x, y] = z and (x, y) = z means exactly the same thing + e: ListExpr | TupleExpr = TupleExpr(expr_list) + else: + e = ListExpr(expr_list) + return self.set_line(e, n) + + # Tuple(expr* elts, expr_context ctx) + def visit_Tuple(self, n: ast3.Tuple) -> TupleExpr: + e = TupleExpr(self.translate_expr_list(n.elts)) + return self.set_line(e, n) + + # Slice(expr? lower, expr? upper, expr? step) + def visit_Slice(self, n: ast3.Slice) -> SliceExpr: + e = SliceExpr(self.visit(n.lower), self.visit(n.upper), self.visit(n.step)) + return self.set_line(e, n) + + # Match(expr subject, match_case* cases) # python 3.10 and later + def visit_Match(self, n: ast3.Match) -> MatchStmt: + node = MatchStmt( + self.visit(n.subject), + [self.visit(c.pattern) for c in n.cases], + [self.visit(c.guard) for c in n.cases], + [self.as_required_block(c.body) for c in n.cases], + ) + return self.set_line(node, n) + + def visit_MatchValue(self, n: ast3.MatchValue) -> ValuePattern: + node = ValuePattern(self.visit(n.value)) + return self.set_line(node, n) + + def visit_MatchSingleton(self, n: ast3.MatchSingleton) -> SingletonPattern: + node = SingletonPattern(n.value) + return self.set_line(node, n) + + def visit_MatchSequence(self, n: ast3.MatchSequence) -> SequencePattern: + patterns = [self.visit(p) for p in n.patterns] + stars = [p for p in patterns if isinstance(p, StarredPattern)] + assert len(stars) < 2 + + node = SequencePattern(patterns) + return self.set_line(node, n) + + def visit_MatchStar(self, n: ast3.MatchStar) -> StarredPattern: + if n.name is None: + node = StarredPattern(None) + else: + name = self.set_line(NameExpr(n.name), n) + node = StarredPattern(name) + + return self.set_line(node, n) + + def visit_MatchMapping(self, n: ast3.MatchMapping) -> MappingPattern: + keys = [self.visit(k) for k in n.keys] + values = [self.visit(v) for v in n.patterns] + + if n.rest is None: + rest = None + else: + rest = self.set_line(NameExpr(n.rest), n) + + node = MappingPattern(keys, values, rest) + return self.set_line(node, n) + + def visit_MatchClass(self, n: ast3.MatchClass) -> ClassPattern: + class_ref = self.visit(n.cls) + assert isinstance(class_ref, RefExpr) + positionals = [self.visit(p) for p in n.patterns] + keyword_keys = n.kwd_attrs + keyword_values = [self.visit(p) for p in n.kwd_patterns] + + node = ClassPattern(class_ref, positionals, keyword_keys, keyword_values) + return self.set_line(node, n) + + # MatchAs(expr pattern, identifier name) + def visit_MatchAs(self, n: ast3.MatchAs) -> AsPattern: + if n.name is None: + name = None + else: + name = NameExpr(n.name) + name = self.set_line(name, n) + node = AsPattern(self.visit(n.pattern), name) + return self.set_line(node, n) + + # MatchOr(expr* pattern) + def visit_MatchOr(self, n: ast3.MatchOr) -> OrPattern: + node = OrPattern([self.visit(pattern) for pattern in n.patterns]) + return self.set_line(node, n) + + def validate_type_alias(self, n: ast_TypeAlias) -> None: + incorrect_expr = find_disallowed_expression_in_annotation_scope(n.value) + if incorrect_expr is None: + return + if isinstance(incorrect_expr, (ast3.Yield, ast3.YieldFrom)): + self.fail( + message_registry.TYPE_ALIAS_WITH_YIELD_EXPRESSION, + n.lineno, + n.col_offset, + blocker=True, + ) + if isinstance(incorrect_expr, ast3.NamedExpr): + self.fail( + message_registry.TYPE_ALIAS_WITH_NAMED_EXPRESSION, + n.lineno, + n.col_offset, + blocker=True, + ) + if isinstance(incorrect_expr, ast3.Await): + self.fail( + message_registry.TYPE_ALIAS_WITH_AWAIT_EXPRESSION, + n.lineno, + n.col_offset, + blocker=True, + ) + + # TypeAlias(identifier name, type_param* type_params, expr value) + def visit_TypeAlias(self, n: ast_TypeAlias) -> TypeAliasStmt | AssignmentStmt: + node: TypeAliasStmt | AssignmentStmt + type_params = self.translate_type_params(n.type_params) + self.validate_type_alias(n) + value = self.visit(n.value) + # Since the value is evaluated lazily, wrap the value inside a lambda. + # This helps mypyc. + ret = ReturnStmt(value) + self.set_line(ret, n.value) + value_func = LambdaExpr(body=Block([ret])) + self.set_line(value_func, n.value) + node = TypeAliasStmt(self.visit_Name(n.name), type_params, value_func) + return self.set_line(node, n) + + +class TypeConverter: + def __init__( + self, + errors: Errors | None, + line: int = -1, + override_column: int = -1, + is_evaluated: bool = True, + ) -> None: + self.errors = errors + self.line = line + self.override_column = override_column + self.node_stack: list[AST] = [] + self.is_evaluated = is_evaluated + + def convert_column(self, column: int) -> int: + """Apply column override if defined; otherwise return column. + + Column numbers are sometimes incorrect in the AST and the column + override can be used to work around that. + """ + if self.override_column < 0: + return column + else: + return self.override_column + + def invalid_type(self, node: AST, note: str | None = None) -> RawExpressionType: + """Constructs a type representing some expression that normally forms an invalid type. + For example, if we see a type hint that says "3 + 4", we would transform that + expression into a RawExpressionType. + + The semantic analysis layer will report an "Invalid type" error when it + encounters this type, along with the given note if one is provided. + + See RawExpressionType's docstring for more details on how it's used. + """ + return RawExpressionType( + None, "typing.Any", line=self.line, column=getattr(node, "col_offset", -1), note=note + ) + + @overload + def visit(self, node: ast3.expr) -> ProperType: ... + + @overload + def visit(self, node: AST | None) -> ProperType | None: ... + + def visit(self, node: AST | None) -> ProperType | None: + """Modified visit -- keep track of the stack of nodes""" + if node is None: + return None + self.node_stack.append(node) + try: + method = "visit_" + node.__class__.__name__ + visitor = getattr(self, method, None) + if visitor is not None: + typ = visitor(node) + assert isinstance(typ, ProperType) + return typ + else: + return self.invalid_type(node) + finally: + self.node_stack.pop() + + def parent(self) -> AST | None: + """Return the AST node above the one we are processing""" + if len(self.node_stack) < 2: + return None + return self.node_stack[-2] + + def fail(self, msg: ErrorMessage, line: int, column: int) -> None: + if self.errors: + self.errors.report(line, column, msg.value, blocker=True, code=msg.code) + + def note(self, msg: str, line: int, column: int) -> None: + if self.errors: + self.errors.report(line, column, msg, severity="note", code=codes.SYNTAX) + + def translate_expr_list(self, l: Sequence[ast3.expr]) -> list[Type]: + return [self.visit(e) for e in l] + + def visit_Call(self, e: Call) -> Type: + # Parse the arg constructor + f = e.func + constructor = stringify_name(f) + + if not isinstance(self.parent(), ast3.List): + note = None + if constructor: + note = "Suggestion: use {0}[...] instead of {0}(...)".format(constructor) + return self.invalid_type(e, note=note) + if not constructor: + self.fail(message_registry.ARG_CONSTRUCTOR_NAME_EXPECTED, e.lineno, e.col_offset) + + name: str | None = None + default_type = AnyType(TypeOfAny.special_form) + typ: Type = default_type + for i, arg in enumerate(e.args): + if i == 0: + converted = self.visit(arg) + assert converted is not None + typ = converted + elif i == 1: + name = self._extract_argument_name(arg) + else: + self.fail(message_registry.ARG_CONSTRUCTOR_TOO_MANY_ARGS, f.lineno, f.col_offset) + for k in e.keywords: + value = k.value + if k.arg == "name": + if name is not None: + self.fail( + message_registry.MULTIPLE_VALUES_FOR_NAME_KWARG.format(constructor), + f.lineno, + f.col_offset, + ) + name = self._extract_argument_name(value) + elif k.arg == "type": + if typ is not default_type: + self.fail( + message_registry.MULTIPLE_VALUES_FOR_TYPE_KWARG.format(constructor), + f.lineno, + f.col_offset, + ) + converted = self.visit(value) + assert converted is not None + typ = converted + else: + self.fail( + message_registry.ARG_CONSTRUCTOR_UNEXPECTED_ARG.format(k.arg), + value.lineno, + value.col_offset, + ) + return CallableArgument(typ, name, constructor, e.lineno, e.col_offset) + + def translate_argument_list(self, l: Sequence[ast3.expr]) -> TypeList: + return TypeList([self.visit(e) for e in l], line=self.line) + + def _extract_argument_name(self, n: ast3.expr) -> str | None: + if isinstance(n, ast3.Constant) and isinstance(n.value, str): + return n.value.strip() + elif isinstance(n, ast3.Constant) and n.value is None: + return None + self.fail( + message_registry.ARG_NAME_EXPECTED_STRING_LITERAL.format(type(n).__name__), + self.line, + 0, + ) + return None + + def visit_Name(self, n: Name) -> Type: + return UnboundType(n.id, line=self.line, column=self.convert_column(n.col_offset)) + + def visit_BinOp(self, n: ast3.BinOp) -> Type: + if not isinstance(n.op, ast3.BitOr): + return self.invalid_type(n) + + left = self.visit(n.left) + right = self.visit(n.right) + return UnionType( + [left, right], + line=self.line, + column=self.convert_column(n.col_offset), + is_evaluated=self.is_evaluated, + uses_pep604_syntax=True, + ) + + def visit_Constant(self, n: ast3.Constant) -> Type: + val = n.value + if val is None: + # None is a type. + return UnboundType("None", line=self.line) + if isinstance(val, str): + # Parse forward reference. + return parse_type_string(val, "builtins.str", self.line, n.col_offset) + if val is Ellipsis: + # '...' is valid in some types. + return EllipsisType(line=self.line) + if isinstance(val, bool): + # Special case for True/False. + return RawExpressionType(val, "builtins.bool", line=self.line) + if isinstance(val, (int, float, complex)): + return self.numeric_type(val, n) + if isinstance(val, bytes): + contents = bytes_to_human_readable_repr(val) + return RawExpressionType(contents, "builtins.bytes", self.line, column=n.col_offset) + # Everything else is invalid. + + # UnaryOp(op, operand) + def visit_UnaryOp(self, n: UnaryOp) -> Type: + # We support specifically Literal[-4], Literal[+4], and nothing else. + # For example, Literal[~6] or Literal[not False] is not supported. + typ = self.visit(n.operand) + if ( + isinstance(typ, RawExpressionType) + # Use type() because we do not want to allow bools. + and type(typ.literal_value) is int + ): + if isinstance(n.op, USub): + typ.literal_value *= -1 + return typ + if isinstance(n.op, UAdd): + return typ + return self.invalid_type(n) + + def numeric_type(self, value: object, n: AST) -> Type: + # The node's field has the type complex, but complex isn't *really* + # a parent of int and float, and this causes isinstance below + # to think that the complex branch is always picked. Avoid + # this by throwing away the type. + if isinstance(value, int): + numeric_value: int | None = value + type_name = "builtins.int" + else: + # Other kinds of numbers (floats, complex) are not valid parameters for + # RawExpressionType so we just pass in 'None' for now. We'll report the + # appropriate error at a later stage. + numeric_value = None + type_name = f"builtins.{type(value).__name__}" + return RawExpressionType( + numeric_value, type_name, line=self.line, column=getattr(n, "col_offset", -1) + ) + + def visit_Slice(self, n: ast3.Slice) -> Type: + return self.invalid_type(n, note="did you mean to use ',' instead of ':' ?") + + # Subscript(expr value, expr slice, expr_context ctx) + def visit_Subscript(self, n: ast3.Subscript) -> Type: + empty_tuple_index = False + if isinstance(n.slice, ast3.Tuple): + params = self.translate_expr_list(n.slice.elts) + if len(n.slice.elts) == 0: + empty_tuple_index = True + else: + params = [self.visit(n.slice)] + + value = self.visit(n.value) + if isinstance(value, UnboundType) and not value.args: + result = UnboundType( + value.name, + params, + line=self.line, + column=value.column, + empty_tuple_index=empty_tuple_index, + ) + result.end_column = n.end_col_offset + result.end_line = n.end_lineno + return result + else: + return self.invalid_type(n) + + def visit_Tuple(self, n: ast3.Tuple) -> Type: + return TupleType( + self.translate_expr_list(n.elts), + _dummy_fallback, + implicit=True, + line=self.line, + column=self.convert_column(n.col_offset), + ) + + def visit_Dict(self, n: ast3.Dict) -> Type: + if not n.keys: + return self.invalid_type(n) + items: dict[str, Type] = {} + extra_items_from = [] + for item_name, value in zip(n.keys, n.values): + if not isinstance(item_name, ast3.Constant) or not isinstance(item_name.value, str): + if item_name is None: + extra_items_from.append(self.visit(value)) + continue + return self.invalid_type(n) + items[item_name.value] = self.visit(value) + result = TypedDictType(items, set(), set(), _dummy_fallback, n.lineno, n.col_offset) + result.extra_items_from = extra_items_from + return result + + # Attribute(expr value, identifier attr, expr_context ctx) + def visit_Attribute(self, n: Attribute) -> Type: + before_dot = self.visit(n.value) + + if isinstance(before_dot, UnboundType) and not before_dot.args: + return UnboundType(f"{before_dot.name}.{n.attr}", line=self.line, column=n.col_offset) + else: + return self.invalid_type(n) + + # Used for Callable[[X *Ys, Z], R] etc. + def visit_Starred(self, n: ast3.Starred) -> Type: + return UnpackType(self.visit(n.value), from_star_syntax=True) + + # List(expr* elts, expr_context ctx) + def visit_List(self, n: ast3.List) -> Type: + assert isinstance(n.ctx, ast3.Load) + result = self.translate_argument_list(n.elts) + return result + + +def stringify_name(n: AST) -> str | None: + if isinstance(n, Name): + return n.id + elif isinstance(n, Attribute): + sv = stringify_name(n.value) + if sv is not None: + return f"{sv}.{n.attr}" + return None # Can't do it. + + +class FindAttributeAssign(TraverserVisitor): + """Check if an AST contains attribute assignments (e.g. self.x = 0).""" + + def __init__(self) -> None: + self.lvalue = False + self.found = False + + def visit_assignment_stmt(self, s: AssignmentStmt) -> None: + self.lvalue = True + for lv in s.lvalues: + lv.accept(self) + self.lvalue = False + + def visit_with_stmt(self, s: WithStmt) -> None: + self.lvalue = True + for lv in s.target: + if lv is not None: + lv.accept(self) + self.lvalue = False + s.body.accept(self) + + def visit_for_stmt(self, s: ForStmt) -> None: + self.lvalue = True + s.index.accept(self) + self.lvalue = False + s.body.accept(self) + if s.else_body: + s.else_body.accept(self) + + def visit_expression_stmt(self, s: ExpressionStmt) -> None: + # No need to look inside these + pass + + def visit_call_expr(self, e: CallExpr) -> None: + # No need to look inside these + pass + + def visit_index_expr(self, e: IndexExpr) -> None: + # No need to look inside these + pass + + def visit_member_expr(self, e: MemberExpr) -> None: + if self.lvalue and isinstance(e.expr, NameExpr): + self.found = True + + +class FindYield(TraverserVisitor): + """Check if an AST contains yields or yield froms.""" # codespell:ignore froms + + def __init__(self) -> None: + self.found = False + + def visit_yield_expr(self, e: YieldExpr) -> None: + self.found = True + + def visit_yield_from_expr(self, e: YieldFromExpr) -> None: + self.found = True + + +def is_possible_trivial_body(s: list[Statement]) -> bool: + """Could the statements form a "trivial" function body, such as 'pass'? + + This mimics mypy.semanal.is_trivial_body, but this runs before + semantic analysis so some checks must be conservative. + """ + l = len(s) + if l == 0: + return False + i = 0 + if isinstance(s[0], ExpressionStmt) and isinstance(s[0].expr, StrExpr): + # Skip docstring + i += 1 + if i == l: + return True + if l > i + 1: + return False + stmt = s[i] + return isinstance(stmt, (PassStmt, RaiseStmt)) or ( + isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr) + ) diff --git a/micromamba_root/Lib/site-packages/mypy/find_sources.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/find_sources.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..3d28dc16a4b1058abb0859948d7b01604d0c0a26 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/find_sources.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/find_sources.py b/micromamba_root/Lib/site-packages/mypy/find_sources.py new file mode 100644 index 0000000000000000000000000000000000000000..e1edebe90985b091021580fc88d9a66ead9de40a --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/find_sources.py @@ -0,0 +1,257 @@ +"""Routines for finding the sources that mypy will check""" + +from __future__ import annotations + +import functools +import os +from collections.abc import Sequence +from typing import Final + +from mypy.fscache import FileSystemCache +from mypy.modulefinder import ( + PYTHON_EXTENSIONS, + BuildSource, + matches_exclude, + matches_gitignore, + mypy_path, +) +from mypy.options import Options + +PY_EXTENSIONS: Final = tuple(PYTHON_EXTENSIONS) + + +class InvalidSourceList(Exception): + """Exception indicating a problem in the list of sources given to mypy.""" + + +def create_source_list( + paths: Sequence[str], + options: Options, + fscache: FileSystemCache | None = None, + allow_empty_dir: bool = False, +) -> list[BuildSource]: + """From a list of source files/directories, makes a list of BuildSources. + + Raises InvalidSourceList on errors. + """ + fscache = fscache or FileSystemCache() + finder = SourceFinder(fscache, options) + + sources = [] + for path in paths: + path = os.path.normpath(path) + if path.endswith(PY_EXTENSIONS): + # Can raise InvalidSourceList if a directory doesn't have a valid module name. + name, base_dir = finder.crawl_up(path) + sources.append(BuildSource(path, name, None, base_dir)) + elif fscache.isdir(path): + sub_sources = finder.find_sources_in_dir(path) + if not sub_sources and not allow_empty_dir: + raise InvalidSourceList(f"There are no .py[i] files in directory '{path}'") + sources.extend(sub_sources) + else: + mod = os.path.basename(path) if options.scripts_are_modules else None + sources.append(BuildSource(path, mod, None)) + return sources + + +def keyfunc(name: str) -> tuple[bool, int, str]: + """Determines sort order for directory listing. + + The desirable properties are: + 1) foo < foo.pyi < foo.py + 2) __init__.py[i] < foo + """ + base, suffix = os.path.splitext(name) + for i, ext in enumerate(PY_EXTENSIONS): + if suffix == ext: + return (base != "__init__", i, base) + return (base != "__init__", -1, name) + + +def normalise_package_base(root: str) -> str: + if not root: + root = os.curdir + root = os.path.abspath(root) + if root.endswith(os.sep): + root = root[:-1] + return root + + +def get_explicit_package_bases(options: Options) -> list[str] | None: + """Returns explicit package bases to use if the option is enabled, or None if disabled. + + We currently use MYPYPATH and the current directory as the package bases. In the future, + when --namespace-packages is the default could also use the values passed with the + --package-root flag, see #9632. + + Values returned are normalised so we can use simple string comparisons in + SourceFinder.is_explicit_package_base + """ + if not options.explicit_package_bases: + return None + roots = mypy_path() + options.mypy_path + [os.getcwd()] + return [normalise_package_base(root) for root in roots] + + +class SourceFinder: + def __init__(self, fscache: FileSystemCache, options: Options) -> None: + self.fscache = fscache + self.explicit_package_bases = get_explicit_package_bases(options) + self.namespace_packages = options.namespace_packages + self.exclude = options.exclude + self.exclude_gitignore = options.exclude_gitignore + self.verbosity = options.verbosity + + def is_explicit_package_base(self, path: str) -> bool: + assert self.explicit_package_bases + return normalise_package_base(path) in self.explicit_package_bases + + def find_sources_in_dir(self, path: str) -> list[BuildSource]: + sources = [] + + seen: set[str] = set() + names = sorted(self.fscache.listdir(path), key=keyfunc) + for name in names: + # Skip certain names altogether + if name in ("__pycache__", "site-packages", "node_modules") or name.startswith("."): + continue + subpath = os.path.join(path, name) + + if matches_exclude(subpath, self.exclude, self.fscache, self.verbosity >= 2): + continue + if self.exclude_gitignore and matches_gitignore( + subpath, self.fscache, self.verbosity >= 2 + ): + continue + + if self.fscache.isdir(subpath): + sub_sources = self.find_sources_in_dir(subpath) + if sub_sources: + seen.add(name) + sources.extend(sub_sources) + else: + stem, suffix = os.path.splitext(name) + if stem not in seen and suffix in PY_EXTENSIONS: + seen.add(stem) + module, base_dir = self.crawl_up(subpath) + sources.append(BuildSource(subpath, module, None, base_dir)) + + return sources + + def crawl_up(self, path: str) -> tuple[str, str]: + """Given a .py[i] filename, return module and base directory. + + For example, given "xxx/yyy/foo/bar.py", we might return something like: + ("foo.bar", "xxx/yyy") + + If namespace packages is off, we crawl upwards until we find a directory without + an __init__.py + + If namespace packages is on, we crawl upwards until the nearest explicit base directory. + Failing that, we return one past the highest directory containing an __init__.py + + We won't crawl past directories with invalid package names. + The base directory returned is an absolute path. + """ + path = os.path.abspath(path) + parent, filename = os.path.split(path) + + module_name = strip_py(filename) or filename + + parent_module, base_dir = self.crawl_up_dir(parent) + if module_name == "__init__": + return parent_module, base_dir + + # Note that module_name might not actually be a valid identifier, but that's okay + # Ignoring this possibility sidesteps some search path confusion + module = module_join(parent_module, module_name) + return module, base_dir + + def crawl_up_dir(self, dir: str) -> tuple[str, str]: + return self._crawl_up_helper(dir) or ("", dir) + + @functools.lru_cache # noqa: B019 + def _crawl_up_helper(self, dir: str) -> tuple[str, str] | None: + """Given a directory, maybe returns module and base directory. + + We return a non-None value if we were able to find something clearly intended as a base + directory (as adjudicated by being an explicit base directory or by containing a package + with __init__.py). + + This distinction is necessary for namespace packages, so that we know when to treat + ourselves as a subpackage. + """ + # stop crawling if we're an explicit base directory + if self.explicit_package_bases is not None and self.is_explicit_package_base(dir): + return "", dir + + parent, name = os.path.split(dir) + name = name.removesuffix("-stubs") # PEP-561 stub-only directory + + # recurse if there's an __init__.py + init_file = self.get_init_file(dir) + if init_file is not None: + if not name.isidentifier(): + # in most cases the directory name is invalid, we'll just stop crawling upwards + # but if there's an __init__.py in the directory, something is messed up + raise InvalidSourceList( + f"{name} contains {os.path.basename(init_file)} " + "but is not a valid Python package name" + ) + # we're definitely a package, so we always return a non-None value + mod_prefix, base_dir = self.crawl_up_dir(parent) + return module_join(mod_prefix, name), base_dir + + # stop crawling if we're out of path components or our name is an invalid identifier + if not name or not parent or not name.isidentifier(): + return None + + # stop crawling if namespace packages is off (since we don't have an __init__.py) + if not self.namespace_packages: + return None + + # at this point: namespace packages is on, we don't have an __init__.py and we're not an + # explicit base directory + result = self._crawl_up_helper(parent) + if result is None: + # we're not an explicit base directory and we don't have an __init__.py + # and none of our parents are either, so return + return None + # one of our parents was an explicit base directory or had an __init__.py, so we're + # definitely a subpackage! chain our name to the module. + mod_prefix, base_dir = result + return module_join(mod_prefix, name), base_dir + + def get_init_file(self, dir: str) -> str | None: + """Check whether a directory contains a file named __init__.py[i]. + + If so, return the file's name (with dir prefixed). If not, return None. + + This prefers .pyi over .py (because of the ordering of PY_EXTENSIONS). + """ + for ext in PY_EXTENSIONS: + f = os.path.join(dir, "__init__" + ext) + if self.fscache.isfile(f): + return f + if ext == ".py" and self.fscache.init_under_package_root(f): + return f + return None + + +def module_join(parent: str, child: str) -> str: + """Join module ids, accounting for a possibly empty parent.""" + if parent: + return parent + "." + child + return child + + +def strip_py(arg: str) -> str | None: + """Strip a trailing .py or .pyi suffix. + + Return None if no such suffix is found. + """ + for ext in PY_EXTENSIONS: + if arg.endswith(ext): + return arg[: -len(ext)] + return None diff --git a/micromamba_root/Lib/site-packages/mypy/fixup.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/fixup.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..549621bcecf43d784900ecb89ac7fb8f7954ddab Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/fixup.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/fixup.py b/micromamba_root/Lib/site-packages/mypy/fixup.py new file mode 100644 index 0000000000000000000000000000000000000000..d0205f64b7207e1e092ab1f1f476923f9aed4c41 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/fixup.py @@ -0,0 +1,444 @@ +"""Fix up various things after deserialization.""" + +from __future__ import annotations + +from typing import Any, Final + +from mypy.lookup import lookup_fully_qualified +from mypy.nodes import ( + Block, + ClassDef, + Decorator, + FuncDef, + MypyFile, + OverloadedFuncDef, + ParamSpecExpr, + SymbolTable, + TypeAlias, + TypeInfo, + TypeVarExpr, + TypeVarTupleExpr, + Var, +) +from mypy.types import ( + NOT_READY, + AnyType, + CallableType, + Instance, + LiteralType, + Overloaded, + Parameters, + ParamSpecType, + ProperType, + TupleType, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeType, + TypeVarTupleType, + TypeVarType, + TypeVisitor, + UnboundType, + UnionType, + UnpackType, +) +from mypy.visitor import NodeVisitor + + +# N.B: we do a allow_missing fixup when fixing up a fine-grained +# incremental cache load (since there may be cross-refs into deleted +# modules) +def fixup_module(tree: MypyFile, modules: dict[str, MypyFile], allow_missing: bool) -> None: + node_fixer = NodeFixer(modules, allow_missing) + node_fixer.visit_symbol_table(tree.names, tree.fullname) + + +# TODO: Fix up .info when deserializing, i.e. much earlier. +class NodeFixer(NodeVisitor[None]): + current_info: TypeInfo | None = None + + def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None: + self.modules = modules + self.allow_missing = allow_missing + self.type_fixer = TypeFixer(self.modules, allow_missing) + + # NOTE: This method isn't (yet) part of the NodeVisitor API. + def visit_type_info(self, info: TypeInfo) -> None: + save_info = self.current_info + try: + self.current_info = info + if info.defn: + info.defn.accept(self) + if info.names: + self.visit_symbol_table(info.names, info.fullname) + if info.bases: + for base in info.bases: + base.accept(self.type_fixer) + if info._promote: + for p in info._promote: + p.accept(self.type_fixer) + if info.tuple_type: + info.tuple_type.accept(self.type_fixer) + info.update_tuple_type(info.tuple_type) + if info.special_alias: + info.special_alias.alias_tvars = list(info.defn.type_vars) + for i, t in enumerate(info.defn.type_vars): + if isinstance(t, TypeVarTupleType): + info.special_alias.tvar_tuple_index = i + if info.typeddict_type: + info.typeddict_type.accept(self.type_fixer) + info.update_typeddict_type(info.typeddict_type) + if info.special_alias: + info.special_alias.alias_tvars = list(info.defn.type_vars) + for i, t in enumerate(info.defn.type_vars): + if isinstance(t, TypeVarTupleType): + info.special_alias.tvar_tuple_index = i + if info.declared_metaclass: + info.declared_metaclass.accept(self.type_fixer) + if info.metaclass_type: + info.metaclass_type.accept(self.type_fixer) + if info.self_type: + info.self_type.accept(self.type_fixer) + if info.alt_promote: + info.alt_promote.accept(self.type_fixer) + instance = Instance(info, []) + # Hack: We may also need to add a backwards promotion (from int to native int), + # since it might not be serialized. + if instance not in info.alt_promote.type._promote: + info.alt_promote.type._promote.append(instance) + if info._mro_refs: + info.mro = [ + lookup_fully_qualified_typeinfo( + self.modules, name, allow_missing=self.allow_missing + ) + for name in info._mro_refs + ] + info._mro_refs = None + finally: + self.current_info = save_info + + # NOTE: This method *definitely* isn't part of the NodeVisitor API. + def visit_symbol_table(self, symtab: SymbolTable, table_fullname: str) -> None: + # Copy the items because we may mutate symtab. + for key in list(symtab): + value = symtab[key] + cross_ref = value.cross_ref + if cross_ref is not None: # Fix up cross-reference. + value.cross_ref = None + if cross_ref in self.modules: + value.node = self.modules[cross_ref] + else: + stnode = lookup_fully_qualified( + cross_ref, self.modules, raise_on_missing=not self.allow_missing + ) + if stnode is not None: + if stnode is value: + # The node seems to refer to itself, which can mean that + # the target is a deleted submodule of the current module, + # and thus lookup falls back to the symbol table of the parent + # package. Here's how this may happen: + # + # pkg/__init__.py: + # from pkg import sub + # + # Now if pkg.sub is deleted, the pkg.sub symbol table entry + # appears to refer to itself. Replace the entry with a + # placeholder to avoid a crash. We can't delete the entry, + # as it would stop dependency propagation. + value.node = Var(key + "@deleted") + else: + assert stnode.node is not None, (table_fullname + "." + key, cross_ref) + value.node = stnode.node + elif not self.allow_missing: + assert False, f"Could not find cross-ref {cross_ref}" + else: + # We have a missing crossref in allow missing mode, need to put something + value.node = missing_info(self.modules) + else: + if isinstance(value.node, TypeInfo): + # TypeInfo has no accept(). TODO: Add it? + self.visit_type_info(value.node) + elif value.node is not None: + value.node.accept(self) + else: + assert False, f"Unexpected empty node {key!r}: {value}" + + def visit_func_def(self, func: FuncDef) -> None: + if self.current_info is not None: + func.info = self.current_info + if func.type is not None: + func.type.accept(self.type_fixer) + if isinstance(func.type, CallableType): + func.type.definition = func + + def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None: + if self.current_info is not None: + o.info = self.current_info + if o.type: + o.type.accept(self.type_fixer) + for item in o.items: + item.accept(self) + if o.impl: + o.impl.accept(self) + if isinstance(o.type, Overloaded): + # For error messages we link the original definition for each item. + for typ, item in zip(o.type.items, o.items): + typ.definition = item + + def visit_decorator(self, d: Decorator) -> None: + if self.current_info is not None: + d.var.info = self.current_info + if d.func: + d.func.accept(self) + if d.var: + d.var.accept(self) + for node in d.decorators: + node.accept(self) + typ = d.var.type + if isinstance(typ, ProperType) and isinstance(typ, CallableType): + typ.definition = d.func + + def visit_class_def(self, c: ClassDef) -> None: + for v in c.type_vars: + v.accept(self.type_fixer) + + def visit_type_var_expr(self, tv: TypeVarExpr) -> None: + for value in tv.values: + value.accept(self.type_fixer) + tv.upper_bound.accept(self.type_fixer) + tv.default.accept(self.type_fixer) + + def visit_paramspec_expr(self, p: ParamSpecExpr) -> None: + p.upper_bound.accept(self.type_fixer) + p.default.accept(self.type_fixer) + + def visit_type_var_tuple_expr(self, tv: TypeVarTupleExpr) -> None: + tv.upper_bound.accept(self.type_fixer) + tv.tuple_fallback.accept(self.type_fixer) + tv.default.accept(self.type_fixer) + + def visit_var(self, v: Var) -> None: + if self.current_info is not None: + v.info = self.current_info + if v.type is not None: + v.type.accept(self.type_fixer) + if v.setter_type is not None: + v.setter_type.accept(self.type_fixer) + + def visit_type_alias(self, a: TypeAlias) -> None: + a.target.accept(self.type_fixer) + for v in a.alias_tvars: + v.accept(self.type_fixer) + + +class TypeFixer(TypeVisitor[None]): + def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None: + self.modules = modules + self.allow_missing = allow_missing + + def visit_instance(self, inst: Instance) -> None: + # TODO: Combine Instances that are exactly the same? + type_ref = inst.type_ref + if type_ref is None: + return # We've already been here. + inst.type_ref = None + inst.type = lookup_fully_qualified_typeinfo( + self.modules, type_ref, allow_missing=self.allow_missing + ) + # TODO: Is this needed or redundant? + # Also fix up the bases, just in case. + for base in inst.type.bases: + if base.type is NOT_READY: + base.accept(self) + for a in inst.args: + a.accept(self) + if inst.last_known_value is not None: + inst.last_known_value.accept(self) + if inst.extra_attrs: + for v in inst.extra_attrs.attrs.values(): + v.accept(self) + + def visit_type_alias_type(self, t: TypeAliasType) -> None: + type_ref = t.type_ref + if type_ref is None: + return # We've already been here. + t.type_ref = None + t.alias = lookup_fully_qualified_alias( + self.modules, type_ref, allow_missing=self.allow_missing + ) + for a in t.args: + a.accept(self) + + def visit_any(self, o: Any) -> None: + pass # Nothing to descend into. + + def visit_callable_type(self, ct: CallableType) -> None: + if ct.fallback: + ct.fallback.accept(self) + for argt in ct.arg_types: + # argt may be None, e.g. for __self in NamedTuple constructors. + if argt is not None: + argt.accept(self) + if ct.ret_type is not None: + ct.ret_type.accept(self) + for v in ct.variables: + v.accept(self) + if ct.type_guard is not None: + ct.type_guard.accept(self) + if ct.type_is is not None: + ct.type_is.accept(self) + + def visit_overloaded(self, t: Overloaded) -> None: + for ct in t.items: + ct.accept(self) + + def visit_erased_type(self, o: Any) -> None: + # This type should exist only temporarily during type inference + raise RuntimeError("Shouldn't get here", o) + + def visit_deleted_type(self, o: Any) -> None: + pass # Nothing to descend into. + + def visit_none_type(self, o: Any) -> None: + pass # Nothing to descend into. + + def visit_uninhabited_type(self, o: Any) -> None: + pass # Nothing to descend into. + + def visit_partial_type(self, o: Any) -> None: + raise RuntimeError("Shouldn't get here", o) + + def visit_tuple_type(self, tt: TupleType) -> None: + if tt.items: + for it in tt.items: + it.accept(self) + if tt.partial_fallback is not None: + tt.partial_fallback.accept(self) + + def visit_typeddict_type(self, tdt: TypedDictType) -> None: + if tdt.items: + for it in tdt.items.values(): + it.accept(self) + if tdt.fallback is not None: + if tdt.fallback.type_ref is not None: + if ( + lookup_fully_qualified( + tdt.fallback.type_ref, + self.modules, + raise_on_missing=not self.allow_missing, + ) + is None + ): + # We reject fake TypeInfos for TypedDict fallbacks because + # the latter are used in type checking and must be valid. + tdt.fallback.type_ref = "typing._TypedDict" + tdt.fallback.accept(self) + + def visit_literal_type(self, lt: LiteralType) -> None: + lt.fallback.accept(self) + + def visit_type_var(self, tvt: TypeVarType) -> None: + if tvt.values: + for vt in tvt.values: + vt.accept(self) + tvt.upper_bound.accept(self) + tvt.default.accept(self) + + def visit_param_spec(self, p: ParamSpecType) -> None: + p.upper_bound.accept(self) + p.default.accept(self) + p.prefix.accept(self) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> None: + t.tuple_fallback.accept(self) + t.upper_bound.accept(self) + t.default.accept(self) + + def visit_unpack_type(self, u: UnpackType) -> None: + u.type.accept(self) + + def visit_parameters(self, p: Parameters) -> None: + for argt in p.arg_types: + if argt is not None: + argt.accept(self) + for var in p.variables: + var.accept(self) + + def visit_unbound_type(self, o: UnboundType) -> None: + for a in o.args: + a.accept(self) + + def visit_union_type(self, ut: UnionType) -> None: + if ut.items: + for it in ut.items: + it.accept(self) + + def visit_type_type(self, t: TypeType) -> None: + t.item.accept(self) + + +def lookup_fully_qualified_typeinfo( + modules: dict[str, MypyFile], name: str, *, allow_missing: bool +) -> TypeInfo: + stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing) + node = stnode.node if stnode else None + if isinstance(node, TypeInfo): + return node + else: + # Looks like a missing TypeInfo during an initial daemon load, put something there + assert ( + allow_missing + ), "Should never get here in normal mode, got {}:{} instead of TypeInfo".format( + type(node).__name__, node.fullname if node else "" + ) + return missing_info(modules) + + +def lookup_fully_qualified_alias( + modules: dict[str, MypyFile], name: str, *, allow_missing: bool +) -> TypeAlias: + stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing) + node = stnode.node if stnode else None + if isinstance(node, TypeAlias): + return node + elif isinstance(node, TypeInfo): + if node.special_alias: + # Already fixed up. + return node.special_alias + if node.tuple_type: + alias = TypeAlias.from_tuple_type(node) + elif node.typeddict_type: + alias = TypeAlias.from_typeddict_type(node) + else: + assert allow_missing + return missing_alias() + node.special_alias = alias + return alias + else: + # Looks like a missing TypeAlias during an initial daemon load, put something there + assert ( + allow_missing + ), "Should never get here in normal mode, got {}:{} instead of TypeAlias".format( + type(node).__name__, node.fullname if node else "" + ) + return missing_alias() + + +_SUGGESTION: Final = "" + + +def missing_info(modules: dict[str, MypyFile]) -> TypeInfo: + suggestion = _SUGGESTION.format("info") + dummy_def = ClassDef(suggestion, Block([])) + dummy_def.fullname = suggestion + + info = TypeInfo(SymbolTable(), dummy_def, "") + obj_type = lookup_fully_qualified_typeinfo(modules, "builtins.object", allow_missing=False) + info.bases = [Instance(obj_type, [])] + info.mro = [info, obj_type] + return info + + +def missing_alias() -> TypeAlias: + suggestion = _SUGGESTION.format("alias") + return TypeAlias(AnyType(TypeOfAny.special_form), suggestion, "", line=-1, column=-1) diff --git a/micromamba_root/Lib/site-packages/mypy/freetree.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/freetree.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..762a07c7d2915372384b2c1c81ef57d890bd8343 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/freetree.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/freetree.py b/micromamba_root/Lib/site-packages/mypy/freetree.py new file mode 100644 index 0000000000000000000000000000000000000000..75b89e2623aefcf5bccc255b7d606da91cb5f9b7 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/freetree.py @@ -0,0 +1,23 @@ +"""Generic node traverser visitor""" + +from __future__ import annotations + +from mypy.nodes import Block, MypyFile +from mypy.traverser import TraverserVisitor + + +class TreeFreer(TraverserVisitor): + def visit_block(self, block: Block) -> None: + super().visit_block(block) + block.body.clear() + + +def free_tree(tree: MypyFile) -> None: + """Free all the ASTs associated with a module. + + This needs to be done recursively, since symbol tables contain + references to definitions, so those won't be freed but we want their + contents to be. + """ + tree.accept(TreeFreer()) + tree.defs.clear() diff --git a/micromamba_root/Lib/site-packages/mypy/fscache.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/fscache.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..99c3245771aaf7d51bc65d35a497ab65a484d69d Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/fscache.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/fscache.py b/micromamba_root/Lib/site-packages/mypy/fscache.py new file mode 100644 index 0000000000000000000000000000000000000000..240370159fff6c939b9247adfc50ca2c65ffa6f6 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/fscache.py @@ -0,0 +1,307 @@ +"""Interface for accessing the file system with automatic caching. + +The idea is to cache the results of any file system state reads during +a single transaction. This has two main benefits: + +* This avoids redundant syscalls, as we won't perform the same OS + operations multiple times. + +* This makes it easier to reason about concurrent FS updates, as different + operations targeting the same paths can't report different state during + a transaction. + +Note that this only deals with reading state, not writing. + +Properties maintained by the API: + +* The contents of the file are always from the same or later time compared + to the reported mtime of the file, even if mtime is queried after reading + a file. + +* Repeating an operation produces the same result as the first one during + a transaction. + +* Call flush() to start a new transaction (flush the caches). + +The API is a bit limited. It's easy to add new cached operations, however. +You should perform all file system reads through the API to actually take +advantage of the benefits. +""" + +from __future__ import annotations + +import os +import stat + +from mypy_extensions import mypyc_attr + +from mypy.util import hash_digest + + +@mypyc_attr(allow_interpreted_subclasses=True) # for tests +class FileSystemCache: + def __init__(self) -> None: + # The package root is not flushed with the caches. + # It is set by set_package_root() below. + self.package_root: list[str] = [] + self.flush() + + def set_package_root(self, package_root: list[str]) -> None: + self.package_root = package_root + + def flush(self) -> None: + """Start another transaction and empty all caches.""" + self.stat_or_none_cache: dict[str, os.stat_result | None] = {} + + self.listdir_cache: dict[str, list[str]] = {} + self.listdir_error_cache: dict[str, OSError] = {} + self.isfile_case_cache: dict[str, bool] = {} + self.exists_case_cache: dict[str, bool] = {} + self.read_cache: dict[str, bytes] = {} + self.read_error_cache: dict[str, Exception] = {} + self.hash_cache: dict[str, str] = {} + self.fake_package_cache: set[str] = set() + + def stat_or_none(self, path: str) -> os.stat_result | None: + if path in self.stat_or_none_cache: + return self.stat_or_none_cache[path] + + st = None + try: + st = os.stat(path) + except OSError: + if self.init_under_package_root(path): + try: + st = self._fake_init(path) + except OSError: + pass + + self.stat_or_none_cache[path] = st + return st + + def init_under_package_root(self, path: str) -> bool: + """Is this path an __init__.py under a package root? + + This is used to detect packages that don't contain __init__.py + files, which is needed to support Bazel. The function should + only be called for non-existing files. + + It will return True if it refers to a __init__.py file that + Bazel would create, so that at runtime Python would think the + directory containing it is a package. For this to work you + must pass one or more package roots using the --package-root + flag. + + As an exceptional case, any directory that is a package root + itself will not be considered to contain a __init__.py file. + This is different from the rules Bazel itself applies, but is + necessary for mypy to properly distinguish packages from other + directories. + + See https://docs.bazel.build/versions/master/be/python.html, + where this behavior is described under legacy_create_init. + """ + if not self.package_root: + return False + dirname, basename = os.path.split(path) + if basename != "__init__.py": + return False + if not os.path.basename(dirname).isidentifier(): + # Can't put an __init__.py in a place that's not an identifier + return False + + st = self.stat_or_none(dirname) + if st is None: + return False + else: + if not stat.S_ISDIR(st.st_mode): + return False + ok = False + + # skip if on a different drive + current_drive, _ = os.path.splitdrive(os.getcwd()) + drive, _ = os.path.splitdrive(path) + if drive != current_drive: + return False + if os.path.isabs(path): + path = os.path.relpath(path) + path = os.path.normpath(path) + for root in self.package_root: + if path.startswith(root): + if path == root + basename: + # A package root itself is never a package. + ok = False + break + else: + ok = True + return ok + + def _fake_init(self, path: str) -> os.stat_result: + """Prime the cache with a fake __init__.py file. + + This makes code that looks for path believe an empty file by + that name exists. Should only be called after + init_under_package_root() returns True. + """ + dirname, basename = os.path.split(path) + assert basename == "__init__.py", path + assert not os.path.exists(path), path # Not cached! + dirname = os.path.normpath(dirname) + st = os.stat(dirname) # May raise OSError + # Get stat result as a list so we can modify it. + seq: list[float] = list(st) + seq[stat.ST_MODE] = stat.S_IFREG | 0o444 + seq[stat.ST_INO] = 1 + seq[stat.ST_NLINK] = 1 + seq[stat.ST_SIZE] = 0 + st = os.stat_result(seq) + # Make listdir() and read() also pretend this file exists. + self.fake_package_cache.add(dirname) + return st + + def listdir(self, path: str) -> list[str]: + path = os.path.normpath(path) + if path in self.listdir_cache: + res = self.listdir_cache[path] + # Check the fake cache. + if path in self.fake_package_cache and "__init__.py" not in res: + res.append("__init__.py") # Updates the result as well as the cache + return res + if path in self.listdir_error_cache: + raise copy_os_error(self.listdir_error_cache[path]) + try: + results = os.listdir(path) + except OSError as err: + # Like above, take a copy to reduce memory use. + self.listdir_error_cache[path] = copy_os_error(err) + raise err + self.listdir_cache[path] = results + # Check the fake cache. + if path in self.fake_package_cache and "__init__.py" not in results: + results.append("__init__.py") + return results + + def isfile(self, path: str) -> bool: + st = self.stat_or_none(path) + if st is None: + return False + return stat.S_ISREG(st.st_mode) + + def isfile_case(self, path: str, prefix: str) -> bool: + """Return whether path exists and is a file. + + On case-insensitive filesystems (like Mac or Windows) this returns + False if the case of path's last component does not exactly match + the case found in the filesystem. + + We check also the case of other path components up to prefix. + For example, if path is 'user-stubs/pack/mod.pyi' and prefix is 'user-stubs', + we check that the case of 'pack' and 'mod.py' matches exactly, 'user-stubs' will be + case insensitive on case insensitive filesystems. + + The caller must ensure that prefix is a valid file system prefix of path. + """ + if not self.isfile(path): + # Fast path + return False + if path in self.isfile_case_cache: + return self.isfile_case_cache[path] + head, tail = os.path.split(path) + if not tail: + self.isfile_case_cache[path] = False + return False + try: + names = self.listdir(head) + # This allows one to check file name case sensitively in + # case-insensitive filesystems. + res = tail in names + except OSError: + res = False + if res: + # Also recursively check the other path components in case sensitive way. + res = self.exists_case(head, prefix) + self.isfile_case_cache[path] = res + return res + + def exists_case(self, path: str, prefix: str) -> bool: + """Return whether path exists - checking path components in case sensitive + fashion, up to prefix. + """ + if path in self.exists_case_cache: + return self.exists_case_cache[path] + head, tail = os.path.split(path) + if not head.startswith(prefix) or not tail: + # Only perform the check for paths under prefix. + self.exists_case_cache[path] = True + return True + try: + names = self.listdir(head) + # This allows one to check file name case sensitively in + # case-insensitive filesystems. + res = tail in names + except OSError: + res = False + if res: + # Also recursively check other path components. + res = self.exists_case(head, prefix) + self.exists_case_cache[path] = res + return res + + def isdir(self, path: str) -> bool: + st = self.stat_or_none(path) + if st is None: + return False + return stat.S_ISDIR(st.st_mode) + + def exists(self, path: str) -> bool: + st = self.stat_or_none(path) + return st is not None + + def read(self, path: str) -> bytes: + if path in self.read_cache: + return self.read_cache[path] + if path in self.read_error_cache: + raise self.read_error_cache[path] + + # Need to stat first so that the contents of file are from no + # earlier instant than the mtime reported by self.stat(). + self.stat_or_none(path) + + dirname, basename = os.path.split(path) + dirname = os.path.normpath(dirname) + # Check the fake cache. + if basename == "__init__.py" and dirname in self.fake_package_cache: + data = b"" + else: + try: + with open(path, "rb") as f: + data = f.read() + except OSError as err: + self.read_error_cache[path] = err + raise + + self.read_cache[path] = data + self.hash_cache[path] = hash_digest(data) + return data + + def hash_digest(self, path: str) -> str: + if path not in self.hash_cache: + self.read(path) + return self.hash_cache[path] + + def samefile(self, f1: str, f2: str) -> bool: + s1 = self.stat_or_none(f1) + s2 = self.stat_or_none(f2) + if s1 is None or s2 is None: + return False + return os.path.samestat(s1, s2) + + +def copy_os_error(e: OSError) -> OSError: + new = OSError(*e.args) + new.errno = e.errno + new.strerror = e.strerror + new.filename = e.filename + if e.filename2: + new.filename2 = e.filename2 + return new diff --git a/micromamba_root/Lib/site-packages/mypy/fswatcher.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/fswatcher.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..779f1eb756a38d2f55b28e7e20d74229652cdb20 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/fswatcher.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/fswatcher.py b/micromamba_root/Lib/site-packages/mypy/fswatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..d5873f3a0a99655189c797064e910b479d0c7c3e --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/fswatcher.py @@ -0,0 +1,106 @@ +"""Watch parts of the file system for changes.""" + +from __future__ import annotations + +import os +from collections.abc import Iterable, Set as AbstractSet +from typing import NamedTuple + +from mypy.fscache import FileSystemCache + + +class FileData(NamedTuple): + st_mtime: float + st_size: int + hash: str + + +class FileSystemWatcher: + """Watcher for file system changes among specific paths. + + All file system access is performed using FileSystemCache. We + detect changed files by stat()ing them all and comparing hashes + of potentially changed files. If a file has both size and mtime + unmodified, the file is assumed to be unchanged. + + An important goal of this class is to make it easier to eventually + use file system events to detect file changes. + + Note: This class doesn't flush the file system cache. If you don't + manually flush it, changes won't be seen. + """ + + # TODO: Watching directories? + # TODO: Handle non-files + + def __init__(self, fs: FileSystemCache) -> None: + self.fs = fs + self._paths: set[str] = set() + self._file_data: dict[str, FileData | None] = {} + + def dump_file_data(self) -> dict[str, tuple[float, int, str]]: + return {k: v for k, v in self._file_data.items() if v is not None} + + def set_file_data(self, path: str, data: FileData) -> None: + self._file_data[path] = data + + def add_watched_paths(self, paths: Iterable[str]) -> None: + for path in paths: + if path not in self._paths: + # By storing None this path will get reported as changed by + # find_changed if it exists. + self._file_data[path] = None + self._paths |= set(paths) + + def remove_watched_paths(self, paths: Iterable[str]) -> None: + for path in paths: + if path in self._file_data: + del self._file_data[path] + self._paths -= set(paths) + + def _update(self, path: str, st: os.stat_result) -> None: + hash_digest = self.fs.hash_digest(path) + self._file_data[path] = FileData(st.st_mtime, st.st_size, hash_digest) + + def _find_changed(self, paths: Iterable[str]) -> AbstractSet[str]: + changed = set() + for path in paths: + old = self._file_data[path] + st = self.fs.stat_or_none(path) + if st is None: + if old is not None: + # File was deleted. + changed.add(path) + self._file_data[path] = None + else: + if old is None: + # File is new. + changed.add(path) + self._update(path, st) + # Round mtimes down, to match the mtimes we write to meta files + elif st.st_size != old.st_size or int(st.st_mtime) != int(old.st_mtime): + # Only look for changes if size or mtime has changed as an + # optimization, since calculating hash is expensive. + new_hash = self.fs.hash_digest(path) + self._update(path, st) + if st.st_size != old.st_size or new_hash != old.hash: + # Changed file. + changed.add(path) + return changed + + def find_changed(self) -> AbstractSet[str]: + """Return paths that have changes since the last call, in the watched set.""" + return self._find_changed(self._paths) + + def update_changed(self, remove: list[str], update: list[str]) -> AbstractSet[str]: + """Alternative to find_changed() given explicit changes. + + This only calls self.fs.stat() on added or updated files, not + on all files. It believes all other files are unchanged! + + Implies add_watched_paths() for add and update, and + remove_watched_paths() for remove. + """ + self.remove_watched_paths(remove) + self.add_watched_paths(update) + return self._find_changed(update) diff --git a/micromamba_root/Lib/site-packages/mypy/gclogger.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/gclogger.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..64f980de351dd22e1dc166b68e9a3fa623cde1a8 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/gclogger.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/gclogger.py b/micromamba_root/Lib/site-packages/mypy/gclogger.py new file mode 100644 index 0000000000000000000000000000000000000000..bc908bdb6107dab5187c0e4b79613987a49f2b56 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/gclogger.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +import gc +import time +from collections.abc import Mapping + + +class GcLogger: + """Context manager to log GC stats and overall time.""" + + def __enter__(self) -> GcLogger: + self.gc_start_time: float | None = None + self.gc_time = 0.0 + self.gc_calls = 0 + self.gc_collected = 0 + self.gc_uncollectable = 0 + gc.callbacks.append(self.gc_callback) + self.start_time = time.time() + return self + + def gc_callback(self, phase: str, info: Mapping[str, int]) -> None: + if phase == "start": + assert self.gc_start_time is None, "Start phase out of sequence" + self.gc_start_time = time.time() + elif phase == "stop": + assert self.gc_start_time is not None, "Stop phase out of sequence" + self.gc_calls += 1 + self.gc_time += time.time() - self.gc_start_time + self.gc_start_time = None + self.gc_collected += info["collected"] + self.gc_uncollectable += info["uncollectable"] + else: + assert False, f"Unrecognized gc phase ({phase!r})" + + def __exit__(self, *args: object) -> None: + while self.gc_callback in gc.callbacks: + gc.callbacks.remove(self.gc_callback) + + def get_stats(self) -> Mapping[str, float]: + end_time = time.time() + result = { + "gc_time": self.gc_time, + "gc_calls": self.gc_calls, + "gc_collected": self.gc_collected, + "gc_uncollectable": self.gc_uncollectable, + "build_time": end_time - self.start_time, + } + return result diff --git a/micromamba_root/Lib/site-packages/mypy/git.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/git.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..c894e39e0ef46d08edad00e933a70f85253546bf Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/git.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/git.py b/micromamba_root/Lib/site-packages/mypy/git.py new file mode 100644 index 0000000000000000000000000000000000000000..1c63bf6471dccc1c7aec2686bd90245412738560 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/git.py @@ -0,0 +1,34 @@ +"""Git utilities.""" + +# Used also from setup.py, so don't pull in anything additional here (like mypy or typing): +from __future__ import annotations + +import os +import subprocess + + +def is_git_repo(dir: str) -> bool: + """Is the given directory version-controlled with git?""" + return os.path.exists(os.path.join(dir, ".git")) + + +def have_git() -> bool: + """Can we run the git executable?""" + try: + subprocess.check_output(["git", "--help"]) + return True + except subprocess.CalledProcessError: + return False + except OSError: + return False + + +def git_revision(dir: str) -> bytes: + """Get the SHA-1 of the HEAD of a git repository.""" + return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=dir).strip() + + +def is_dirty(dir: str) -> bool: + """Check whether a git repository has uncommitted changes.""" + output = subprocess.check_output(["git", "status", "-uno", "--porcelain"], cwd=dir) + return output.strip() != b"" diff --git a/micromamba_root/Lib/site-packages/mypy/graph_utils.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/graph_utils.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..1f10682fc68f20f7f0af34265b2e80328420d9d8 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/graph_utils.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/graph_utils.py b/micromamba_root/Lib/site-packages/mypy/graph_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5699bab3f7e2f9c93132c7f351281ac611eca428 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/graph_utils.py @@ -0,0 +1,161 @@ +"""Helpers for manipulations with graphs.""" + +from __future__ import annotations + +from collections.abc import Iterator, Set as AbstractSet +from typing import TypeVar + +T = TypeVar("T") + + +def strongly_connected_components( + vertices: AbstractSet[T], edges: dict[T, list[T]] +) -> Iterator[set[T]]: + """Compute Strongly Connected Components of a directed graph. + + Args: + vertices: the labels for the vertices + edges: for each vertex, gives the target vertices of its outgoing edges + + Returns: + An iterator yielding strongly connected components, each + represented as a set of vertices. Each input vertex will occur + exactly once; vertices not part of a SCC are returned as + singleton sets. + + From https://code.activestate.com/recipes/578507/. + """ + identified: set[T] = set() + stack: list[T] = [] + index: dict[T, int] = {} + boundaries: list[int] = [] + + def dfs(v: T) -> Iterator[set[T]]: + index[v] = len(stack) + stack.append(v) + boundaries.append(index[v]) + + for w in edges[v]: + if w not in index: + yield from dfs(w) + elif w not in identified: + while index[w] < boundaries[-1]: + boundaries.pop() + + if boundaries[-1] == index[v]: + boundaries.pop() + scc = set(stack[index[v] :]) + del stack[index[v] :] + identified.update(scc) + yield scc + + for v in vertices: + if v not in index: + yield from dfs(v) + + +def prepare_sccs( + sccs: list[set[T]], edges: dict[T, list[T]] +) -> dict[AbstractSet[T], set[AbstractSet[T]]]: + """Use original edges to organize SCCs in a graph by dependencies between them.""" + sccsmap = {} + for scc in sccs: + scc_frozen = frozenset(scc) + for v in scc: + sccsmap[v] = scc_frozen + data: dict[AbstractSet[T], set[AbstractSet[T]]] = {} + for scc in sccs: + deps: set[AbstractSet[T]] = set() + for v in scc: + deps.update(sccsmap[x] for x in edges[v]) + data[frozenset(scc)] = deps + return data + + +class topsort(Iterator[set[T]]): # noqa: N801 + """Topological sort using Kahn's algorithm. + + Uses in-degree counters and a reverse adjacency list, so the total work + is O(V + E). + + Implemented as a class rather than a generator for better mypyc + compilation. + + Args: + data: A map from vertices to all vertices that it has an edge + connecting it to. NOTE: dependency sets in this data + structure are modified in place to remove self-dependencies. + Orphans are handled internally and are not added to `data`. + + Returns: + An iterator yielding sets of vertices that have an equivalent + ordering. + + Example: + Suppose the input has the following structure: + + {A: {B, C}, B: {D}, C: {D}} + + The algorithm treats orphan dependencies as if normalized to: + + {A: {B, C}, B: {D}, C: {D}, D: {}} + + It will yield the following values: + + {D} + {B, C} + {A} + """ + + def __init__(self, data: dict[T, set[T]]) -> None: + # Single pass: remove self-deps, build reverse adjacency list, + # compute in-degree counts, detect orphans, and find initial ready set. + in_degree: dict[T, int] = {} + rev: dict[T, list[T]] = {} + ready: set[T] = set() + for item, deps in data.items(): + deps.discard(item) # Ignore self dependencies. + deg = len(deps) + in_degree[item] = deg + if deg == 0: + ready.add(item) + if item not in rev: + rev[item] = [] + for dep in deps: + if dep in rev: + rev[dep].append(item) + else: + rev[dep] = [item] + if dep not in data: + # Orphan: appears as dependency but has no entry in data. + in_degree[dep] = 0 + ready.add(dep) + + self.in_degree = in_degree + self.rev = rev + self.ready = ready + self.remaining = len(in_degree) - len(ready) + + def __iter__(self) -> Iterator[set[T]]: + return self + + def __next__(self) -> set[T]: + ready = self.ready + if not ready: + assert self.remaining == 0, ( + f"A cyclic dependency exists amongst " + f"{[k for k, deg in self.in_degree.items() if deg > 0]!r}" + ) + raise StopIteration + in_degree = self.in_degree + rev = self.rev + new_ready: set[T] = set() + for item in ready: + for dependent in rev[item]: + new_deg = in_degree[dependent] - 1 + in_degree[dependent] = new_deg + if new_deg == 0: + new_ready.add(dependent) + self.remaining -= len(new_ready) + self.ready = new_ready + return ready diff --git a/micromamba_root/Lib/site-packages/mypy/indirection.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/indirection.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..171c6440eb2c11738a6a41235c6bdb2b45eb44eb Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/indirection.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/indirection.py b/micromamba_root/Lib/site-packages/mypy/indirection.py new file mode 100644 index 0000000000000000000000000000000000000000..c5f3fa89b8c4af53dc872f5c942b896d03d44c3b --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/indirection.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +from collections.abc import Iterable + +import mypy.types as types +from mypy.types import TypeVisitor + + +class TypeIndirectionVisitor(TypeVisitor[None]): + """Returns all module references within a particular type.""" + + def __init__(self) -> None: + # Module references are collected here + self.modules: set[str] = set() + # User to avoid infinite recursion with recursive types + self.seen_types: set[types.TypeAliasType | types.Instance] = set() + + def find_modules(self, typs: Iterable[types.Type]) -> set[str]: + self.modules = set() + self.seen_types = set() + for typ in typs: + self._visit(typ) + return self.modules + + def _visit(self, typ: types.Type) -> None: + # Note: instances are needed for `class str(Sequence[str]): ...` + if ( + isinstance(typ, types.TypeAliasType) + or isinstance(typ, types.ProperType) + and isinstance(typ, types.Instance) + ): + # Avoid infinite recursion for recursive types. + if typ in self.seen_types: + return + self.seen_types.add(typ) + typ.accept(self) + + def _visit_type_tuple(self, typs: tuple[types.Type, ...]) -> None: + # Micro-optimization: Specialized version of _visit for lists + for typ in typs: + if ( + isinstance(typ, types.TypeAliasType) + or isinstance(typ, types.ProperType) + and isinstance(typ, types.Instance) + ): + # Avoid infinite recursion for recursive types. + if typ in self.seen_types: + continue + self.seen_types.add(typ) + typ.accept(self) + + def _visit_type_list(self, typs: list[types.Type]) -> None: + # Micro-optimization: Specialized version of _visit for tuples + for typ in typs: + if ( + isinstance(typ, types.TypeAliasType) + or isinstance(typ, types.ProperType) + and isinstance(typ, types.Instance) + ): + # Avoid infinite recursion for recursive types. + if typ in self.seen_types: + continue + self.seen_types.add(typ) + typ.accept(self) + + def visit_unbound_type(self, t: types.UnboundType) -> None: + self._visit_type_tuple(t.args) + + def visit_any(self, t: types.AnyType) -> None: + pass + + def visit_none_type(self, t: types.NoneType) -> None: + pass + + def visit_uninhabited_type(self, t: types.UninhabitedType) -> None: + pass + + def visit_erased_type(self, t: types.ErasedType) -> None: + pass + + def visit_deleted_type(self, t: types.DeletedType) -> None: + pass + + def visit_type_var(self, t: types.TypeVarType) -> None: + self._visit_type_list(t.values) + self._visit(t.upper_bound) + self._visit(t.default) + + def visit_param_spec(self, t: types.ParamSpecType) -> None: + self._visit(t.upper_bound) + self._visit(t.default) + self._visit(t.prefix) + + def visit_type_var_tuple(self, t: types.TypeVarTupleType) -> None: + self._visit(t.upper_bound) + self._visit(t.default) + + def visit_unpack_type(self, t: types.UnpackType) -> None: + t.type.accept(self) + + def visit_parameters(self, t: types.Parameters) -> None: + self._visit_type_list(t.arg_types) + + def visit_instance(self, t: types.Instance) -> None: + # Instance is named, record its definition and continue digging into + # components that constitute semantic meaning of this type: bases, metaclass, + # tuple type, and typeddict type. + # Note: we cannot simply record the MRO, in case an intermediate base contains + # a reference to type alias, this affects meaning of map_instance_to_supertype(), + # see e.g. testDoubleReexportGenericUpdated. + self._visit_type_tuple(t.args) + if t.type: + # Important optimization: instead of simply recording the definition and + # recursing into bases, record the MRO and only traverse generic bases. + for s in t.type.mro: + self.modules.add(s.module_name) + for base in s.bases: + if base.args: + self._visit_type_tuple(base.args) + if t.type.metaclass_type: + self._visit(t.type.metaclass_type) + if t.type.typeddict_type: + self._visit(t.type.typeddict_type) + if t.type.tuple_type: + self._visit(t.type.tuple_type) + if t.type.is_protocol: + # For protocols, member types constitute the semantic meaning of the type. + # TODO: this doesn't cover some edge cases, like setter types and exotic nodes. + for m in t.type.protocol_members: + node = t.type.names.get(m) + if node and node.type: + self._visit(node.type) + + def visit_callable_type(self, t: types.CallableType) -> None: + self._visit_type_list(t.arg_types) + self._visit(t.ret_type) + self._visit_type_tuple(t.variables) + + def visit_overloaded(self, t: types.Overloaded) -> None: + for item in t.items: + self._visit(item) + self._visit(t.fallback) + + def visit_tuple_type(self, t: types.TupleType) -> None: + self._visit_type_list(t.items) + self._visit(t.partial_fallback) + + def visit_typeddict_type(self, t: types.TypedDictType) -> None: + self._visit_type_list(list(t.items.values())) + self._visit(t.fallback) + + def visit_literal_type(self, t: types.LiteralType) -> None: + self._visit(t.fallback) + + def visit_union_type(self, t: types.UnionType) -> None: + self._visit_type_list(t.items) + + def visit_partial_type(self, t: types.PartialType) -> None: + pass + + def visit_type_type(self, t: types.TypeType) -> None: + self._visit(t.item) + + def visit_type_alias_type(self, t: types.TypeAliasType) -> None: + # Type alias is named, record its definition and continue digging into + # components that constitute semantic meaning of this type: target and args. + if t.alias: + self.modules.add(t.alias.module) + self._visit(t.alias.target) + self._visit_type_list(t.args) diff --git a/micromamba_root/Lib/site-packages/mypy/infer.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/infer.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..b5028a808581e3875fa72076e73b3cb89d542d97 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/infer.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/infer.py b/micromamba_root/Lib/site-packages/mypy/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc43797d3b164ed9891a1439f3f14460b8ec451 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/infer.py @@ -0,0 +1,76 @@ +"""Utilities for type argument inference.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import NamedTuple + +from mypy.constraints import ( + SUBTYPE_OF, + SUPERTYPE_OF, + infer_constraints, + infer_constraints_for_callable, +) +from mypy.nodes import ArgKind +from mypy.solve import solve_constraints +from mypy.types import CallableType, Instance, Type, TypeVarLikeType + + +class ArgumentInferContext(NamedTuple): + """Type argument inference context. + + We need this because we pass around ``Mapping`` and ``Iterable`` types. + These types are only known by ``TypeChecker`` itself. + It is required for ``*`` and ``**`` argument inference. + + https://github.com/python/mypy/issues/11144 + """ + + mapping_type: Instance + iterable_type: Instance + + +def infer_function_type_arguments( + callee_type: CallableType, + arg_types: Sequence[Type | None], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None] | None, + formal_to_actual: list[list[int]], + context: ArgumentInferContext, + strict: bool = True, + allow_polymorphic: bool = False, +) -> tuple[list[Type | None], list[TypeVarLikeType]]: + """Infer the type arguments of a generic function. + + Return an array of lower bound types for the type variables -1 (at + index 0), -2 (at index 1), etc. A lower bound is None if a value + could not be inferred. + + Arguments: + callee_type: the target generic function + arg_types: argument types at the call site (each optional; if None, + we are not considering this argument in the current pass) + arg_kinds: nodes.ARG_* values for arg_types + formal_to_actual: mapping from formal to actual variable indices + """ + # Infer constraints. + constraints = infer_constraints_for_callable( + callee_type, arg_types, arg_kinds, arg_names, formal_to_actual, context + ) + + # Solve constraints. + type_vars = callee_type.variables + return solve_constraints(type_vars, constraints, strict, allow_polymorphic) + + +def infer_type_arguments( + type_vars: Sequence[TypeVarLikeType], + template: Type, + actual: Type, + is_supertype: bool = False, + skip_unsatisfied: bool = False, +) -> list[Type | None]: + # Like infer_function_type_arguments, but only match a single type + # against a generic type. + constraints = infer_constraints(template, actual, SUPERTYPE_OF if is_supertype else SUBTYPE_OF) + return solve_constraints(type_vars, constraints, skip_unsatisfied=skip_unsatisfied)[0] diff --git a/micromamba_root/Lib/site-packages/mypy/inspections.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/inspections.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e2d5ff12c77c0ce063ef2bbbc012c7f1769c323e Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/inspections.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/inspections.py b/micromamba_root/Lib/site-packages/mypy/inspections.py new file mode 100644 index 0000000000000000000000000000000000000000..1a869438101fe19ba87876558f9a863547ed3004 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/inspections.py @@ -0,0 +1,626 @@ +from __future__ import annotations + +import os +from collections import defaultdict +from collections.abc import Callable +from functools import cmp_to_key + +from mypy.build import State +from mypy.messages import format_type +from mypy.modulefinder import PYTHON_EXTENSIONS +from mypy.nodes import ( + LDEF, + Decorator, + Expression, + FuncBase, + MemberExpr, + MypyFile, + Node, + OverloadedFuncDef, + RefExpr, + SymbolNode, + TypeInfo, + Var, +) +from mypy.server.update import FineGrainedBuildManager +from mypy.traverser import ExtendedTraverserVisitor +from mypy.typeops import tuple_fallback +from mypy.types import ( + FunctionLike, + Instance, + LiteralType, + ProperType, + TupleType, + TypedDictType, + TypeVarType, + UnionType, + get_proper_type, +) +from mypy.typevars import fill_typevars_with_any + + +def node_starts_after(o: Node, line: int, column: int) -> bool: + return o.line > line or o.line == line and o.column > column + + +def node_ends_before(o: Node, line: int, column: int) -> bool: + # Unfortunately, end positions for some statements are a mess, + # e.g. overloaded functions, so we return False when we don't know. + if o.end_line is not None and o.end_column is not None: + if o.end_line < line or o.end_line == line and o.end_column < column: + return True + return False + + +def expr_span(expr: Expression) -> str: + """Format expression span as in mypy error messages.""" + return f"{expr.line}:{expr.column + 1}:{expr.end_line}:{expr.end_column}" + + +def get_instance_fallback(typ: ProperType) -> list[Instance]: + """Returns the Instance fallback for this type if one exists or None.""" + if isinstance(typ, Instance): + return [typ] + elif isinstance(typ, TupleType): + return [tuple_fallback(typ)] + elif isinstance(typ, TypedDictType): + return [typ.fallback] + elif isinstance(typ, FunctionLike): + return [typ.fallback] + elif isinstance(typ, LiteralType): + return [typ.fallback] + elif isinstance(typ, TypeVarType): + if typ.values: + res = [] + for t in typ.values: + res.extend(get_instance_fallback(get_proper_type(t))) + return res + return get_instance_fallback(get_proper_type(typ.upper_bound)) + elif isinstance(typ, UnionType): + res = [] + for t in typ.items: + res.extend(get_instance_fallback(get_proper_type(t))) + return res + return [] + + +def find_node(name: str, info: TypeInfo) -> Var | FuncBase | None: + """Find the node defining member 'name' in given TypeInfo.""" + # TODO: this code shares some logic with checkmember.py + method = info.get_method(name) + if method: + if isinstance(method, Decorator): + return method.var + if method.is_property: + assert isinstance(method, OverloadedFuncDef) + dec = method.items[0] + assert isinstance(dec, Decorator) + return dec.var + return method + else: + # don't have such method, maybe variable? + node = info.get(name) + v = node.node if node else None + if isinstance(v, Var): + return v + return None + + +def find_module_by_fullname(fullname: str, modules: dict[str, State]) -> State | None: + """Find module by a node fullname. + + This logic mimics the one we use in fixup, so should be good enough. + """ + head = fullname + # Special case: a module symbol is considered to be defined in itself, not in enclosing + # package, since this is what users want when clicking go to definition on a module. + if head in modules: + return modules[head] + while True: + if "." not in head: + return None + head, tail = head.rsplit(".", maxsplit=1) + mod = modules.get(head) + if mod is not None: + return mod + + +class SearchVisitor(ExtendedTraverserVisitor): + """Visitor looking for an expression whose span matches given one exactly.""" + + def __init__(self, line: int, column: int, end_line: int, end_column: int) -> None: + self.line = line + self.column = column + self.end_line = end_line + self.end_column = end_column + self.result: Expression | None = None + + def visit(self, o: Node) -> bool: + if node_starts_after(o, self.line, self.column): + return False + if node_ends_before(o, self.end_line, self.end_column): + return False + if ( + o.line == self.line + and o.end_line == self.end_line + and o.column == self.column + and o.end_column == self.end_column + ): + if isinstance(o, Expression): + self.result = o + return self.result is None + + +def find_by_location( + tree: MypyFile, line: int, column: int, end_line: int, end_column: int +) -> Expression | None: + """Find an expression matching given span, or None if not found.""" + if end_line < line: + raise ValueError('"end_line" must not be before "line"') + if end_line == line and end_column <= column: + raise ValueError('"end_column" must be after "column"') + visitor = SearchVisitor(line, column, end_line, end_column) + tree.accept(visitor) + return visitor.result + + +class SearchAllVisitor(ExtendedTraverserVisitor): + """Visitor looking for all expressions whose spans enclose given position.""" + + def __init__(self, line: int, column: int) -> None: + self.line = line + self.column = column + self.result: list[Expression] = [] + + def visit(self, o: Node) -> bool: + if node_starts_after(o, self.line, self.column): + return False + if node_ends_before(o, self.line, self.column): + return False + if isinstance(o, Expression): + self.result.append(o) + return True + + +def find_all_by_location(tree: MypyFile, line: int, column: int) -> list[Expression]: + """Find all expressions enclosing given position starting from innermost.""" + visitor = SearchAllVisitor(line, column) + tree.accept(visitor) + return list(reversed(visitor.result)) + + +class InspectionEngine: + """Engine for locating and statically inspecting expressions.""" + + def __init__( + self, + fg_manager: FineGrainedBuildManager, + *, + verbosity: int = 0, + limit: int = 0, + include_span: bool = False, + include_kind: bool = False, + include_object_attrs: bool = False, + union_attrs: bool = False, + force_reload: bool = False, + ) -> None: + self.fg_manager = fg_manager + self.verbosity = verbosity + self.limit = limit + self.include_span = include_span + self.include_kind = include_kind + self.include_object_attrs = include_object_attrs + self.union_attrs = union_attrs + self.force_reload = force_reload + # Module for which inspection was requested. + self.module: State | None = None + + def reload_module(self, state: State) -> None: + """Reload given module while temporary exporting types.""" + old = self.fg_manager.manager.options.export_types + self.fg_manager.manager.options.export_types = True + try: + self.fg_manager.flush_cache() + assert state.path is not None + self.fg_manager.update([(state.id, state.path)], []) + finally: + self.fg_manager.manager.options.export_types = old + + def expr_type(self, expression: Expression) -> tuple[str, bool]: + """Format type for an expression using current options. + + If type is known, second item returned is True. If type is not known, an error + message is returned instead, and second item returned is False. + """ + expr_type = self.fg_manager.manager.all_types.get(expression) + if expr_type is None: + return self.missing_type(expression), False + + type_str = format_type( + expr_type, self.fg_manager.manager.options, verbosity=self.verbosity + ) + return self.add_prefixes(type_str, expression), True + + def object_type(self) -> Instance: + builtins = self.fg_manager.graph["builtins"].tree + assert builtins is not None + object_node = builtins.names["object"].node + assert isinstance(object_node, TypeInfo) + return Instance(object_node, []) + + def collect_attrs(self, instances: list[Instance]) -> dict[TypeInfo, list[str]]: + """Collect attributes from all union/typevar variants.""" + + def item_attrs(attr_dict: dict[TypeInfo, list[str]]) -> set[str]: + attrs = set() + for base in attr_dict: + attrs |= set(attr_dict[base]) + return attrs + + def cmp_types(x: TypeInfo, y: TypeInfo) -> int: + if x in y.mro: + return 1 + if y in x.mro: + return -1 + return 0 + + # First gather all attributes for every union variant. + assert instances + all_attrs = [] + for instance in instances: + attrs = {} + mro = instance.type.mro + if not self.include_object_attrs: + mro = mro[:-1] + for base in mro: + attrs[base] = sorted(base.names) + all_attrs.append(attrs) + + # Find attributes valid for all variants in a union or type variable. + intersection = item_attrs(all_attrs[0]) + for item in all_attrs[1:]: + intersection &= item_attrs(item) + + # Combine attributes from all variants into a single dict while + # also removing invalid attributes (unless using --union-attrs). + combined_attrs = defaultdict(list) + for item in all_attrs: + for base in item: + if base in combined_attrs: + continue + for name in item[base]: + if self.union_attrs or name in intersection: + combined_attrs[base].append(name) + + # Sort bases by MRO, unrelated will appear in the order they appeared as union variants. + sorted_bases = sorted(combined_attrs.keys(), key=cmp_to_key(cmp_types)) + result = {} + for base in sorted_bases: + if not combined_attrs[base]: + # Skip bases where everytihng was filtered out. + continue + result[base] = combined_attrs[base] + return result + + def _fill_from_dict( + self, attrs_strs: list[str], attrs_dict: dict[TypeInfo, list[str]] + ) -> None: + for base in attrs_dict: + cls_name = base.name if self.verbosity < 1 else base.fullname + attrs = [f'"{attr}"' for attr in attrs_dict[base]] + attrs_strs.append(f'"{cls_name}": [{", ".join(attrs)}]') + + def expr_attrs(self, expression: Expression) -> tuple[str, bool]: + """Format attributes that are valid for a given expression. + + If expression type is not an Instance, try using fallback. Attributes are + returned as a JSON (ordered by MRO) that maps base class name to list of + attributes. Attributes may appear in multiple bases if overridden (we simply + follow usual mypy logic for creating new Vars etc). + """ + expr_type = self.fg_manager.manager.all_types.get(expression) + if expr_type is None: + return self.missing_type(expression), False + + expr_type = get_proper_type(expr_type) + instances = get_instance_fallback(expr_type) + if not instances: + # Everything is an object in Python. + instances = [self.object_type()] + + attrs_dict = self.collect_attrs(instances) + + # Special case: modules have names apart from those from ModuleType. + if isinstance(expression, RefExpr) and isinstance(expression.node, MypyFile): + node = expression.node + names = sorted(node.names) + if "__builtins__" in names: + # This is just to make tests stable. No one will really need this name. + names.remove("__builtins__") + mod_dict = {f'"<{node.fullname}>"': [f'"{name}"' for name in names]} + else: + mod_dict = {} + + # Special case: for class callables, prepend with the class attributes. + # TODO: also handle cases when such callable appears in a union. + if isinstance(expr_type, FunctionLike) and expr_type.is_type_obj(): + template = fill_typevars_with_any(expr_type.type_object()) + class_dict = self.collect_attrs(get_instance_fallback(template)) + else: + class_dict = {} + + # We don't use JSON dump to be sure keys order is always preserved. + base_attrs = [] + if mod_dict: + for mod in mod_dict: + base_attrs.append(f'{mod}: [{", ".join(mod_dict[mod])}]') + self._fill_from_dict(base_attrs, class_dict) + self._fill_from_dict(base_attrs, attrs_dict) + return self.add_prefixes(f'{{{", ".join(base_attrs)}}}', expression), True + + def format_node(self, module: State, node: FuncBase | SymbolNode) -> str: + return f"{module.path}:{node.line}:{node.column + 1}:{node.name}" + + def collect_nodes(self, expression: RefExpr) -> list[FuncBase | SymbolNode]: + """Collect nodes that can be referred to by an expression. + + Note: it can be more than one for example in case of a union attribute. + """ + node: FuncBase | SymbolNode | None = expression.node + nodes: list[FuncBase | SymbolNode] + if node is None: + # Tricky case: instance attribute + if isinstance(expression, MemberExpr) and expression.kind is None: + base_type = self.fg_manager.manager.all_types.get(expression.expr) + if base_type is None: + return [] + + # Now we use the base type to figure out where the attribute is defined. + base_type = get_proper_type(base_type) + instances = get_instance_fallback(base_type) + nodes = [] + for instance in instances: + node = find_node(expression.name, instance.type) + if node: + nodes.append(node) + if not nodes: + # Try checking class namespace if attribute is on a class object. + if isinstance(base_type, FunctionLike) and base_type.is_type_obj(): + instances = get_instance_fallback( + fill_typevars_with_any(base_type.type_object()) + ) + for instance in instances: + node = find_node(expression.name, instance.type) + if node: + nodes.append(node) + else: + # Still no luck, give up. + return [] + else: + return [] + else: + # Easy case: a module-level definition + nodes = [node] + return nodes + + def modules_for_nodes( + self, nodes: list[FuncBase | SymbolNode], expression: RefExpr + ) -> tuple[dict[FuncBase | SymbolNode, State], bool]: + """Gather modules where given nodes where defined. + + Also check if they need to be refreshed (cached nodes may have + lines/columns missing). + """ + modules = {} + reload_needed = False + for node in nodes: + module = find_module_by_fullname(node.fullname, self.fg_manager.graph) + if not module: + if expression.kind == LDEF and self.module: + module = self.module + else: + continue + modules[node] = module + if not module.tree or module.tree.is_cache_skeleton or self.force_reload: + reload_needed |= not module.tree or module.tree.is_cache_skeleton + self.reload_module(module) + return modules, reload_needed + + def expression_def(self, expression: Expression) -> tuple[str, bool]: + """Find and format definition location for an expression. + + If it is not a RefExpr, it is effectively skipped by returning an + empty result. + """ + if not isinstance(expression, RefExpr): + # If there are no suitable matches at all, we return error later. + return "", True + + nodes = self.collect_nodes(expression) + + if not nodes: + return self.missing_node(expression), False + + modules, reload_needed = self.modules_for_nodes(nodes, expression) + if reload_needed: + # TODO: line/column are not stored in cache for vast majority of symbol nodes. + # Adding them will make thing faster, but will have visible memory impact. + nodes = self.collect_nodes(expression) + modules, reload_needed = self.modules_for_nodes(nodes, expression) + assert not reload_needed + + result = [] + for node in modules: + result.append(self.format_node(modules[node], node)) + + if not result: + return self.missing_node(expression), False + + return self.add_prefixes(", ".join(result), expression), True + + def missing_type(self, expression: Expression) -> str: + alt_suggestion = "" + if not self.force_reload: + alt_suggestion = " or try --force-reload" + return ( + f'No known type available for "{type(expression).__name__}"' + f" (maybe unreachable{alt_suggestion})" + ) + + def missing_node(self, expression: Expression) -> str: + return ( + f'Cannot find definition for "{type(expression).__name__}" at {expr_span(expression)}' + ) + + def add_prefixes(self, result: str, expression: Expression) -> str: + prefixes = [] + if self.include_kind: + prefixes.append(f"{type(expression).__name__}") + if self.include_span: + prefixes.append(expr_span(expression)) + if prefixes: + prefix = ":".join(prefixes) + " -> " + else: + prefix = "" + return prefix + result + + def run_inspection_by_exact_location( + self, + tree: MypyFile, + line: int, + column: int, + end_line: int, + end_column: int, + method: Callable[[Expression], tuple[str, bool]], + ) -> dict[str, object]: + """Get type of an expression matching a span. + + Type or error is returned as a standard daemon response dict. + """ + try: + expression = find_by_location(tree, line, column - 1, end_line, end_column) + except ValueError as err: + return {"error": str(err)} + + if expression is None: + span = f"{line}:{column}:{end_line}:{end_column}" + return {"out": f"Can't find expression at span {span}", "err": "", "status": 1} + + inspection_str, success = method(expression) + return {"out": inspection_str, "err": "", "status": 0 if success else 1} + + def run_inspection_by_position( + self, + tree: MypyFile, + line: int, + column: int, + method: Callable[[Expression], tuple[str, bool]], + ) -> dict[str, object]: + """Get types of all expressions enclosing a position. + + Types and/or errors are returned as a standard daemon response dict. + """ + expressions = find_all_by_location(tree, line, column - 1) + if not expressions: + position = f"{line}:{column}" + return { + "out": f"Can't find any expressions at position {position}", + "err": "", + "status": 1, + } + + inspection_strs = [] + status = 0 + for expression in expressions: + inspection_str, success = method(expression) + if not success: + status = 1 + if inspection_str: + inspection_strs.append(inspection_str) + if self.limit: + inspection_strs = inspection_strs[: self.limit] + return {"out": "\n".join(inspection_strs), "err": "", "status": status} + + def find_module(self, file: str) -> tuple[State | None, dict[str, object]]: + """Find module by path, or return a suitable error message. + + Note we don't use exceptions to simplify handling 1 vs 2 statuses. + """ + if not any(file.endswith(ext) for ext in PYTHON_EXTENSIONS): + return None, {"error": "Source file is not a Python file"} + + # We are using a bit slower but robust way to find a module by path, + # to be sure that namespace packages are handled properly. + abs_path = os.path.abspath(file) + state = next((s for s in self.fg_manager.graph.values() if s.abspath == abs_path), None) + self.module = state + return ( + state, + {"out": f"Unknown module: {file}", "err": "", "status": 1} if state is None else {}, + ) + + def run_inspection( + self, location: str, method: Callable[[Expression], tuple[str, bool]] + ) -> dict[str, object]: + """Top-level logic to inspect expression(s) at a location. + + This can be reused by various simple inspections. + """ + try: + file, pos = parse_location(location) + except ValueError as err: + return {"error": str(err)} + + state, err_dict = self.find_module(file) + if state is None: + assert err_dict + return err_dict + + # Force reloading to load from cache, account for any edits, etc. + if not state.tree or state.tree.is_cache_skeleton or self.force_reload: + self.reload_module(state) + assert state.tree is not None + + if len(pos) == 4: + # Full span, return an exact match only. + line, column, end_line, end_column = pos + return self.run_inspection_by_exact_location( + state.tree, line, column, end_line, end_column, method + ) + assert len(pos) == 2 + # Inexact location, return all expressions. + line, column = pos + return self.run_inspection_by_position(state.tree, line, column, method) + + def get_type(self, location: str) -> dict[str, object]: + """Get types of expression(s) at a location.""" + return self.run_inspection(location, self.expr_type) + + def get_attrs(self, location: str) -> dict[str, object]: + """Get attributes of expression(s) at a location.""" + return self.run_inspection(location, self.expr_attrs) + + def get_definition(self, location: str) -> dict[str, object]: + """Get symbol definitions of expression(s) at a location.""" + result = self.run_inspection(location, self.expression_def) + if "out" in result and not result["out"]: + # None of the expressions found turns out to be a RefExpr. + _, location = location.split(":", maxsplit=1) + result["out"] = f"No name or member expressions at {location}" + result["status"] = 1 + return result + + +def parse_location(location: str) -> tuple[str, list[int]]: + if location.count(":") < 2: + raise ValueError("Format should be file:line:column[:end_line:end_column]") + parts = location.rsplit(":", maxsplit=2) + start, *rest = parts + # Note: we must allow drive prefix like `C:` on Windows. + if start.count(":") < 2: + return start, [int(p) for p in rest] + parts = start.rsplit(":", maxsplit=2) + start, *start_rest = parts + if start.count(":") < 2: + return start, [int(p) for p in start_rest + rest] + raise ValueError("Format should be file:line:column[:end_line:end_column]") diff --git a/micromamba_root/Lib/site-packages/mypy/ipc.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/ipc.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..01d2db7b8835fe4cadd755cd4cb61a16e2666da6 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/ipc.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/ipc.py b/micromamba_root/Lib/site-packages/mypy/ipc.py new file mode 100644 index 0000000000000000000000000000000000000000..29710cd57a915f2ff5be2781837765dc58c76b09 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/ipc.py @@ -0,0 +1,457 @@ +"""Cross-platform abstractions for inter-process communication + +On Unix, this uses AF_UNIX sockets. +On Windows, this uses NamedPipes. +""" + +from __future__ import annotations + +import json +import os +import shutil +import struct +import sys +import tempfile +from abc import abstractmethod +from collections.abc import Callable +from select import select +from types import TracebackType +from typing import Final +from typing_extensions import Self + +from librt.base64 import urlsafe_b64encode +from librt.internal import ReadBuffer, WriteBuffer + +if sys.platform == "win32": + # This may be private, but it is needed for IPC on Windows, and is basically stable + import _winapi + import ctypes + + _IPCHandle = int + + kernel32 = ctypes.windll.kernel32 + DisconnectNamedPipe: Callable[[_IPCHandle], int] = kernel32.DisconnectNamedPipe + FlushFileBuffers: Callable[[_IPCHandle], int] = kernel32.FlushFileBuffers +else: + import socket + + _IPCHandle = socket.socket + +# Size of the message packed as !L, i.e. 4 bytes in network order (big-endian). +HEADER_SIZE = 4 + + +# TODO: we should make sure consistent exceptions are raised on different platforms. +# Currently we raise either IPCException or OSError for equivalent conditions. +class IPCException(Exception): + """Exception for IPC issues.""" + + +class IPCBase: + """Base class for communication between the dmypy client and server. + + This contains logic shared between the client and server, such as reading + and writing. + We want to be able to send multiple "messages" over a single connection and + to be able to separate the messages. We do this by prefixing each message + with its size in a fixed format. + """ + + connection: _IPCHandle + + def __init__(self, name: str, timeout: float | None) -> None: + self.name = name + self.timeout = timeout + self.message_size: int | None = None + self.buffer = bytearray() + + def frame_from_buffer(self) -> bytes | None: + """Return a full frame from the bytes we have in the buffer.""" + size = len(self.buffer) + if size < HEADER_SIZE: + return None + if self.message_size is None: + self.message_size = struct.unpack("!L", self.buffer[:HEADER_SIZE])[0] + if size < self.message_size + HEADER_SIZE: + return None + # We have a full frame, avoid extra copy in case we get a large frame. + bdata = memoryview(self.buffer)[HEADER_SIZE : HEADER_SIZE + self.message_size] + self.buffer = self.buffer[HEADER_SIZE + self.message_size :] + self.message_size = None + return bytes(bdata) + + def read(self, size: int = 100000) -> str: + return self.read_bytes(size).decode("utf-8") + + def read_bytes(self, size: int = 100000) -> bytes: + """Read bytes from an IPC connection until we have a full frame.""" + if sys.platform == "win32": + while True: + # Check if we already have a message in the buffer before + # receiving any more data from the socket. + bdata = self.frame_from_buffer() + if bdata is not None: + break + + # Receive more data into the buffer. + ov, err = _winapi.ReadFile(self.connection, size, overlapped=True) + try: + if err == _winapi.ERROR_IO_PENDING: + timeout = int(self.timeout * 1000) if self.timeout else _winapi.INFINITE + res = _winapi.WaitForSingleObject(ov.event, timeout) + if res != _winapi.WAIT_OBJECT_0: + raise IPCException(f"Bad result from I/O wait: {res}") + except BaseException: + ov.cancel() + raise + _, err = ov.GetOverlappedResult(True) + more = ov.getbuffer() + if more: + self.buffer.extend(more) + bdata = self.frame_from_buffer() + if bdata is not None: + break + if err == 0: + # we are done! + break + elif err == _winapi.ERROR_MORE_DATA: + # read again + continue + elif err == _winapi.ERROR_OPERATION_ABORTED: + raise IPCException("ReadFile operation aborted.") + else: + while True: + # Check if we already have a message in the buffer before + # receiving any more data from the socket. + bdata = self.frame_from_buffer() + if bdata is not None: + break + + # Receive more data into the buffer. + more = self.connection.recv(size) + if not more: + # Connection closed + break + self.buffer.extend(more) + + if not bdata: + # Socket was empty, and we didn't get any frame. + # This should only happen if the socket was closed. + return b"" + return bdata + + def write(self, data: str) -> None: + self.write_bytes(data.encode("utf-8")) + + def write_bytes(self, data: bytes) -> None: + """Write to an IPC connection.""" + + # Frame the data by adding fixed size header. + encoded_data = struct.pack("!L", len(data)) + data + + if sys.platform == "win32": + try: + ov, err = _winapi.WriteFile(self.connection, encoded_data, overlapped=True) + try: + if err == _winapi.ERROR_IO_PENDING: + timeout = int(self.timeout * 1000) if self.timeout else _winapi.INFINITE + res = _winapi.WaitForSingleObject(ov.event, timeout) + if res != _winapi.WAIT_OBJECT_0: + raise IPCException(f"Bad result from I/O wait: {res}") + elif err != 0: + raise IPCException(f"Failed writing to pipe with error: {err}") + except BaseException: + ov.cancel() + raise + bytes_written, err = ov.GetOverlappedResult(True) + assert err == 0, err + assert bytes_written == len(encoded_data) + except OSError as e: + raise IPCException(f"Failed to write with error: {e.winerror}") from e + else: + self.connection.sendall(encoded_data) + + def close(self) -> None: + if sys.platform == "win32": + if self.connection != _winapi.NULL: + _winapi.CloseHandle(self.connection) + else: + self.connection.close() + + +class IPCClient(IPCBase): + """The client side of an IPC connection.""" + + def __init__(self, name: str, timeout: float | None) -> None: + super().__init__(name, timeout) + if sys.platform == "win32": + timeout = int(self.timeout * 1000) if self.timeout else _winapi.NMPWAIT_WAIT_FOREVER + try: + _winapi.WaitNamedPipe(self.name, timeout) + except FileNotFoundError as e: + raise IPCException(f"The NamedPipe at {self.name} was not found.") from e + except OSError as e: + if e.winerror == _winapi.ERROR_SEM_TIMEOUT: + raise IPCException("Timed out waiting for connection.") from e + else: + raise + try: + self.connection = _winapi.CreateFile( + self.name, + _winapi.GENERIC_READ | _winapi.GENERIC_WRITE, + 0, + _winapi.NULL, + _winapi.OPEN_EXISTING, + _winapi.FILE_FLAG_OVERLAPPED, + _winapi.NULL, + ) + except OSError as e: + if e.winerror == _winapi.ERROR_PIPE_BUSY: + raise IPCException("The connection is busy.") from e + else: + raise + _winapi.SetNamedPipeHandleState( + self.connection, _winapi.PIPE_READMODE_MESSAGE, None, None + ) + else: + self.connection = socket.socket(socket.AF_UNIX) + self.connection.settimeout(timeout) + self.connection.connect(name) + + def __enter__(self) -> IPCClient: + return self + + def __exit__( + self, + exc_ty: type[BaseException] | None = None, + exc_val: BaseException | None = None, + exc_tb: TracebackType | None = None, + ) -> None: + self.close() + + +class IPCServer(IPCBase): + BUFFER_SIZE: Final = 2**16 + + def __init__(self, name: str, timeout: float | None = None) -> None: + if sys.platform == "win32": + name = r"\\.\pipe\{}-{}.pipe".format(name, urlsafe_b64encode(os.urandom(6)).decode()) + else: + name = f"{name}.sock" + super().__init__(name, timeout) + if sys.platform == "win32": + self.connection = _winapi.CreateNamedPipe( + self.name, + _winapi.PIPE_ACCESS_DUPLEX + | _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE + | _winapi.FILE_FLAG_OVERLAPPED, + _winapi.PIPE_READMODE_MESSAGE + | _winapi.PIPE_TYPE_MESSAGE + | _winapi.PIPE_WAIT + | 0x8, # PIPE_REJECT_REMOTE_CLIENTS + 1, # one instance + self.BUFFER_SIZE, + self.BUFFER_SIZE, + _winapi.NMPWAIT_WAIT_FOREVER, + 0, # Use default security descriptor + ) + if self.connection == -1: # INVALID_HANDLE_VALUE + err = _winapi.GetLastError() + raise IPCException(f"Invalid handle to pipe: {err}") + else: + self.sock_directory = tempfile.mkdtemp() + sockfile = os.path.join(self.sock_directory, self.name) + self.sock = socket.socket(socket.AF_UNIX) + self.sock.bind(sockfile) + self.sock.listen(1) + if timeout is not None: + self.sock.settimeout(timeout) + + def __enter__(self) -> IPCServer: + if sys.platform == "win32": + # NOTE: It is theoretically possible that this will hang forever if the + # client never connects, though this can be "solved" by killing the server + try: + ov = _winapi.ConnectNamedPipe(self.connection, overlapped=True) + except OSError as e: + # Don't raise if the client already exists, or the client already connected + if e.winerror not in (_winapi.ERROR_PIPE_CONNECTED, _winapi.ERROR_NO_DATA): + raise + else: + try: + timeout = int(self.timeout * 1000) if self.timeout else _winapi.INFINITE + res = _winapi.WaitForSingleObject(ov.event, timeout) + assert res == _winapi.WAIT_OBJECT_0 + except BaseException: + ov.cancel() + _winapi.CloseHandle(self.connection) + raise + _, err = ov.GetOverlappedResult(True) + assert err == 0 + else: + try: + self.connection, _ = self.sock.accept() + except TimeoutError as e: + raise IPCException("The socket timed out") from e + return self + + def __exit__( + self, + exc_ty: type[BaseException] | None = None, + exc_val: BaseException | None = None, + exc_tb: TracebackType | None = None, + ) -> None: + if sys.platform == "win32": + try: + # Wait for the client to finish reading the last write before disconnecting + if not FlushFileBuffers(self.connection): + raise IPCException( + "Failed to flush NamedPipe buffer, maybe the client hung up?" + ) + finally: + DisconnectNamedPipe(self.connection) + else: + self.close() + + def cleanup(self) -> None: + if sys.platform == "win32": + self.close() + else: + shutil.rmtree(self.sock_directory) + + @property + def connection_name(self) -> str: + if sys.platform == "win32": + return self.name + elif sys.platform == "gnu0": + # GNU/Hurd returns empty string from getsockname() + # for AF_UNIX sockets + return os.path.join(self.sock_directory, self.name) + else: + name = self.sock.getsockname() + assert isinstance(name, str) + return name + + +class BadStatus(Exception): + """Exception raised when there is something wrong with the status file. + + For example: + - No status file found + - Status file malformed + - Process whose pid is in the status file does not exist + """ + + +def read_status(status_file: str) -> dict[str, object]: + """Read status file. + + Raise BadStatus if the status file doesn't exist or contains + invalid JSON or the JSON is not a dict. + """ + if not os.path.isfile(status_file): + raise BadStatus("No status file found") + with open(status_file) as f: + try: + data = json.load(f) + except Exception as e: + raise BadStatus(f"Malformed status file: {str(e)}") from e + if not isinstance(data, dict): + raise BadStatus(f"Invalid status file (not a dict): {data}") + return data + + +def ready_to_read(conns: list[IPCClient], timeout: float | None = None) -> list[int]: + """Wait until some connections are readable. + + Return index of each readable connection in the original list. + """ + if sys.platform == "win32": + # Windows doesn't support select() on named pipes. Instead, start an overlapped + # ReadFile on each pipe (which internally creates an event via CreateEventW), + # then WaitForMultipleObjects on those events for efficient OS-level waiting. + # Any data consumed by the probe reads is stored into each connection's buffer + # so the subsequent read_bytes() call will find it via frame_from_buffer(). + WAIT_FAILED = 0xFFFFFFFF + pending: list[tuple[int, _winapi.Overlapped]] = [] + events: list[int] = [] + ready: list[int] = [] + + for i, conn in enumerate(conns): + try: + ov, err = _winapi.ReadFile(conn.connection, 1, overlapped=True) + except OSError: + # Broken/closed pipe. Mimic Linux behavior here, caller will get + # the exception when trying to read from this socket. + ready.append(i) + continue + if err == _winapi.ERROR_IO_PENDING: + events.append(ov.event) + pending.append((i, ov)) + else: + # Data was immediately available (err == 0 or ERROR_MORE_DATA) + _, err = ov.GetOverlappedResult(True) + data = ov.getbuffer() + if data: + conn.buffer.extend(data) + ready.append(i) + + # Wait only if nothing is immediately ready and there are pending operations + if not ready and events: + timeout_ms = int(timeout * 1000) if timeout is not None else _winapi.INFINITE + res = _winapi.WaitForMultipleObjects(events, False, timeout_ms) + if res == WAIT_FAILED: + for _, ov in pending: + ov.cancel() + raise IPCException(f"Failed to wait for connections: {_winapi.GetLastError()}") + + # Check which pending operations completed, cancel the rest + for i, ov in pending: + if _winapi.WaitForSingleObject(ov.event, 0) == _winapi.WAIT_OBJECT_0: + _, err = ov.GetOverlappedResult(True) + data = ov.getbuffer() + if data: + conns[i].buffer.extend(data) + ready.append(i) + else: + ov.cancel() + + return ready + + else: + connections = [conn.connection for conn in conns] + ready, _, _ = select(connections, [], [], timeout) + return [connections.index(r) for r in ready] + + +def send(connection: IPCBase, data: IPCMessage) -> None: + """Send data to a connection encoded and framed. + + The data must be a non-abstract IPCMessage. We assume that a single send call is a + single frame to be sent. + """ + buf = WriteBuffer() + data.write(buf) + connection.write_bytes(buf.getvalue()) + + +def receive(connection: IPCBase) -> ReadBuffer: + """Receive single encoded IPCMessage frame from a connection. + + Raise OSError if the data received is not valid. + """ + bdata = connection.read_bytes() + if not bdata: + raise OSError("No data received") + return ReadBuffer(bdata) + + +class IPCMessage: + @classmethod + @abstractmethod + def read(cls, buf: ReadBuffer) -> Self: + raise NotImplementedError + + @abstractmethod + def write(self, buf: WriteBuffer) -> None: + raise NotImplementedError diff --git a/micromamba_root/Lib/site-packages/mypy/join.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/join.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..a09d55c63069c59c99870b58a6c9294d770a7229 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/join.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/join.py b/micromamba_root/Lib/site-packages/mypy/join.py new file mode 100644 index 0000000000000000000000000000000000000000..a8c9910e60bb733df732ca42a66a49416dd9e349 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/join.py @@ -0,0 +1,916 @@ +"""Calculation of the least upper bound types (joins).""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import overload + +import mypy.typeops +from mypy.expandtype import expand_type +from mypy.maptype import map_instance_to_supertype +from mypy.nodes import CONTRAVARIANT, COVARIANT, INVARIANT, VARIANCE_NOT_READY, TypeInfo +from mypy.state import state +from mypy.subtypes import ( + SubtypeContext, + find_member, + is_equivalent, + is_proper_subtype, + is_protocol_implementation, + is_subtype, +) +from mypy.types import ( + AnyType, + CallableType, + DeletedType, + ErasedType, + FunctionLike, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + TypeVisitor, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + find_unpack_in_list, + get_proper_type, + get_proper_types, + split_with_prefix_and_suffix, +) + + +class InstanceJoiner: + def __init__(self) -> None: + self.seen_instances: list[tuple[Instance, Instance]] = [] + + def join_instances(self, t: Instance, s: Instance) -> ProperType: + if (t, s) in self.seen_instances or (s, t) in self.seen_instances: + return object_from_instance(t) + + self.seen_instances.append((t, s)) + + # Calculate the join of two instance types + if t.type == s.type: + # Simplest case: join two types with the same base type (but + # potentially different arguments). + + # Combine type arguments. + args: list[Type] = [] + # N.B: We use zip instead of indexing because the lengths might have + # mismatches during daemon reprocessing. + if t.type.has_type_var_tuple_type: + # We handle joins of variadic instances by simply creating correct mapping + # for type arguments and compute the individual joins same as for regular + # instances. All the heavy lifting is done in the join of tuple types. + assert s.type.type_var_tuple_prefix is not None + assert s.type.type_var_tuple_suffix is not None + prefix = s.type.type_var_tuple_prefix + suffix = s.type.type_var_tuple_suffix + tvt = s.type.defn.type_vars[prefix] + assert isinstance(tvt, TypeVarTupleType) + fallback = tvt.tuple_fallback + s_prefix, s_middle, s_suffix = split_with_prefix_and_suffix(s.args, prefix, suffix) + t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix(t.args, prefix, suffix) + s_args = s_prefix + (TupleType(list(s_middle), fallback),) + s_suffix + t_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix + else: + t_args = t.args + s_args = s.args + for ta, sa, type_var in zip(t_args, s_args, t.type.defn.type_vars): + ta_proper = get_proper_type(ta) + sa_proper = get_proper_type(sa) + new_type: Type | None = None + if isinstance(ta_proper, AnyType): + new_type = AnyType(TypeOfAny.from_another_any, ta_proper) + elif isinstance(sa_proper, AnyType): + new_type = AnyType(TypeOfAny.from_another_any, sa_proper) + elif isinstance(type_var, TypeVarType): + if type_var.variance in (COVARIANT, VARIANCE_NOT_READY): + new_type = join_types(ta, sa, self) + if len(type_var.values) != 0 and new_type not in type_var.values: + self.seen_instances.pop() + return object_from_instance(t) + if not is_subtype(new_type, type_var.upper_bound): + self.seen_instances.pop() + return object_from_instance(t) + # TODO: contravariant case should use meet but pass seen instances as + # an argument to keep track of recursive checks. + elif type_var.variance in (INVARIANT, CONTRAVARIANT): + if isinstance(ta_proper, UninhabitedType) and ta_proper.ambiguous: + new_type = sa + elif isinstance(sa_proper, UninhabitedType) and sa_proper.ambiguous: + new_type = ta + elif not is_equivalent(ta, sa): + self.seen_instances.pop() + return object_from_instance(t) + else: + # If the types are different but equivalent, then an Any is involved + # so using a join in the contravariant case is also OK. + new_type = join_types(ta, sa, self) + elif isinstance(type_var, TypeVarTupleType): + new_type = get_proper_type(join_types(ta, sa, self)) + # Put the joined arguments back into instance in the normal form: + # a) Tuple[X, Y, Z] -> [X, Y, Z] + # b) tuple[X, ...] -> [*tuple[X, ...]] + if isinstance(new_type, Instance): + assert new_type.type.fullname == "builtins.tuple" + new_type = UnpackType(new_type) + else: + assert isinstance(new_type, TupleType) + args.extend(new_type.items) + continue + else: + # ParamSpec type variables behave the same, independent of variance + if not is_equivalent(ta, sa): + return get_proper_type(type_var.upper_bound) + new_type = join_types(ta, sa, self) + assert new_type is not None + args.append(new_type) + result: ProperType = Instance(t.type, args) + elif t.type.bases and is_proper_subtype( + t, s, subtype_context=SubtypeContext(ignore_type_params=True) + ): + result = self.join_instances_via_supertype(t, s) + else: + # Now t is not a subtype of s, and t != s. Now s could be a subtype + # of t; alternatively, we need to find a common supertype. This works + # in of the both cases. + result = self.join_instances_via_supertype(s, t) + + self.seen_instances.pop() + return result + + def join_instances_via_supertype(self, t: Instance, s: Instance) -> ProperType: + # Give preference to joins via duck typing relationship, so that + # join(int, float) == float, for example. + for p in t.type._promote: + if is_subtype(p, s): + return join_types(p, s, self) + for p in s.type._promote: + if is_subtype(p, t): + return join_types(t, p, self) + + # Compute the "best" supertype of t when joined with s. + # The definition of "best" may evolve; for now it is the one with + # the longest MRO. Ties are broken by using the earlier base. + + # Go over both sets of bases in case there's an explicit Protocol base. This is important + # to ensure commutativity of join (although in cases where both classes have relevant + # Protocol bases this maybe might still not be commutative) + base_types: dict[TypeInfo, None] = {} # dict to deduplicate but preserve order + for base in t.type.bases: + base_types[base.type] = None + for base in s.type.bases: + if base.type.is_protocol and is_subtype(t, base): + base_types[base.type] = None + + best: ProperType | None = None + for base_type in base_types: + mapped = map_instance_to_supertype(t, base_type) + res = self.join_instances(mapped, s) + if best is None or is_better(res, best): + best = res + assert best is not None + for promote in t.type._promote: + if isinstance(promote, Instance): + res = self.join_instances(promote, s) + if is_better(res, best): + best = res + return best + + +def trivial_join(s: Type, t: Type) -> Type: + """Return one of types (expanded) if it is a supertype of other, otherwise top type.""" + if is_subtype(s, t): + return t + elif is_subtype(t, s): + return s + else: + return object_or_any_from_type(get_proper_type(t)) + + +@overload +def join_types( + s: ProperType, t: ProperType, instance_joiner: InstanceJoiner | None = None +) -> ProperType: ... + + +@overload +def join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type: ... + + +def join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type: + """Return the least upper bound of s and t. + + For example, the join of 'int' and 'object' is 'object'. + """ + if mypy.typeops.is_recursive_pair(s, t): + # This case can trigger an infinite recursion, general support for this will be + # tricky so we use a trivial join (like for protocols). + return trivial_join(s, t) + s = get_proper_type(s) + t = get_proper_type(t) + + if (s.can_be_true, s.can_be_false) != (t.can_be_true, t.can_be_false): + # if types are restricted in different ways, use the more general versions + s = mypy.typeops.true_or_false(s) + t = mypy.typeops.true_or_false(t) + + if isinstance(s, UnionType) and not isinstance(t, UnionType): + s, t = t, s + + if isinstance(s, AnyType): + return s + + if isinstance(s, ErasedType): + return t + + if isinstance(s, NoneType) and not isinstance(t, NoneType): + s, t = t, s + + if isinstance(s, UninhabitedType) and not isinstance(t, UninhabitedType): + s, t = t, s + + # Meets/joins require callable type normalization. + s, t = normalize_callables(s, t) + + # Use a visitor to handle non-trivial cases. + return t.accept(TypeJoinVisitor(s, instance_joiner)) + + +class TypeJoinVisitor(TypeVisitor[ProperType]): + """Implementation of the least upper bound algorithm. + + Attributes: + s: The other (left) type operand. + """ + + def __init__(self, s: ProperType, instance_joiner: InstanceJoiner | None = None) -> None: + self.s = s + self.instance_joiner = instance_joiner + + def visit_unbound_type(self, t: UnboundType) -> ProperType: + return AnyType(TypeOfAny.special_form) + + def visit_union_type(self, t: UnionType) -> ProperType: + if is_proper_subtype(self.s, t): + return t + else: + return mypy.typeops.make_simplified_union([self.s, t]) + + def visit_any(self, t: AnyType) -> ProperType: + return t + + def visit_none_type(self, t: NoneType) -> ProperType: + if state.strict_optional: + if isinstance(self.s, (NoneType, UninhabitedType)): + return t + elif isinstance(self.s, (UnboundType, AnyType)): + return AnyType(TypeOfAny.special_form) + else: + return mypy.typeops.make_simplified_union([self.s, t]) + else: + return self.s + + def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType: + return self.s + + def visit_deleted_type(self, t: DeletedType) -> ProperType: + return self.s + + def visit_erased_type(self, t: ErasedType) -> ProperType: + return self.s + + def visit_type_var(self, t: TypeVarType) -> ProperType: + if isinstance(self.s, TypeVarType): + if self.s.id == t.id: + if self.s.upper_bound == t.upper_bound: + return self.s + return self.s.copy_modified( + upper_bound=join_types(self.s.upper_bound, t.upper_bound) + ) + # Fix non-commutative joins + return get_proper_type(join_types(self.s.upper_bound, t.upper_bound)) + else: + return self.default(self.s) + + def visit_param_spec(self, t: ParamSpecType) -> ProperType: + if self.s == t: + return t + return self.default(self.s) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType: + if self.s == t: + return t + if isinstance(self.s, Instance) and is_subtype(t.upper_bound, self.s): + # TODO: should we do this more generally and for all TypeVarLikeTypes? + return self.s + return self.default(self.s) + + def visit_unpack_type(self, t: UnpackType) -> UnpackType: + raise NotImplementedError + + def visit_parameters(self, t: Parameters) -> ProperType: + if isinstance(self.s, Parameters): + if not is_similar_params(t, self.s): + # TODO: it would be prudent to return [*object, **object] instead of Any. + return self.default(self.s) + from mypy.meet import meet_types + + return t.copy_modified( + arg_types=[ + meet_types(s_a, t_a) for s_a, t_a in zip(self.s.arg_types, t.arg_types) + ], + arg_names=combine_arg_names(self.s, t), + ) + else: + return self.default(self.s) + + def visit_instance(self, t: Instance) -> ProperType: + if isinstance(self.s, Instance): + if self.instance_joiner is None: + self.instance_joiner = InstanceJoiner() + nominal = self.instance_joiner.join_instances(t, self.s) + structural: Instance | None = None + if t.type.is_protocol and is_protocol_implementation(self.s, t): + structural = t + elif self.s.type.is_protocol and is_protocol_implementation(t, self.s): + structural = self.s + # Structural join is preferred in the case where we have found both + # structural and nominal and they have same MRO length (see two comments + # in join_instances_via_supertype). Otherwise, just return the nominal join. + if not structural or is_better(nominal, structural): + return nominal + return structural + elif isinstance(self.s, FunctionLike): + if t.type.is_protocol: + call = unpack_callback_protocol(t) + if call: + return join_types(call, self.s) + return join_types(t, self.s.fallback) + elif isinstance(self.s, TypeType): + return join_types(t, self.s) + elif isinstance(self.s, TypedDictType): + return join_types(t, self.s) + elif isinstance(self.s, TupleType): + return join_types(t, self.s) + elif isinstance(self.s, LiteralType): + return join_types(t, self.s) + elif isinstance(self.s, TypeVarTupleType) and is_subtype(self.s.upper_bound, t): + return t + else: + return self.default(self.s) + + def visit_callable_type(self, t: CallableType) -> ProperType: + if isinstance(self.s, CallableType): + if is_similar_callables(t, self.s): + if is_equivalent(t, self.s): + return combine_similar_callables(t, self.s) + result = join_similar_callables(t, self.s) + if any( + isinstance(tp, (NoneType, UninhabitedType)) + for tp in get_proper_types(result.arg_types) + ): + # We don't want to return unusable Callable, attempt fallback instead. + return join_types(t.fallback, self.s) + # We set the from_type_type flag to suppress error when a collection of + # concrete class objects gets inferred as their common abstract superclass. + if not ( + (t.is_type_obj() and t.type_object().is_abstract) + or (self.s.is_type_obj() and self.s.type_object().is_abstract) + ): + result.from_type_type = True + return result + else: + s2, t2 = self.s, t + if t2.is_var_arg: + s2, t2 = t2, s2 + if is_subtype(s2, t2): + return t2.copy_modified() + elif is_subtype(t2, s2): + return s2.copy_modified() + return join_types(t.fallback, self.s) + elif isinstance(self.s, Overloaded): + # Switch the order of arguments to that we'll get to visit_overloaded. + return join_types(t, self.s) + elif isinstance(self.s, Instance) and self.s.type.is_protocol: + call = unpack_callback_protocol(self.s) + if call: + return join_types(t, call) + return join_types(t.fallback, self.s) + + def visit_overloaded(self, t: Overloaded) -> ProperType: + # This is more complex than most other cases. Here are some + # examples that illustrate how this works. + # + # First let's define a concise notation: + # - Cn are callable types (for n in 1, 2, ...) + # - Ov(C1, C2, ...) is an overloaded type with items C1, C2, ... + # - Callable[[T, ...], S] is written as [T, ...] -> S. + # + # We want some basic properties to hold (assume Cn are all + # unrelated via Any-similarity): + # + # join(Ov(C1, C2), C1) == C1 + # join(Ov(C1, C2), Ov(C1, C2)) == Ov(C1, C2) + # join(Ov(C1, C2), Ov(C1, C3)) == C1 + # join(Ov(C2, C2), C3) == join of fallback types + # + # The presence of Any types makes things more interesting. The join is the + # most general type we can get with respect to Any: + # + # join(Ov([int] -> int, [str] -> str), [Any] -> str) == Any -> str + # + # We could use a simplification step that removes redundancies, but that's not + # implemented right now. Consider this example, where we get a redundancy: + # + # join(Ov([int, Any] -> Any, [str, Any] -> Any), [Any, int] -> Any) == + # Ov([Any, int] -> Any, [Any, int] -> Any) + # + # TODO: Consider more cases of callable subtyping. + result: list[CallableType] = [] + s = self.s + if isinstance(s, FunctionLike): + # The interesting case where both types are function types. + for t_item in t.items: + for s_item in s.items: + if is_similar_callables(t_item, s_item): + if is_equivalent(t_item, s_item): + result.append(combine_similar_callables(t_item, s_item)) + elif is_subtype(t_item, s_item): + result.append(s_item) + if result: + # TODO: Simplify redundancies from the result. + if len(result) == 1: + return result[0] + else: + return Overloaded(result) + return join_types(t.fallback, s.fallback) + elif isinstance(s, Instance) and s.type.is_protocol: + call = unpack_callback_protocol(s) + if call: + return join_types(t, call) + return join_types(t.fallback, s) + + def join_tuples(self, s: TupleType, t: TupleType) -> list[Type] | None: + """Join two tuple types while handling variadic entries. + + This is surprisingly tricky, and we don't handle some tricky corner cases. + Most of the trickiness comes from the variadic tuple items like *tuple[X, ...] + since they can have arbitrary partial overlaps (while *Ts can't be split). + """ + s_unpack_index = find_unpack_in_list(s.items) + t_unpack_index = find_unpack_in_list(t.items) + if s_unpack_index is None and t_unpack_index is None: + if s.length() == t.length(): + items: list[Type] = [] + for i in range(t.length()): + items.append(join_types(t.items[i], s.items[i])) + return items + return None + if s_unpack_index is not None and t_unpack_index is not None: + # The most complex case: both tuples have an unpack item. + s_unpack = s.items[s_unpack_index] + assert isinstance(s_unpack, UnpackType) + s_unpacked = get_proper_type(s_unpack.type) + t_unpack = t.items[t_unpack_index] + assert isinstance(t_unpack, UnpackType) + t_unpacked = get_proper_type(t_unpack.type) + if s.length() == t.length() and s_unpack_index == t_unpack_index: + # We can handle a case where arity is perfectly aligned, e.g. + # join(Tuple[X1, *tuple[Y1, ...], Z1], Tuple[X2, *tuple[Y2, ...], Z2]). + # We can essentially perform the join elementwise. + prefix_len = t_unpack_index + suffix_len = t.length() - t_unpack_index - 1 + items = [] + for si, ti in zip(s.items[:prefix_len], t.items[:prefix_len]): + items.append(join_types(si, ti)) + joined = join_types(s_unpacked, t_unpacked) + if isinstance(joined, TypeVarTupleType): + items.append(UnpackType(joined)) + elif isinstance(joined, Instance) and joined.type.fullname == "builtins.tuple": + items.append(UnpackType(joined)) + else: + if isinstance(t_unpacked, Instance): + assert t_unpacked.type.fullname == "builtins.tuple" + tuple_instance = t_unpacked + else: + assert isinstance(t_unpacked, TypeVarTupleType) + tuple_instance = t_unpacked.tuple_fallback + items.append( + UnpackType( + tuple_instance.copy_modified( + args=[object_from_instance(tuple_instance)] + ) + ) + ) + if suffix_len: + for si, ti in zip(s.items[-suffix_len:], t.items[-suffix_len:]): + items.append(join_types(si, ti)) + return items + if s.length() == 1 or t.length() == 1: + # Another case we can handle is when one of tuple is purely variadic + # (i.e. a non-normalized form of tuple[X, ...]), in this case the join + # will be again purely variadic. + if not (isinstance(s_unpacked, Instance) and isinstance(t_unpacked, Instance)): + return None + assert s_unpacked.type.fullname == "builtins.tuple" + assert t_unpacked.type.fullname == "builtins.tuple" + mid_joined = join_types(s_unpacked.args[0], t_unpacked.args[0]) + t_other = [a for i, a in enumerate(t.items) if i != t_unpack_index] + s_other = [a for i, a in enumerate(s.items) if i != s_unpack_index] + other_joined = join_type_list(s_other + t_other) + mid_joined = join_types(mid_joined, other_joined) + return [UnpackType(s_unpacked.copy_modified(args=[mid_joined]))] + # TODO: are there other case we can handle (e.g. both prefix/suffix are shorter)? + return None + if s_unpack_index is not None: + variadic = s + unpack_index = s_unpack_index + fixed = t + else: + assert t_unpack_index is not None + variadic = t + unpack_index = t_unpack_index + fixed = s + # Case where one tuple has variadic item and the other one doesn't. The join will + # be variadic, since fixed tuple is a subtype of variadic, but not vice versa. + unpack = variadic.items[unpack_index] + assert isinstance(unpack, UnpackType) + unpacked = get_proper_type(unpack.type) + if not isinstance(unpacked, Instance): + return None + if fixed.length() < variadic.length() - 1: + # There are no non-trivial types that are supertype of both. + return None + prefix_len = unpack_index + suffix_len = variadic.length() - prefix_len - 1 + prefix, middle, suffix = split_with_prefix_and_suffix( + tuple(fixed.items), prefix_len, suffix_len + ) + items = [] + for fi, vi in zip(prefix, variadic.items[:prefix_len]): + items.append(join_types(fi, vi)) + mid_joined = join_type_list(list(middle)) + mid_joined = join_types(mid_joined, unpacked.args[0]) + items.append(UnpackType(unpacked.copy_modified(args=[mid_joined]))) + if suffix_len: + for fi, vi in zip(suffix, variadic.items[-suffix_len:]): + items.append(join_types(fi, vi)) + return items + + def visit_tuple_type(self, t: TupleType) -> ProperType: + # When given two fixed-length tuples: + # * If they have the same length, join their subtypes item-wise: + # Tuple[int, bool] + Tuple[bool, bool] becomes Tuple[int, bool] + # * If lengths do not match, return a variadic tuple: + # Tuple[bool, int] + Tuple[bool] becomes Tuple[int, ...] + # + # Otherwise, `t` is a fixed-length tuple but `self.s` is NOT: + # * Joining with a variadic tuple returns variadic tuple: + # Tuple[int, bool] + Tuple[bool, ...] becomes Tuple[int, ...] + # * Joining with any Sequence also returns a Sequence: + # Tuple[int, bool] + List[bool] becomes Sequence[int] + if isinstance(self.s, TupleType): + if self.instance_joiner is None: + self.instance_joiner = InstanceJoiner() + fallback = self.instance_joiner.join_instances( + mypy.typeops.tuple_fallback(self.s), mypy.typeops.tuple_fallback(t) + ) + assert isinstance(fallback, Instance) + items = self.join_tuples(self.s, t) + if items is not None: + if len(items) == 1 and isinstance(item := items[0], UnpackType): + if isinstance(unpacked := get_proper_type(item.type), Instance): + # Avoid double-wrapping tuple[*tuple[X, ...]] + return unpacked + return TupleType(items, fallback) + else: + # TODO: should this be a default fallback behaviour like for meet? + if is_proper_subtype(self.s, t): + return t + if is_proper_subtype(t, self.s): + return self.s + return fallback + else: + return join_types(self.s, mypy.typeops.tuple_fallback(t)) + + def visit_typeddict_type(self, t: TypedDictType) -> ProperType: + if isinstance(self.s, TypedDictType): + items = { + item_name: s_item_type + for (item_name, s_item_type, t_item_type) in self.s.zip(t) + if ( + is_equivalent(s_item_type, t_item_type) + and (item_name in t.required_keys) == (item_name in self.s.required_keys) + ) + } + fallback = self.s.create_anonymous_fallback() + all_keys = set(items.keys()) + # We need to filter by items.keys() since some required keys present in both t and + # self.s might be missing from the join if the types are incompatible. + required_keys = all_keys & t.required_keys & self.s.required_keys + # If one type has a key as readonly, we mark it as readonly for both: + readonly_keys = (t.readonly_keys | t.readonly_keys) & all_keys + return TypedDictType(items, required_keys, readonly_keys, fallback) + elif isinstance(self.s, Instance): + return join_types(self.s, t.fallback) + else: + return self.default(self.s) + + def visit_literal_type(self, t: LiteralType) -> ProperType: + if isinstance(self.s, LiteralType): + if t == self.s: + return t + if self.s.fallback.type.is_enum and t.fallback.type.is_enum: + return mypy.typeops.make_simplified_union([self.s, t]) + return join_types(self.s.fallback, t.fallback) + elif isinstance(self.s, Instance) and self.s.last_known_value == t: + return t + else: + return join_types(self.s, t.fallback) + + def visit_partial_type(self, t: PartialType) -> ProperType: + # We only have partial information so we can't decide the join result. We should + # never get here. + assert False, "Internal error" + + def visit_type_type(self, t: TypeType) -> ProperType: + if isinstance(self.s, TypeType): + return TypeType.make_normalized( + join_types(t.item, self.s.item), + line=t.line, + is_type_form=self.s.is_type_form or t.is_type_form, + ) + elif isinstance(self.s, Instance) and self.s.type.fullname == "builtins.type": + return self.s + else: + return self.default(self.s) + + def visit_type_alias_type(self, t: TypeAliasType) -> ProperType: + assert False, f"This should be never called, got {t}" + + def default(self, typ: Type) -> ProperType: + typ = get_proper_type(typ) + if isinstance(typ, Instance): + return object_from_instance(typ) + elif isinstance(typ, TypeType): + return self.default(typ.item) + elif isinstance(typ, UnboundType): + return AnyType(TypeOfAny.special_form) + elif isinstance(typ, TupleType): + return self.default(mypy.typeops.tuple_fallback(typ)) + elif isinstance(typ, TypedDictType): + return self.default(typ.fallback) + elif isinstance(typ, FunctionLike): + return self.default(typ.fallback) + elif isinstance(typ, TypeVarType): + return self.default(typ.upper_bound) + elif isinstance(typ, ParamSpecType): + return self.default(typ.upper_bound) + else: + return AnyType(TypeOfAny.special_form) + + +def is_better(t: Type, s: Type) -> bool: + # Given two possible results from join_instances_via_supertype(), + # indicate whether t is the better one. + t = get_proper_type(t) + s = get_proper_type(s) + + if isinstance(t, Instance): + if not isinstance(s, Instance): + return True + if t.type.is_protocol != s.type.is_protocol: + if t.type.fullname != "builtins.object" and s.type.fullname != "builtins.object": + # mro of protocol is not really relevant + return not t.type.is_protocol + # Use len(mro) as a proxy for the better choice. + if len(t.type.mro) > len(s.type.mro): + return True + return False + + +def normalize_callables(s: ProperType, t: ProperType) -> tuple[ProperType, ProperType]: + if isinstance(s, (CallableType, Overloaded)): + s = s.with_unpacked_kwargs() + if isinstance(t, (CallableType, Overloaded)): + t = t.with_unpacked_kwargs() + return s, t + + +def is_similar_callables(t: CallableType, s: CallableType) -> bool: + """Return True if t and s have identical numbers of + arguments, default arguments and varargs. + """ + return ( + len(t.arg_types) == len(s.arg_types) + and t.min_args == s.min_args + and t.is_var_arg == s.is_var_arg + ) + + +def is_similar_params(t: Parameters, s: Parameters) -> bool: + # This matches the logic in is_similar_callables() above. + return ( + len(t.arg_types) == len(s.arg_types) + and t.min_args == s.min_args + and (t.var_arg() is not None) == (s.var_arg() is not None) + ) + + +def update_callable_ids(c: CallableType, ids: list[TypeVarId]) -> CallableType: + tv_map = {} + tvs = [] + for tv, new_id in zip(c.variables, ids): + new_tv = tv.copy_modified(id=new_id) + tvs.append(new_tv) + tv_map[tv.id] = new_tv + return expand_type(c, tv_map).copy_modified(variables=tvs) + + +def match_generic_callables(t: CallableType, s: CallableType) -> tuple[CallableType, CallableType]: + # The case where we combine/join/meet similar callables, situation where both are generic + # requires special care. A more principled solution may involve unify_generic_callable(), + # but it would have two problems: + # * This adds risk of infinite recursion: e.g. join -> unification -> solver -> join + # * Using unification is an incorrect thing for meets, as it "widens" the types + # Finally, this effectively falls back to an old behaviour before namespaces were added to + # type variables, and it worked relatively well. + max_len = max(len(t.variables), len(s.variables)) + min_len = min(len(t.variables), len(s.variables)) + if min_len == 0: + return t, s + new_ids = [TypeVarId.new(meta_level=0) for _ in range(max_len)] + # Note: this relies on variables being in order they appear in function definition. + return update_callable_ids(t, new_ids), update_callable_ids(s, new_ids) + + +def join_similar_callables(t: CallableType, s: CallableType) -> CallableType: + t, s = match_generic_callables(t, s) + arg_types: list[Type] = [] + for i in range(len(t.arg_types)): + arg_types.append(safe_meet(t.arg_types[i], s.arg_types[i])) + # TODO in combine_similar_callables also applies here (names and kinds; user metaclasses) + # The fallback type can be either 'function', 'type', or some user-provided metaclass. + # The result should always use 'function' as a fallback if either operands are using it. + if t.fallback.type.fullname == "builtins.function": + fallback = t.fallback + else: + fallback = s.fallback + return t.copy_modified( + arg_types=arg_types, + arg_names=combine_arg_names(t, s), + ret_type=join_types(t.ret_type, s.ret_type), + fallback=fallback, + name=None, + ) + + +def safe_join(t: Type, s: Type) -> Type: + # This is a temporary solution to prevent crashes in combine_similar_callables() etc., + # until relevant TODOs on handling arg_kinds will be addressed there. + if not isinstance(t, UnpackType) and not isinstance(s, UnpackType): + return join_types(t, s) + if isinstance(t, UnpackType) and isinstance(s, UnpackType): + return UnpackType(join_types(t.type, s.type)) + return object_or_any_from_type(get_proper_type(t)) + + +def safe_meet(t: Type, s: Type) -> Type: + # Similar to above but for meet_types(). + from mypy.meet import meet_types + + if not isinstance(t, UnpackType) and not isinstance(s, UnpackType): + return meet_types(t, s) + if isinstance(t, UnpackType) and isinstance(s, UnpackType): + unpacked = get_proper_type(t.type) + if isinstance(unpacked, TypeVarTupleType): + fallback_type = unpacked.tuple_fallback.type + elif isinstance(unpacked, TupleType): + fallback_type = unpacked.partial_fallback.type + else: + assert isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple" + fallback_type = unpacked.type + res = meet_types(t.type, s.type) + if isinstance(res, UninhabitedType): + res = Instance(fallback_type, [res]) + return UnpackType(res) + return UninhabitedType() + + +def combine_similar_callables(t: CallableType, s: CallableType) -> CallableType: + t, s = match_generic_callables(t, s) + arg_types: list[Type] = [] + for i in range(len(t.arg_types)): + arg_types.append(safe_join(t.arg_types[i], s.arg_types[i])) + # TODO kinds and argument names + # TODO what should happen if one fallback is 'type' and the other is a user-provided metaclass? + # The fallback type can be either 'function', 'type', or some user-provided metaclass. + # The result should always use 'function' as a fallback if either operands are using it. + if t.fallback.type.fullname == "builtins.function": + fallback = t.fallback + else: + fallback = s.fallback + return t.copy_modified( + arg_types=arg_types, + arg_names=combine_arg_names(t, s), + ret_type=join_types(t.ret_type, s.ret_type), + fallback=fallback, + name=None, + ) + + +def combine_arg_names( + t: CallableType | Parameters, s: CallableType | Parameters +) -> list[str | None]: + """Produces a list of argument names compatible with both callables. + + For example, suppose 't' and 's' have the following signatures: + + - t: (a: int, b: str, X: str) -> None + - s: (a: int, b: str, Y: str) -> None + + This function would return ["a", "b", None]. This information + is then used above to compute the join of t and s, which results + in a signature of (a: int, b: str, str) -> None. + + Note that the third argument's name is omitted and 't' and 's' + are both valid subtypes of this inferred signature. + + Precondition: is_similar_types(t, s) is true. + """ + num_args = len(t.arg_types) + new_names = [] + for i in range(num_args): + t_name = t.arg_names[i] + s_name = s.arg_names[i] + if t_name == s_name or t.arg_kinds[i].is_named() or s.arg_kinds[i].is_named(): + new_names.append(t_name) + else: + new_names.append(None) + return new_names + + +def object_from_instance(instance: Instance) -> Instance: + """Construct the type 'builtins.object' from an instance type.""" + # Use the fact that 'object' is always the last class in the mro. + res = Instance(instance.type.mro[-1], []) + return res + + +def object_or_any_from_type(typ: ProperType) -> ProperType: + # Similar to object_from_instance() but tries hard for all types. + # TODO: find a better way to get object, or make this more reliable. + if isinstance(typ, Instance): + return object_from_instance(typ) + elif isinstance(typ, (CallableType, TypedDictType, LiteralType)): + return object_from_instance(typ.fallback) + elif isinstance(typ, TupleType): + return object_from_instance(typ.partial_fallback) + elif isinstance(typ, TypeType): + return object_or_any_from_type(typ.item) + elif isinstance(typ, TypeVarLikeType) and isinstance(typ.upper_bound, ProperType): + return object_or_any_from_type(typ.upper_bound) + elif isinstance(typ, UnionType): + for item in typ.items: + if isinstance(item, ProperType): + candidate = object_or_any_from_type(item) + if isinstance(candidate, Instance): + return candidate + elif isinstance(typ, UnpackType): + object_or_any_from_type(get_proper_type(typ.type)) + return AnyType(TypeOfAny.implementation_artifact) + + +def join_type_list(types: Sequence[Type]) -> Type: + if not types: + # This is a little arbitrary but reasonable. Any empty tuple should be compatible + # with all variable length tuples, and this makes it possible. + return UninhabitedType() + joined = types[0] + for t in types[1:]: + joined = join_types(joined, t) + return joined + + +def unpack_callback_protocol(t: Instance) -> ProperType | None: + assert t.type.is_protocol + if t.type.protocol_members == ["__call__"]: + return get_proper_type(find_member("__call__", t, t, is_operator=True)) + return None diff --git a/micromamba_root/Lib/site-packages/mypy/literals.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/literals.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..625116cb3519a8dada45c3010c5f59f74a87f062 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/literals.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/literals.py b/micromamba_root/Lib/site-packages/mypy/literals.py new file mode 100644 index 0000000000000000000000000000000000000000..f572a6f9c624fed778c64ec082418c6150f20dcc --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/literals.py @@ -0,0 +1,327 @@ +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any, Final, TypeAlias as _TypeAlias + +from mypy.nodes import ( + LITERAL_NO, + LITERAL_TYPE, + LITERAL_YES, + AssertTypeExpr, + AssignmentExpr, + AwaitExpr, + BytesExpr, + CallExpr, + CastExpr, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + EnumCallExpr, + Expression, + FloatExpr, + GeneratorExpr, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MemberExpr, + NamedTupleExpr, + NameExpr, + NewTypeExpr, + OpExpr, + ParamSpecExpr, + PromoteExpr, + RevealExpr, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + StrExpr, + SuperExpr, + TemplateStrExpr, + TempNode, + TupleExpr, + TypeAliasExpr, + TypeApplication, + TypedDictExpr, + TypeFormExpr, + TypeVarExpr, + TypeVarTupleExpr, + UnaryExpr, + Var, + YieldExpr, + YieldFromExpr, +) +from mypy.visitor import ExpressionVisitor + +# [Note Literals and literal_hash] +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# +# Mypy uses the term "literal" to refer to any expression built out of +# the following: +# +# * Plain literal expressions, like `1` (integer, float, string, etc.) +# +# * Compound literal expressions, like `(lit1, lit2)` (list, dict, +# set, or tuple) +# +# * Operator expressions, like `lit1 + lit2` +# +# * Variable references, like `x` +# +# * Member references, like `lit.m` +# +# * Index expressions, like `lit[0]` +# +# A typical "literal" looks like `x[(i,j+1)].m`. +# +# An expression that is a literal has a `literal_hash`, with the +# following properties. +# +# * `literal_hash` is a Key: a tuple containing basic data types and +# possibly other Keys. So it can be used as a key in a dictionary +# that will be compared by value (as opposed to the Node itself, +# which is compared by identity). +# +# * Two expressions have equal `literal_hash`es if and only if they +# are syntactically equal expressions. (NB: Actually, we also +# identify as equal expressions like `3` and `3.0`; is this a good +# idea?) +# +# * The elements of `literal_hash` that are tuples are exactly the +# subexpressions of the original expression (e.g. the base and index +# of an index expression, or the operands of an operator expression). + + +Key: _TypeAlias = tuple[Any, ...] + + +def literal_hash(e: Expression) -> Key | None: + """Generate a hashable, (mostly) opaque key for expressions supported by the binder. + + These allow using expressions as dictionary keys based on structural/value + matching (instead of based on expression identity). + + Return None if the expression type is not supported (it cannot be narrowed). + + See the comment above for more information. + + NOTE: This is not directly related to literal types. + """ + return e.accept(_hasher) + + +def literal(e: Expression) -> int: + """Return the literal kind for an expression.""" + + if isinstance(e, ComparisonExpr): + return min(literal(o) for o in e.operands) + + elif isinstance(e, OpExpr): + return min(literal(e.left), literal(e.right)) + + elif isinstance(e, (MemberExpr, UnaryExpr, StarExpr)): + return literal(e.expr) + + elif isinstance(e, AssignmentExpr): + return literal(e.target) + + elif isinstance(e, IndexExpr): + if literal(e.index) == LITERAL_YES: + return literal(e.base) + else: + return LITERAL_NO + + elif isinstance(e, NameExpr): + if isinstance(e.node, Var) and e.node.is_final and e.node.final_value is not None: + return LITERAL_YES + return LITERAL_TYPE + + if isinstance(e, (IntExpr, FloatExpr, ComplexExpr, StrExpr, BytesExpr)): + return LITERAL_YES + + if literal_hash(e): + return LITERAL_YES + + return LITERAL_NO + + +def subkeys(key: Key) -> Iterable[Key]: + return [elt for elt in key if isinstance(elt, tuple)] + + +def extract_var_from_literal_hash(key: Key) -> Var | None: + """If key refers to a Var node, return it. + + Return None otherwise. + """ + if len(key) == 2 and key[0] == "Var" and isinstance(key[1], Var): + return key[1] + return None + + +class _Hasher(ExpressionVisitor[Key | None]): + def visit_int_expr(self, e: IntExpr) -> Key: + return ("Literal", e.value) + + def visit_str_expr(self, e: StrExpr) -> Key: + return ("Literal", e.value) + + def visit_bytes_expr(self, e: BytesExpr) -> Key: + return ("Literal", e.value) + + def visit_float_expr(self, e: FloatExpr) -> Key: + return ("Literal", e.value) + + def visit_complex_expr(self, e: ComplexExpr) -> Key: + return ("Literal", e.value) + + def visit_star_expr(self, e: StarExpr) -> Key: + return ("Star", literal_hash(e.expr)) + + def visit_name_expr(self, e: NameExpr) -> Key: + if isinstance(e.node, Var) and e.node.is_final and e.node.final_value is not None: + return ("Literal", e.node.final_value) + # N.B: We use the node itself as the key, and not the name, + # because using the name causes issues when there is shadowing + # (for example, in list comprehensions). + return ("Var", e.node) + + def visit_member_expr(self, e: MemberExpr) -> Key: + return ("Member", literal_hash(e.expr), e.name) + + def visit_op_expr(self, e: OpExpr) -> Key: + return ("Binary", e.op, literal_hash(e.left), literal_hash(e.right)) + + def visit_comparison_expr(self, e: ComparisonExpr) -> Key: + rest: tuple[str | Key | None, ...] = tuple(e.operators) + rest += tuple(literal_hash(o) for o in e.operands) + return ("Comparison",) + rest + + def visit_unary_expr(self, e: UnaryExpr) -> Key: + return ("Unary", e.op, literal_hash(e.expr)) + + def seq_expr(self, e: ListExpr | TupleExpr | SetExpr, name: str) -> Key | None: + if all(literal(x) == LITERAL_YES for x in e.items): + rest: tuple[Key | None, ...] = tuple(literal_hash(x) for x in e.items) + return (name,) + rest + return None + + def visit_list_expr(self, e: ListExpr) -> Key | None: + return self.seq_expr(e, "List") + + def visit_dict_expr(self, e: DictExpr) -> Key | None: + if all(a and literal(a) == literal(b) == LITERAL_YES for a, b in e.items): + rest: tuple[Key | None, ...] = tuple( + (literal_hash(a) if a else None, literal_hash(b)) for a, b in e.items + ) + return ("Dict",) + rest + return None + + def visit_tuple_expr(self, e: TupleExpr) -> Key | None: + return self.seq_expr(e, "Tuple") + + def visit_set_expr(self, e: SetExpr) -> Key | None: + return self.seq_expr(e, "Set") + + def visit_index_expr(self, e: IndexExpr) -> Key | None: + if literal(e.index) == LITERAL_YES: + return ("Index", literal_hash(e.base), literal_hash(e.index)) + return None + + def visit_assignment_expr(self, e: AssignmentExpr) -> Key | None: + return literal_hash(e.target) + + def visit_call_expr(self, e: CallExpr) -> None: + return None + + def visit_slice_expr(self, e: SliceExpr) -> None: + return None + + def visit_cast_expr(self, e: CastExpr) -> None: + return None + + def visit_type_form_expr(self, e: TypeFormExpr) -> None: + return None + + def visit_assert_type_expr(self, e: AssertTypeExpr) -> None: + return None + + def visit_conditional_expr(self, e: ConditionalExpr) -> None: + return None + + def visit_ellipsis(self, e: EllipsisExpr) -> None: + return None + + def visit_yield_from_expr(self, e: YieldFromExpr) -> None: + return None + + def visit_yield_expr(self, e: YieldExpr) -> None: + return None + + def visit_reveal_expr(self, e: RevealExpr) -> None: + return None + + def visit_super_expr(self, e: SuperExpr) -> None: + return None + + def visit_type_application(self, e: TypeApplication) -> None: + return None + + def visit_lambda_expr(self, e: LambdaExpr) -> None: + return None + + def visit_list_comprehension(self, e: ListComprehension) -> None: + return None + + def visit_set_comprehension(self, e: SetComprehension) -> None: + return None + + def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> None: + return None + + def visit_generator_expr(self, e: GeneratorExpr) -> None: + return None + + def visit_type_var_expr(self, e: TypeVarExpr) -> None: + return None + + def visit_paramspec_expr(self, e: ParamSpecExpr) -> None: + return None + + def visit_type_var_tuple_expr(self, e: TypeVarTupleExpr) -> None: + return None + + def visit_type_alias_expr(self, e: TypeAliasExpr) -> None: + return None + + def visit_namedtuple_expr(self, e: NamedTupleExpr) -> None: + return None + + def visit_enum_call_expr(self, e: EnumCallExpr) -> None: + return None + + def visit_typeddict_expr(self, e: TypedDictExpr) -> None: + return None + + def visit_newtype_expr(self, e: NewTypeExpr) -> None: + return None + + def visit__promote_expr(self, e: PromoteExpr) -> None: + return None + + def visit_await_expr(self, e: AwaitExpr) -> None: + return None + + def visit_template_str_expr(self, e: TemplateStrExpr) -> None: + return None + + def visit_temp_node(self, e: TempNode) -> None: + return None + + +_hasher: Final = _Hasher() diff --git a/micromamba_root/Lib/site-packages/mypy/lookup.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/lookup.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..47bb4264ddc2caf58b8517d67362314c29c4ab43 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/lookup.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/lookup.py b/micromamba_root/Lib/site-packages/mypy/lookup.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b195567fa0d0a9656bdb9ebbe61c38fbffdb07 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/lookup.py @@ -0,0 +1,68 @@ +""" +This is a module for various lookup functions: +functions that will find a semantic node by its name. +""" + +from __future__ import annotations + +from mypy.nodes import MypyFile, SymbolTableNode, TypeInfo + +# TODO: gradually move existing lookup functions to this module. + + +def lookup_fully_qualified( + name: str, modules: dict[str, MypyFile], *, raise_on_missing: bool = False +) -> SymbolTableNode | None: + """Find a symbol using it fully qualified name. + + The algorithm has two steps: first we try splitting the name on '.' to find + the module, then iteratively look for each next chunk after a '.' (e.g. for + nested classes). + + This function should *not* be used to find a module. Those should be looked + in the modules dictionary. + """ + # 1. Exclude the names of ad hoc instance intersections from step 2. + i = name.find(" os.stat_result: + try: + st = orig_stat(path) + except OSError as err: + print(f"stat({path!r}) -> {err}") + raise + else: + print( + "stat(%r) -> (st_mode=%o, st_mtime=%d, st_size=%d)" + % (path, st.st_mode, st.st_mtime, st.st_size) + ) + return st + + +def main( + *, + args: list[str] | None = None, + stdout: TextIO = sys.stdout, + stderr: TextIO = sys.stderr, + clean_exit: bool = False, +) -> None: + """Main entry point to the type checker. + + Args: + args: Custom command-line arguments. If not given, sys.argv[1:] will + be used. + clean_exit: Don't hard kill the process on exit. This allows catching + SystemExit. + """ + util.check_python_version("mypy") + t0 = time.time() + # To log stat() calls: os.stat = stat_proxy + sys.setrecursionlimit(RECURSION_LIMIT) + if args is None: + args = sys.argv[1:] + + # Write an escape sequence instead of raising an exception on encoding errors. + if isinstance(stdout, TextIOWrapper) and stdout.errors == "strict": + stdout.reconfigure(errors="backslashreplace") + + fscache = FileSystemCache() + sources, options = process_options(args, stdout=stdout, stderr=stderr, fscache=fscache) + if clean_exit: + options.fast_exit = False + + formatter = util.FancyFormatter( + stdout, stderr, options.hide_error_codes, hide_success=bool(options.output) + ) + + if options.num_workers: + # Supporting both parsers would be really tricky, so just support the new one. + options.native_parser = True + + if options.allow_redefinition_new and not options.local_partial_types: + fail( + "error: --local-partial-types must be enabled if using --allow-redefinition-new", + stderr, + options, + ) + + if options.allow_redefinition_new and options.allow_redefinition_old: + fail( + "--allow-redefinition-old and --allow-redefinition-new should not be used together", + stderr, + options, + ) + + if options.install_types and (stdout is not sys.stdout or stderr is not sys.stderr): + # Since --install-types performs user input, we want regular stdout and stderr. + fail("error: --install-types not supported in this mode of running mypy", stderr, options) + + if options.non_interactive and not options.install_types: + fail("error: --non-interactive is only supported with --install-types", stderr, options) + + if options.install_types and not options.incremental: + fail( + "error: --install-types not supported with incremental mode disabled", stderr, options + ) + + if options.install_types and options.python_executable is None: + fail( + "error: --install-types not supported without python executable or site packages", + stderr, + options, + ) + + if options.install_types and not sources: + install_types(formatter, options, non_interactive=options.non_interactive) + return + + res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr) + + if options.non_interactive: + missing_pkgs = read_types_packages_to_install(options.cache_dir, after_run=True) + if missing_pkgs: + # Install missing type packages and rerun build. + install_types(formatter, options, after_run=True, non_interactive=True) + fscache.flush() + print() + res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr) + show_messages(messages, stderr, formatter, options) + + if MEM_PROFILE: + from mypy.memprofile import print_memory_profile + + print_memory_profile() + + code = 0 + n_errors, n_notes, n_files = util.count_stats(messages) + if messages and n_notes < len(messages): + code = 2 if blockers else 1 + if options.error_summary: + if n_errors: + summary = formatter.format_error( + n_errors, n_files, len(sources), blockers=blockers, use_color=options.color_output + ) + stdout.write(summary + "\n") + # Only notes should also output success + elif not messages or n_notes == len(messages): + stdout.write(formatter.format_success(len(sources), options.color_output) + "\n") + stdout.flush() + + if options.install_types and not options.non_interactive: + result = install_types(formatter, options, after_run=True, non_interactive=False) + if result: + print() + print("note: Run mypy again for up-to-date results with installed types") + code = 2 + + if options.fast_exit: + # Exit without freeing objects -- it's faster. + # + # NOTE: We don't flush all open files on exit (or run other destructors)! + util.hard_exit(code) + elif code: + sys.exit(code) + + # HACK: keep res alive so that mypyc won't free it before the hard_exit + list([res]) # noqa: C410 + + +class BuildResultThunk: + # We pass this around so that we avoid freeing memory, which is slow + def __init__(self, build_result: build.BuildResult | None) -> None: + self._result = build_result + + +def run_build( + sources: list[BuildSource], + options: Options, + fscache: FileSystemCache, + t0: float, + stdout: TextIO, + stderr: TextIO, +) -> tuple[BuildResultThunk | None, list[str], bool]: + formatter = util.FancyFormatter( + stdout, stderr, options.hide_error_codes, hide_success=bool(options.output) + ) + + messages = [] + messages_by_file = defaultdict(list) + + def flush_errors(filename: str | None, new_messages: list[str], serious: bool) -> None: + if options.pretty: + new_messages = formatter.fit_in_terminal(new_messages) + messages.extend(new_messages) + if new_messages: + messages_by_file[filename].extend(new_messages) + if options.non_interactive: + # Collect messages and possibly show them later. + return + f = stderr if serious else stdout + show_messages(new_messages, f, formatter, options) + + serious = False + blockers = False + res = None + try: + # Keep a dummy reference (res) for memory profiling afterwards, as otherwise + # the result could be freed. + res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr) + except CompileError as e: + blockers = True + if not e.use_stdout: + serious = True + + if res: + res.manager.metastore.close() + + maybe_write_junit_xml(time.time() - t0, serious, messages, messages_by_file, options) + return BuildResultThunk(res), messages, blockers + + +def show_messages( + messages: list[str], f: TextIO, formatter: util.FancyFormatter, options: Options +) -> None: + for msg in messages: + if options.color_output: + msg = formatter.colorize(msg) + f.write(msg + "\n") + f.flush() + + +# Make the help output a little less jarring. +class AugmentedHelpFormatter(argparse.RawDescriptionHelpFormatter): + def __init__(self, prog: str, **kwargs: Any) -> None: + super().__init__(prog=prog, max_help_position=28, **kwargs) + + def _fill_text(self, text: str, width: int, indent: str) -> str: + if "\n" in text: + # Assume we want to manually format the text + return super()._fill_text(text, width, indent) + # Format the text like argparse, but overflow rather than + # breaking long words (like URLs) + text = self._whitespace_matcher.sub(" ", text).strip() + import textwrap + + return textwrap.fill( + text, + width, + initial_indent=indent, + subsequent_indent=indent, + break_on_hyphens=False, + break_long_words=False, + ) + + +# Define pairs of flag prefixes with inverse meaning. +flag_prefix_pairs: Final = [("allow", "disallow"), ("show", "hide")] +flag_prefix_map: Final[dict[str, str]] = {} +for a, b in flag_prefix_pairs: + flag_prefix_map[a] = b + flag_prefix_map[b] = a + + +def invert_flag_name(flag: str) -> str: + split = flag[2:].split("-", 1) + if len(split) == 2: + prefix, rest = split + if prefix in flag_prefix_map: + return f"--{flag_prefix_map[prefix]}-{rest}" + elif prefix == "no": + return f"--{rest}" + + return f"--no-{flag[2:]}" + + +class PythonExecutableInferenceError(Exception): + """Represents a failure to infer the version or executable while searching.""" + + +def python_executable_prefix(v: str) -> list[str]: + if sys.platform == "win32": + # on Windows, all Python executables are named `python`. To handle this, there + # is the `py` launcher, which can be passed a version e.g. `py -3.8`, and it will + # execute an installed Python 3.8 interpreter. See also: + # https://docs.python.org/3/using/windows.html#python-launcher-for-windows + return ["py", f"-{v}"] + else: + return [f"python{v}"] + + +def _python_executable_from_version(python_version: tuple[int, int]) -> str: + if sys.version_info[:2] == python_version: + return sys.executable + str_ver = ".".join(map(str, python_version)) + try: + sys_exe = ( + subprocess.check_output( + python_executable_prefix(str_ver) + ["-c", "import sys; print(sys.executable)"], + stderr=subprocess.STDOUT, + ) + .decode() + .strip() + ) + return sys_exe + except (subprocess.CalledProcessError, FileNotFoundError) as e: + raise PythonExecutableInferenceError( + "failed to find a Python executable matching version {}," + " perhaps try --python-executable, or --no-site-packages?".format(python_version) + ) from e + + +def infer_python_executable(options: Options, special_opts: argparse.Namespace) -> None: + """Infer the Python executable from the given version. + + This function mutates options based on special_opts to infer the correct Python executable + to use. + """ + # TODO: (ethanhs) Look at folding these checks and the site packages subprocess calls into + # one subprocess call for speed. + + # Use the command line specified executable, or fall back to one set in the + # config file. If an executable is not specified, infer it from the version + # (unless no_executable is set) + python_executable = special_opts.python_executable or options.python_executable + + if python_executable is None: + if not special_opts.no_executable and not options.no_site_packages: + python_executable = _python_executable_from_version(options.python_version) + options.python_executable = python_executable + + +HEADER: Final = """%(prog)s [-h] [-v] [-V] [more options; see below] + [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]""" + + +DESCRIPTION: Final = """ +Mypy is a program that will type check your Python code. + +Pass in any files or folders you want to type check. Mypy will +recursively traverse any provided folders to find .py files: + + $ mypy my_program.py my_src_folder + +For more information on getting started, see: + +- https://mypy.readthedocs.io/en/stable/getting_started.html + +For more details on both running mypy and using the flags below, see: + +- https://mypy.readthedocs.io/en/stable/running_mypy.html +- https://mypy.readthedocs.io/en/stable/command_line.html + +You can also use a config file to configure mypy instead of using +command line flags. For more details, see: + +- https://mypy.readthedocs.io/en/stable/config_file.html +""" + +FOOTER: Final = """Environment variables: + Define MYPYPATH for additional module search path entries. + Define MYPY_CACHE_DIR to override configuration cache_dir path.""" + + +class CapturableArgumentParser(argparse.ArgumentParser): + """Override ArgumentParser methods that use sys.stdout/sys.stderr directly. + + This is needed because hijacking sys.std* is not thread-safe, + yet output must be captured to properly support mypy.api.run. + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + self.stdout = kwargs.pop("stdout", sys.stdout) + self.stderr = kwargs.pop("stderr", sys.stderr) + super().__init__(*args, **kwargs) + + # ===================== + # Help-printing methods + # ===================== + def print_usage(self, file: SupportsWrite[str] | None = None) -> None: + if file is None: + file = self.stdout + self._print_message(self.format_usage(), file) + + def print_help(self, file: SupportsWrite[str] | None = None) -> None: + if file is None: + file = self.stdout + self._print_message(self.format_help(), file) + + def _print_message(self, message: str, file: SupportsWrite[str] | None = None) -> None: + if message: + if file is None: + file = self.stderr + file.write(message) + + # =============== + # Exiting methods + # =============== + def exit(self, status: int = 0, message: str | None = None) -> NoReturn: + if message: + self._print_message(message, self.stderr) + sys.exit(status) + + def error(self, message: str) -> NoReturn: + """error(message: string) + + Prints a usage message incorporating the message to stderr and + exits. + + If you override this in a subclass, it should not return -- it + should either exit or raise an exception. + """ + self.print_usage(self.stderr) + args = {"prog": self.prog, "message": message} + self.exit(2, gettext("%(prog)s: error: %(message)s\n") % args) + + +class CapturableVersionAction(argparse.Action): + """Supplement CapturableArgumentParser to handle --version. + + This is nearly identical to argparse._VersionAction except, + like CapturableArgumentParser, it allows output to be captured. + + Another notable difference is that version is mandatory. + This allows removing a line in __call__ that falls back to parser.version + (which does not appear to exist). + """ + + def __init__( + self, + option_strings: Sequence[str], + version: str, + dest: str = argparse.SUPPRESS, + default: str = argparse.SUPPRESS, + help: str = "show program's version number and exit", + stdout: IO[str] | None = None, + ) -> None: + super().__init__( + option_strings=option_strings, dest=dest, default=default, nargs=0, help=help + ) + self.version = version + self.stdout = stdout or sys.stdout + + def __call__( + self, + parser: argparse.ArgumentParser, + namespace: argparse.Namespace, + values: str | Sequence[Any] | None, + option_string: str | None = None, + ) -> NoReturn: + formatter = parser._get_formatter() + formatter.add_text(self.version) + parser._print_message(formatter.format_help(), self.stdout) + parser.exit() + + +def define_options( + program: str = "mypy", + header: str = HEADER, + stdout: TextIO = sys.stdout, + stderr: TextIO = sys.stderr, + server_options: bool = False, +) -> tuple[CapturableArgumentParser, list[str], list[tuple[str, bool]]]: + """Define the options in the parser (by calling a bunch of methods that express/build our desired command-line flags). + Returns a tuple of: + a parser object, that can parse command line arguments to mypy (expected consumer: main's process_options), + a list of what flags are strict (expected consumer: docs' html_builder's _add_strict_list), + strict_flag_assignments (expected consumer: main's process_options).""" + parser = CapturableArgumentParser( + prog=program, + usage=header, + description=DESCRIPTION, + epilog=FOOTER, + fromfile_prefix_chars="@", + formatter_class=AugmentedHelpFormatter, + add_help=False, + stdout=stdout, + stderr=stderr, + ) + + strict_flag_names: list[str] = [] + strict_flag_assignments: list[tuple[str, bool]] = [] + + def add_invertible_flag( + flag: str, + *, + inverse: str | None = None, + default: bool, + dest: str | None = None, + help: str, + strict_flag: bool = False, + group: argparse._ActionsContainer | None = None, + ) -> None: + if inverse is None: + inverse = invert_flag_name(flag) + if group is None: + group = parser + + if help is not argparse.SUPPRESS: + help += f" (inverse: {inverse})" + + arg = group.add_argument( + flag, action="store_false" if default else "store_true", dest=dest, help=help + ) + dest = arg.dest + group.add_argument( + inverse, + action="store_true" if default else "store_false", + dest=dest, + help=argparse.SUPPRESS, + ) + if strict_flag: + assert dest is not None + strict_flag_names.append(flag) + strict_flag_assignments.append((dest, not default)) + + # Unless otherwise specified, arguments will be parsed directly onto an + # Options object. Options that require further processing should have + # their `dest` prefixed with `special-opts:`, which will cause them to be + # parsed into the separate special_opts namespace object. + + # Our style guide for formatting the output of running `mypy --help`: + # Flags: + # 1. The flag help text should start with a capital letter but never end with a period. + # 2. Keep the flag help text brief -- ideally just a single sentence. + # 3. All flags must be a part of a group, unless the flag is deprecated or suppressed. + # 4. Avoid adding new flags to the "miscellaneous" groups -- instead add them to an + # existing group or, if applicable, create a new group. Feel free to move existing + # flags to a new group: just be sure to also update the documentation to match. + # + # Groups: + # 1. The group title and description should start with a capital letter. + # 2. The first sentence of a group description should be written in the bare infinitive. + # Tip: try substituting the group title and description into the following sentence: + # > {group_title}: these flags will {group_description} + # Feel free to add subsequent sentences that add additional details. + # 3. If you cannot think of a meaningful description for a new group, omit it entirely. + # (E.g. see the "miscellaneous" sections). + # 4. The text of the group description should end with a period, optionally followed + # by a documentation reference (URL). + # 5. If you want to include a documentation reference, place it at the end of the + # description. Feel free to open with a brief reference ("See also:", "For more + # information:", etc.), followed by a space, then the entire URL including + # "https://" scheme identifier and fragment ("#some-target-heading"), if any. + # Do not end with a period (or any other characters not part of the URL). + # URLs longer than the available terminal width will overflow without being + # broken apart. This facilitates both URL detection, and manual copy-pasting. + + general_group = parser.add_argument_group(title="Optional arguments") + general_group.add_argument( + "-h", "--help", action="help", help="Show this help message and exit" + ) + general_group.add_argument( + "-v", "--verbose", action="count", dest="verbosity", help="More verbose messages" + ) + + compilation_status = "no" if __file__.endswith(".py") else "yes" + general_group.add_argument( + "-V", + "--version", + action=CapturableVersionAction, + version="%(prog)s " + __version__ + f" (compiled: {compilation_status})", + help="Show program's version number and exit", + stdout=stdout, + ) + + general_group.add_argument( + "-O", + "--output", + metavar="FORMAT", + help="Set a custom output format", + choices=OUTPUT_CHOICES, + ) + + config_group = parser.add_argument_group( + title="Config file", + description="Use a config file instead of command line arguments. " + "This is useful if you are using many flags or want " + "to set different options per each module.", + ) + config_group.add_argument( + "--config-file", + help=( + f"Configuration file, must have a [mypy] section " + f"(defaults to {', '.join(defaults.CONFIG_NAMES + defaults.SHARED_CONFIG_NAMES)})" + ), + ) + add_invertible_flag( + "--warn-unused-configs", + default=False, + help="Warn about unused '[mypy-]' or '[[tool.mypy.overrides]]' config sections", + group=config_group, + ) + + imports_group = parser.add_argument_group( + title="Import discovery", description="Configure how imports are discovered and followed." + ) + add_invertible_flag( + "--no-namespace-packages", + dest="namespace_packages", + default=True, + help="Disable support for namespace packages (PEP 420, __init__.py-less)", + group=imports_group, + ) + imports_group.add_argument( + "--ignore-missing-imports", + action="store_true", + help="Silently ignore imports of missing modules", + ) + imports_group.add_argument( + "--follow-untyped-imports", + action="store_true", + help="Typecheck modules without stubs or py.typed marker", + ) + imports_group.add_argument( + "--follow-imports", + choices=["normal", "silent", "skip", "error"], + default="normal", + help="How to treat imports (default normal)", + ) + imports_group.add_argument( + "--python-executable", + action="store", + metavar="EXECUTABLE", + help="Python executable used for finding PEP 561 compliant installed packages and stubs", + dest="special-opts:python_executable", + ) + imports_group.add_argument( + "--no-site-packages", + action="store_true", + dest="special-opts:no_executable", + help="Do not search for installed PEP 561 compliant packages", + ) + imports_group.add_argument( + "--no-silence-site-packages", + action="store_true", + help="Do not silence errors in PEP 561 compliant installed packages", + ) + + platform_group = parser.add_argument_group( + title="Platform configuration", + description="Type check code assuming it will be run under certain " + "runtime conditions. By default, mypy assumes your code " + "will be run using the same operating system and Python " + "version you are using to run mypy itself.", + ) + platform_group.add_argument( + "--python-version", + type=parse_version, + metavar="x.y", + help="Type check code assuming it will be running on Python x.y", + dest="special-opts:python_version", + ) + platform_group.add_argument( + "--platform", + action="store", + metavar="PLATFORM", + help="Type check special-cased code for the given OS platform (defaults to sys.platform)", + ) + platform_group.add_argument( + "--always-true", + metavar="NAME", + action="append", + default=[], + help="Additional variable to be considered True (may be repeated)", + ) + platform_group.add_argument( + "--always-false", + metavar="NAME", + action="append", + default=[], + help="Additional variable to be considered False (may be repeated)", + ) + + disallow_any_group = parser.add_argument_group( + title="Disallow dynamic typing", + description="Disallow the use of the dynamic 'Any' type under certain conditions.", + ) + disallow_any_group.add_argument( + "--disallow-any-expr", + default=False, + action="store_true", + help="Disallow all expressions that have type Any", + ) + disallow_any_group.add_argument( + "--disallow-any-decorated", + default=False, + action="store_true", + help="Disallow functions that have Any in their signature after decorator transformation", + ) + disallow_any_group.add_argument( + "--disallow-any-explicit", + default=False, + action="store_true", + help="Disallow explicit Any in type positions", + ) + add_invertible_flag( + "--disallow-any-generics", + default=False, + strict_flag=True, + help="Disallow usage of generic types that do not specify explicit type parameters", + group=disallow_any_group, + ) + add_invertible_flag( + "--disallow-any-unimported", + default=False, + help="Disallow Any types resulting from unfollowed imports", + group=disallow_any_group, + ) + add_invertible_flag( + "--disallow-subclassing-any", + default=False, + strict_flag=True, + help="Disallow subclassing values of type 'Any' when defining classes", + group=disallow_any_group, + ) + + untyped_group = parser.add_argument_group( + title="Untyped definitions and calls", + description="Configure how untyped definitions and calls are handled. " + "Note: by default, mypy ignores any untyped function definitions " + "and assumes any calls to such functions have a return " + "type of 'Any'.", + ) + add_invertible_flag( + "--disallow-untyped-calls", + default=False, + strict_flag=True, + help="Disallow calling functions without type annotations" + " from functions with type annotations", + group=untyped_group, + ) + untyped_group.add_argument( + "--untyped-calls-exclude", + metavar="MODULE", + action="append", + default=[], + help="Disable --disallow-untyped-calls for functions/methods coming" + " from specific package, module, or class", + ) + add_invertible_flag( + "--disallow-untyped-defs", + default=False, + strict_flag=True, + help="Disallow defining functions without type annotations" + " or with incomplete type annotations", + group=untyped_group, + ) + add_invertible_flag( + "--disallow-incomplete-defs", + default=False, + strict_flag=True, + help="Disallow defining functions with incomplete type annotations " + "(while still allowing entirely unannotated definitions)", + group=untyped_group, + ) + add_invertible_flag( + "--check-untyped-defs", + default=False, + strict_flag=True, + help="Type check the interior of functions without type annotations", + group=untyped_group, + ) + add_invertible_flag( + "--disallow-untyped-decorators", + default=False, + strict_flag=True, + help="Disallow decorating typed functions with untyped decorators", + group=untyped_group, + ) + + none_group = parser.add_argument_group( + title="None and Optional handling", + description="Adjust how values of type 'None' are handled. For more context on " + "how mypy handles values of type 'None', see: " + "https://mypy.readthedocs.io/en/stable/kinds_of_types.html#optional-types-and-the-none-type", + ) + add_invertible_flag( + "--implicit-optional", + default=False, + help="Assume arguments with default values of None are Optional", + group=none_group, + ) + none_group.add_argument("--strict-optional", action="store_true", help=argparse.SUPPRESS) + none_group.add_argument( + "--no-strict-optional", + action="store_false", + dest="strict_optional", + help="Disable strict Optional checks (inverse: --strict-optional)", + ) + + lint_group = parser.add_argument_group( + title="Configuring warnings", + description="Detect code that is sound but redundant or problematic.", + ) + add_invertible_flag( + "--warn-redundant-casts", + default=False, + strict_flag=True, + help="Warn about casting an expression to its inferred type", + group=lint_group, + ) + add_invertible_flag( + "--warn-unused-ignores", + default=False, + strict_flag=True, + help="Warn about unneeded '# type: ignore' comments", + group=lint_group, + ) + add_invertible_flag( + "--no-warn-no-return", + dest="warn_no_return", + default=True, + help="Do not warn about functions that end without returning", + group=lint_group, + ) + add_invertible_flag( + "--warn-return-any", + default=False, + strict_flag=True, + help="Warn about returning values of type Any from non-Any typed functions", + group=lint_group, + ) + add_invertible_flag( + "--warn-unreachable", + default=False, + strict_flag=False, + help="Warn about statements or expressions inferred to be unreachable", + group=lint_group, + ) + add_invertible_flag( + "--report-deprecated-as-note", + default=False, + strict_flag=False, + help="Report importing or using deprecated features as notes instead of errors", + group=lint_group, + ) + lint_group.add_argument( + "--deprecated-calls-exclude", + metavar="MODULE", + action="append", + default=[], + help="Disable deprecated warnings for functions/methods coming" + " from specific package, module, or class", + ) + + # Note: this group is intentionally added here even though we don't add + # --strict to this group near the end. + # + # That way, this group will appear after the various strictness groups + # but before the remaining flags. + # We add `--strict` near the end so we don't accidentally miss any strictness + # flags that are added after this group. + strictness_group = parser.add_argument_group(title="Miscellaneous strictness flags") + + add_invertible_flag( + "--allow-untyped-globals", + default=False, + strict_flag=False, + help="Suppress toplevel errors caused by missing annotations", + group=strictness_group, + ) + + add_invertible_flag( + "--allow-redefinition", + default=False, + strict_flag=False, + help="Alias to --allow-redefinition-old; will point to --allow-redefinition-new in v2.0", + group=strictness_group, + dest="allow_redefinition_old", + ) + + add_invertible_flag( + "--allow-redefinition-old", + default=False, + strict_flag=False, + help="Allow restricted, unconditional variable redefinition with a new type", + group=strictness_group, + ) + + add_invertible_flag( + "--allow-redefinition-new", + default=False, + strict_flag=False, + help="Allow more flexible variable redefinition semantics", + group=strictness_group, + ) + + add_invertible_flag( + "--no-implicit-reexport", + default=True, + strict_flag=True, + dest="implicit_reexport", + help="Treat imports as private unless aliased", + group=strictness_group, + ) + + add_invertible_flag( + "--strict-equality", + default=False, + strict_flag=True, + help="Prohibit equality, identity, and container checks for non-overlapping types " + "(except `None`)", + group=strictness_group, + ) + + add_invertible_flag( + "--strict-equality-for-none", + default=False, + strict_flag=False, + help="Extend `--strict-equality` for `None` checks", + group=strictness_group, + ) + + add_invertible_flag( + "--strict-bytes", + default=False, + strict_flag=True, + help="Disable treating bytearray and memoryview as subtypes of bytes", + group=strictness_group, + ) + + add_invertible_flag( + "--extra-checks", + default=False, + strict_flag=True, + help="Enable additional checks that are technically correct but may be impractical " + "in real code. For example, this prohibits partial overlap in TypedDict updates, " + "and makes arguments prepended via Concatenate positional-only", + group=strictness_group, + ) + + strict_help = "Strict mode; enables the following flags: {}".format( + ", ".join(strict_flag_names) + ) + strictness_group.add_argument( + "--strict", action="store_true", dest="special-opts:strict", help=strict_help + ) + + strictness_group.add_argument( + "--disable-error-code", + metavar="NAME", + action="append", + default=[], + help="Disable a specific error code", + ) + strictness_group.add_argument( + "--enable-error-code", + metavar="NAME", + action="append", + default=[], + help="Enable a specific error code", + ) + + error_group = parser.add_argument_group( + title="Configuring error messages", + description="Adjust the amount of detail shown in error messages.", + ) + add_invertible_flag( + "--show-error-context", + default=False, + dest="show_error_context", + help='Precede errors with "note:" messages explaining context', + group=error_group, + ) + add_invertible_flag( + "--show-column-numbers", + default=False, + help="Show column numbers in error messages", + group=error_group, + ) + add_invertible_flag( + "--show-error-end", + default=False, + help="Show end line/end column numbers in error messages." + " This implies --show-column-numbers", + group=error_group, + ) + add_invertible_flag( + "--hide-error-codes", + default=False, + help="Hide error codes in error messages", + group=error_group, + ) + add_invertible_flag( + "--show-error-code-links", + default=False, + help="Show links to error code documentation", + group=error_group, + ) + add_invertible_flag( + "--pretty", + default=False, + help="Use visually nicer output in error messages:" + " Use soft word wrap, show source code snippets," + " and show error location markers", + group=error_group, + ) + add_invertible_flag( + "--no-color-output", + dest="color_output", + default=True, + help="Do not colorize error messages", + group=error_group, + ) + add_invertible_flag( + "--no-error-summary", + dest="error_summary", + default=True, + help="Do not show error stats summary", + group=error_group, + ) + add_invertible_flag( + "--show-absolute-path", + default=False, + help="Show absolute paths to files", + group=error_group, + ) + error_group.add_argument( + "--soft-error-limit", + default=defaults.MANY_ERRORS_THRESHOLD, + type=int, + dest="many_errors_threshold", + help=argparse.SUPPRESS, + ) + + incremental_group = parser.add_argument_group( + title="Incremental mode", + description="Adjust how mypy incrementally type checks and caches modules. " + "Mypy caches type information about modules into a cache to " + "let you speed up future invocations of mypy. Also see " + "mypy's daemon mode: " + "https://mypy.readthedocs.io/en/stable/mypy_daemon.html#mypy-daemon", + ) + incremental_group.add_argument( + "-i", "--incremental", action="store_true", help=argparse.SUPPRESS + ) + incremental_group.add_argument( + "--no-incremental", + action="store_false", + dest="incremental", + help="Disable module cache (inverse: --incremental)", + ) + incremental_group.add_argument( + "--cache-dir", + action="store", + metavar="DIR", + help="Store module cache info in the given folder in incremental mode " + "(defaults to '{}')".format(defaults.CACHE_DIR), + ) + add_invertible_flag( + "--sqlite-cache", + default=False, + help="Use a sqlite database to store the cache", + group=incremental_group, + ) + incremental_group.add_argument( + "--cache-fine-grained", + action="store_true", + help="Include fine-grained dependency information in the cache for the mypy daemon", + ) + add_invertible_flag( + "--no-fixed-format-cache", + dest="fixed_format_cache", + default=True, + help="Do not use new fixed format cache", + group=incremental_group, + ) + incremental_group.add_argument( + "--skip-version-check", + action="store_true", + help="Allow using cache written by older mypy version", + ) + incremental_group.add_argument( + "--skip-cache-mtime-checks", + action="store_true", + help="Skip cache internal consistency checks based on mtime", + ) + + internals_group = parser.add_argument_group( + title="Advanced options", description="Debug and customize mypy internals." + ) + internals_group.add_argument("--pdb", action="store_true", help="Invoke pdb on fatal error") + internals_group.add_argument( + "--show-traceback", "--tb", action="store_true", help="Show traceback on fatal error" + ) + internals_group.add_argument( + "--raise-exceptions", action="store_true", help="Raise exception on fatal error" + ) + internals_group.add_argument( + "--custom-typing-module", + metavar="MODULE", + dest="custom_typing_module", + help="Use a custom typing module", + ) + internals_group.add_argument( + "--old-type-inference", action="store_true", help=argparse.SUPPRESS + ) + internals_group.add_argument( + "--disable-expression-cache", action="store_true", help=argparse.SUPPRESS + ) + parser.add_argument( + "--enable-incomplete-feature", + action="append", + metavar="{" + ",".join(sorted(INCOMPLETE_FEATURES)) + "}", + help="Enable support of incomplete/experimental features for early preview", + ) + internals_group.add_argument( + "--custom-typeshed-dir", metavar="DIR", help="Use the custom typeshed in DIR" + ) + add_invertible_flag( + "--warn-incomplete-stub", + default=False, + help="Warn if missing type annotation in typeshed, only relevant with" + " --disallow-untyped-defs or --disallow-incomplete-defs enabled", + group=internals_group, + ) + internals_group.add_argument( + "--shadow-file", + nargs=2, + metavar=("SOURCE_FILE", "SHADOW_FILE"), + dest="shadow_file", + action="append", + help="When encountering SOURCE_FILE, read and type check " + "the contents of SHADOW_FILE instead.", + ) + internals_group.add_argument("--fast-exit", action="store_true", help=argparse.SUPPRESS) + internals_group.add_argument( + "--no-fast-exit", action="store_false", dest="fast_exit", help=argparse.SUPPRESS + ) + # This flag is useful for mypy tests, where function bodies may be omitted. Plugin developers + # may want to use this as well in their tests. + add_invertible_flag( + "--allow-empty-bodies", default=False, help=argparse.SUPPRESS, group=internals_group + ) + # This undocumented feature exports limited line-level dependency information. + internals_group.add_argument("--export-ref-info", action="store_true", help=argparse.SUPPRESS) + + # Experimental parallel type-checking support. + internals_group.add_argument( + "-n", "--num-workers", type=int, default=0, help=argparse.SUPPRESS + ) + + report_group = parser.add_argument_group( + title="Report generation", description="Generate a report in the specified format." + ) + for report_type in sorted(defaults.REPORTER_NAMES): + if report_type not in {"memory-xml"}: + report_group.add_argument( + f"--{report_type.replace('_', '-')}-report", + metavar="DIR", + dest=f"special-opts:{report_type}_report", + ) + + # Undocumented mypyc feature: generate annotated HTML source file + report_group.add_argument( + "-a", dest="mypyc_annotation_file", type=str, default=None, help=argparse.SUPPRESS + ) + # Hidden mypyc feature: do not write any C files (keep existing ones and assume they exist). + # This can be useful when debugging mypyc bugs. + report_group.add_argument( + "--skip-c-gen", dest="mypyc_skip_c_generation", action="store_true", help=argparse.SUPPRESS + ) + + misc_group = parser.add_argument_group(title="Miscellaneous") + misc_group.add_argument("--quickstart-file", help=argparse.SUPPRESS) + misc_group.add_argument( + "--junit-xml", + metavar="JUNIT_XML_OUTPUT_FILE", + help="Write a JUnit XML test result document with type checking results to the given file", + ) + misc_group.add_argument( + "--junit-format", + choices=["global", "per_file"], + default="global", + help="If --junit-xml is set, specifies format. global (default): single test with all errors; per_file: one test entry per file with failures", + ) + misc_group.add_argument( + "--find-occurrences", + metavar="CLASS.MEMBER", + dest="special-opts:find_occurrences", + help="Print out all usages of a class member (experimental)", + ) + misc_group.add_argument( + "--scripts-are-modules", + action="store_true", + help="Script x becomes module x instead of __main__", + ) + + add_invertible_flag( + "--install-types", + default=False, + strict_flag=False, + help="Install detected missing library stub packages using pip", + group=misc_group, + ) + add_invertible_flag( + "--non-interactive", + default=False, + strict_flag=False, + help=( + "Install stubs without asking for confirmation and hide " + + "errors, with --install-types" + ), + group=misc_group, + inverse="--interactive", + ) + + if server_options: + misc_group.add_argument( + "--use-fine-grained-cache", + action="store_true", + help="Use the cache in fine-grained incremental mode", + ) + + # hidden options + parser.add_argument( + "--stats", action="store_true", dest="dump_type_stats", help=argparse.SUPPRESS + ) + parser.add_argument( + "--inferstats", action="store_true", dest="dump_inference_stats", help=argparse.SUPPRESS + ) + parser.add_argument("--dump-build-stats", action="store_true", help=argparse.SUPPRESS) + # Dump timing stats for each processed file into the given output file + parser.add_argument("--timing-stats", dest="timing_stats", help=argparse.SUPPRESS) + # Dump per line type checking timing stats for each processed file into the given + # output file. Only total time spent in each top level expression will be shown. + # Times are show in microseconds. + parser.add_argument( + "--line-checking-stats", dest="line_checking_stats", help=argparse.SUPPRESS + ) + # --debug-cache will disable any cache-related compressions/optimizations, + # which will make the cache writing process output pretty-printed JSON (which + # is easier to debug). + parser.add_argument("--debug-cache", action="store_true", help=argparse.SUPPRESS) + # --dump-deps will dump all fine-grained dependencies to stdout + parser.add_argument("--dump-deps", action="store_true", help=argparse.SUPPRESS) + # --dump-graph will dump the contents of the graph of SCCs and exit. + parser.add_argument("--dump-graph", action="store_true", help=argparse.SUPPRESS) + # --semantic-analysis-only does exactly that. + parser.add_argument("--semantic-analysis-only", action="store_true", help=argparse.SUPPRESS) + # Some tests use this to tell mypy that we are running a test. + parser.add_argument("--test-env", action="store_true", help=argparse.SUPPRESS) + # --local-partial-types disallows partial types spanning module top level and a function + # (implicitly defined in fine-grained incremental mode) + add_invertible_flag("--local-partial-types", default=False, help=argparse.SUPPRESS) + # --native-parser enables the native parser (experimental) + add_invertible_flag("--native-parser", default=False, help=argparse.SUPPRESS) + # --logical-deps adds some more dependencies that are not semantically needed, but + # may be helpful to determine relative importance of classes and functions for overall + # type precision in a code base. It also _removes_ some deps, so this flag should be never + # used except for generating code stats. This also automatically enables --cache-fine-grained. + # NOTE: This is an experimental option that may be modified or removed at any time. + parser.add_argument("--logical-deps", action="store_true", help=argparse.SUPPRESS) + # --bazel changes some behaviors for use with Bazel (https://bazel.build). + parser.add_argument("--bazel", action="store_true", help=argparse.SUPPRESS) + # --package-root adds a directory below which directories are considered + # packages even without __init__.py. May be repeated. + parser.add_argument( + "--package-root", metavar="ROOT", action="append", default=[], help=argparse.SUPPRESS + ) + # --cache-map FILE ... gives a mapping from source files to cache files. + # Each triple of arguments is a source file, a cache meta file, and a cache data file. + # Modules not mentioned in the file will go through cache_dir. + # Must be followed by another flag or by '--' (and then only file args may follow). + parser.add_argument( + "--cache-map", nargs="+", dest="special-opts:cache_map", help=argparse.SUPPRESS + ) + # --debug-serialize will run tree.serialize() even if cache generation is disabled. + # Useful for mypy_primer to detect serialize errors earlier. + parser.add_argument("--debug-serialize", action="store_true", help=argparse.SUPPRESS) + + parser.add_argument( + "--disable-bytearray-promotion", action="store_true", help=argparse.SUPPRESS + ) + parser.add_argument( + "--disable-memoryview-promotion", action="store_true", help=argparse.SUPPRESS + ) + # This flag is deprecated, it has been moved to --extra-checks + parser.add_argument("--strict-concatenate", action="store_true", help=argparse.SUPPRESS) + + # options specifying code to check + code_group = parser.add_argument_group( + title="Running code", + description="Specify the code you want to type check. For more details, see " + "https://mypy.readthedocs.io/en/stable/running_mypy.html#running-mypy", + ) + add_invertible_flag( + "--explicit-package-bases", + default=False, + help="Use current directory and MYPYPATH to determine module names of files passed", + group=code_group, + ) + add_invertible_flag( + "--fast-module-lookup", default=False, help=argparse.SUPPRESS, group=code_group + ) + code_group.add_argument( + "--exclude", + action="append", + metavar="PATTERN", + default=[], + help=( + "Regular expression to match file names, directory names or paths which mypy should " + "ignore while recursively discovering files to check, e.g. --exclude '/setup\\.py$'. " + "May be specified more than once, eg. --exclude a --exclude b" + ), + ) + add_invertible_flag( + "--exclude-gitignore", + default=False, + help=( + "Use .gitignore file(s) to exclude files from checking " + "(in addition to any explicit --exclude if present)" + ), + group=code_group, + ) + code_group.add_argument( + "-m", + "--module", + action="append", + metavar="MODULE", + default=[], + dest="special-opts:modules", + help="Type-check module; can repeat for more modules", + ) + code_group.add_argument( + "-p", + "--package", + action="append", + metavar="PACKAGE", + default=[], + dest="special-opts:packages", + help="Type-check package recursively; can be repeated", + ) + code_group.add_argument( + "-c", + "--command", + action="append", + metavar="PROGRAM_TEXT", + dest="special-opts:command", + help="Type-check program passed in as string", + ) + code_group.add_argument( + metavar="files", + nargs="*", + dest="special-opts:files", + help="Type-check given files or directories", + ) + return parser, strict_flag_names, strict_flag_assignments + + +def process_options( + args: list[str], + stdout: TextIO | None = None, + stderr: TextIO | None = None, + require_targets: bool = True, + server_options: bool = False, + fscache: FileSystemCache | None = None, + program: str = "mypy", + header: str = HEADER, + mypyc: bool = False, +) -> tuple[list[BuildSource], Options]: + """Parse command line arguments. + + If a FileSystemCache is passed in, and package_root options are given, + call fscache.set_package_root() to set the cache's package root. + + Returns a tuple of: a list of source files, an Options collected from flags. + """ + stdout = stdout if stdout is not None else sys.stdout + stderr = stderr if stderr is not None else sys.stderr + + parser, _, strict_flag_assignments = define_options( + program, header, stdout, stderr, server_options + ) + + # Parse arguments once into a dummy namespace so we can get the + # filename for the config file and know if the user requested all strict options. + dummy = argparse.Namespace() + parser.parse_args(args, dummy) + config_file = dummy.config_file + # Don't explicitly test if "config_file is not None" for this check. + # This lets `--config-file=` (an empty string) be used to disable all config files. + if config_file and not os.path.exists(config_file): + parser.error(f"Cannot find config file '{config_file}'") + + options = Options() + strict_option_set = False + if mypyc: + # Mypyc has strict_bytes enabled by default + options.strict_bytes = True + + def set_strict_flags() -> None: + nonlocal strict_option_set + strict_option_set = True + for dest, value in strict_flag_assignments: + setattr(options, dest, value) + + # Parse config file first, so command line can override. + parse_config_file(options, set_strict_flags, config_file, stdout, stderr) + + # Set strict flags before parsing (if strict mode enabled), so other command + # line options can override. + if getattr(dummy, "special-opts:strict"): + set_strict_flags() + + # Override cache_dir if provided in the environment + environ_cache_dir = os.getenv("MYPY_CACHE_DIR", "") + if environ_cache_dir.strip(): + options.cache_dir = environ_cache_dir + options.cache_dir = os.path.expanduser(options.cache_dir) + + # Parse command line for real, using a split namespace. + special_opts = argparse.Namespace() + parser.parse_args(args, SplitNamespace(options, special_opts, "special-opts:")) + + # The python_version is either the default, which can be overridden via a config file, + # or stored in special_opts and is passed via the command line. + options.python_version = special_opts.python_version or options.python_version + if options.python_version < (3,): + parser.error( + "Mypy no longer supports checking Python 2 code. " + "Consider pinning to mypy<0.980 if you need to check Python 2 code." + ) + try: + infer_python_executable(options, special_opts) + except PythonExecutableInferenceError as e: + parser.error(str(e)) + + if special_opts.no_executable or options.no_site_packages: + options.python_executable = None + + # Paths listed in the config file will be ignored if any paths, modules or packages + # are passed on the command line. + if not (special_opts.files or special_opts.packages or special_opts.modules): + if options.files: + special_opts.files = options.files + if options.packages: + special_opts.packages = options.packages + if options.modules: + special_opts.modules = options.modules + + # Check for invalid argument combinations. + if require_targets: + code_methods = sum( + bool(c) + for c in [ + special_opts.modules + special_opts.packages, + special_opts.command, + special_opts.files, + ] + ) + if code_methods == 0 and not options.install_types: + parser.error("Missing target module, package, files, or command.") + elif code_methods > 1: + parser.error("May only specify one of: module/package, files, or command.") + if options.explicit_package_bases and not options.namespace_packages: + parser.error( + "Can only use --explicit-package-bases with --namespace-packages, since otherwise " + "examining __init__.py's is sufficient to determine module names for files" + ) + + # Check for overlapping `--always-true` and `--always-false` flags. + overlap = set(options.always_true) & set(options.always_false) + if overlap: + parser.error( + "You can't make a variable always true and always false (%s)" + % ", ".join(sorted(overlap)) + ) + + validate_package_allow_list(options.untyped_calls_exclude) + validate_package_allow_list(options.deprecated_calls_exclude) + + options.process_incomplete_features(error_callback=parser.error, warning_callback=print) + + # Compute absolute path for custom typeshed (if present). + if options.custom_typeshed_dir is not None: + options.abs_custom_typeshed_dir = os.path.abspath(options.custom_typeshed_dir) + + # Set build flags. + if special_opts.find_occurrences: + _find_occurrences = tuple(special_opts.find_occurrences.split(".")) + if len(_find_occurrences) < 2: + parser.error("Can only find occurrences of class members.") + if len(_find_occurrences) != 2: + parser.error("Can only find occurrences of non-nested class members.") + state.find_occurrences = _find_occurrences + + # Set reports. + for flag, val in vars(special_opts).items(): + if flag.endswith("_report") and val is not None: + report_type = flag[:-7].replace("_", "-") + report_dir = val + options.report_dirs[report_type] = report_dir + + # Process --package-root. + if options.package_root: + process_package_roots(fscache, parser, options) + + # Process --cache-map. + if special_opts.cache_map: + if options.sqlite_cache: + parser.error("--cache-map is incompatible with --sqlite-cache") + + process_cache_map(parser, special_opts, options) + + # Process --strict-bytes + options.process_strict_bytes() + + # An explicitly specified cache_fine_grained implies local_partial_types + # (because otherwise the cache is not compatible with dmypy) + if options.cache_fine_grained: + options.local_partial_types = True + + # Implicitly show column numbers if error location end is shown + if options.show_error_end: + options.show_column_numbers = True + + # Let logical_deps imply cache_fine_grained (otherwise the former is useless). + if options.logical_deps: + options.cache_fine_grained = True + + if options.strict_concatenate and not strict_option_set: + print("Warning: --strict-concatenate is deprecated; use --extra-checks instead") + + # Set target. + if special_opts.modules + special_opts.packages: + options.build_type = BuildType.MODULE + sys_path, _ = get_search_dirs(options.python_executable) + search_paths = SearchPaths( + (os.getcwd(),), tuple(mypy_path() + options.mypy_path), tuple(sys_path), () + ) + targets = [] + # TODO: use the same cache that the BuildManager will + cache = FindModuleCache(search_paths, fscache, options) + for p in special_opts.packages: + if os.sep in p or os.altsep and os.altsep in p: + fail(f"Package name '{p}' cannot have a slash in it.", stderr, options) + p_targets = cache.find_modules_recursive(p) + if not p_targets: + reason = cache.find_module(p) + if reason is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: + fail( + f"Package '{p}' cannot be type checked due to missing py.typed marker. See https://mypy.readthedocs.io/en/stable/installed_packages.html for more details", + stderr, + options, + ) + else: + fail(f"Can't find package '{p}'", stderr, options) + targets.extend(p_targets) + for m in special_opts.modules: + targets.append(BuildSource(None, m, None)) + elif special_opts.command: + options.build_type = BuildType.PROGRAM_TEXT + targets = [BuildSource(None, None, "\n".join(special_opts.command))] + else: + try: + targets = create_source_list(special_opts.files, options, fscache) + # Variable named e2 instead of e to work around mypyc bug #620 + # which causes issues when using the same variable to catch + # exceptions of different types. + except InvalidSourceList as e2: + fail(str(e2), stderr, options) + return targets, options + + +def process_package_roots( + fscache: FileSystemCache | None, parser: argparse.ArgumentParser, options: Options +) -> None: + """Validate and normalize package_root.""" + if fscache is None: + parser.error("--package-root does not work here (no fscache)") + assert fscache is not None # Since mypy doesn't know parser.error() raises. + # Do some stuff with drive letters to make Windows happy (esp. tests). + current_drive, _ = os.path.splitdrive(os.getcwd()) + dot = os.curdir + dotslash = os.curdir + os.sep + dotdotslash = os.pardir + os.sep + trivial_paths = {dot, dotslash} + package_root = [] + for root in options.package_root: + if os.path.isabs(root): + parser.error(f"Package root cannot be absolute: {root!r}") + drive, root = os.path.splitdrive(root) + if drive and drive != current_drive: + parser.error(f"Package root must be on current drive: {drive + root!r}") + # Empty package root is always okay. + if root: + root = os.path.relpath(root) # Normalize the heck out of it. + if not root.endswith(os.sep): + root = root + os.sep + if root.startswith(dotdotslash): + parser.error(f"Package root cannot be above current directory: {root!r}") + if root in trivial_paths: + root = "" + package_root.append(root) + options.package_root = package_root + # Pass the package root on the filesystem cache. + fscache.set_package_root(package_root) + + +def process_cache_map( + parser: argparse.ArgumentParser, special_opts: argparse.Namespace, options: Options +) -> None: + """Validate cache_map and copy into options.cache_map.""" + n = len(special_opts.cache_map) + if n % 3 != 0: + parser.error("--cache-map requires one or more triples (see source)") + for i in range(0, n, 3): + source, meta_file, data_file = special_opts.cache_map[i : i + 3] + if source in options.cache_map: + parser.error(f"Duplicate --cache-map source {source})") + if not source.endswith(".py") and not source.endswith(".pyi"): + parser.error(f"Invalid --cache-map source {source} (triple[0] must be *.py[i])") + if not meta_file.endswith(".meta.json"): + parser.error( + "Invalid --cache-map meta_file %s (triple[1] must be *.meta.json)" % meta_file + ) + if not data_file.endswith(".data.json"): + parser.error( + "Invalid --cache-map data_file %s (triple[2] must be *.data.json)" % data_file + ) + options.cache_map[source] = (meta_file, data_file) + + +def maybe_write_junit_xml( + td: float, + serious: bool, + all_messages: list[str], + messages_by_file: dict[str | None, list[str]], + options: Options, +) -> None: + if options.junit_xml: + py_version = f"{options.python_version[0]}_{options.python_version[1]}" + if options.junit_format == "global": + util.write_junit_xml( + td, + serious, + {None: all_messages} if all_messages else {}, + options.junit_xml, + py_version, + options.platform, + ) + else: + # per_file + util.write_junit_xml( + td, serious, messages_by_file, options.junit_xml, py_version, options.platform + ) + + +def fail(msg: str, stderr: TextIO, options: Options) -> NoReturn: + """Fail with a serious error.""" + stderr.write(f"{msg}\n") + maybe_write_junit_xml( + 0.0, serious=True, all_messages=[msg], messages_by_file={None: [msg]}, options=options + ) + sys.exit(2) + + +def read_types_packages_to_install(cache_dir: str, after_run: bool) -> list[str]: + if not os.path.isdir(cache_dir): + if not after_run: + sys.stderr.write( + "error: Can't determine which types to install with no files to check " + + "(and no cache from previous mypy run)\n" + ) + else: + sys.stderr.write( + "error: --install-types failed (an error blocked analysis of which types to install)\n" + ) + fnam = build.missing_stubs_file(cache_dir) + if not os.path.isfile(fnam): + # No missing stubs. + return [] + with open(fnam) as f: + return [line.strip() for line in f] + + +def install_types( + formatter: util.FancyFormatter, + options: Options, + *, + after_run: bool = False, + non_interactive: bool = False, +) -> bool: + """Install stub packages using pip if some missing stubs were detected.""" + packages = read_types_packages_to_install(options.cache_dir, after_run) + if not packages: + # If there are no missing stubs, generate no output. + return False + if after_run and not non_interactive: + print() + print("Installing missing stub packages:") + assert options.python_executable, "Python executable required to install types" + cmd = [options.python_executable, "-m", "pip", "install"] + packages + print(formatter.style(" ".join(cmd), "none", bold=True)) + print() + if not non_interactive: + x = input("Install? [yN] ") + if not x.strip() or not x.lower().startswith("y"): + print(formatter.style("mypy: Skipping installation", "red", bold=True)) + sys.exit(2) + print() + subprocess.run(cmd) + return True diff --git a/micromamba_root/Lib/site-packages/mypy/maptype.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/maptype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e4f7b1b530764c620c9b9fbc684d7b78937a6f8b Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/maptype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/maptype.py b/micromamba_root/Lib/site-packages/mypy/maptype.py new file mode 100644 index 0000000000000000000000000000000000000000..59ecb2bc9993025e435b83ceef15acc5becef859 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/maptype.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +from mypy.expandtype import expand_type_by_instance +from mypy.nodes import TypeInfo +from mypy.types import AnyType, Instance, TupleType, TypeOfAny, has_type_vars + + +def map_instance_to_supertype(instance: Instance, superclass: TypeInfo) -> Instance: + """Produce a supertype of `instance` that is an Instance + of `superclass`, mapping type arguments up the chain of bases. + + If `superclass` is not a nominal superclass of `instance.type`, + then all type arguments are mapped to 'Any'. + """ + if instance.type == superclass: + # Fast path: `instance` already belongs to `superclass`. + return instance + + if superclass.fullname == "builtins.tuple" and instance.type.tuple_type: + if has_type_vars(instance.type.tuple_type): + # We special case mapping generic tuple types to tuple base, because for + # such tuples fallback can't be calculated before applying type arguments. + alias = instance.type.special_alias + assert alias is not None + if not alias._is_recursive: + # Unfortunately we can't support this for generic recursive tuples. + # If we skip this special casing we will fall back to tuple[Any, ...]. + tuple_type = expand_type_by_instance(instance.type.tuple_type, instance) + if isinstance(tuple_type, TupleType): + # Make the import here to avoid cyclic imports. + import mypy.typeops + + return mypy.typeops.tuple_fallback(tuple_type) + elif isinstance(tuple_type, Instance): + # This can happen after normalizing variadic tuples. + return tuple_type + + if not superclass.type_vars: + # Fast path: `superclass` has no type variables to map to. + return Instance(superclass, []) + + return map_instance_to_supertypes(instance, superclass)[0] + + +def map_instance_to_supertypes(instance: Instance, supertype: TypeInfo) -> list[Instance]: + # FIX: Currently we should only have one supertype per interface, so no + # need to return an array + result: list[Instance] = [] + for path in class_derivation_paths(instance.type, supertype): + types = [instance] + for sup in path: + a: list[Instance] = [] + for t in types: + a.extend(map_instance_to_direct_supertypes(t, sup)) + types = a + result.extend(types) + if result: + return result + else: + # Nothing. Presumably due to an error. Construct a dummy using Any. + any_type = AnyType(TypeOfAny.from_error) + return [Instance(supertype, [any_type] * len(supertype.type_vars))] + + +def class_derivation_paths(typ: TypeInfo, supertype: TypeInfo) -> list[list[TypeInfo]]: + """Return an array of non-empty paths of direct base classes from + type to supertype. Return [] if no such path could be found. + + InterfaceImplementationPaths(A, B) == [[B]] if A inherits B + InterfaceImplementationPaths(A, C) == [[B, C]] if A inherits B and + B inherits C + """ + # FIX: Currently we might only ever have a single path, so this could be + # simplified + result: list[list[TypeInfo]] = [] + + for base in typ.bases: + btype = base.type + if btype == supertype: + result.append([btype]) + else: + # Try constructing a longer path via the base class. + for path in class_derivation_paths(btype, supertype): + result.append([btype] + path) + + return result + + +def map_instance_to_direct_supertypes(instance: Instance, supertype: TypeInfo) -> list[Instance]: + # FIX: There should only be one supertypes, always. + typ = instance.type + result: list[Instance] = [] + + for b in typ.bases: + if b.type == supertype: + t = expand_type_by_instance(b, instance) + assert isinstance(t, Instance) + result.append(t) + + if result: + return result + else: + # Relationship with the supertype not specified explicitly. Use dynamic + # type arguments implicitly. + any_type = AnyType(TypeOfAny.unannotated) + return [Instance(supertype, [any_type] * len(supertype.type_vars))] diff --git a/micromamba_root/Lib/site-packages/mypy/meet.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/meet.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..0fa5233afc44965824438ecb5902354ab7d2a024 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/meet.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/meet.py b/micromamba_root/Lib/site-packages/mypy/meet.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c54bbe03b32b5b60d3f0d362d49cc303a5d71e --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/meet.py @@ -0,0 +1,1286 @@ +from __future__ import annotations + +from collections.abc import Callable + +from mypy import join +from mypy.erasetype import erase_type +from mypy.maptype import map_instance_to_supertype +from mypy.state import state +from mypy.subtypes import ( + are_parameters_compatible, + find_member, + is_callable_compatible, + is_equivalent, + is_proper_subtype, + is_same_type, + is_subtype, +) +from mypy.typeops import is_recursive_pair, make_simplified_union, tuple_fallback +from mypy.types import ( + MYPYC_NATIVE_INT_NAMES, + TUPLE_LIKE_INSTANCE_NAMES, + AnyType, + CallableType, + DeletedType, + ErasedType, + FunctionLike, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeGuardedType, + TypeOfAny, + TypeType, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + TypeVisitor, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + find_unpack_in_list, + get_proper_type, + get_proper_types, + has_type_vars, + is_named_instance, + split_with_prefix_and_suffix, +) + +# TODO Describe this module. + + +def trivial_meet(s: Type, t: Type) -> ProperType: + """Return one of types (expanded) if it is a subtype of other, otherwise bottom type.""" + if is_subtype(s, t): + return get_proper_type(s) + elif is_subtype(t, s): + return get_proper_type(t) + else: + if state.strict_optional: + return UninhabitedType() + else: + return NoneType() + + +def meet_types(s: Type, t: Type) -> ProperType: + """Return the greatest lower bound of two types.""" + if is_recursive_pair(s, t): + # This case can trigger an infinite recursion, general support for this will be + # tricky, so we use a trivial meet (like for protocols). + return trivial_meet(s, t) + s = get_proper_type(s) + t = get_proper_type(t) + + if isinstance(s, Instance) and isinstance(t, Instance) and s.type == t.type: + # Code in checker.py should merge any extra_items where possible, so we + # should have only compatible extra_items here. We check this before + # the below subtype check, so that extra_attrs will not get erased. + if (s.extra_attrs or t.extra_attrs) and is_same_type(s, t): + if s.extra_attrs and t.extra_attrs: + if len(s.extra_attrs.attrs) > len(t.extra_attrs.attrs): + # Return the one that has more precise information. + return s + return t + if s.extra_attrs: + return s + return t + + if not isinstance(s, UnboundType) and not isinstance(t, UnboundType): + if is_proper_subtype(s, t, ignore_promotions=True): + return s + if is_proper_subtype(t, s, ignore_promotions=True): + return t + + if isinstance(s, ErasedType): + return s + if isinstance(s, AnyType): + return t + if isinstance(s, UnionType) and not isinstance(t, UnionType): + s, t = t, s + + # Meets/joins require callable type normalization. + s, t = join.normalize_callables(s, t) + + return t.accept(TypeMeetVisitor(s)) + + +def narrow_declared_type(declared: Type, narrowed: Type) -> Type: + """Return the declared type narrowed down to another type.""" + # TODO: check infinite recursion for aliases here. + if isinstance(narrowed, TypeGuardedType): + # A type guard forces the new type even if it doesn't overlap the old... + if is_proper_subtype(declared, narrowed.type_guard, ignore_promotions=True): + # ...unless it is a proper supertype of declared type. + return declared + return narrowed.type_guard + + original_declared = declared + original_narrowed = narrowed + declared = get_proper_type(declared) + narrowed = get_proper_type(narrowed) + + if declared == narrowed: + return original_declared + if isinstance(declared, UnionType): + declared_items = declared.relevant_items() + if isinstance(narrowed, UnionType): + narrowed_items = narrowed.relevant_items() + else: + narrowed_items = [narrowed] + return make_simplified_union( + [ + narrow_declared_type(d, n) + for d in declared_items + for n in narrowed_items + # This (ugly) special-casing is needed to support checking + # branches like this: + # x: Union[float, complex] + # if isinstance(x, int): + # ... + # And assignments like this: + # x: float | None + # y: int | None + # x = y + if ( + is_overlapping_types(d, n, ignore_promotions=True) + or is_subtype(n, d, ignore_promotions=False) + ) + ] + ) + if is_enum_overlapping_union(declared, narrowed): + # Quick check before reaching `is_overlapping_types`. If it's enum/literal overlap, + # avoid full expansion and make it faster. + assert isinstance(narrowed, UnionType) + return make_simplified_union( + [narrow_declared_type(declared, x) for x in narrowed.relevant_items()] + ) + elif ( + isinstance(declared, TypeVarType) + and not has_type_vars(original_narrowed) + and is_subtype(original_narrowed, declared.upper_bound) + ): + # We put this branch early to get T(bound=Union[A, B]) instead of + # Union[T(bound=A), T(bound=B)] that will be confusing for users. + return declared.copy_modified( + upper_bound=narrow_declared_type(declared.upper_bound, original_narrowed) + ) + elif not is_overlapping_types(declared, narrowed): + if state.strict_optional: + return UninhabitedType() + else: + return NoneType() + elif isinstance(narrowed, UnionType): + return make_simplified_union( + [narrow_declared_type(declared, x) for x in narrowed.relevant_items()] + ) + elif isinstance(narrowed, AnyType): + return original_narrowed + elif isinstance(narrowed, TypeVarType) and is_subtype(narrowed.upper_bound, declared): + return narrowed + elif isinstance(declared, TypeType) and isinstance(narrowed, TypeType): + return TypeType.make_normalized( + narrow_declared_type(declared.item, narrowed.item), + is_type_form=declared.is_type_form and narrowed.is_type_form, + ) + elif ( + isinstance(declared, TypeType) + and isinstance(narrowed, Instance) + and narrowed.type.is_metaclass() + ): + if declared.is_type_form: + # The declared TypeForm[T] after narrowing must be a kind of + # type object at least as narrow as Type[T] + return narrow_declared_type( + TypeType.make_normalized( + declared.item, line=declared.line, column=declared.column, is_type_form=False + ), + original_narrowed, + ) + # We'd need intersection types, so give up. + return original_declared + elif isinstance(declared, Instance): + if declared.type.alt_promote: + # Special case: low-level integer type can't be narrowed + return original_declared + if ( + isinstance(narrowed, Instance) + and narrowed.type.alt_promote + and narrowed.type.alt_promote.type is declared.type + ): + # Special case: 'int' can't be narrowed down to a native int type such as + # i64, since they have different runtime representations. + return original_declared + return meet_types(original_declared, original_narrowed) + elif isinstance(declared, (TupleType, TypeType, LiteralType)): + return meet_types(original_declared, original_narrowed) + elif isinstance(declared, TypedDictType) and isinstance(narrowed, Instance): + # Special case useful for selecting TypedDicts from unions using isinstance(x, dict). + if narrowed.type.fullname == "builtins.dict" and all( + isinstance(t, AnyType) for t in get_proper_types(narrowed.args) + ): + return original_declared + return meet_types(original_declared, original_narrowed) + elif ( + isinstance(declared, CallableType) + and isinstance(narrowed, CallableType) + and has_type_vars(declared.ret_type) + ): + return narrowed.copy_modified( + ret_type=narrow_declared_type(declared.ret_type, narrowed.ret_type) + ) + + return original_narrowed + + +def get_possible_variants(typ: Type) -> list[Type]: + """This function takes any "Union-like" type and returns a list of the available "options". + + Specifically, there are currently exactly three different types that can have + "variants" or are "union-like": + + - Unions + - TypeVars with value restrictions + - Overloads + + This function will return a list of each "option" present in those types. + + If this function receives any other type, we return a list containing just that + original type. (E.g. pretend the type was contained within a singleton union). + + The only current exceptions are regular TypeVars and ParamSpecs. For these "TypeVarLike"s, + we return a list containing that TypeVarLike's upper bound. + + This function is useful primarily when checking to see if two types are overlapping: + the algorithm to check if two unions are overlapping is fundamentally the same as + the algorithm for checking if two overloads are overlapping. + + Normalizing both kinds of types in the same way lets us reuse the same algorithm + for both. + """ + typ = get_proper_type(typ) + + if isinstance(typ, TypeVarType): + if len(typ.values) > 0: + return typ.values + else: + return [typ.upper_bound] + elif isinstance(typ, ParamSpecType): + # Extract 'object' from the final mro item + upper_bound = get_proper_type(typ.upper_bound) + if isinstance(upper_bound, Instance): + return [Instance(upper_bound.type.mro[-1], [])] + return [AnyType(TypeOfAny.implementation_artifact)] + elif isinstance(typ, TypeVarTupleType): + return [typ.upper_bound] + elif isinstance(typ, UnionType): + return list(typ.items) + elif isinstance(typ, Overloaded): + # Note: doing 'return typ.items()' makes mypy + # infer a too-specific return type of List[CallableType] + return list(typ.items) + else: + return [typ] + + +def is_enum_overlapping_union(x: ProperType, y: ProperType) -> bool: + """Return True if x is an Enum, and y is an Union with at least one Literal from x""" + return ( + isinstance(x, Instance) + and x.type.is_enum + and isinstance(y, UnionType) + and any( + isinstance(p := get_proper_type(z), LiteralType) and x.type == p.fallback.type + for z in y.relevant_items() + ) + ) + + +def is_literal_in_union(x: ProperType, y: ProperType) -> bool: + """Return True if x is a Literal and y is an Union that includes x""" + return ( + isinstance(x, LiteralType) + and isinstance(y, UnionType) + and any(x == get_proper_type(z) for z in y.items) + ) + + +def is_object(t: ProperType) -> bool: + return isinstance(t, Instance) and t.type.fullname == "builtins.object" + + +def is_none_object_overlap(t1: ProperType, t2: ProperType) -> bool: + return ( + isinstance(t1, NoneType) + and isinstance(t2, Instance) + and t2.type.fullname == "builtins.object" + ) + + +def are_related_types( + left: Type, right: Type, *, proper_subtype: bool, ignore_promotions: bool +) -> bool: + if proper_subtype: + return is_proper_subtype( + left, right, ignore_promotions=ignore_promotions + ) or is_proper_subtype(right, left, ignore_promotions=ignore_promotions) + else: + return is_subtype(left, right, ignore_promotions=ignore_promotions) or is_subtype( + right, left, ignore_promotions=ignore_promotions + ) + + +def is_overlapping_types( + left: Type, + right: Type, + ignore_promotions: bool = False, + overlap_for_overloads: bool = False, + seen_types: set[tuple[Type, Type]] | None = None, +) -> bool: + """Can a value of type 'left' also be of type 'right' or vice-versa? + + If 'ignore_promotions' is True, we ignore promotions while checking for overlaps. + If 'overlap_for_overloads' is True, we check for overlaps more strictly (to avoid false + positives), for example: None only overlaps with explicitly optional types, Any + doesn't overlap with anything except object, we don't ignore positional argument names. + """ + if isinstance(left, TypeGuardedType) or isinstance(right, TypeGuardedType): + # A type guard forces the new type even if it doesn't overlap the old. + return True + + if seen_types is None: + seen_types = set() + elif (left, right) in seen_types: + return True + if is_recursive_pair(left, right): + seen_types.add((left, right)) + + left, right = get_proper_types((left, right)) + + # We should never encounter this type. + if isinstance(left, PartialType) or isinstance(right, PartialType): + assert False, "Unexpectedly encountered partial type" + + # We should also never encounter these types, but it's possible a few + # have snuck through due to unrelated bugs. For now, we handle these + # in the same way we handle 'Any'. + # + # TODO: Replace these with an 'assert False' once we are more confident. + illegal_types = (UnboundType, ErasedType, DeletedType) + if isinstance(left, illegal_types) or isinstance(right, illegal_types): + return True + + # When running under non-strict optional mode, simplify away types of + # the form 'Union[A, B, C, None]' into just 'Union[A, B, C]'. + + if not state.strict_optional: + if isinstance(left, UnionType): + left = UnionType.make_union(left.relevant_items()) + if isinstance(right, UnionType): + right = UnionType.make_union(right.relevant_items()) + left, right = get_proper_types((left, right)) + + # 'Any' may or may not be overlapping with the other type + if isinstance(left, AnyType) or isinstance(right, AnyType): + return not overlap_for_overloads or is_object(left) or is_object(right) + + # We check for complete overlaps next as a general-purpose failsafe. + # If this check fails, we start checking to see if there exists a + # *partial* overlap between types. + # + # These checks will also handle the NoneType and UninhabitedType cases for us. + + # enums are sometimes expanded into an Union of Literals + # when that happens we want to make sure we treat the two as overlapping + # and crucially, we want to do that *fast* in case the enum is large + # so we do it before expanding variants below to avoid O(n**2) behavior + if ( + is_enum_overlapping_union(left, right) + or is_enum_overlapping_union(right, left) + or is_literal_in_union(left, right) + or is_literal_in_union(right, left) + ): + return True + + if overlap_for_overloads: + if is_none_object_overlap(left, right) or is_none_object_overlap(right, left): + return False + + if are_related_types( + left, right, proper_subtype=overlap_for_overloads, ignore_promotions=ignore_promotions + ): + return True + + # See the docstring for 'get_possible_variants' for more info on what the + # following lines are doing. + + left_possible = get_possible_variants(left) + right_possible = get_possible_variants(right) + + # Now move on to checking multi-variant types like Unions. We also perform + # the same logic if either type happens to be a TypeVar/ParamSpec/TypeVarTuple. + # + # Handling the TypeVarLikes now lets us simulate having them bind to the corresponding + # type -- if we deferred these checks, the "return-early" logic of the other + # checks will prevent us from detecting certain overlaps. + # + # If both types are singleton variants (and are not TypeVarLikes), we've hit the base case: + # we skip these checks to avoid infinitely recursing. + + def _is_overlapping_types(left: Type, right: Type) -> bool: + """Encode the kind of overlapping check to perform. + + This function mostly exists, so we don't have to repeat keyword arguments everywhere. + """ + return is_overlapping_types( + left, + right, + ignore_promotions=ignore_promotions, + overlap_for_overloads=overlap_for_overloads, + seen_types=seen_types.copy(), + ) + + if ( + len(left_possible) > 1 + or len(right_possible) > 1 + or isinstance(left, TypeVarLikeType) + or isinstance(right, TypeVarLikeType) + ): + for l in left_possible: + for r in right_possible: + if _is_overlapping_types(l, r): + return True + return False + + # Now that we've finished handling TypeVarLikes, we're free to end early + # if one one of the types is None and we're running in strict-optional mode. + # (None only overlaps with None in strict-optional mode). + # + # We must perform this check after the TypeVarLike checks because + # a TypeVar could be bound to None, for example. + + if state.strict_optional and isinstance(left, NoneType) != isinstance(right, NoneType): + return False + + # Next, we handle single-variant types that may be inherently partially overlapping: + # + # - TypedDicts + # - Tuples + # + # If we cannot identify a partial overlap and end early, we degrade these two types + # into their 'Instance' fallbacks. + + if isinstance(left, TypedDictType) and isinstance(right, TypedDictType): + return are_typed_dicts_overlapping(left, right, _is_overlapping_types) + elif typed_dict_mapping_pair(left, right): + # Overlaps between TypedDicts and Mappings require dedicated logic. + return typed_dict_mapping_overlap(left, right, overlapping=_is_overlapping_types) + elif isinstance(left, TypedDictType): + left = left.fallback + elif isinstance(right, TypedDictType): + right = right.fallback + + if is_tuple(left) and is_tuple(right): + return are_tuples_overlapping(left, right, _is_overlapping_types) + elif isinstance(left, TupleType): + left = tuple_fallback(left) + elif isinstance(right, TupleType): + right = tuple_fallback(right) + + # Next, we handle single-variant types that cannot be inherently partially overlapping, + # but do require custom logic to inspect. + # + # As before, we degrade into 'Instance' whenever possible. + + if isinstance(left, TypeType) and isinstance(right, TypeType): + return _is_overlapping_types(left.item, right.item) + + if isinstance(left, TypeType) or isinstance(right, TypeType): + + def _type_object_overlap(left: Type, right: Type) -> bool: + """Special cases for type object types overlaps.""" + # TODO: these checks are a bit in gray area, adjust if they cause problems. + left, right = get_proper_types((left, right)) + # 1. Type[C] vs Callable[..., C] overlap even if the latter is not class object. + if isinstance(left, TypeType) and isinstance(right, CallableType): + return _is_overlapping_types(left.item, right.ret_type) + # 2. Type[C] vs Meta, where Meta is a metaclass for C. + if isinstance(left, TypeType) and isinstance(right, Instance): + if isinstance(left.item, Instance): + left_meta = left.item.type.metaclass_type + if left_meta is not None: + return _is_overlapping_types(left_meta, right) + # builtins.type (default metaclass) overlaps with all metaclasses + return right.type.has_base("builtins.type") + elif isinstance(left.item, AnyType): + return right.type.has_base("builtins.type") + # 3. Callable[..., C] vs Meta is considered below, when we switch to fallbacks. + return False + + return _type_object_overlap(left, right) or _type_object_overlap(right, left) + + if isinstance(left, Parameters) and isinstance(right, Parameters): + return are_parameters_compatible( + left, + right, + is_compat=_is_overlapping_types, + is_proper_subtype=False, + ignore_pos_arg_names=not overlap_for_overloads, + allow_partial_overlap=True, + ) + # A `Parameters` does not overlap with anything else, however + if isinstance(left, Parameters) or isinstance(right, Parameters): + return False + + if isinstance(left, CallableType) and isinstance(right, CallableType): + # We run is_callable_compatible in both directions, similar to the logic + # in is_unsafe_overlapping_overload_signatures + # See comments in https://github.com/python/mypy/pull/5476 + return is_callable_compatible( + left, + right, + is_compat=_is_overlapping_types, + is_proper_subtype=False, + ignore_pos_arg_names=not overlap_for_overloads, + allow_partial_overlap=True, + ) or is_callable_compatible( + right, + left, + is_compat=_is_overlapping_types, + is_proper_subtype=False, + ignore_pos_arg_names=not overlap_for_overloads, + check_args_covariantly=True, + allow_partial_overlap=True, + ) + + call = None + other = None + if isinstance(left, CallableType) and isinstance(right, Instance): + call = find_member("__call__", right, right, is_operator=True) + other = left + if isinstance(right, CallableType) and isinstance(left, Instance): + call = find_member("__call__", left, left, is_operator=True) + other = right + if isinstance(get_proper_type(call), FunctionLike): + assert call is not None and other is not None + return _is_overlapping_types(call, other) + + if isinstance(left, CallableType): + left = left.fallback + if isinstance(right, CallableType): + right = right.fallback + + if isinstance(left, LiteralType) and isinstance(right, LiteralType): + if left.value == right.value: + # If values are the same, we still need to check if fallbacks are overlapping, + # this is done below. + left = left.fallback + right = right.fallback + else: + return False + elif isinstance(left, LiteralType): + left = left.fallback + elif isinstance(right, LiteralType): + right = right.fallback + + # Finally, we handle the case where left and right are instances. + + if isinstance(left, Instance) and isinstance(right, Instance): + # First we need to handle promotions and structural compatibility for instances + # that came as fallbacks, so simply call is_subtype() to avoid code duplication. + if are_related_types( + left, right, proper_subtype=overlap_for_overloads, ignore_promotions=ignore_promotions + ): + return True + + if right.type.fullname == "builtins.int" and left.type.fullname in MYPYC_NATIVE_INT_NAMES: + return True + + # Two unrelated types cannot be partially overlapping: they're disjoint. + if left.type.has_base(right.type.fullname): + left = map_instance_to_supertype(left, right.type) + elif right.type.has_base(left.type.fullname): + right = map_instance_to_supertype(right, left.type) + else: + return False + + if right.type.has_type_var_tuple_type: + # Similar to subtyping, we delegate the heavy lifting to the tuple overlap. + assert right.type.type_var_tuple_prefix is not None + assert right.type.type_var_tuple_suffix is not None + prefix = right.type.type_var_tuple_prefix + suffix = right.type.type_var_tuple_suffix + tvt = right.type.defn.type_vars[prefix] + assert isinstance(tvt, TypeVarTupleType) + fallback = tvt.tuple_fallback + left_prefix, left_middle, left_suffix = split_with_prefix_and_suffix( + left.args, prefix, suffix + ) + right_prefix, right_middle, right_suffix = split_with_prefix_and_suffix( + right.args, prefix, suffix + ) + left_args = left_prefix + (TupleType(list(left_middle), fallback),) + left_suffix + right_args = right_prefix + (TupleType(list(right_middle), fallback),) + right_suffix + else: + left_args = left.args + right_args = right.args + if len(left_args) == len(right_args): + # Note: we don't really care about variance here, since the overlapping check + # is symmetric and since we want to return 'True' even for partial overlaps. + # + # For example, suppose we have two types Wrapper[Parent] and Wrapper[Child]. + # It doesn't matter whether Wrapper is covariant or contravariant since + # either way, one of the two types will overlap with the other. + # + # Similarly, if Wrapper was invariant, the two types could still be partially + # overlapping -- what if Wrapper[Parent] happened to contain only instances of + # specifically Child? + # + # Or, to use a more concrete example, List[Union[A, B]] and List[Union[B, C]] + # would be considered partially overlapping since it's possible for both lists + # to contain only instances of B at runtime. + if all( + _is_overlapping_types(left_arg, right_arg) + for left_arg, right_arg in zip(left_args, right_args) + ): + return True + + return False + + # We ought to have handled every case by now: we conclude the + # two types are not overlapping, either completely or partially. + # + # Note: it's unclear however, whether returning False is the right thing + # to do when inferring reachability -- see https://github.com/python/mypy/issues/5529 + + assert type(left) != type(right), f"{type(left)} vs {type(right)}" + return False + + +def is_overlapping_erased_types( + left: Type, right: Type, *, ignore_promotions: bool = False +) -> bool: + """The same as 'is_overlapping_erased_types', except the types are erased first.""" + return is_overlapping_types( + erase_type(left), erase_type(right), ignore_promotions=ignore_promotions + ) + + +def are_typed_dicts_overlapping( + left: TypedDictType, right: TypedDictType, is_overlapping: Callable[[Type, Type], bool] +) -> bool: + """Returns 'true' if left and right are overlapping TypeDictTypes.""" + # All required keys in left are present and overlapping with something in right + for key in left.required_keys: + if key not in right.items: + return False + if not is_overlapping(left.items[key], right.items[key]): + return False + + # Repeat check in the other direction + for key in right.required_keys: + if key not in left.items: + return False + if not is_overlapping(left.items[key], right.items[key]): + return False + + # The presence of any additional optional keys does not affect whether the two + # TypedDicts are partially overlapping: the dicts would be overlapping if the + # keys happened to be missing. + return True + + +def are_tuples_overlapping( + left: Type, right: Type, is_overlapping: Callable[[Type, Type], bool] +) -> bool: + """Returns true if left and right are overlapping tuples.""" + left, right = get_proper_types((left, right)) + left = adjust_tuple(left, right) or left + right = adjust_tuple(right, left) or right + assert isinstance(left, TupleType), f"Type {left} is not a tuple" + assert isinstance(right, TupleType), f"Type {right} is not a tuple" + + # This algorithm works well if only one tuple is variadic, if both are + # variadic we may get rare false negatives for overlapping prefix/suffix. + # Also, this ignores empty unpack case, but it is probably consistent with + # how we handle e.g. empty lists in overload overlaps. + # TODO: write a more robust algorithm for cases where both types are variadic. + left_unpack = find_unpack_in_list(left.items) + right_unpack = find_unpack_in_list(right.items) + if left_unpack is not None: + left = expand_tuple_if_possible(left, len(right.items)) + if right_unpack is not None: + right = expand_tuple_if_possible(right, len(left.items)) + + if len(left.items) != len(right.items): + return False + if not all(is_overlapping(l, r) for l, r in zip(left.items, right.items)): + return False + + # Check that the tuples aren't from e.g. different NamedTuples. + if is_named_instance(right.partial_fallback, "builtins.tuple") or is_named_instance( + left.partial_fallback, "builtins.tuple" + ): + return True + else: + return is_overlapping(left.partial_fallback, right.partial_fallback) + + +def expand_tuple_if_possible(tup: TupleType, target: int) -> TupleType: + if len(tup.items) > target + 1: + return tup + extra = target + 1 - len(tup.items) + new_items = [] + for it in tup.items: + if not isinstance(it, UnpackType): + new_items.append(it) + continue + unpacked = get_proper_type(it.type) + if isinstance(unpacked, TypeVarTupleType): + instance = unpacked.tuple_fallback + else: + # Nested non-variadic tuples should be normalized at this point. + assert isinstance(unpacked, Instance) + instance = unpacked + assert instance.type.fullname == "builtins.tuple" + new_items.extend([instance.args[0]] * extra) + return tup.copy_modified(items=new_items) + + +def adjust_tuple(left: ProperType, r: ProperType) -> TupleType | None: + """Find out if `left` is a Tuple[A, ...], and adjust its length to `right`""" + if isinstance(left, Instance) and left.type.fullname == "builtins.tuple": + n = r.length() if isinstance(r, TupleType) else 1 + return TupleType([left.args[0]] * n, left) + return None + + +def is_tuple(typ: Type) -> bool: + typ = get_proper_type(typ) + return isinstance(typ, TupleType) or ( + isinstance(typ, Instance) and typ.type.fullname == "builtins.tuple" + ) + + +class TypeMeetVisitor(TypeVisitor[ProperType]): + def __init__(self, s: ProperType) -> None: + self.s = s + + def visit_unbound_type(self, t: UnboundType) -> ProperType: + if isinstance(self.s, NoneType): + if state.strict_optional: + return UninhabitedType() + else: + return self.s + elif isinstance(self.s, UninhabitedType): + return self.s + else: + return AnyType(TypeOfAny.special_form) + + def visit_any(self, t: AnyType) -> ProperType: + return self.s + + def visit_union_type(self, t: UnionType) -> ProperType: + if isinstance(self.s, UnionType): + meets: list[Type] = [] + for x in t.items: + for y in self.s.items: + meets.append(meet_types(x, y)) + else: + meets = [meet_types(x, self.s) for x in t.items] + return make_simplified_union(meets) + + def visit_none_type(self, t: NoneType) -> ProperType: + if state.strict_optional: + if isinstance(self.s, NoneType) or ( + isinstance(self.s, Instance) and self.s.type.fullname == "builtins.object" + ): + return t + else: + return UninhabitedType() + else: + return t + + def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType: + return t + + def visit_deleted_type(self, t: DeletedType) -> ProperType: + if isinstance(self.s, NoneType): + if state.strict_optional: + return t + else: + return self.s + elif isinstance(self.s, UninhabitedType): + return self.s + else: + return t + + def visit_erased_type(self, t: ErasedType) -> ProperType: + return self.s + + def visit_type_var(self, t: TypeVarType) -> ProperType: + if isinstance(self.s, TypeVarType) and self.s.id == t.id: + if self.s.upper_bound == t.upper_bound: + return self.s + return self.s.copy_modified(upper_bound=self.meet(self.s.upper_bound, t.upper_bound)) + else: + return self.default(self.s) + + def visit_param_spec(self, t: ParamSpecType) -> ProperType: + if self.s == t: + return self.s + else: + return self.default(self.s) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType: + if isinstance(self.s, TypeVarTupleType) and self.s.id == t.id: + return self.s if self.s.min_len > t.min_len else t + else: + return self.default(self.s) + + def visit_unpack_type(self, t: UnpackType) -> ProperType: + raise NotImplementedError + + def visit_parameters(self, t: Parameters) -> ProperType: + if isinstance(self.s, Parameters): + if len(t.arg_types) != len(self.s.arg_types): + return self.default(self.s) + from mypy.join import join_types + + return t.copy_modified( + arg_types=[join_types(s_a, t_a) for s_a, t_a in zip(self.s.arg_types, t.arg_types)] + ) + else: + return self.default(self.s) + + def visit_instance(self, t: Instance) -> ProperType: + if isinstance(self.s, Instance): + if t.type == self.s.type: + if is_subtype(t, self.s) or is_subtype(self.s, t): + # Combine type arguments. We could have used join below + # equivalently. + args: list[Type] = [] + # N.B: We use zip instead of indexing because the lengths might have + # mismatches during daemon reprocessing. + if t.type.has_type_var_tuple_type: + # We handle meet of variadic instances by simply creating correct mapping + # for type arguments and compute the individual meets same as for regular + # instances. All the heavy lifting is done in the meet of tuple types. + s = self.s + assert s.type.type_var_tuple_prefix is not None + assert s.type.type_var_tuple_suffix is not None + prefix = s.type.type_var_tuple_prefix + suffix = s.type.type_var_tuple_suffix + tvt = s.type.defn.type_vars[prefix] + assert isinstance(tvt, TypeVarTupleType) + fallback = tvt.tuple_fallback + s_prefix, s_middle, s_suffix = split_with_prefix_and_suffix( + s.args, prefix, suffix + ) + t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix( + t.args, prefix, suffix + ) + s_args = s_prefix + (TupleType(list(s_middle), fallback),) + s_suffix + t_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix + else: + t_args = t.args + s_args = self.s.args + for ta, sa, tv in zip(t_args, s_args, t.type.defn.type_vars): + meet = self.meet(ta, sa) + if isinstance(tv, TypeVarTupleType): + # Correctly unpack possible outcomes of meets of tuples: it can be + # either another tuple type or Never (normalized as *tuple[Never, ...]) + if isinstance(meet, TupleType): + args.extend(meet.items) + continue + else: + assert isinstance(meet, UninhabitedType) + meet = UnpackType(tv.tuple_fallback.copy_modified(args=[meet])) + args.append(meet) + return Instance(t.type, args) + else: + if state.strict_optional: + return UninhabitedType() + else: + return NoneType() + else: + alt_promote = t.type.alt_promote + if alt_promote and alt_promote.type is self.s.type: + return t + alt_promote = self.s.type.alt_promote + if alt_promote and alt_promote.type is t.type: + return self.s + if is_subtype(t, self.s): + return t + elif is_subtype(self.s, t): + # See also above comment. + return self.s + else: + if state.strict_optional: + return UninhabitedType() + else: + return NoneType() + elif isinstance(self.s, FunctionLike) and t.type.is_protocol: + call = join.unpack_callback_protocol(t) + if call: + return meet_types(call, self.s) + elif isinstance(self.s, FunctionLike) and self.s.is_type_obj() and t.type.is_metaclass(): + if is_subtype(self.s.fallback, t): + return self.s + return self.default(self.s) + elif isinstance(self.s, TypeType): + return meet_types(t, self.s) + elif isinstance(self.s, TupleType): + return meet_types(t, self.s) + elif isinstance(self.s, LiteralType): + return meet_types(t, self.s) + elif isinstance(self.s, TypedDictType): + return meet_types(t, self.s) + return self.default(self.s) + + def visit_callable_type(self, t: CallableType) -> ProperType: + if isinstance(self.s, CallableType) and join.is_similar_callables(t, self.s): + if is_equivalent(t, self.s): + return join.combine_similar_callables(t, self.s) + result = meet_similar_callables(t, self.s) + # We set the from_type_type flag to suppress error when a collection of + # concrete class objects gets inferred as their common abstract superclass. + if not ( + (t.is_type_obj() and t.type_object().is_abstract) + or (self.s.is_type_obj() and self.s.type_object().is_abstract) + ): + result.from_type_type = True + if isinstance(get_proper_type(result.ret_type), UninhabitedType): + # Return a plain None or instead of a weird function. + return self.default(self.s) + return result + elif isinstance(self.s, TypeType) and t.is_type_obj() and not t.is_generic(): + # In this case we are able to potentially produce a better meet. + res = meet_types(self.s.item, t.ret_type) + if not isinstance(res, (NoneType, UninhabitedType)): + return TypeType.make_normalized(res) + return self.default(self.s) + elif isinstance(self.s, Instance) and self.s.type.is_protocol: + call = join.unpack_callback_protocol(self.s) + if call: + return meet_types(t, call) + return self.default(self.s) + + def visit_overloaded(self, t: Overloaded) -> ProperType: + # TODO: Implement a better algorithm that covers at least the same cases + # as TypeJoinVisitor.visit_overloaded(). + s = self.s + if isinstance(s, FunctionLike): + if s.items == t.items: + return Overloaded(t.items) + elif is_subtype(s, t): + return s + elif is_subtype(t, s): + return t + else: + return meet_types(t.fallback, s.fallback) + elif isinstance(self.s, Instance) and self.s.type.is_protocol: + call = join.unpack_callback_protocol(self.s) + if call: + return meet_types(t, call) + return meet_types(t.fallback, s) + + def meet_tuples(self, s: TupleType, t: TupleType) -> list[Type] | None: + """Meet two tuple types while handling variadic entries. + + This is surprisingly tricky, and we don't handle some tricky corner cases. + Most of the trickiness comes from the variadic tuple items like *tuple[X, ...] + since they can have arbitrary partial overlaps (while *Ts can't be split). This + function is roughly a mirror of join_tuples() w.r.t. to the fact that fixed + tuples are subtypes of variadic ones but not vice versa. + """ + s_unpack_index = find_unpack_in_list(s.items) + t_unpack_index = find_unpack_in_list(t.items) + if s_unpack_index is None and t_unpack_index is None: + if s.length() == t.length(): + items: list[Type] = [] + for i in range(t.length()): + items.append(self.meet(t.items[i], s.items[i])) + return items + return None + if s_unpack_index is not None and t_unpack_index is not None: + # The only simple case we can handle if both tuples are variadic + # is when their structure fully matches. Other cases are tricky because + # a variadic item is effectively a union of tuples of all length, thus + # potentially causing overlap between a suffix in `s` and a prefix + # in `t` (see how this is handled in is_subtype() for details). + # TODO: handle more cases (like when both prefix/suffix are shorter in s or t). + if s.length() == t.length() and s_unpack_index == t_unpack_index: + unpack_index = s_unpack_index + s_unpack = s.items[unpack_index] + assert isinstance(s_unpack, UnpackType) + s_unpacked = get_proper_type(s_unpack.type) + t_unpack = t.items[unpack_index] + assert isinstance(t_unpack, UnpackType) + t_unpacked = get_proper_type(t_unpack.type) + if not (isinstance(s_unpacked, Instance) and isinstance(t_unpacked, Instance)): + return None + meet = self.meet(s_unpacked, t_unpacked) + if not isinstance(meet, Instance): + return None + m_prefix: list[Type] = [] + for si, ti in zip(s.items[:unpack_index], t.items[:unpack_index]): + m_prefix.append(meet_types(si, ti)) + m_suffix: list[Type] = [] + for si, ti in zip(s.items[unpack_index + 1 :], t.items[unpack_index + 1 :]): + m_suffix.append(meet_types(si, ti)) + return m_prefix + [UnpackType(meet)] + m_suffix + return None + if s_unpack_index is not None: + variadic = s + unpack_index = s_unpack_index + fixed = t + else: + assert t_unpack_index is not None + variadic = t + unpack_index = t_unpack_index + fixed = s + # If one tuple is variadic one, and the other one is fixed, the meet will be fixed. + unpack = variadic.items[unpack_index] + assert isinstance(unpack, UnpackType) + unpacked = get_proper_type(unpack.type) + if not isinstance(unpacked, Instance): + return None + if fixed.length() < variadic.length() - 1: + return None + prefix_len = unpack_index + suffix_len = variadic.length() - prefix_len - 1 + prefix, middle, suffix = split_with_prefix_and_suffix( + tuple(fixed.items), prefix_len, suffix_len + ) + items = [] + for fi, vi in zip(prefix, variadic.items[:prefix_len]): + items.append(self.meet(fi, vi)) + for mi in middle: + items.append(self.meet(mi, unpacked.args[0])) + if suffix_len: + for fi, vi in zip(suffix, variadic.items[-suffix_len:]): + items.append(self.meet(fi, vi)) + return items + + def visit_tuple_type(self, t: TupleType) -> ProperType: + if isinstance(self.s, TupleType): + items = self.meet_tuples(self.s, t) + if items is None: + return self.default(self.s) + # TODO: What if the fallbacks are different? + return TupleType(items, tuple_fallback(t)) + elif isinstance(self.s, Instance): + # meet(Tuple[t1, t2, <...>], Tuple[s, ...]) == Tuple[meet(t1, s), meet(t2, s), <...>]. + if self.s.type.fullname in TUPLE_LIKE_INSTANCE_NAMES and self.s.args: + return t.copy_modified(items=[meet_types(it, self.s.args[0]) for it in t.items]) + elif is_proper_subtype(t, self.s): + # A named tuple that inherits from a normal class + return t + elif self.s.type.has_type_var_tuple_type and is_subtype(t, self.s): + # This is a bit ad-hoc but more principled handling is tricky, and this + # special case is important for type narrowing in binder to work. + return t + return self.default(self.s) + + def visit_typeddict_type(self, t: TypedDictType) -> ProperType: + if isinstance(self.s, TypedDictType): + for name, l, r in self.s.zip(t): + if not is_equivalent(l, r) or (name in t.required_keys) != ( + name in self.s.required_keys + ): + return self.default(self.s) + item_list: list[tuple[str, Type]] = [] + for item_name, s_item_type, t_item_type in self.s.zipall(t): + if s_item_type is not None: + item_list.append((item_name, s_item_type)) + else: + # at least one of s_item_type and t_item_type is not None + assert t_item_type is not None + item_list.append((item_name, t_item_type)) + items = dict(item_list) + fallback = self.s.create_anonymous_fallback() + required_keys = t.required_keys | self.s.required_keys + readonly_keys = t.readonly_keys | self.s.readonly_keys + return TypedDictType(items, required_keys, readonly_keys, fallback) + elif isinstance(self.s, Instance) and is_subtype(t, self.s): + return t + else: + return self.default(self.s) + + def visit_literal_type(self, t: LiteralType) -> ProperType: + if isinstance(self.s, LiteralType) and self.s == t: + return t + elif isinstance(self.s, Instance) and is_subtype(t.fallback, self.s): + return t + else: + return self.default(self.s) + + def visit_partial_type(self, t: PartialType) -> ProperType: + # We can't determine the meet of partial types. We should never get here. + assert False, "Internal error" + + def visit_type_type(self, t: TypeType) -> ProperType: + if isinstance(self.s, TypeType): + typ = self.meet(t.item, self.s.item) + if not isinstance(typ, NoneType): + typ = TypeType.make_normalized( + typ, line=t.line, is_type_form=self.s.is_type_form and t.is_type_form + ) + return typ + elif isinstance(self.s, Instance) and self.s.type.fullname == "builtins.type": + return t + elif isinstance(self.s, CallableType): + return self.meet(t, self.s) + else: + return self.default(self.s) + + def visit_type_alias_type(self, t: TypeAliasType) -> ProperType: + assert False, f"This should be never called, got {t}" + + def meet(self, s: Type, t: Type) -> ProperType: + return meet_types(s, t) + + def default(self, typ: Type) -> ProperType: + if isinstance(typ, UnboundType): + return AnyType(TypeOfAny.special_form) + else: + if state.strict_optional: + return UninhabitedType() + else: + return NoneType() + + +def meet_similar_callables(t: CallableType, s: CallableType) -> CallableType: + from mypy.join import match_generic_callables, safe_join + + t, s = match_generic_callables(t, s) + arg_types: list[Type] = [] + for i in range(len(t.arg_types)): + arg_types.append(safe_join(t.arg_types[i], s.arg_types[i])) + # TODO in combine_similar_callables also applies here (names and kinds) + # The fallback type can be either 'function' or 'type'. The result should have 'function' as + # fallback only if both operands have it as 'function'. + if t.fallback.type.fullname != "builtins.function": + fallback = t.fallback + else: + fallback = s.fallback + return t.copy_modified( + arg_types=arg_types, + ret_type=meet_types(t.ret_type, s.ret_type), + fallback=fallback, + name=None, + ) + + +def meet_type_list(types: list[Type]) -> Type: + if not types: + # This should probably be builtins.object but that is hard to get and + # it doesn't matter for any current users. + return AnyType(TypeOfAny.implementation_artifact) + met = types[0] + for t in types[1:]: + met = meet_types(met, t) + return met + + +def typed_dict_mapping_pair(left: Type, right: Type) -> bool: + """Is this a pair where one type is a TypedDict and another one is an instance of Mapping? + + This case requires a precise/principled consideration because there are two use cases + that push the boundary the opposite ways: we need to avoid spurious overlaps to avoid + false positives for overloads, but we also need to avoid spuriously non-overlapping types + to avoid false positives with --strict-equality. + """ + left, right = get_proper_types((left, right)) + assert not isinstance(left, TypedDictType) or not isinstance(right, TypedDictType) + + if isinstance(left, TypedDictType): + _, other = left, right + elif isinstance(right, TypedDictType): + _, other = right, left + else: + return False + return isinstance(other, Instance) and other.type.has_base("typing.Mapping") + + +def typed_dict_mapping_overlap( + left: Type, right: Type, overlapping: Callable[[Type, Type], bool] +) -> bool: + """Check if a TypedDict type is overlapping with a Mapping. + + The basic logic here consists of two rules: + + * A TypedDict with some required keys is overlapping with Mapping[str, ] + if and only if every key type is overlapping with . For example: + + - TypedDict(x=int, y=str) overlaps with Dict[str, Union[str, int]] + - TypedDict(x=int, y=str) doesn't overlap with Dict[str, int] + + Note that any additional non-required keys can't change the above result. + + * A TypedDict with no required keys overlaps with Mapping[str, ] if and + only if at least one of key types overlaps with . For example: + + - TypedDict(x=str, y=str, total=False) overlaps with Dict[str, str] + - TypedDict(x=str, y=str, total=False) doesn't overlap with Dict[str, int] + - TypedDict(x=int, y=str, total=False) overlaps with Dict[str, str] + + * A TypedDict with at least one ReadOnly[] key does not overlap + with Dict or MutableMapping, because they assume mutable data. + + As usual empty, dictionaries lie in a gray area. In general, List[str] and List[str] + are considered non-overlapping despite empty list belongs to both. However, List[int] + and List[Never] are considered overlapping. + + So here we follow the same logic: a TypedDict with no required keys is considered + non-overlapping with Mapping[str, ], but is considered overlapping with + Mapping[Never, Never]. This way we avoid false positives for overloads, and also + avoid false positives for comparisons like SomeTypedDict == {} under --strict-equality. + """ + left, right = get_proper_types((left, right)) + assert not isinstance(left, TypedDictType) or not isinstance(right, TypedDictType) + + if isinstance(left, TypedDictType): + assert isinstance(right, Instance) + typed, other = left, right + else: + assert isinstance(left, Instance) + assert isinstance(right, TypedDictType) + typed, other = right, left + + mutable_mapping = next( + (base for base in other.type.mro if base.fullname == "typing.MutableMapping"), None + ) + if mutable_mapping is not None and typed.readonly_keys: + return False + + mapping = next(base for base in other.type.mro if base.fullname == "typing.Mapping") + other = map_instance_to_supertype(other, mapping) + key_type, value_type = get_proper_types(other.args) + + # TODO: is there a cleaner way to get str_type here? + fallback = typed.create_anonymous_fallback() + str_type = fallback.type.bases[0].args[0] # typing._TypedDict inherits Mapping[str, object] + + # Special case: a TypedDict with no required keys overlaps with an empty dict. + if isinstance(key_type, UninhabitedType) and isinstance(value_type, UninhabitedType): + return not typed.required_keys + + if typed.required_keys: + if not overlapping(key_type, str_type): + return False + return all(overlapping(typed.items[k], value_type) for k in typed.required_keys) + else: + if not overlapping(key_type, str_type): + return False + non_required = set(typed.items.keys()) - typed.required_keys + return any(overlapping(typed.items[k], value_type) for k in non_required) diff --git a/micromamba_root/Lib/site-packages/mypy/memprofile.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/memprofile.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..12906dd879e658f2aa6052a7afd4edb45fd85eea Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/memprofile.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/memprofile.py b/micromamba_root/Lib/site-packages/mypy/memprofile.py new file mode 100644 index 0000000000000000000000000000000000000000..4bab4ecb262eec7127f896ccdf977e2c6dfd7d94 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/memprofile.py @@ -0,0 +1,122 @@ +"""Utility for dumping memory usage stats. + +This is tailored to mypy and knows (a little) about which list objects are +owned by particular AST nodes, etc. +""" + +from __future__ import annotations + +import gc +import sys +from collections import defaultdict +from collections.abc import Iterable +from typing import cast + +from mypy.nodes import FakeInfo, Node +from mypy.types import Type +from mypy.util import get_class_descriptors + + +def collect_memory_stats() -> tuple[dict[str, int], dict[str, int]]: + """Return stats about memory use. + + Return a tuple with these items: + - Dict from object kind to number of instances of that kind + - Dict from object kind to total bytes used by all instances of that kind + """ + objs = gc.get_objects() + find_recursive_objects(objs) + + inferred = {} + for obj in objs: + if type(obj) is FakeInfo: + # Processing these would cause a crash. + continue + n = type(obj).__name__ + if hasattr(obj, "__dict__"): + # Keep track of which class a particular __dict__ is associated with. + inferred[id(obj.__dict__)] = f"{n} (__dict__)" + if isinstance(obj, (Node, Type)): # type: ignore[misc] + if hasattr(obj, "__dict__"): + for x in obj.__dict__.values(): + if isinstance(x, list): + # Keep track of which node a list is associated with. + inferred[id(x)] = f"{n} (list)" + if isinstance(x, tuple): + # Keep track of which node a list is associated with. + inferred[id(x)] = f"{n} (tuple)" + + for k in get_class_descriptors(type(obj)): + x = getattr(obj, k, None) + if isinstance(x, list): + inferred[id(x)] = f"{n} (list)" + if isinstance(x, tuple): + inferred[id(x)] = f"{n} (tuple)" + + freqs: dict[str, int] = {} + memuse: dict[str, int] = {} + for obj in objs: + if id(obj) in inferred: + name = inferred[id(obj)] + else: + name = type(obj).__name__ + freqs[name] = freqs.get(name, 0) + 1 + memuse[name] = memuse.get(name, 0) + sys.getsizeof(obj) + + return freqs, memuse + + +def print_memory_profile(run_gc: bool = True) -> None: + if not sys.platform.startswith("win"): + import resource + + system_memuse = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + else: + system_memuse = -1 # TODO: Support this on Windows + if run_gc: + gc.collect() + freqs, memuse = collect_memory_stats() + print("%7s %7s %7s %s" % ("Freq", "Size(k)", "AvgSize", "Type")) + print("-------------------------------------------") + totalmem = 0 + i = 0 + for n, mem in sorted(memuse.items(), key=lambda x: -x[1]): + f = freqs[n] + if i < 50: + print("%7d %7d %7.0f %s" % (f, mem // 1024, mem / f, n)) + i += 1 + totalmem += mem + print() + print("Mem usage RSS ", system_memuse // 1024) + print("Total reachable ", totalmem // 1024) + + +def find_recursive_objects(objs: list[object]) -> None: + """Find additional objects referenced by objs and append them to objs. + + We use this since gc.get_objects() does not return objects without pointers + in them such as strings. + """ + seen = {id(o) for o in objs} + + def visit(o: object) -> None: + if id(o) not in seen: + objs.append(o) + seen.add(id(o)) + + for obj in objs.copy(): + if type(obj) is FakeInfo: + # Processing these would cause a crash. + continue + if type(obj) in (dict, defaultdict): + for key, val in cast(dict[object, object], obj).items(): + visit(key) + visit(val) + if type(obj) in (list, tuple, set): + for x in cast(Iterable[object], obj): + visit(x) + if hasattr(obj, "__slots__"): + for base in type.mro(type(obj)): + for slot in getattr(base, "__slots__", ()): + if hasattr(obj, slot): + visit(getattr(obj, slot)) diff --git a/micromamba_root/Lib/site-packages/mypy/message_registry.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/message_registry.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..807e7e8492c42f375a39e81e4be582185486522f Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/message_registry.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/message_registry.py b/micromamba_root/Lib/site-packages/mypy/message_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..8140e28e16d7a21aed7482fe22e0ae5313929632 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/message_registry.py @@ -0,0 +1,376 @@ +"""Message constants for generating error messages during type checking. + +Literal messages should be defined as constants in this module so they won't get out of sync +if used in more than one place, and so that they can be easily introspected. These messages are +ultimately consumed by messages.MessageBuilder.fail(). For more non-trivial message generation, +add a method to MessageBuilder and call this instead. +""" + +from __future__ import annotations + +from typing import Final, NamedTuple + +from mypy import errorcodes as codes +from mypy.errorcodes import ErrorCode + + +class ErrorMessage(NamedTuple): + value: str + code: ErrorCode | None = None + + def format(self, *args: object, **kwargs: object) -> ErrorMessage: + return ErrorMessage(self.value.format(*args, **kwargs), code=self.code) + + def with_additional_msg(self, info: str) -> ErrorMessage: + return ErrorMessage(self.value + info, code=self.code) + + +# Invalid types +INVALID_TYPE_RAW_ENUM_VALUE: Final = ErrorMessage( + "Invalid type: try using Literal[{}.{}] instead?", codes.VALID_TYPE +) + +# Type checker error message constants +NO_RETURN_VALUE_EXPECTED: Final = ErrorMessage("No return value expected", codes.RETURN_VALUE) +MISSING_RETURN_STATEMENT: Final = ErrorMessage("Missing return statement", codes.RETURN) +EMPTY_BODY_ABSTRACT: Final = ErrorMessage( + "If the method is meant to be abstract, use @abc.abstractmethod", codes.EMPTY_BODY +) +INVALID_IMPLICIT_RETURN: Final = ErrorMessage("Implicit return in function which does not return") +INCOMPATIBLE_RETURN_VALUE_TYPE: Final = ErrorMessage( + "Incompatible return value type", codes.RETURN_VALUE +) +RETURN_VALUE_EXPECTED: Final = ErrorMessage("Return value expected", codes.RETURN_VALUE) +NO_RETURN_EXPECTED: Final = ErrorMessage("Return statement in function which does not return") +INVALID_EXCEPTION: Final = ErrorMessage("Exception must be derived from BaseException") +INVALID_EXCEPTION_TYPE: Final = ErrorMessage( + "Exception type must be derived from BaseException (or be a tuple of exception classes)" +) +INVALID_EXCEPTION_GROUP: Final = ErrorMessage( + "Exception type in except* cannot derive from BaseExceptionGroup" +) +RETURN_IN_ASYNC_GENERATOR: Final = ErrorMessage( + '"return" with value in async generator is not allowed' +) +INVALID_RETURN_TYPE_FOR_GENERATOR: Final = ErrorMessage( + 'The return type of a generator function should be "Generator" or one of its supertypes' +) +INVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR: Final = ErrorMessage( + 'The return type of an async generator function should be "AsyncGenerator" or one of its ' + "supertypes" +) +YIELD_VALUE_EXPECTED: Final = ErrorMessage("Yield value expected") +INCOMPATIBLE_TYPES: Final = ErrorMessage("Incompatible types") +INCOMPATIBLE_TYPES_IN_ASSIGNMENT: Final = ErrorMessage( + "Incompatible types in assignment", code=codes.ASSIGNMENT +) +COVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE: Final = ErrorMessage( + "Covariant override of a mutable attribute", code=codes.MUTABLE_OVERRIDE +) +INCOMPATIBLE_TYPES_IN_AWAIT: Final = ErrorMessage('Incompatible types in "await"') +INCOMPATIBLE_REDEFINITION: Final = ErrorMessage("Incompatible redefinition") +INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AENTER: Final = ( + 'Incompatible types in "async with" for "__aenter__"' +) +INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AEXIT: Final = ( + 'Incompatible types in "async with" for "__aexit__"' +) +INCOMPATIBLE_TYPES_IN_ASYNC_FOR: Final = 'Incompatible types in "async for"' +INVALID_TYPE_FOR_SLOTS: Final = 'Invalid type for "__slots__"' + +ASYNC_FOR_OUTSIDE_COROUTINE: Final = '"async for" outside async function' +ASYNC_WITH_OUTSIDE_COROUTINE: Final = '"async with" outside async function' + +INCOMPATIBLE_TYPES_IN_YIELD: Final = ErrorMessage('Incompatible types in "yield"') +INCOMPATIBLE_TYPES_IN_YIELD_FROM: Final = ErrorMessage('Incompatible types in "yield from"') +INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION: Final = "Incompatible types in string interpolation" +INCOMPATIBLE_TYPES_IN_CAPTURE: Final = ErrorMessage("Incompatible types in capture pattern") +MUST_HAVE_NONE_RETURN_TYPE: Final = ErrorMessage('The return type of "{}" must be None') +TUPLE_INDEX_OUT_OF_RANGE: Final = ErrorMessage("Tuple index out of range") +AMBIGUOUS_SLICE_OF_VARIADIC_TUPLE: Final = ErrorMessage("Ambiguous slice of a variadic tuple") +TOO_MANY_TARGETS_FOR_VARIADIC_UNPACK: Final = ErrorMessage( + "Too many assignment targets for variadic unpack" +) +INVALID_SLICE_INDEX: Final = ErrorMessage("Slice index must be an integer, SupportsIndex or None") +CANNOT_INFER_LAMBDA_TYPE: Final = ErrorMessage("Cannot infer type of lambda") +CANNOT_ACCESS_INIT: Final = ( + 'Accessing "__init__" on an instance is unsound, since instance.__init__ could be from' + " an incompatible subclass" +) +NON_INSTANCE_NEW_TYPE: Final = ErrorMessage('"__new__" must return a class instance (got {})') +INVALID_NEW_TYPE: Final = ErrorMessage('Incompatible return type for "__new__"') +BAD_CONSTRUCTOR_TYPE: Final = ErrorMessage("Unsupported decorated constructor type") +CANNOT_ASSIGN_TO_METHOD: Final = "Cannot assign to a method" +CANNOT_ASSIGN_TO_TYPE: Final = "Cannot assign to a type" +INCONSISTENT_ABSTRACT_OVERLOAD: Final = ErrorMessage( + "Overloaded method has both abstract and non-abstract variants" +) +MULTIPLE_OVERLOADS_REQUIRED: Final = ErrorMessage("Single overload definition, multiple required") +READ_ONLY_PROPERTY_OVERRIDES_READ_WRITE: Final = ErrorMessage( + "Read-only property cannot override read-write property" +) +FORMAT_REQUIRES_MAPPING: Final = "Format requires a mapping" +RETURN_TYPE_CANNOT_BE_CONTRAVARIANT: Final = ErrorMessage( + "Cannot use a contravariant type variable as return type" +) +FUNCTION_PARAMETER_CANNOT_BE_COVARIANT: Final = ErrorMessage( + "Cannot use a covariant type variable as a parameter" +) +INCOMPATIBLE_IMPORT_OF: Final = ErrorMessage('Incompatible import of "{}"', code=codes.ASSIGNMENT) +FUNCTION_TYPE_EXPECTED: Final = ErrorMessage( + "Function is missing a type annotation", codes.NO_UNTYPED_DEF +) +ONLY_CLASS_APPLICATION: Final = ErrorMessage( + "Type application is only supported for generic classes" +) +RETURN_TYPE_EXPECTED: Final = ErrorMessage( + "Function is missing a return type annotation", codes.NO_UNTYPED_DEF +) +PARAM_TYPE_EXPECTED: Final = ErrorMessage( + "Function is missing a type annotation for one or more parameters", codes.NO_UNTYPED_DEF +) +KEYWORD_ARGUMENT_REQUIRES_STR_KEY_TYPE: Final = ErrorMessage( + 'Keyword argument only valid with "str" key type in call to "dict"' +) +ALL_MUST_BE_SEQ_STR: Final = ErrorMessage("Type of __all__ must be {}, not {}") +INVALID_TYPEDDICT_ARGS: Final = ErrorMessage( + "Expected keyword arguments, {...}, or dict(...) in TypedDict constructor" +) +TYPEDDICT_KEY_MUST_BE_STRING_LITERAL: Final = ErrorMessage( + "Expected TypedDict key to be string literal" +) +TYPEDDICT_OVERRIDE_MERGE: Final = 'Overwriting TypedDict field "{}" while merging' +MALFORMED_ASSERT: Final = ErrorMessage("Assertion is always true, perhaps remove parentheses?") +DUPLICATE_TYPE_SIGNATURES: Final = ErrorMessage("Function has duplicate type signatures") +DESCRIPTOR_SET_NOT_CALLABLE: Final = ErrorMessage("{}.__set__ is not callable") +DESCRIPTOR_GET_NOT_CALLABLE: Final = "{}.__get__ is not callable" +MODULE_LEVEL_GETATTRIBUTE: Final = ErrorMessage( + "__getattribute__ is not valid at the module level" +) +CLASS_VAR_CONFLICTS_SLOTS: Final = '"{}" in __slots__ conflicts with class variable access' +NAME_NOT_IN_SLOTS: Final = ErrorMessage( + 'Trying to assign name "{}" that is not in "__slots__" of type "{}"' +) +TYPE_ALWAYS_TRUE: Final = ErrorMessage( + "{} which does not implement __bool__ or __len__ " + "so it could always be true in boolean context", + code=codes.TRUTHY_BOOL, +) +TYPE_ALWAYS_TRUE_UNIONTYPE: Final = ErrorMessage( + "{} of which no members implement __bool__ or __len__ " + "so it could always be true in boolean context", + code=codes.TRUTHY_BOOL, +) +FUNCTION_ALWAYS_TRUE: Final = ErrorMessage( + "Function {} could always be true in boolean context", code=codes.TRUTHY_FUNCTION +) +ITERABLE_ALWAYS_TRUE: Final = ErrorMessage( + "{} which can always be true in boolean context. Consider using {} instead.", + code=codes.TRUTHY_ITERABLE, +) +NOT_CALLABLE: Final = "{} not callable" +TYPE_MUST_BE_USED: Final = "Value of type {} must be used" + +# Generic +GENERIC_INSTANCE_VAR_CLASS_ACCESS: Final = ( + "Access to generic instance variables via class is ambiguous" +) +GENERIC_CLASS_VAR_ACCESS: Final = "Access to generic class variables is ambiguous" +BARE_GENERIC: Final = "Missing type arguments for generic type {}" +IMPLICIT_GENERIC_ANY_BUILTIN: Final = ( + 'Implicit generic "Any". Use "{}" and specify generic parameters' +) +INVALID_UNPACK: Final = "{} cannot be unpacked (must be tuple or TypeVarTuple)" +INVALID_UNPACK_POSITION: Final = "Unpack is only valid in a variadic position" +INVALID_PARAM_SPEC_LOCATION: Final = "Invalid location for ParamSpec {}" +INVALID_PARAM_SPEC_LOCATION_NOTE: Final = ( + 'You can use ParamSpec as the first argument to Callable, e.g., "Callable[{}, int]"' +) + +# TypeVar +INCOMPATIBLE_TYPEVAR_VALUE: Final = 'Value of type variable "{}" of {} cannot be {}' +INVALID_TYPEVAR_AS_TYPEARG: Final = 'Type variable "{}" not valid as type argument value for "{}"' +INVALID_TYPEVAR_ARG_BOUND: Final = 'Type argument {} of "{}" must be a subtype of {}' +INVALID_TYPEVAR_ARG_VALUE: Final = 'Invalid type argument value for "{}"' +TYPEVAR_VARIANCE_DEF: Final = 'TypeVar "{}" may only be a literal bool' +TYPEVAR_ARG_MUST_BE_TYPE: Final = '{} "{}" must be a type' +TYPEVAR_UNEXPECTED_ARGUMENT: Final = 'Unexpected argument to "TypeVar()"' +UNBOUND_TYPEVAR: Final = ( + "A function returning TypeVar should receive at least one argument containing the same TypeVar" +) +TYPE_PARAMETERS_SHOULD_BE_DECLARED: Final = ( + "All type parameters should be declared ({} not declared)" +) + +# Super +TOO_MANY_ARGS_FOR_SUPER: Final = ErrorMessage('Too many arguments for "super"') +SUPER_WITH_SINGLE_ARG_NOT_SUPPORTED: Final = ErrorMessage( + '"super" with a single argument not supported' +) +UNSUPPORTED_ARG_1_FOR_SUPER: Final = ErrorMessage('Unsupported argument 1 for "super"') +UNSUPPORTED_ARG_2_FOR_SUPER: Final = ErrorMessage('Unsupported argument 2 for "super"') +SUPER_VARARGS_NOT_SUPPORTED: Final = ErrorMessage('Varargs not supported with "super"') +SUPER_POSITIONAL_ARGS_REQUIRED: Final = ErrorMessage('"super" only accepts positional arguments') +SUPER_ARG_2_NOT_INSTANCE_OF_ARG_1: Final = ErrorMessage( + 'Argument 2 for "super" not an instance of argument 1' +) +TARGET_CLASS_HAS_NO_BASE_CLASS: Final = ErrorMessage("Target class has no base class") +SUPER_OUTSIDE_OF_METHOD_NOT_SUPPORTED: Final = ErrorMessage( + '"super()" outside of a method is not supported' +) +SUPER_ENCLOSING_POSITIONAL_ARGS_REQUIRED: Final = ErrorMessage( + '"super()" requires one or two positional arguments in enclosing function' +) + +# Self-type +MISSING_OR_INVALID_SELF_TYPE: Final = ErrorMessage( + '"self" parameter missing for a non-static method (or an invalid type for self)' +) +ERASED_SELF_TYPE_NOT_SUPERTYPE: Final = ErrorMessage( + 'The erased type of self "{}" is not a supertype of its class "{}"' +) + +# Final +CANNOT_INHERIT_FROM_FINAL: Final = ErrorMessage('Cannot inherit from final class "{}"') +DEPENDENT_FINAL_IN_CLASS_BODY: Final = ErrorMessage( + "Final name declared in class body cannot depend on type variables" +) +CANNOT_ACCESS_FINAL_INSTANCE_ATTR: Final = ( + 'Cannot access final instance attribute "{}" on class object' +) +CANNOT_ACCESS_INSTANCE_ONLY_ATTR: Final = ( + 'Cannot access instance-only attribute "{}" on class object' +) +CANNOT_MAKE_DELETABLE_FINAL: Final = ErrorMessage("Deletable attribute cannot be final") + +# Disjoint bases +INCOMPATIBLE_DISJOINT_BASES: Final = ErrorMessage('Class "{}" has incompatible disjoint bases') + +# Enum +ENUM_MEMBERS_ATTR_WILL_BE_OVERRIDDEN: Final = ErrorMessage( + 'Assigned "__members__" will be overridden by "Enum" internally' +) + +# ClassVar +CANNOT_OVERRIDE_INSTANCE_VAR: Final = ErrorMessage( + 'Cannot override instance variable (previously declared on base class "{}") with class ' + "variable" +) +CANNOT_OVERRIDE_CLASS_VAR: Final = ErrorMessage( + 'Cannot override class variable (previously declared on base class "{}") with instance ' + "variable" +) +CLASS_VAR_WITH_GENERIC_SELF: Final = "ClassVar cannot contain Self type in generic classes" +CLASS_VAR_OUTSIDE_OF_CLASS: Final = "ClassVar can only be used for assignments in class body" + +# Protocol +RUNTIME_PROTOCOL_EXPECTED: Final = ErrorMessage( + "Only @runtime_checkable protocols can be used with instance and class checks" +) +CANNOT_INSTANTIATE_PROTOCOL: Final = ErrorMessage('Cannot instantiate protocol class "{}"') +TOO_MANY_UNION_COMBINATIONS: Final = ErrorMessage( + "Not all union combinations were tried because there are too many unions" +) + +CONTIGUOUS_ITERABLE_EXPECTED: Final = ErrorMessage("Contiguous iterable with same type expected") +ITERABLE_TYPE_EXPECTED: Final = ErrorMessage("Invalid type '{}' for *expr (iterable expected)") +TYPE_GUARD_POS_ARG_REQUIRED: Final = ErrorMessage("Type {} requires positional argument") + +# Match Statement +MISSING_MATCH_ARGS: Final = 'Class "{}" doesn\'t define "__match_args__"' +OR_PATTERN_ALTERNATIVE_NAMES: Final = "Alternative patterns bind different names" +CLASS_PATTERN_GENERIC_TYPE_ALIAS: Final = ( + "Class pattern class must not be a type alias with type parameters" +) +CLASS_PATTERN_TYPE_REQUIRED: Final = 'Expected type in class pattern; found "{}"' +CLASS_PATTERN_TOO_MANY_POSITIONAL_ARGS: Final = "Too many positional patterns for class pattern" +CLASS_PATTERN_KEYWORD_MATCHES_POSITIONAL: Final = ( + 'Keyword "{}" already matches a positional pattern' +) +CLASS_PATTERN_DUPLICATE_KEYWORD_PATTERN: Final = 'Duplicate keyword pattern "{}"' +CLASS_PATTERN_UNKNOWN_KEYWORD: Final = 'Class "{}" has no attribute "{}"' +CLASS_PATTERN_CLASS_OR_STATIC_METHOD: Final = "Cannot have both classmethod and staticmethod" +MULTIPLE_ASSIGNMENTS_IN_PATTERN: Final = 'Multiple assignments to name "{}" in pattern' +CANNOT_MODIFY_MATCH_ARGS: Final = 'Cannot assign to "__match_args__"' + +DATACLASS_FIELD_ALIAS_MUST_BE_LITERAL: Final = ( + '"alias" argument to dataclass field must be a string literal' +) +DATACLASS_POST_INIT_MUST_BE_A_FUNCTION: Final = '"__post_init__" method must be an instance method' + +# fastparse +FAILED_TO_MERGE_OVERLOADS: Final = ErrorMessage( + "Condition can't be inferred, unable to merge overloads" +) +TYPE_IGNORE_WITH_ERRCODE_ON_MODULE: Final = ErrorMessage( + "Type ignore with error code is not supported for modules; " + 'use `# mypy: disable-error-code="{}"`', + codes.SYNTAX, +) +INVALID_TYPE_IGNORE: Final = ErrorMessage('Invalid "type: ignore" comment', codes.SYNTAX) +TYPE_COMMENT_SYNTAX_ERROR_VALUE: Final = ErrorMessage( + 'Syntax error in type comment "{}"', codes.SYNTAX +) +ELLIPSIS_WITH_OTHER_TYPEPARAMS: Final = ErrorMessage( + "Ellipses cannot accompany other parameter types in function type signature", codes.SYNTAX +) +TYPE_SIGNATURE_TOO_MANY_PARAMS: Final = ErrorMessage( + "Type signature has too many parameters", codes.SYNTAX +) +TYPE_SIGNATURE_TOO_FEW_PARAMS: Final = ErrorMessage( + "Type signature has too few parameters", codes.SYNTAX +) +ARG_CONSTRUCTOR_NAME_EXPECTED: Final = ErrorMessage("Expected arg constructor name", codes.SYNTAX) +ARG_CONSTRUCTOR_TOO_MANY_ARGS: Final = ErrorMessage( + "Too many arguments for argument constructor", codes.SYNTAX +) +MULTIPLE_VALUES_FOR_NAME_KWARG: Final = ErrorMessage( + '"{}" gets multiple values for keyword argument "name"', codes.SYNTAX +) +MULTIPLE_VALUES_FOR_TYPE_KWARG: Final = ErrorMessage( + '"{}" gets multiple values for keyword argument "type"', codes.SYNTAX +) +ARG_CONSTRUCTOR_UNEXPECTED_ARG: Final = ErrorMessage( + 'Unexpected argument "{}" for argument constructor', codes.SYNTAX +) +ARG_NAME_EXPECTED_STRING_LITERAL: Final = ErrorMessage( + "Expected string literal for argument name, got {}", codes.SYNTAX +) +NARROWED_TYPE_NOT_SUBTYPE: Final = ErrorMessage( + "Narrowed type {} is not a subtype of input type {}", codes.NARROWED_TYPE_NOT_SUBTYPE +) +TYPE_VAR_TOO_FEW_CONSTRAINED_TYPES: Final = ErrorMessage( + "Type variable must have at least two constrained types", codes.MISC +) + +TYPE_VAR_YIELD_EXPRESSION_IN_BOUND: Final = ErrorMessage( + "Yield expression cannot be used as a type variable bound", codes.SYNTAX +) + +TYPE_VAR_NAMED_EXPRESSION_IN_BOUND: Final = ErrorMessage( + "Named expression cannot be used as a type variable bound", codes.SYNTAX +) + +TYPE_VAR_AWAIT_EXPRESSION_IN_BOUND: Final = ErrorMessage( + "Await expression cannot be used as a type variable bound", codes.SYNTAX +) + +TYPE_VAR_GENERIC_CONSTRAINT_TYPE: Final = ErrorMessage( + "TypeVar constraint type cannot be parametrized by type variables", codes.MISC +) + +TYPE_VAR_REDECLARED_IN_NESTED_CLASS: Final = ErrorMessage( + 'Type variable "{}" is bound by an outer class', codes.VALID_TYPE +) + +TYPE_ALIAS_WITH_YIELD_EXPRESSION: Final = ErrorMessage( + "Yield expression cannot be used within a type alias", codes.SYNTAX +) + +TYPE_ALIAS_WITH_NAMED_EXPRESSION: Final = ErrorMessage( + "Named expression cannot be used within a type alias", codes.SYNTAX +) + +TYPE_ALIAS_WITH_AWAIT_EXPRESSION: Final = ErrorMessage( + "Await expression cannot be used within a type alias", codes.SYNTAX +) diff --git a/micromamba_root/Lib/site-packages/mypy/messages.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/messages.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e2e629ee755f1f511c3c1ad36b414cd3256834d4 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/messages.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/messages.py b/micromamba_root/Lib/site-packages/mypy/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..51bb0b7ee9be62e0208540dedb30992d89bbcce1 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/messages.py @@ -0,0 +1,3427 @@ +"""Facilities for generating error messages during type checking. + +Don't add any non-trivial message construction logic to the type +checker, as it can compromise clarity and make messages less +consistent. Add such logic to this module instead. Literal messages, including those +with format args, should be defined as constants in mypy.message_registry. + +Historically we tried to avoid all message string literals in the type +checker but we are moving away from this convention. +""" + +from __future__ import annotations + +import difflib +import itertools +import re +from collections.abc import Callable, Collection, Iterable, Iterator, Sequence +from contextlib import contextmanager +from textwrap import dedent +from typing import Any, Final, cast + +import mypy.typeops +from mypy import errorcodes as codes, message_registry +from mypy.erasetype import erase_type +from mypy.errorcodes import ErrorCode +from mypy.errors import ( + ErrorInfo, + Errors, + ErrorWatcher, + IterationDependentErrors, + IterationErrorWatcher, + NonOverlapErrorInfo, +) +from mypy.nodes import ( + ARG_NAMED, + ARG_NAMED_OPT, + ARG_OPT, + ARG_POS, + ARG_STAR, + ARG_STAR2, + CONTRAVARIANT, + COVARIANT, + SYMBOL_FUNCBASE_TYPES, + ArgKind, + CallExpr, + Context, + Expression, + FuncDef, + IndexExpr, + MypyFile, + NameExpr, + ReturnStmt, + StrExpr, + SymbolNode, + SymbolTable, + TypeInfo, + Var, + get_func_def, + reverse_builtin_aliases, +) +from mypy.operators import op_methods, op_methods_to_symbols +from mypy.options import Options +from mypy.subtypes import ( + IS_CLASS_OR_STATIC, + IS_CLASSVAR, + IS_EXPLICIT_SETTER, + IS_SETTABLE, + IS_VAR, + find_member, + get_member_flags, + is_same_type, + is_subtype, +) +from mypy.typeops import separate_union_literals +from mypy.types import ( + AnyType, + CallableType, + DeletedType, + FunctionLike, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeStrVisitor, + TypeType, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + flatten_nested_unions, + get_proper_type, + get_proper_types, +) +from mypy.typetraverser import TypeTraverserVisitor +from mypy.util import plural_s, unmangle + +TYPES_FOR_UNIMPORTED_HINTS: Final = { + "typing.Any", + "typing.Callable", + "typing.Dict", + "typing.Iterable", + "typing.Iterator", + "typing.List", + "typing.Optional", + "typing.Set", + "typing.Tuple", + "typing.TypeVar", + "typing.Union", + "typing.cast", +} + + +ARG_CONSTRUCTOR_NAMES: Final = { + ARG_POS: "Arg", + ARG_OPT: "DefaultArg", + ARG_NAMED: "NamedArg", + ARG_NAMED_OPT: "DefaultNamedArg", + ARG_STAR: "VarArg", + ARG_STAR2: "KwArg", +} + + +# Map from the full name of a missing definition to the test fixture (under +# test-data/unit/fixtures/) that provides the definition. This is used for +# generating better error messages when running mypy tests only. +SUGGESTED_TEST_FIXTURES: Final = { + "builtins.set": "set.pyi", + "builtins.tuple": "tuple.pyi", + "builtins.bool": "bool.pyi", + "builtins.Exception": "exception.pyi", + "builtins.BaseException": "exception.pyi", + "builtins.isinstance": "isinstancelist.pyi", + "builtins.property": "property.pyi", + "builtins.classmethod": "classmethod.pyi", + "typing._SpecialForm": "typing-medium.pyi", +} + +UNSUPPORTED_NUMBERS_TYPES: Final = { + "numbers.Number", + "numbers.Complex", + "numbers.Real", + "numbers.Rational", + "numbers.Integral", +} + +MAX_TUPLE_ITEMS = 10 +MAX_UNION_ITEMS = 10 + + +class MessageBuilder: + """Helper class for reporting type checker error messages with parameters. + + The methods of this class need to be provided with the context within a + file; the errors member manages the wider context. + + IDEA: Support a 'verbose mode' that includes full information about types + in error messages and that may otherwise produce more detailed error + messages. + """ + + # Report errors using this instance. It knows about the current file and + # import context. + errors: Errors + + modules: dict[str, MypyFile] + + # Hack to deduplicate error messages from union types + _disable_type_names: list[bool] + + def __init__(self, errors: Errors, modules: dict[str, MypyFile]) -> None: + self.errors = errors + self.options = errors.options + self.modules = modules + self._disable_type_names = [] + + # + # Helpers + # + + def filter_errors( + self, + *, + filter_errors: bool | Callable[[str, ErrorInfo], bool] = True, + save_filtered_errors: bool = False, + filter_deprecated: bool = False, + filter_revealed_type: bool = False, + ) -> ErrorWatcher: + return ErrorWatcher( + self.errors, + filter_errors=filter_errors, + save_filtered_errors=save_filtered_errors, + filter_deprecated=filter_deprecated, + filter_revealed_type=filter_revealed_type, + ) + + def add_errors(self, errors: list[ErrorInfo]) -> None: + """Add errors in messages to this builder.""" + for info in errors: + self.errors.add_error_info(info) + + @contextmanager + def disable_type_names(self) -> Iterator[None]: + self._disable_type_names.append(True) + try: + yield + finally: + self._disable_type_names.pop() + + def are_type_names_disabled(self) -> bool: + return len(self._disable_type_names) > 0 and self._disable_type_names[-1] + + def prefer_simple_messages(self) -> bool: + """Should we generate simple/fast error messages? + + If errors aren't shown to the user, we don't want to waste cycles producing + complex error messages. + """ + return self.errors.prefer_simple_messages() + + def span_from_context(self, ctx: Context) -> Iterable[int]: + """This determines where a type: ignore for a given context has effect.""" + if not isinstance(ctx, Expression): + return [ctx.line] + return range(ctx.line, (ctx.end_line or ctx.line) + 1) + + def report( + self, + msg: str, + context: Context, + severity: str, + offset: int = 0, + *, + code: ErrorCode | None = None, + origin_context: Context | None, + parent_error: ErrorInfo | None = None, + ) -> ErrorInfo: + """Report an error or note (unless disabled). + + Note that context controls where error is reported, while origin_context + controls where # type: ignore comments have effect. + """ + + origin_span = self.span_from_context(context) + if origin_context is not None: + origin_span = itertools.chain(origin_span, self.span_from_context(origin_context)) + + return self.errors.report( + context.line if context else -1, + context.column if context else -1, + msg, + code=code, + severity=severity, + offset=offset, + origin_span=origin_span, + end_line=context.end_line if context else -1, + end_column=context.end_column if context else -1, + parent_error=parent_error, + ) + + def fail( + self, + msg: str, + context: Context, + *, + code: ErrorCode | None = None, + origin_context: Context | None = None, + ) -> ErrorInfo: + """Report an error message (unless disabled).""" + return self.report(msg, context, "error", code=code, origin_context=origin_context) + + def note( + self, + msg: str, + context: Context, + offset: int = 0, + *, + code: ErrorCode | None = None, + origin_context: Context | None = None, + parent_error: ErrorInfo | None = None, + ) -> None: + """Report a note (unless disabled).""" + self.report( + msg, + context, + "note", + offset=offset, + code=code, + origin_context=origin_context, + parent_error=parent_error, + ) + + def note_multiline( + self, + messages: str, + context: Context, + offset: int = 0, + *, + code: ErrorCode | None = None, + origin_context: Context | None = None, + parent_error: ErrorInfo | None = None, + ) -> None: + """Report as many notes as lines in the message (unless disabled).""" + for msg in dedent(messages.lstrip("\n")).splitlines(): + self.report( + msg, + context, + "note", + offset, + code=code, + origin_context=origin_context, + parent_error=parent_error, + ) + + # + # Specific operations + # + + # The following operations are for generating specific error messages. They + # get some information as arguments, and they build an error message based + # on them. + + def has_no_attr( + self, + original_type: Type, + typ: Type, + member: str, + context: Context, + module_symbol_table: SymbolTable | None = None, + ) -> ErrorCode | None: + """Report a missing or non-accessible member. + + original_type is the top-level type on which the error occurred. + typ is the actual type that is missing the member. These can be + different, e.g., in a union, original_type will be the union and typ + will be the specific item in the union that does not have the member + attribute. + + 'module_symbol_table' is passed to this function if the type for which we + are trying to get a member was originally a module. The SymbolTable allows + us to look up and suggests attributes of the module since they are not + directly available on original_type + + If member corresponds to an operator, use the corresponding operator + name in the messages. Return the error code that was produced, if any. + """ + original_type = get_proper_type(original_type) + typ = get_proper_type(typ) + + if isinstance(original_type, Instance) and original_type.type.has_readable_member(member): + self.fail(f'Member "{member}" is not assignable', context) + return None + elif member == "__contains__": + self.fail( + f"Unsupported right operand type for in ({format_type(original_type, self.options)})", + context, + code=codes.OPERATOR, + ) + return codes.OPERATOR + elif member in op_methods.values(): + # Access to a binary operator member (e.g. _add). This case does + # not handle indexing operations. + for op, method in op_methods.items(): + if method == member: + self.unsupported_left_operand(op, original_type, context) + return codes.OPERATOR + elif member == "__neg__": + self.fail( + f"Unsupported operand type for unary - ({format_type(original_type, self.options)})", + context, + code=codes.OPERATOR, + ) + return codes.OPERATOR + elif member == "__pos__": + self.fail( + f"Unsupported operand type for unary + ({format_type(original_type, self.options)})", + context, + code=codes.OPERATOR, + ) + return codes.OPERATOR + elif member == "__invert__": + self.fail( + f"Unsupported operand type for ~ ({format_type(original_type, self.options)})", + context, + code=codes.OPERATOR, + ) + return codes.OPERATOR + elif member == "__getitem__": + # Indexed get. + # TODO: Fix this consistently in format_type + if isinstance(original_type, FunctionLike) and original_type.is_type_obj(): + self.fail( + "The type {} is not generic and not indexable".format( + format_type(original_type, self.options) + ), + context, + ) + return None + else: + self.fail( + f"Value of type {format_type(original_type, self.options)} is not indexable", + context, + code=codes.INDEX, + ) + return codes.INDEX + elif member == "__setitem__": + # Indexed set. + self.fail( + "Unsupported target for indexed assignment ({})".format( + format_type(original_type, self.options) + ), + context, + code=codes.INDEX, + ) + return codes.INDEX + elif member == "__call__": + if isinstance(original_type, Instance) and ( + original_type.type.fullname == "builtins.function" + ): + # "'function' not callable" is a confusing error message. + # Explain that the problem is that the type of the function is not known. + self.fail("Cannot call function of unknown type", context, code=codes.OPERATOR) + return codes.OPERATOR + else: + self.fail( + message_registry.NOT_CALLABLE.format(format_type(original_type, self.options)), + context, + code=codes.OPERATOR, + ) + return codes.OPERATOR + else: + # The non-special case: a missing ordinary attribute. + extra = "" + if member == "__iter__": + extra = " (not iterable)" + elif member == "__aiter__": + extra = " (not async iterable)" + if not self.are_type_names_disabled(): + failed = False + if isinstance(original_type, Instance) and original_type.type.names: + if ( + module_symbol_table is not None + and member in module_symbol_table + and not module_symbol_table[member].module_public + ): + self.fail( + f"{format_type(original_type, self.options, module_names=True)} does not " + f'explicitly export attribute "{member}"', + context, + code=codes.ATTR_DEFINED, + ) + failed = True + else: + alternatives = set(original_type.type.names.keys()) + if module_symbol_table is not None: + alternatives |= { + k for k, v in module_symbol_table.items() if v.module_public + } + # Rare but possible, see e.g. testNewAnalyzerCyclicDefinitionCrossModule + alternatives.discard(member) + + matches = [m for m in COMMON_MISTAKES.get(member, []) if m in alternatives] + matches.extend(best_matches(member, alternatives, n=3)) + if member == "__aiter__" and matches == ["__iter__"]: + matches = [] # Avoid misleading suggestion + if matches: + self.fail( + '{} has no attribute "{}"; maybe {}?{}'.format( + format_type(original_type, self.options), + member, + pretty_seq(matches, "or"), + extra, + ), + context, + code=codes.ATTR_DEFINED, + ) + failed = True + if not failed: + self.fail( + '{} has no attribute "{}"{}'.format( + format_type(original_type, self.options), member, extra + ), + context, + code=codes.ATTR_DEFINED, + ) + return codes.ATTR_DEFINED + elif isinstance(original_type, UnionType): + # The checker passes "object" in lieu of "None" for attribute + # checks, so we manually convert it back. + typ_format, orig_type_format = format_type_distinctly( + typ, original_type, options=self.options + ) + if typ_format == '"object"' and any( + type(item) == NoneType for item in original_type.items + ): + typ_format = '"None"' + self.fail( + 'Item {} of {} has no attribute "{}"{}'.format( + typ_format, orig_type_format, member, extra + ), + context, + code=codes.UNION_ATTR, + ) + return codes.UNION_ATTR + elif isinstance(original_type, TypeVarType): + bound = get_proper_type(original_type.upper_bound) + if isinstance(bound, UnionType): + typ_fmt, bound_fmt = format_type_distinctly(typ, bound, options=self.options) + original_type_fmt = format_type(original_type, self.options) + self.fail( + "Item {} of the upper bound {} of type variable {} has no " + 'attribute "{}"{}'.format( + typ_fmt, bound_fmt, original_type_fmt, member, extra + ), + context, + code=codes.UNION_ATTR, + ) + return codes.UNION_ATTR + else: + self.fail( + '{} has no attribute "{}"{}'.format( + format_type(original_type, self.options), member, extra + ), + context, + code=codes.ATTR_DEFINED, + ) + return codes.ATTR_DEFINED + return None + + def unsupported_operand_types( + self, + op: str, + left_type: Any, + right_type: Any, + context: Context, + *, + code: ErrorCode = codes.OPERATOR, + ) -> ErrorInfo: + """Report unsupported operand types for a binary operation. + + Types can be Type objects or strings. + """ + left_str = "" + if isinstance(left_type, str): + left_str = left_type + else: + left_str = format_type(left_type, self.options) + + right_str = "" + if isinstance(right_type, str): + right_str = right_type + else: + right_str = format_type(right_type, self.options) + + if self.are_type_names_disabled(): + msg = f"Unsupported operand types for {op} (likely involving Union)" + else: + msg = f"Unsupported operand types for {op} ({left_str} and {right_str})" + return self.fail(msg, context, code=code) + + def unsupported_left_operand(self, op: str, typ: Type, context: Context) -> None: + if self.are_type_names_disabled(): + msg = f"Unsupported left operand type for {op} (some union)" + else: + msg = f"Unsupported left operand type for {op} ({format_type(typ, self.options)})" + self.fail(msg, context, code=codes.OPERATOR) + + def not_callable(self, typ: Type, context: Context) -> Type: + self.fail(message_registry.NOT_CALLABLE.format(format_type(typ, self.options)), context) + return AnyType(TypeOfAny.from_error) + + def untyped_function_call(self, callee: CallableType, context: Context) -> Type: + name = callable_name(callee) or "(unknown)" + self.fail( + f"Call to untyped function {name} in typed context", + context, + code=codes.NO_UNTYPED_CALL, + ) + return AnyType(TypeOfAny.from_error) + + def incompatible_argument( + self, + n: int, + m: int, + callee: CallableType, + arg_type: Type, + arg_kind: ArgKind, + object_type: Type | None, + context: Context, + outer_context: Context, + ) -> ErrorInfo: + """Report an error about an incompatible argument type. + + The argument type is arg_type, argument number is n and the + callee type is 'callee'. If the callee represents a method + that corresponds to an operator, use the corresponding + operator name in the messages. + + Return the error code that used for the argument (multiple error + codes are possible). + """ + arg_type = get_proper_type(arg_type) + + target = "" + callee_name = callable_name(callee) + if callee_name is not None: + name = callee_name + if object_type is not None: + base = format_type(object_type, self.options) + else: + base = extract_type(name) + + if name.startswith('"__getitem__" of'): + return self.invalid_index_type( + arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX + ) + elif name.startswith('"__setitem__" of'): + if n == 1: + return self.invalid_index_type( + arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX + ) + else: + arg_type_str, callee_type_str = format_type_distinctly( + arg_type, callee.arg_types[n - 1], options=self.options + ) + info = ( + f" (expression has type {arg_type_str}, target has type {callee_type_str})" + ) + error_msg = ( + message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT.with_additional_msg(info) + ) + return self.fail(error_msg.value, context, code=error_msg.code) + elif name.startswith('"__'): + for method, op in op_methods_to_symbols.items(): + for variant in method, "__r" + method[2:]: + # FIX: do not rely on textual formatting + if name.startswith(f'"{variant}" of'): + if op == "in" or variant != method: + # Reversed order of base/argument. + return self.unsupported_operand_types( + op, arg_type, base, context, code=codes.OPERATOR + ) + else: + return self.unsupported_operand_types( + op, base, arg_type, context, code=codes.OPERATOR + ) + + target = f"to {name} " + + msg = "" + code = codes.MISC + notes: list[str] = [] + if callee_name == "": + name = callee_name[1:-1] + n -= 1 + actual_type_str, expected_type_str = format_type_distinctly( + arg_type, callee.arg_types[0], options=self.options + ) + msg = "{} item {} has incompatible type {}; expected {}".format( + name.title(), n, actual_type_str, expected_type_str + ) + code = codes.LIST_ITEM + elif callee_name == "" and isinstance( + get_proper_type(callee.arg_types[n - 1]), TupleType + ): + name = callee_name[1:-1] + n -= 1 + key_type, value_type = cast(TupleType, arg_type).items + expected_key_type, expected_value_type = cast(TupleType, callee.arg_types[n]).items + + # don't increase verbosity unless there is need to do so + if is_subtype(key_type, expected_key_type): + key_type_str = format_type(key_type, self.options) + expected_key_type_str = format_type(expected_key_type, self.options) + else: + key_type_str, expected_key_type_str = format_type_distinctly( + key_type, expected_key_type, options=self.options + ) + if is_subtype(value_type, expected_value_type): + value_type_str = format_type(value_type, self.options) + expected_value_type_str = format_type(expected_value_type, self.options) + else: + value_type_str, expected_value_type_str = format_type_distinctly( + value_type, expected_value_type, options=self.options + ) + + msg = "{} entry {} has incompatible type {}: {}; expected {}: {}".format( + name.title(), + n, + key_type_str, + value_type_str, + expected_key_type_str, + expected_value_type_str, + ) + code = codes.DICT_ITEM + elif callee_name == "": + value_type_str, expected_value_type_str = format_type_distinctly( + arg_type, callee.arg_types[n - 1], options=self.options + ) + msg = "Unpacked dict entry {} has incompatible type {}; expected {}".format( + n - 1, value_type_str, expected_value_type_str + ) + code = codes.DICT_ITEM + elif callee_name == "": + actual_type_str, expected_type_str = map( + strip_quotes, + format_type_distinctly(arg_type, callee.arg_types[0], options=self.options), + ) + msg = "List comprehension has incompatible type List[{}]; expected List[{}]".format( + actual_type_str, expected_type_str + ) + elif callee_name == "": + actual_type_str, expected_type_str = map( + strip_quotes, + format_type_distinctly(arg_type, callee.arg_types[0], options=self.options), + ) + msg = "Set comprehension has incompatible type Set[{}]; expected Set[{}]".format( + actual_type_str, expected_type_str + ) + elif callee_name == "": + actual_type_str, expected_type_str = format_type_distinctly( + arg_type, callee.arg_types[n - 1], options=self.options + ) + msg = ( + "{} expression in dictionary comprehension has incompatible type {}; " + "expected type {}" + ).format("Key" if n == 1 else "Value", actual_type_str, expected_type_str) + elif callee_name == "": + actual_type_str, expected_type_str = format_type_distinctly( + arg_type, callee.arg_types[0], options=self.options + ) + msg = "Generator has incompatible item type {}; expected {}".format( + actual_type_str, expected_type_str + ) + else: + if self.prefer_simple_messages(): + msg = "Argument has incompatible type" + else: + try: + expected_type = callee.arg_types[m - 1] + except IndexError: # Varargs callees + expected_type = callee.arg_types[-1] + arg_type_str, expected_type_str = format_type_distinctly( + arg_type, expected_type, bare=True, options=self.options + ) + if arg_kind == ARG_STAR: + arg_type_str = "*" + arg_type_str + elif arg_kind == ARG_STAR2: + arg_type_str = "**" + arg_type_str + + # For function calls with keyword arguments, display the argument name rather + # than the number. + arg_label = str(n) + if isinstance(outer_context, CallExpr) and len(outer_context.arg_names) >= n: + arg_name = outer_context.arg_names[n - 1] + if arg_name is not None: + arg_label = f'"{arg_name}"' + if ( + arg_kind == ARG_STAR2 + and isinstance(arg_type, TypedDictType) + and m <= len(callee.arg_names) + and callee.arg_names[m - 1] is not None + and callee.arg_kinds[m - 1] != ARG_STAR2 + ): + arg_name = callee.arg_names[m - 1] + assert arg_name is not None + arg_type_str, expected_type_str = format_type_distinctly( + arg_type.items[arg_name], expected_type, bare=True, options=self.options + ) + arg_label = f'"{arg_name}"' + if isinstance(outer_context, IndexExpr) and isinstance( + outer_context.index, StrExpr + ): + msg = 'Value of "{}" has incompatible type {}; expected {}'.format( + outer_context.index.value, + quote_type_string(arg_type_str), + quote_type_string(expected_type_str), + ) + else: + msg = "Argument {} {}has incompatible type {}; expected {}".format( + arg_label, + target, + quote_type_string(arg_type_str), + quote_type_string(expected_type_str), + ) + expected_type = get_proper_type(expected_type) + if isinstance(expected_type, UnionType): + expected_types = get_proper_types(expected_type.items) + else: + expected_types = [expected_type] + for type in expected_types: + if isinstance(arg_type, Instance) and isinstance(type, Instance): + notes = append_invariance_notes(notes, arg_type, type) + notes = append_numbers_notes(notes, arg_type, type) + object_type = get_proper_type(object_type) + if isinstance(object_type, TypedDictType): + code = codes.TYPEDDICT_ITEM + else: + code = codes.ARG_TYPE + error = self.fail(msg, context, code=code) + if notes: + for note_msg in notes: + self.note(note_msg, context, code=code) + return error + + def incompatible_argument_note( + self, + original_caller_type: ProperType, + callee_type: ProperType, + context: Context, + parent_error: ErrorInfo, + ) -> None: + if self.prefer_simple_messages(): + return + if isinstance( + original_caller_type, (Instance, TupleType, TypedDictType, TypeType, CallableType) + ): + if isinstance(callee_type, Instance) and callee_type.type.is_protocol: + self.report_protocol_problems( + original_caller_type, callee_type, context, parent_error=parent_error + ) + if isinstance(callee_type, UnionType): + for item in callee_type.items: + item = get_proper_type(item) + if isinstance(item, Instance) and item.type.is_protocol: + self.report_protocol_problems( + original_caller_type, item, context, parent_error=parent_error + ) + if isinstance(callee_type, CallableType) and isinstance(original_caller_type, Instance): + call = find_member( + "__call__", original_caller_type, original_caller_type, is_operator=True + ) + if call: + self.note_call(original_caller_type, call, context, code=parent_error.code) + if isinstance(callee_type, Instance) and callee_type.type.is_protocol: + call = find_member("__call__", callee_type, callee_type, is_operator=True) + if call: + self.note_call(callee_type, call, context, code=parent_error.code) + self.maybe_note_concatenate_pos_args( + original_caller_type, callee_type, context, parent_error.code + ) + + def maybe_note_concatenate_pos_args( + self, + original_caller_type: ProperType, + callee_type: ProperType, + context: Context, + code: ErrorCode | None = None, + ) -> None: + # pos-only vs positional can be confusing, with Concatenate + if ( + isinstance(callee_type, CallableType) + and isinstance(original_caller_type, CallableType) + and (original_caller_type.from_concatenate or callee_type.from_concatenate) + ): + names: list[str] = [] + for c, o in zip( + callee_type.formal_arguments(), original_caller_type.formal_arguments() + ): + if None in (c.pos, o.pos): + # non-positional + continue + if c.name != o.name and c.name is None and o.name is not None: + names.append(o.name) + + if names: + missing_arguments = '"' + '", "'.join(names) + '"' + self.note( + f'This is likely because "{original_caller_type.name}" has named arguments: ' + f"{missing_arguments}. Consider marking them positional-only", + context, + code=code, + ) + + def invalid_index_type( + self, + index_type: Type, + expected_type: Type, + base_str: str, + context: Context, + *, + code: ErrorCode, + ) -> ErrorInfo: + index_str, expected_str = format_type_distinctly( + index_type, expected_type, options=self.options + ) + return self.fail( + "Invalid index type {} for {}; expected type {}".format( + index_str, base_str, expected_str + ), + context, + code=code, + ) + + def readonly_keys_mutated(self, keys: set[str], context: Context) -> None: + if len(keys) == 1: + suffix = "is" + else: + suffix = "are" + self.fail( + "ReadOnly {} TypedDict {} mutated".format(format_key_list(sorted(keys)), suffix), + code=codes.TYPEDDICT_READONLY_MUTATED, + context=context, + ) + + def too_few_arguments( + self, callee: CallableType, context: Context, argument_names: Sequence[str | None] | None + ) -> None: + if self.prefer_simple_messages(): + msg = "Too few arguments" + elif argument_names is not None: + num_positional_args = sum(k is None for k in argument_names) + arguments_left = callee.arg_names[num_positional_args : callee.min_args] + diff = [k for k in arguments_left if k not in argument_names] + if len(diff) == 1: + msg = "Missing positional argument" + else: + msg = "Missing positional arguments" + callee_name = callable_name(callee) + if callee_name is not None and diff and all(d is not None for d in diff): + args = '", "'.join(cast(list[str], diff)) + msg += f' "{args}" in call to {callee_name}' + else: + msg = "Too few arguments" + for_function(callee) + + else: + msg = "Too few arguments" + for_function(callee) + self.fail(msg, context, code=codes.CALL_ARG) + + def missing_named_argument(self, callee: CallableType, context: Context, name: str) -> None: + msg = f'Missing named argument "{name}"' + for_function(callee) + self.fail(msg, context, code=codes.CALL_ARG) + self.note_defined_here(callee, context) + + def too_many_arguments(self, callee: CallableType, context: Context) -> None: + if self.prefer_simple_messages(): + msg = "Too many arguments" + else: + msg = "Too many arguments" + for_function(callee) + self.fail(msg, context, code=codes.CALL_ARG) + self.maybe_note_about_special_args(callee, context) + + def too_many_arguments_from_typed_dict( + self, callee: CallableType, arg_type: TypedDictType, context: Context + ) -> None: + # Try to determine the name of the extra argument. + for key in arg_type.items: + if key not in callee.arg_names: + msg = f'Extra argument "{key}" from **args' + for_function(callee) + break + else: + self.too_many_arguments(callee, context) + return + self.fail(msg, context) + + def too_many_positional_arguments(self, callee: CallableType, context: Context) -> None: + if self.prefer_simple_messages(): + msg = "Too many positional arguments" + else: + msg = "Too many positional arguments" + for_function(callee) + self.fail(msg, context) + self.maybe_note_about_special_args(callee, context) + + def maybe_note_about_special_args(self, callee: CallableType, context: Context) -> None: + if self.prefer_simple_messages(): + return + # https://github.com/python/mypy/issues/11309 + first_arg = get_first_arg(callee) + if first_arg and first_arg not in {"self", "cls", "mcs"}: + self.note( + "Looks like the first special argument in a method " + 'is not named "self", "cls", or "mcs", ' + "maybe it is missing?", + context, + ) + + def unexpected_keyword_argument_for_function( + self, for_func: str, name: str, context: Context, *, matches: list[str] | None = None + ) -> None: + msg = f'Unexpected keyword argument "{name}"' + for_func + if matches: + msg += f"; did you mean {pretty_seq(matches, 'or')}?" + self.fail(msg, context, code=codes.CALL_ARG) + + def unexpected_keyword_argument( + self, callee: CallableType, name: str, arg_type: Type, context: Context + ) -> None: + # Suggest intended keyword, look for type match else fallback on any match. + matching_type_args = [] + not_matching_type_args = [] + for i, kwarg_type in enumerate(callee.arg_types): + callee_arg_name = callee.arg_names[i] + if callee_arg_name is not None and callee.arg_kinds[i] != ARG_STAR: + if is_subtype(arg_type, kwarg_type): + matching_type_args.append(callee_arg_name) + else: + not_matching_type_args.append(callee_arg_name) + matches = best_matches(name, matching_type_args, n=3) + if not matches: + matches = best_matches(name, not_matching_type_args, n=3) + self.unexpected_keyword_argument_for_function( + for_function(callee), name, context, matches=matches + ) + self.note_defined_here(callee, context) + + def note_defined_here(self, callee: CallableType, context: Context) -> None: + module = find_defining_module(self.modules, callee) + if ( + module + and module.path != self.errors.file + and module.fullname not in ("builtins", "typing") + ): + assert callee.definition is not None + fname = callable_name(callee) + if not fname: # an alias to function with a different name + fname = "Called function" + else: + fname = fname.split(" of ")[0] # use short method names in the note + self.note(f'{fname} defined in "{module.fullname}"', context, code=codes.CALL_ARG) + + def duplicate_argument_value(self, callee: CallableType, index: int, context: Context) -> None: + self.fail( + '{} gets multiple values for keyword argument "{}"'.format( + callable_name(callee) or "Function", callee.arg_names[index] + ), + context, + ) + + def does_not_return_value(self, callee_type: Type | None, context: Context) -> None: + """Report an error about use of an unusable type.""" + callee_type = get_proper_type(callee_type) + callee_name = callable_name(callee_type) if isinstance(callee_type, FunctionLike) else None + name = callee_name or "Function" + message = f"{name} does not return a value (it only ever returns None)" + self.fail(message, context, code=codes.FUNC_RETURNS_VALUE) + + def deleted_as_rvalue(self, typ: DeletedType, context: Context) -> None: + """Report an error about using an deleted type as an rvalue.""" + if typ.source is None: + s = "" + else: + s = f' "{typ.source}"' + self.fail(f"Trying to read deleted variable{s}", context) + + def deleted_as_lvalue(self, typ: DeletedType, context: Context) -> None: + """Report an error about using an deleted type as an lvalue. + + Currently, this only occurs when trying to assign to an + exception variable outside the local except: blocks. + """ + if typ.source is None: + s = "" + else: + s = f' "{typ.source}"' + self.fail(f"Assignment to variable{s} outside except: block", context) + + def no_variant_matches_arguments( + self, + overload: Overloaded, + arg_types: list[Type], + context: Context, + *, + code: ErrorCode | None = None, + ) -> None: + code = code or codes.CALL_OVERLOAD + name = callable_name(overload) + if name: + name_str = f" of {name}" + else: + name_str = "" + arg_types_str = ", ".join(format_type(arg, self.options) for arg in arg_types) + num_args = len(arg_types) + if num_args == 0: + self.fail( + f"All overload variants{name_str} require at least one argument", + context, + code=code, + ) + elif num_args == 1: + self.fail( + f"No overload variant{name_str} matches argument type {arg_types_str}", + context, + code=code, + ) + else: + self.fail( + f"No overload variant{name_str} matches argument types {arg_types_str}", + context, + code=code, + ) + + self.note(f"Possible overload variant{plural_s(len(overload.items))}:", context, code=code) + for item in overload.items: + self.note(pretty_callable(item, self.options), context, offset=4, code=code) + + def wrong_number_values_to_unpack( + self, provided: int, expected: int, context: Context + ) -> None: + if provided < expected: + if provided == 1: + self.fail(f"Need more than 1 value to unpack ({expected} expected)", context) + else: + self.fail( + f"Need more than {provided} values to unpack ({expected} expected)", context + ) + elif provided > expected: + self.fail( + f"Too many values to unpack ({expected} expected, {provided} provided)", context + ) + + def unpacking_strings_disallowed(self, context: Context) -> None: + self.fail("Unpacking a string is disallowed", context, code=codes.STR_UNPACK) + + def type_not_iterable(self, type: Type, context: Context) -> None: + self.fail(f"{format_type(type, self.options)} object is not iterable", context) + + def possible_missing_await(self, context: Context, code: ErrorCode | None) -> None: + self.note('Maybe you forgot to use "await"?', context, code=code) + + def incompatible_operator_assignment(self, op: str, context: Context) -> None: + self.fail(f"Result type of {op} incompatible in assignment", context) + + def overload_signature_incompatible_with_supertype( + self, name: str, name_in_super: str, supertype: str, context: Context + ) -> None: + target = self.override_target(name, name_in_super, supertype) + self.fail( + f'Signature of "{name}" incompatible with {target}', context, code=codes.OVERRIDE + ) + + note_template = 'Overload variants must be defined in the same order as they are in "{}"' + self.note(note_template.format(supertype), context, code=codes.OVERRIDE) + + def incompatible_setter_override( + self, defn: Context, typ: Type, original_type: Type, base: TypeInfo + ) -> None: + self.fail("Incompatible override of a setter type", defn, code=codes.OVERRIDE) + base_str, override_str = format_type_distinctly(original_type, typ, options=self.options) + self.note( + f' (base class "{base.name}" defined the type as {base_str},', + defn, + code=codes.OVERRIDE, + ) + self.note(f" override has type {override_str})", defn, code=codes.OVERRIDE) + if is_subtype(typ, original_type): + self.note(" Setter types should behave contravariantly", defn, code=codes.OVERRIDE) + + def signature_incompatible_with_supertype( + self, + name: str, + name_in_super: str, + supertype: str, + context: Context, + *, + original: ProperType, + override: ProperType, + ) -> None: + target = self.override_target(name, name_in_super, supertype) + error = self.fail( + f'Signature of "{name}" incompatible with {target}', context, code=codes.OVERRIDE + ) + + original_str, override_str = format_type_distinctly( + original, override, options=self.options, bare=True + ) + + INCLUDE_DECORATOR = True # Include @classmethod and @staticmethod decorators, if any + ALIGN_OFFSET = 1 # One space, to account for the difference between error and note + OFFSET = 4 # Four spaces, so that notes will look like this: + # error: Signature of "f" incompatible with supertype "A" + # note: Superclass: + # note: def f(self) -> str + # note: Subclass: + # note: def f(self, x: str) -> None + self.note("Superclass:", context, offset=ALIGN_OFFSET + OFFSET, parent_error=error) + if isinstance(original, (CallableType, Overloaded)): + self.pretty_callable_or_overload( + original, + context, + offset=ALIGN_OFFSET + 2 * OFFSET, + add_class_or_static_decorator=INCLUDE_DECORATOR, + parent_error=error, + ) + else: + self.note(original_str, context, offset=ALIGN_OFFSET + 2 * OFFSET, parent_error=error) + + self.note("Subclass:", context, offset=ALIGN_OFFSET + OFFSET, parent_error=error) + if isinstance(override, (CallableType, Overloaded)): + self.pretty_callable_or_overload( + override, + context, + offset=ALIGN_OFFSET + 2 * OFFSET, + add_class_or_static_decorator=INCLUDE_DECORATOR, + parent_error=error, + ) + else: + self.note(override_str, context, offset=ALIGN_OFFSET + 2 * OFFSET, parent_error=error) + + def pretty_callable_or_overload( + self, + tp: CallableType | Overloaded, + context: Context, + *, + parent_error: ErrorInfo, + offset: int = 0, + add_class_or_static_decorator: bool = False, + ) -> None: + if isinstance(tp, CallableType): + if add_class_or_static_decorator: + decorator = pretty_class_or_static_decorator(tp) + if decorator is not None: + self.note(decorator, context, offset=offset, parent_error=parent_error) + self.note( + pretty_callable(tp, self.options), + context, + offset=offset, + parent_error=parent_error, + ) + elif isinstance(tp, Overloaded): + self.pretty_overload( + tp, + context, + offset, + add_class_or_static_decorator=add_class_or_static_decorator, + parent_error=parent_error, + ) + + def argument_incompatible_with_supertype( + self, + arg_num: int, + name: str, + type_name: str | None, + name_in_supertype: str, + arg_type_in_supertype: Type, + supertype: str, + context: Context, + origin_context: Context, + ) -> None: + target = self.override_target(name, name_in_supertype, supertype) + arg_type_in_supertype_f = format_type_bare(arg_type_in_supertype, self.options) + self.fail( + 'Argument {} of "{}" is incompatible with {}; ' + 'supertype defines the argument type as "{}"'.format( + arg_num, name, target, arg_type_in_supertype_f + ), + context, + code=codes.OVERRIDE, + origin_context=origin_context, + ) + if name != "__post_init__": + # `__post_init__` is special, it can be incompatible by design. + # So, this note is misleading. + invariant_message = """ + This violates the Liskov substitution principle + See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides + """ + self.note_multiline( + invariant_message, context, code=codes.OVERRIDE, origin_context=origin_context + ) + if name == "__eq__" and type_name: + eq_message = """ + It is recommended for "__eq__" to work with arbitrary objects, for example: + def __eq__(self, other: object) -> bool: + if not isinstance(other, {class_name}): + return NotImplemented + return + """.format(class_name=type_name) + self.note_multiline( + eq_message, context, code=codes.OVERRIDE, origin_context=origin_context + ) + + def return_type_incompatible_with_supertype( + self, + name: str, + name_in_supertype: str, + supertype: str, + original: Type, + override: Type, + context: Context, + ) -> None: + target = self.override_target(name, name_in_supertype, supertype) + override_str, original_str = format_type_distinctly( + override, original, options=self.options + ) + self.fail( + 'Return type {} of "{}" incompatible with return type {} in {}'.format( + override_str, name, original_str, target + ), + context, + code=codes.OVERRIDE, + ) + + original = get_proper_type(original) + override = get_proper_type(override) + if ( + isinstance(original, Instance) + and isinstance(override, Instance) + and override.type.fullname == "typing.AsyncIterator" + and original.type.fullname == "typing.Coroutine" + and len(original.args) == 3 + and original.args[2] == override + ): + self.note(f'Consider declaring "{name}" in {target} without "async"', context) + self.note( + "See https://mypy.readthedocs.io/en/stable/more_types.html#asynchronous-iterators", + context, + ) + + def override_target(self, name: str, name_in_super: str, supertype: str) -> str: + target = f'supertype "{supertype}"' + if name_in_super != name: + target = f'"{name_in_super}" of {target}' + return target + + def incompatible_type_application( + self, min_arg_count: int, max_arg_count: int, actual_arg_count: int, context: Context + ) -> None: + if max_arg_count == 0: + self.fail("Type application targets a non-generic function or class", context) + return + + if min_arg_count == max_arg_count: + s = f"{max_arg_count} expected" + else: + s = f"expected between {min_arg_count} and {max_arg_count}" + + if actual_arg_count > max_arg_count: + self.fail(f"Type application has too many types ({s})", context) + else: + self.fail(f"Type application has too few types ({s})", context) + + def could_not_infer_type_arguments( + self, callee_type: CallableType, tv: TypeVarLikeType, context: Context + ) -> None: + callee_name = callable_name(callee_type) + if callee_name is not None: + self.fail( + f"Cannot infer value of type parameter {format_type(tv, self.options)} of {callee_name}", + context, + ) + if callee_name == "": + # Invariance in key type causes more of these errors than we would want. + self.note( + "Try assigning the literal to a variable annotated as dict[, ]", + context, + ) + else: + self.fail("Cannot infer function type argument", context) + + def invalid_var_arg(self, typ: Type, context: Context) -> None: + self.fail("Expected iterable as variadic argument", context) + + def invalid_keyword_var_arg(self, typ: Type, is_mapping: bool, context: Context) -> None: + typ = get_proper_type(typ) + if isinstance(typ, Instance) and is_mapping: + self.fail("Argument after ** must have string keys", context, code=codes.ARG_TYPE) + else: + self.fail( + f"Argument after ** must be a mapping, not {format_type(typ, self.options)}", + context, + code=codes.ARG_TYPE, + ) + + def undefined_in_superclass(self, member: str, context: Context) -> None: + self.fail(f'"{member}" undefined in superclass', context) + + def variable_may_be_undefined(self, name: str, context: Context) -> None: + self.fail(f'Name "{name}" may be undefined', context, code=codes.POSSIBLY_UNDEFINED) + + def var_used_before_def(self, name: str, context: Context) -> None: + self.fail(f'Name "{name}" is used before definition', context, code=codes.USED_BEFORE_DEF) + + def first_argument_for_super_must_be_type(self, actual: Type, context: Context) -> None: + actual = get_proper_type(actual) + if isinstance(actual, Instance): + # Don't include type of instance, because it can look confusingly like a type + # object. + type_str = "a non-type instance" + else: + type_str = format_type(actual, self.options) + self.fail( + f'Argument 1 for "super" must be a type object; got {type_str}', + context, + code=codes.ARG_TYPE, + ) + + def unsafe_super(self, method: str, cls: str, ctx: Context) -> None: + self.fail( + f'Call to abstract method "{method}" of "{cls}" with trivial body via super() is unsafe', + ctx, + code=codes.SAFE_SUPER, + ) + + def too_few_string_formatting_arguments(self, context: Context) -> None: + self.fail("Not enough arguments for format string", context, code=codes.STRING_FORMATTING) + + def too_many_string_formatting_arguments(self, context: Context) -> None: + self.fail( + "Not all arguments converted during string formatting", + context, + code=codes.STRING_FORMATTING, + ) + + def unsupported_placeholder(self, placeholder: str, context: Context) -> None: + self.fail( + f'Unsupported format character "{placeholder}"', context, code=codes.STRING_FORMATTING + ) + + def string_interpolation_with_star_and_key(self, context: Context) -> None: + self.fail( + "String interpolation contains both stars and mapping keys", + context, + code=codes.STRING_FORMATTING, + ) + + def requires_int_or_single_byte(self, context: Context, format_call: bool = False) -> None: + self.fail( + '"{}c" requires an integer in range(256) or a single byte'.format( + ":" if format_call else "%" + ), + context, + code=codes.STRING_FORMATTING, + ) + + def requires_int_or_char(self, context: Context, format_call: bool = False) -> None: + self.fail( + '"{}c" requires int or char'.format(":" if format_call else "%"), + context, + code=codes.STRING_FORMATTING, + ) + + def key_not_in_mapping(self, key: str, context: Context) -> None: + self.fail(f'Key "{key}" not found in mapping', context, code=codes.STRING_FORMATTING) + + def string_interpolation_mixing_key_and_non_keys(self, context: Context) -> None: + self.fail( + "String interpolation mixes specifier with and without mapping keys", + context, + code=codes.STRING_FORMATTING, + ) + + def cannot_determine_type(self, name: str, context: Context) -> None: + self.fail(f'Cannot determine type of "{name}"', context, code=codes.HAS_TYPE) + + def cannot_determine_type_in_base(self, name: str, base: str, context: Context) -> None: + self.fail(f'Cannot determine type of "{name}" in base class "{base}"', context) + + def no_formal_self(self, name: str, item: CallableType, context: Context) -> None: + type = format_type(item, self.options) + self.fail( + f'Attribute function "{name}" with type {type} does not accept self argument', context + ) + + def incompatible_self_argument( + self, name: str, arg: Type, sig: CallableType, is_classmethod: bool, context: Context + ) -> None: + kind = "class attribute function" if is_classmethod else "attribute function" + arg_type = format_type(arg, self.options) + sig_type = format_type(sig, self.options) + self.fail( + f'Invalid self argument {arg_type} to {kind} "{name}" with type {sig_type}', context + ) + + def incompatible_conditional_function_def( + self, defn: FuncDef, old_type: FunctionLike, new_type: FunctionLike + ) -> None: + error = self.fail("All conditional function variants must have identical signatures", defn) + if isinstance(old_type, (CallableType, Overloaded)) and isinstance( + new_type, (CallableType, Overloaded) + ): + self.note("Original:", defn) + self.pretty_callable_or_overload(old_type, defn, offset=4, parent_error=error) + self.note("Redefinition:", defn) + self.pretty_callable_or_overload(new_type, defn, offset=4, parent_error=error) + + def cannot_instantiate_abstract_class( + self, class_name: str, abstract_attributes: dict[str, bool], context: Context + ) -> None: + attrs = format_string_list([f'"{a}"' for a in abstract_attributes]) + self.fail( + f'Cannot instantiate abstract class "{class_name}" with abstract ' + f"attribute{plural_s(abstract_attributes)} {attrs}", + context, + code=codes.ABSTRACT, + ) + attrs_with_none = [ + f'"{a}"' + for a, implicit_and_can_return_none in abstract_attributes.items() + if implicit_and_can_return_none + ] + if not attrs_with_none: + return + if len(attrs_with_none) == 1: + note = ( + f"{attrs_with_none[0]} is implicitly abstract because it has an empty function " + "body. If it is not meant to be abstract, explicitly `return` or `return None`." + ) + else: + note = ( + "The following methods were marked implicitly abstract because they have empty " + f"function bodies: {format_string_list(attrs_with_none)}. " + "If they are not meant to be abstract, explicitly `return` or `return None`." + ) + self.note(note, context, code=codes.ABSTRACT) + + def base_class_definitions_incompatible( + self, name: str, base1: TypeInfo, base2: TypeInfo, context: Context + ) -> None: + self.fail( + 'Definition of "{}" in base class "{}" is incompatible ' + 'with definition in base class "{}"'.format(name, base1.name, base2.name), + context, + ) + + def cant_assign_to_method(self, context: Context) -> None: + self.fail(message_registry.CANNOT_ASSIGN_TO_METHOD, context, code=codes.METHOD_ASSIGN) + + def cant_assign_to_classvar(self, name: str, context: Context) -> None: + self.fail(f'Cannot assign to class variable "{name}" via instance', context) + + def no_overridable_method(self, name: str, context: Context) -> None: + self.fail( + f'Method "{name}" is marked as an override, ' + "but no base method was found with this name", + context, + ) + + def explicit_override_decorator_missing( + self, name: str, base_name: str, context: Context + ) -> None: + self.fail( + f'Method "{name}" is not using @override ' + f'but is overriding a method in class "{base_name}"', + context, + code=codes.EXPLICIT_OVERRIDE_REQUIRED, + ) + + def final_cant_override_writable(self, name: str, ctx: Context) -> None: + self.fail(f'Cannot override writable attribute "{name}" with a final one', ctx) + + def cant_override_final(self, name: str, base_name: str, ctx: Context) -> None: + self.fail( + ( + f'Cannot override final attribute "{name}" ' + f'(previously declared in base class "{base_name}")' + ), + ctx, + ) + + def cant_assign_to_final(self, name: str, attr_assign: bool, ctx: Context) -> None: + """Warn about a prohibited assignment to a final attribute. + + Pass `attr_assign=True` if the assignment assigns to an attribute. + """ + kind = "attribute" if attr_assign else "name" + self.fail(f'Cannot assign to final {kind} "{unmangle(name)}"', ctx) + + def protocol_members_cant_be_final(self, ctx: Context) -> None: + self.fail("Protocol member cannot be final", ctx) + + def final_without_value(self, ctx: Context) -> None: + self.fail("Final name must be initialized with a value", ctx) + + def read_only_property(self, name: str, type: TypeInfo, context: Context) -> None: + self.fail(f'Property "{name}" defined in "{type.name}" is read-only', context) + + def incompatible_typevar_value( + self, callee: CallableType, typ: Type, typevar_name: str, context: Context + ) -> None: + self.fail( + message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format( + typevar_name, callable_name(callee) or "function", format_type(typ, self.options) + ), + context, + code=codes.TYPE_VAR, + ) + + def dangerous_comparison(self, left: Type, right: Type, kind: str, ctx: Context) -> None: + # In loops (and similar cases), the same expression might be analysed multiple + # times and thereby confronted with different types. We only want to raise a + # `comparison-overlap` error if it occurs in all cases and therefore collect the + # respective types of the current iteration here so that we can report the error + # later if it is persistent over all iteration steps: + for watcher in self.errors.get_watchers(): + if watcher._filter: + break + if isinstance(watcher, IterationErrorWatcher): + watcher.iteration_dependent_errors.nonoverlapping_types[-1][ + NonOverlapErrorInfo( + line=ctx.line, + column=ctx.column, + end_line=ctx.end_line, + end_column=ctx.end_column, + kind=kind, + ) + ] = (left, right) + return + + left_str = "element" if kind == "container" else "left operand" + right_str = "container item" if kind == "container" else "right operand" + message = "Non-overlapping {} check ({} type: {}, {} type: {})" + left_typ, right_typ = format_type_distinctly(left, right, options=self.options) + self.fail( + message.format(kind, left_str, left_typ, right_str, right_typ), + ctx, + code=codes.COMPARISON_OVERLAP, + ) + + def overload_inconsistently_applies_decorator(self, decorator: str, context: Context) -> None: + self.fail( + f'Overload does not consistently use the "@{decorator}" ' + + "decorator on all function signatures.", + context, + ) + + def overloaded_signatures_overlap( + self, index1: int, index2: int, flip_note: bool, context: Context + ) -> None: + self.fail( + "Overloaded function signatures {} and {} overlap with " + "incompatible return types".format(index1, index2), + context, + code=codes.OVERLOAD_OVERLAP, + ) + if flip_note: + self.note( + "Flipping the order of overloads will fix this error", + context, + code=codes.OVERLOAD_OVERLAP, + ) + + def overloaded_signature_will_never_match( + self, index1: int, index2: int, context: Context + ) -> None: + self.fail( + "Overloaded function signature {index2} will never be matched: " + "signature {index1}'s parameter type(s) are the same or broader".format( + index1=index1, index2=index2 + ), + context, + code=codes.OVERLOAD_CANNOT_MATCH, + ) + + def overloaded_signatures_typevar_specific(self, index: int, context: Context) -> None: + self.fail( + f"Overloaded function implementation cannot satisfy signature {index} " + + "due to inconsistencies in how they use type variables", + context, + ) + + def overloaded_signatures_param_specific(self, index: int, context: Context) -> None: + self.fail( + ( + f"Overloaded function implementation does not accept all possible parameters " + f"of signature {index}" + ), + context, + ) + + def overloaded_signatures_ret_specific(self, index: int, context: Context) -> None: + self.fail( + f"Overloaded function implementation cannot produce return type of signature {index}", + context, + ) + + def warn_both_operands_are_from_unions(self, context: Context) -> None: + self.note("Both left and right operands are unions", context, code=codes.OPERATOR) + + def warn_operand_was_from_union(self, side: str, original: Type, context: Context) -> None: + self.note( + f"{side} operand is of type {format_type(original, self.options)}", + context, + code=codes.OPERATOR, + ) + + def operator_method_signatures_overlap( + self, + reverse_class: TypeInfo, + reverse_method: str, + forward_class: Type, + forward_method: str, + context: Context, + ) -> None: + self.fail( + 'Signatures of "{}" of "{}" and "{}" of {} are unsafely overlapping'.format( + reverse_method, + reverse_class.name, + forward_method, + format_type(forward_class, self.options), + ), + context, + ) + + def forward_operator_not_callable(self, forward_method: str, context: Context) -> None: + self.fail(f'Forward operator "{forward_method}" is not callable', context) + + def signatures_incompatible(self, method: str, other_method: str, context: Context) -> None: + self.fail(f'Signatures of "{method}" and "{other_method}" are incompatible', context) + + def yield_from_invalid_operand_type(self, expr: Type, context: Context) -> Type: + text = ( + format_type(expr, self.options) + if format_type(expr, self.options) != "object" + else expr + ) + self.fail(f'"yield from" can\'t be applied to {text}', context) + return AnyType(TypeOfAny.from_error) + + def invalid_signature(self, func_type: Type, context: Context) -> None: + self.fail(f"Invalid signature {format_type(func_type, self.options)}", context) + + def invalid_signature_for_special_method( + self, func_type: Type, context: Context, method_name: str + ) -> None: + self.fail( + f'Invalid signature {format_type(func_type, self.options)} for "{method_name}"', + context, + ) + + def reveal_type(self, typ: Type, context: Context) -> None: + + # Search for an error watcher that modifies the "normal" behaviour (we do not + # rely on the normal `ErrorWatcher` filtering approach because we might need to + # collect the original types for a later unionised response): + for watcher in self.errors.get_watchers(): + # The `reveal_type` statement should be ignored: + if watcher.filter_revealed_type: + return + # The `reveal_type` statement might be visited iteratively due to being + # placed in a loop or so. Hence, we collect the respective types of + # individual iterations so that we can report them all in one step later: + if isinstance(watcher, IterationErrorWatcher): + watcher.iteration_dependent_errors.revealed_types[ + (context.line, context.column, context.end_line, context.end_column) + ].append(typ) + return + + # Nothing special here; just create the note: + visitor = TypeStrVisitor(options=self.options) + self.note(f'Revealed type is "{typ.accept(visitor)}"', context) + + def reveal_locals(self, type_map: dict[str, Type | None], context: Context) -> None: + # To ensure that the output is predictable on Python < 3.6, + # use an ordered dictionary sorted by variable name + sorted_locals = dict(sorted(type_map.items(), key=lambda t: t[0])) + if sorted_locals: + self.note("Revealed local types are:", context) + for k, v in sorted_locals.items(): + visitor = TypeStrVisitor(options=self.options) + self.note(f" {k}: {v.accept(visitor) if v is not None else None}", context) + else: + self.note("There are no locals to reveal", context) + + def unsupported_type_type(self, item: Type, context: Context) -> None: + self.fail( + f'Cannot instantiate type "type[{format_type_bare(item, self.options)}]"', context + ) + + def redundant_cast(self, typ: Type, context: Context) -> None: + self.fail( + f"Redundant cast to {format_type(typ, self.options)}", + context, + code=codes.REDUNDANT_CAST, + ) + + def assert_type_fail(self, source_type: Type, target_type: Type, context: Context) -> None: + source, target = format_type_distinctly(source_type, target_type, options=self.options) + self.fail(f"Expression is of type {source}, not {target}", context, code=codes.ASSERT_TYPE) + + def unimported_type_becomes_any(self, prefix: str, typ: Type, ctx: Context) -> None: + self.fail( + f"{prefix} becomes {format_type(typ, self.options)} due to an unfollowed import", + ctx, + code=codes.NO_ANY_UNIMPORTED, + ) + + def need_annotation_for_var( + self, node: SymbolNode, context: Context, options: Options | None = None + ) -> None: + hint = "" + # type to recommend the user adds + recommended_type = None + # Only gives hint if it's a variable declaration and the partial type is a builtin type + if options and isinstance(node, Var) and isinstance(node.type, PartialType): + type_dec = "" + if not node.type.type: + # partial None + recommended_type = f"{type_dec} | None" + elif node.type.type.fullname in reverse_builtin_aliases: + # partial types other than partial None + name = node.type.type.fullname.partition(".")[2] + if name == "dict": + type_dec = f"{type_dec}, {type_dec}" + recommended_type = f"{name}[{type_dec}]" + if recommended_type is not None: + hint = f' (hint: "{node.name}: {recommended_type} = ...")' + + self.fail( + f'Need type annotation for "{unmangle(node.name)}"{hint}', + context, + code=codes.VAR_ANNOTATED, + ) + + def explicit_any(self, ctx: Context) -> None: + self.fail('Explicit "Any" is not allowed', ctx, code=codes.EXPLICIT_ANY) + + def unsupported_target_for_star_typeddict(self, typ: Type, ctx: Context) -> None: + self.fail( + "Unsupported type {} for ** expansion in TypedDict".format( + format_type(typ, self.options) + ), + ctx, + code=codes.TYPEDDICT_ITEM, + ) + + def non_required_keys_absent_with_star(self, keys: list[str], ctx: Context) -> None: + self.fail( + "Non-required {} not explicitly found in any ** item".format( + format_key_list(keys, short=True) + ), + ctx, + code=codes.TYPEDDICT_ITEM, + ) + + def unexpected_typeddict_keys( + self, + typ: TypedDictType, + expected_keys: list[str], + actual_keys: list[str], + context: Context, + ) -> None: + actual_set = set(actual_keys) + expected_set = set(expected_keys) + if not typ.is_anonymous(): + # Generate simpler messages for some common special cases. + # Use list comprehension instead of set operations to preserve order. + missing = [key for key in expected_keys if key not in actual_set] + if missing: + self.fail( + "Missing {} for TypedDict {}".format( + format_key_list(missing, short=True), format_type(typ, self.options) + ), + context, + code=codes.TYPEDDICT_ITEM, + ) + extra = [key for key in actual_keys if key not in expected_set] + if extra: + self.fail( + "Extra {} for TypedDict {}".format( + format_key_list(extra, short=True), format_type(typ, self.options) + ), + context, + code=codes.TYPEDDICT_UNKNOWN_KEY, + ) + if missing or extra: + # No need to check for further errors + return + found = format_key_list(actual_keys, short=True) + if not expected_keys: + self.fail(f"Unexpected TypedDict {found}", context) + return + expected = format_key_list(expected_keys) + if actual_keys and actual_set < expected_set: + found = f"only {found}" + self.fail(f"Expected {expected} but found {found}", context, code=codes.TYPEDDICT_ITEM) + + def typeddict_key_must_be_string_literal(self, typ: TypedDictType, context: Context) -> None: + self.fail( + "TypedDict key must be a string literal; expected one of {}".format( + format_item_name_list(typ.items.keys()) + ), + context, + code=codes.LITERAL_REQ, + ) + + def typeddict_key_not_found( + self, typ: TypedDictType, item_name: str, context: Context, setitem: bool = False + ) -> None: + """Handle error messages for TypedDicts that have unknown keys. + + Note, that we differentiate in between reading a value and setting a + value. + Setting a value on a TypedDict is an 'unknown-key' error, whereas + reading it is the more serious/general 'item' error. + """ + if typ.is_anonymous(): + self.fail( + '"{}" is not a valid TypedDict key; expected one of {}'.format( + item_name, format_item_name_list(typ.items.keys()) + ), + context, + ) + else: + err_code = codes.TYPEDDICT_UNKNOWN_KEY if setitem else codes.TYPEDDICT_ITEM + self.fail( + f'TypedDict {format_type(typ, self.options)} has no key "{item_name}"', + context, + code=err_code, + ) + matches = best_matches(item_name, typ.items.keys(), n=3) + if matches: + self.note( + "Did you mean {}?".format(pretty_seq(matches, "or")), context, code=err_code + ) + + def typeddict_context_ambiguous(self, types: list[TypedDictType], context: Context) -> None: + formatted_types = ", ".join(list(format_type_distinctly(*types, options=self.options))) + self.fail( + f"Type of TypedDict is ambiguous, none of ({formatted_types}) matches cleanly", context + ) + + def typeddict_key_cannot_be_deleted( + self, typ: TypedDictType, item_name: str, context: Context + ) -> None: + if typ.is_anonymous(): + self.fail(f'TypedDict key "{item_name}" cannot be deleted', context) + else: + self.fail( + f'Key "{item_name}" of TypedDict {format_type(typ, self.options)} cannot be deleted', + context, + ) + + def typeddict_setdefault_arguments_inconsistent( + self, default: Type, expected: Type, context: Context + ) -> None: + msg = 'Argument 2 to "setdefault" of "TypedDict" has incompatible type {}; expected {}' + self.fail( + msg.format(format_type(default, self.options), format_type(expected, self.options)), + context, + code=codes.TYPEDDICT_ITEM, + ) + + def type_arguments_not_allowed(self, context: Context) -> None: + self.fail("Parameterized generics cannot be used with class or instance checks", context) + + def disallowed_any_type(self, typ: Type, context: Context) -> None: + typ = get_proper_type(typ) + if isinstance(typ, AnyType): + message = 'Expression has type "Any"' + else: + message = f'Expression type contains "Any" (has type {format_type(typ, self.options)})' + self.fail(message, context) + + def incorrectly_returning_any(self, typ: Type, context: Context) -> None: + message = ( + f"Returning Any from function declared to return {format_type(typ, self.options)}" + ) + self.fail(message, context, code=codes.NO_ANY_RETURN) + + def incorrect__exit__return(self, context: Context) -> None: + self.fail( + '"bool" is invalid as return type for "__exit__" that always returns False', + context, + code=codes.EXIT_RETURN, + ) + self.note( + 'Use "typing.Literal[False]" as the return type or change it to "None"', + context, + code=codes.EXIT_RETURN, + ) + self.note( + 'If return type of "__exit__" implies that it may return True, ' + "the context manager may swallow exceptions", + context, + code=codes.EXIT_RETURN, + ) + + def untyped_decorated_function(self, typ: Type, context: Context) -> None: + typ = get_proper_type(typ) + if isinstance(typ, AnyType): + self.fail("Function is untyped after decorator transformation", context) + else: + self.fail( + f'Type of decorated function contains type "Any" ({format_type(typ, self.options)})', + context, + ) + + def typed_function_untyped_decorator(self, func_name: str, context: Context) -> None: + self.fail( + f'Untyped decorator makes function "{func_name}" untyped', + context, + code=codes.UNTYPED_DECORATOR, + ) + + def bad_proto_variance( + self, actual: int, tvar_name: str, expected: int, context: Context + ) -> None: + msg = capitalize( + '{} type variable "{}" used in protocol where {} one is expected'.format( + variance_string(actual), tvar_name, variance_string(expected) + ) + ) + self.fail(msg, context) + + def concrete_only_assign(self, typ: Type, context: Context) -> None: + self.fail( + f"Can only assign concrete classes to a variable of type {format_type(typ, self.options)}", + context, + code=codes.TYPE_ABSTRACT, + ) + + def concrete_only_call(self, typ: Type, context: Context) -> None: + self.fail( + f"Only concrete class can be given where {format_type(typ, self.options)} is expected", + context, + code=codes.TYPE_ABSTRACT, + ) + + def cannot_use_function_with_type( + self, method_name: str, type_name: str, context: Context + ) -> None: + self.fail(f"Cannot use {method_name}() with {type_name} type", context) + + def report_non_method_protocol( + self, tp: TypeInfo, members: list[str], context: Context + ) -> None: + self.fail( + "Only protocols that don't have non-method members can be used with issubclass()", + context, + ) + if len(members) < 3: + attrs = ", ".join(members) + self.note(f'Protocol "{tp.name}" has non-method member(s): {attrs}', context) + + def note_call( + self, subtype: Type, call: Type, context: Context, *, code: ErrorCode | None + ) -> None: + self.note( + '"{}.__call__" has type {}'.format( + format_type_bare(subtype, self.options), + format_type(call, self.options, verbosity=1), + ), + context, + code=code, + ) + + def unreachable_statement(self, context: Context) -> None: + self.fail("Statement is unreachable", context, code=codes.UNREACHABLE) + + def redundant_left_operand(self, op_name: str, context: Context) -> None: + """Indicates that the left operand of a boolean expression is redundant: + it does not change the truth value of the entire condition as a whole. + 'op_name' should either be the string "and" or the string "or". + """ + self.redundant_expr(f'Left operand of "{op_name}"', op_name == "and", context) + + def unreachable_right_operand(self, op_name: str, context: Context) -> None: + """Indicates that the right operand of a boolean expression is redundant: + it does not change the truth value of the entire condition as a whole. + 'op_name' should either be the string "and" or the string "or". + """ + self.fail( + f'Right operand of "{op_name}" is never evaluated', context, code=codes.UNREACHABLE + ) + + def redundant_condition_in_comprehension(self, truthiness: bool, context: Context) -> None: + self.redundant_expr("If condition in comprehension", truthiness, context) + + def redundant_condition_in_if(self, truthiness: bool, context: Context) -> None: + self.redundant_expr("If condition", truthiness, context) + + def redundant_expr(self, description: str, truthiness: bool, context: Context) -> None: + self.fail( + f"{description} is always {str(truthiness).lower()}", + context, + code=codes.REDUNDANT_EXPR, + ) + + def impossible_intersection( + self, formatted_base_class_list: str, reason: str, context: Context + ) -> None: + template = "Subclass of {} cannot exist: {}" + self.fail( + template.format(formatted_base_class_list, reason), context, code=codes.UNREACHABLE + ) + + def tvar_without_default_type( + self, tvar_name: str, last_tvar_name_with_default: str, context: Context + ) -> None: + self.fail( + f'"{tvar_name}" cannot appear after "{last_tvar_name_with_default}" ' + "in type parameter list because it has no default type", + context, + ) + + def report_protocol_problems( + self, + subtype: Instance | TupleType | TypedDictType | TypeType | CallableType, + supertype: Instance, + context: Context, + *, + parent_error: ErrorInfo, + ) -> None: + """Report possible protocol conflicts between 'subtype' and 'supertype'. + + This includes missing members, incompatible types, and incompatible + attribute flags, such as settable vs read-only or class variable vs + instance variable. + """ + OFFSET = 4 # Four spaces, so that notes will look like this: + # note: 'Cls' is missing following 'Proto' members: + # note: method, attr + MAX_ITEMS = 2 # Maximum number of conflicts, missing members, and overloads shown + # List of special situations where we don't want to report additional problems + exclusions: dict[type, list[str]] = { + TypedDictType: ["typing.Mapping"], + TupleType: ["typing.Iterable", "typing.Sequence"], + } + if supertype.type.fullname in exclusions.get(type(subtype), []): + return + if any(isinstance(tp, UninhabitedType) for tp in get_proper_types(supertype.args)): + # We don't want to add notes for failed inference (e.g. Iterable[Never]). + # This will be only confusing a user even more. + return + + class_obj = False + is_module = False + skip = [] + if isinstance(subtype, TupleType): + subtype = subtype.partial_fallback + elif isinstance(subtype, TypedDictType): + subtype = subtype.fallback + elif isinstance(subtype, TypeType): + if not isinstance(subtype.item, Instance): + return + class_obj = True + subtype = subtype.item + elif isinstance(subtype, CallableType): + if subtype.is_type_obj(): + ret_type = get_proper_type(subtype.ret_type) + if isinstance(ret_type, TupleType): + ret_type = ret_type.partial_fallback + if not isinstance(ret_type, Instance): + return + class_obj = True + subtype = ret_type + else: + subtype = subtype.fallback + skip = ["__call__"] + if subtype.extra_attrs and subtype.extra_attrs.mod_name: + is_module = True + + # Report missing members + missing = get_missing_protocol_members(subtype, supertype, skip=skip) + if ( + missing + and (len(missing) < len(supertype.type.protocol_members) or missing == ["__call__"]) + and len(missing) <= MAX_ITEMS + ): + if missing == ["__call__"] and class_obj: + self.note( + '"{}" has constructor incompatible with "__call__" of "{}"'.format( + subtype.type.name, supertype.type.name + ), + context, + parent_error=parent_error, + ) + else: + self.note( + '"{}" is missing following "{}" protocol member{}:'.format( + subtype.type.name, supertype.type.name, plural_s(missing) + ), + context, + parent_error=parent_error, + ) + self.note(", ".join(missing), context, offset=OFFSET, parent_error=parent_error) + elif len(missing) > MAX_ITEMS or len(missing) == len(supertype.type.protocol_members): + # This is an obviously wrong type: too many missing members + return + + # Report member type conflicts + conflict_types = get_conflict_protocol_types( + subtype, supertype, class_obj=class_obj, options=self.options + ) + if conflict_types and ( + not is_subtype(subtype, erase_type(supertype), options=self.options) + or not subtype.type.defn.type_vars + or not supertype.type.defn.type_vars + # Always show detailed message for ParamSpec + or subtype.type.has_param_spec_type + or supertype.type.has_param_spec_type + ): + type_name = format_type(subtype, self.options, module_names=True) + self.note( + f"Following member(s) of {type_name} have conflicts:", + context, + parent_error=parent_error, + ) + for name, got, exp, is_lvalue in conflict_types[:MAX_ITEMS]: + exp = get_proper_type(exp) + got = get_proper_type(got) + setter_suffix = " setter type" if is_lvalue else "" + if ( + not isinstance(exp, (CallableType, Overloaded)) + or not isinstance(got, (CallableType, Overloaded)) + # If expected type is a type object, it means it is a nested class. + # Showing constructor signature in errors would be confusing in this case, + # since we don't check the signature, only subclassing of type objects. + or exp.is_type_obj() + ): + self.note( + "{}: expected{} {}, got {}".format( + name, + setter_suffix, + *format_type_distinctly(exp, got, options=self.options), + ), + context, + offset=OFFSET, + parent_error=parent_error, + ) + if is_lvalue and is_subtype(got, exp, options=self.options): + self.note( + "Setter types should behave contravariantly", + context, + offset=OFFSET, + parent_error=parent_error, + ) + else: + self.note( + "Expected{}:".format(setter_suffix), + context, + offset=OFFSET, + parent_error=parent_error, + ) + if isinstance(exp, CallableType): + self.note( + pretty_callable(exp, self.options, skip_self=class_obj or is_module), + context, + offset=2 * OFFSET, + parent_error=parent_error, + ) + else: + assert isinstance(exp, Overloaded) + self.pretty_overload( + exp, + context, + 2 * OFFSET, + parent_error=parent_error, + skip_self=class_obj or is_module, + ) + self.note("Got:", context, offset=OFFSET, parent_error=parent_error) + if isinstance(got, CallableType): + self.note( + pretty_callable(got, self.options, skip_self=class_obj or is_module), + context, + offset=2 * OFFSET, + parent_error=parent_error, + ) + else: + assert isinstance(got, Overloaded) + self.pretty_overload( + got, + context, + 2 * OFFSET, + parent_error=parent_error, + skip_self=class_obj or is_module, + ) + self.print_more(conflict_types, context, OFFSET, MAX_ITEMS, code=parent_error.code) + + # Report flag conflicts (i.e. settable vs read-only etc.) + conflict_flags = get_bad_protocol_flags(subtype, supertype, class_obj=class_obj) + for name, subflags, superflags in conflict_flags[:MAX_ITEMS]: + if not class_obj and IS_CLASSVAR in subflags and IS_CLASSVAR not in superflags: + self.note( + "Protocol member {}.{} expected instance variable, got class variable".format( + supertype.type.name, name + ), + context, + parent_error=parent_error, + ) + if not class_obj and IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags: + self.note( + "Protocol member {}.{} expected class variable, got instance variable".format( + supertype.type.name, name + ), + context, + parent_error=parent_error, + ) + if IS_SETTABLE in superflags and IS_SETTABLE not in subflags: + self.note( + "Protocol member {}.{} expected settable variable," + " got read-only attribute".format(supertype.type.name, name), + context, + parent_error=parent_error, + ) + if IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags: + self.note( + "Protocol member {}.{} expected class or static method".format( + supertype.type.name, name + ), + context, + parent_error=parent_error, + ) + if ( + class_obj + and IS_VAR in superflags + and (IS_VAR in subflags and IS_CLASSVAR not in subflags) + ): + self.note( + "Only class variables allowed for class object access on protocols," + ' {} is an instance variable of "{}"'.format(name, subtype.type.name), + context, + parent_error=parent_error, + ) + if class_obj and IS_CLASSVAR in superflags: + self.note( + "ClassVar protocol member {}.{} can never be matched by a class object".format( + supertype.type.name, name + ), + context, + parent_error=parent_error, + ) + self.print_more(conflict_flags, context, OFFSET, MAX_ITEMS, code=parent_error.code) + + def pretty_overload( + self, + tp: Overloaded, + context: Context, + offset: int, + *, + parent_error: ErrorInfo, + add_class_or_static_decorator: bool = False, + skip_self: bool = False, + ) -> None: + for item in tp.items: + self.note("@overload", context, offset=offset, parent_error=parent_error) + + if add_class_or_static_decorator: + decorator = pretty_class_or_static_decorator(item) + if decorator is not None: + self.note(decorator, context, offset=offset, parent_error=parent_error) + + self.note( + pretty_callable(item, self.options, skip_self=skip_self), + context, + offset=offset, + parent_error=parent_error, + ) + + def print_more( + self, + conflicts: Sequence[Any], + context: Context, + offset: int, + max_items: int, + *, + code: ErrorCode | None = None, + ) -> None: + if len(conflicts) > max_items: + self.note( + f"<{len(conflicts) - max_items} more conflict(s) not shown>", + context, + offset=offset, + code=code, + ) + + def try_report_long_tuple_assignment_error( + self, + subtype: ProperType, + supertype: ProperType, + context: Context, + msg: message_registry.ErrorMessage, + subtype_label: str | None = None, + supertype_label: str | None = None, + ) -> bool: + """Try to generate meaningful error message for very long tuple assignment + + Returns a bool: True when generating long tuple assignment error, + False when no such error reported + """ + if isinstance(subtype, TupleType): + if ( + len(subtype.items) > MAX_TUPLE_ITEMS + and isinstance(supertype, Instance) + and supertype.type.fullname == "builtins.tuple" + ): + lhs_type = supertype.args[0] + lhs_types = [lhs_type] * len(subtype.items) + self.generate_incompatible_tuple_error(lhs_types, subtype.items, context, msg) + return True + elif isinstance(supertype, TupleType) and ( + len(subtype.items) > MAX_TUPLE_ITEMS or len(supertype.items) > MAX_TUPLE_ITEMS + ): + if len(subtype.items) != len(supertype.items): + if supertype_label is not None and subtype_label is not None: + msg = msg.with_additional_msg( + " ({} {}, {} {})".format( + subtype_label, + self.format_long_tuple_type(subtype), + supertype_label, + self.format_long_tuple_type(supertype), + ) + ) + self.fail(msg.value, context, code=msg.code) + return True + self.generate_incompatible_tuple_error( + supertype.items, subtype.items, context, msg + ) + return True + return False + + def format_long_tuple_type(self, typ: TupleType) -> str: + """Format very long tuple type using an ellipsis notation""" + item_cnt = len(typ.items) + if item_cnt > MAX_TUPLE_ITEMS: + return '"tuple[{}, {}, ... <{} more items>]"'.format( + format_type_bare(typ.items[0], self.options), + format_type_bare(typ.items[1], self.options), + str(item_cnt - 2), + ) + else: + return format_type(typ, self.options) + + def generate_incompatible_tuple_error( + self, + lhs_types: list[Type], + rhs_types: list[Type], + context: Context, + msg: message_registry.ErrorMessage, + ) -> None: + """Generate error message for individual incompatible tuple pairs""" + error_cnt = 0 + notes: list[str] = [] + for i, (lhs_t, rhs_t) in enumerate(zip(lhs_types, rhs_types)): + if not is_subtype(rhs_t, lhs_t): + if error_cnt < 3: + notes.append( + "Expression tuple item {} has type {}; {} expected; ".format( + str(i), + format_type(rhs_t, self.options), + format_type(lhs_t, self.options), + ) + ) + error_cnt += 1 + + info = f" ({str(error_cnt)} tuple items are incompatible" + if error_cnt - 3 > 0: + info += f"; {str(error_cnt - 3)} items are omitted)" + else: + info += ")" + msg = msg.with_additional_msg(info) + self.fail(msg.value, context, code=msg.code) + for note in notes: + self.note(note, context, code=msg.code) + + def add_fixture_note(self, fullname: str, ctx: Context) -> None: + self.note(f'Maybe your test fixture does not define "{fullname}"?', ctx) + if fullname in SUGGESTED_TEST_FIXTURES: + self.note( + "Consider adding [builtins fixtures/{}] to your test description".format( + SUGGESTED_TEST_FIXTURES[fullname] + ), + ctx, + ) + + def annotation_in_unchecked_function(self, context: Context) -> None: + self.note( + "By default the bodies of untyped functions are not checked," + " consider using --check-untyped-defs", + context, + code=codes.ANNOTATION_UNCHECKED, + ) + + def type_parameters_should_be_declared(self, undeclared: list[str], context: Context) -> None: + names = ", ".join('"' + n + '"' for n in undeclared) + self.fail( + message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format(names), + context, + code=codes.VALID_TYPE, + ) + + def match_statement_inexhaustive_match(self, typ: Type, context: Context) -> None: + type_str = format_type(typ, self.options) + msg = f"Match statement has unhandled case for values of type {type_str}" + self.fail(msg, context, code=codes.EXHAUSTIVE_MATCH) + self.note( + "If match statement is intended to be non-exhaustive, add `case _: pass`", + context, + code=codes.EXHAUSTIVE_MATCH, + ) + + def iteration_dependent_errors(self, iter_errors: IterationDependentErrors) -> None: + for error_info in iter_errors.yield_uselessness_error_infos(): + self.fail(*error_info[:2], code=error_info[2]) + for nonoverlaps, kind, context in iter_errors.yield_nonoverlapping_types(): + self.dangerous_comparison( + mypy.typeops.make_simplified_union(nonoverlaps[0]), + mypy.typeops.make_simplified_union(nonoverlaps[1]), + kind, + context, + ) + for types, context in iter_errors.yield_revealed_type_infos(): + self.reveal_type(mypy.typeops.make_simplified_union(types), context) + + +def quote_type_string(type_string: str) -> str: + """Quotes a type representation for use in messages.""" + if ( + type_string in ["Module", "overloaded function", ""] + or type_string.startswith("Module ") + or type_string.endswith("?") + ): + # These messages are easier to read if these aren't quoted. + return type_string + return f'"{type_string}"' + + +def should_format_arg_as_type(arg_kind: ArgKind, arg_name: str | None, verbosity: int) -> bool: + """ + Determine whether a function argument should be formatted as its Type or with name. + """ + return (arg_kind == ARG_POS and arg_name is None) or ( + verbosity == 0 and arg_kind.is_positional() + ) + + +def format_callable_args( + arg_types: list[Type], + arg_kinds: list[ArgKind], + arg_names: list[str | None], + format: Callable[[Type], str], + verbosity: int, +) -> str: + """Format a bunch of Callable arguments into a string""" + arg_strings = [] + for arg_name, arg_type, arg_kind in zip(arg_names, arg_types, arg_kinds): + if should_format_arg_as_type(arg_kind, arg_name, verbosity): + arg_strings.append(format(arg_type)) + else: + constructor = ARG_CONSTRUCTOR_NAMES[arg_kind] + if arg_kind.is_star() or arg_name is None: + arg_strings.append(f"{constructor}({format(arg_type)})") + else: + arg_strings.append(f"{constructor}({format(arg_type)}, {repr(arg_name)})") + + return ", ".join(arg_strings) + + +def format_type_inner( + typ: Type, + verbosity: int, + options: Options, + fullnames: set[str] | None, + module_names: bool = False, + use_pretty_callable: bool = True, +) -> str: + """ + Convert a type to a relatively short string suitable for error messages. + + Args: + typ: type to be formatted + verbosity: a coarse grained control on the verbosity of the type + options: Options object controlling formatting + fullnames: a set of names that should be printed in full + module_names: whether to show module names for module types + use_pretty_callable: use pretty_callable to format Callable types. + """ + + def format(typ: Type) -> str: + return format_type_inner(typ, verbosity, options, fullnames) + + def format_list(types: Sequence[Type]) -> str: + return ", ".join(format(typ) for typ in types) + + def format_union_items(types: Sequence[Type]) -> list[str]: + formatted = [format(typ) for typ in types if format(typ) != "None"] + if len(formatted) > MAX_UNION_ITEMS and verbosity == 0: + more = len(formatted) - MAX_UNION_ITEMS // 2 + formatted = formatted[: MAX_UNION_ITEMS // 2] + else: + more = 0 + if more: + formatted.append(f"<{more} more items>") + if any(format(typ) == "None" for typ in types): + formatted.append("None") + return formatted + + def format_union(types: Sequence[Type]) -> str: + return " | ".join(format_union_items(types)) + + def format_literal_value(typ: LiteralType) -> str: + if typ.is_enum_literal(): + underlying_type = format(typ.fallback) + return f"{underlying_type}.{typ.value}" + else: + return typ.value_repr() + + if isinstance(typ, TypeAliasType) and typ.is_recursive: + if typ.alias is None: + type_str = "" + else: + if verbosity >= 2 or (fullnames and typ.alias.fullname in fullnames): + type_str = typ.alias.fullname + else: + type_str = typ.alias.name + if typ.args: + type_str += f"[{format_list(typ.args)}]" + return type_str + + # TODO: always mention type alias names in errors. + typ = get_proper_type(typ) + + if isinstance(typ, Instance): + itype = typ + # Get the short name of the type. + if itype.type.fullname == "types.ModuleType": + # Make some common error messages simpler and tidier. + base_str = "Module" + if itype.extra_attrs and itype.extra_attrs.mod_name and module_names: + return f'{base_str} "{itype.extra_attrs.mod_name}"' + return base_str + if itype.type.fullname == "typing._SpecialForm": + # This is not a real type but used for some typing-related constructs. + return "" + if verbosity >= 2 or (fullnames and itype.type.fullname in fullnames): + base_str = itype.type.fullname + else: + base_str = itype.type.name + if not itype.args: + if itype.type.has_type_var_tuple_type and len(itype.type.type_vars) == 1: + return base_str + "[()]" + # No type arguments, just return the type name + return base_str + elif itype.type.fullname == "builtins.tuple": + item_type_str = format(itype.args[0]) + return f"tuple[{item_type_str}, ...]" + else: + # There are type arguments. Convert the arguments to strings. + return f"{base_str}[{format_list(itype.args)}]" + elif isinstance(typ, UnpackType): + if options.use_star_unpack(): + return f"*{format(typ.type)}" + return f"Unpack[{format(typ.type)}]" + elif isinstance(typ, TypeVarType): + # This is similar to non-generic instance types. + fullname = scoped_type_var_name(typ) + if verbosity >= 2 or (fullnames and fullname in fullnames): + return fullname + return typ.name + elif isinstance(typ, TypeVarTupleType): + # This is similar to non-generic instance types. + fullname = scoped_type_var_name(typ) + if verbosity >= 2 or (fullnames and fullname in fullnames): + return fullname + return typ.name + elif isinstance(typ, ParamSpecType): + # Concatenate[..., P] + if typ.prefix.arg_types: + args = format_callable_args( + typ.prefix.arg_types, typ.prefix.arg_kinds, typ.prefix.arg_names, format, verbosity + ) + + return f"[{args}, **{typ.name_with_suffix()}]" + else: + # TODO: better disambiguate ParamSpec name clashes. + return typ.name_with_suffix() + elif isinstance(typ, TupleType): + # Prefer the name of the fallback class (if not tuple), as it's more informative. + if typ.partial_fallback.type.fullname != "builtins.tuple": + return format(typ.partial_fallback) + type_items = format_list(typ.items) or "()" + return f"tuple[{type_items}]" + elif isinstance(typ, TypedDictType): + # If the TypedDictType is named, return the name + if not typ.is_anonymous(): + return format(typ.fallback) + items = [] + for item_name, item_type in typ.items.items(): + modifier = "" + if item_name not in typ.required_keys: + modifier += "?" + if item_name in typ.readonly_keys: + modifier += "=" + items.append(f"{item_name!r}{modifier}: {format(item_type)}") + return f"TypedDict({{{', '.join(items)}}})" + elif isinstance(typ, LiteralType): + return f"Literal[{format_literal_value(typ)}]" + elif isinstance(typ, UnionType): + typ = get_proper_type(ignore_last_known_values(typ)) + if not isinstance(typ, UnionType): + return format(typ) + literal_items, union_items = separate_union_literals(typ) + + # Coalesce multiple Literal[] members. This also changes output order. + # If there's just one Literal item, retain the original ordering. + if len(literal_items) > 1: + literal_str = "Literal[{}]".format( + ", ".join(format_literal_value(t) for t in literal_items) + ) + + if len(union_items) == 1 and isinstance(get_proper_type(union_items[0]), NoneType): + return f"{literal_str} | None" + elif union_items: + return f"{literal_str} | {format_union(union_items)}" + else: + return literal_str + else: + # Only print Union as Optional if the Optional wouldn't have to contain another Union + print_as_optional = ( + len(typ.items) - sum(isinstance(get_proper_type(t), NoneType) for t in typ.items) + == 1 + ) + if print_as_optional: + rest = [t for t in typ.items if not isinstance(get_proper_type(t), NoneType)] + return f"{format(rest[0])} | None" + else: + s = format_union(typ.items) + return s + elif isinstance(typ, NoneType): + return "None" + elif isinstance(typ, AnyType): + return "Any" + elif isinstance(typ, DeletedType): + return "" + elif isinstance(typ, UninhabitedType): + return "Never" + elif isinstance(typ, TypeType): + if typ.is_type_form: + type_name = "TypeForm" + else: + type_name = "type" + return f"{type_name}[{format(typ.item)}]" + elif isinstance(typ, FunctionLike): + func = typ + if func.is_type_obj(): + # The type of a type object type can be derived from the + # return type (this always works). + return format(TypeType.make_normalized(func.items[0].ret_type)) + elif isinstance(func, CallableType): + if func.type_guard is not None: + return_type = f"TypeGuard[{format(func.type_guard)}]" + elif func.type_is is not None: + return_type = f"TypeIs[{format(func.type_is)}]" + else: + return_type = format(func.ret_type) + if func.is_ellipsis_args: + return f"Callable[..., {return_type}]" + param_spec = func.param_spec() + if param_spec is not None: + return f"Callable[{format(param_spec)}, {return_type}]" + + # Use pretty format (def-style) for complex signatures with named, optional, or star args. + # Use compact Callable[[...], ...] only for signatures with all simple positional args. + if use_pretty_callable: + if any( + not should_format_arg_as_type(kind, name, verbosity) + for kind, name in zip(func.arg_kinds, func.arg_names) + ): + return pretty_callable(func, options) + + args = format_callable_args( + func.arg_types, func.arg_kinds, func.arg_names, format, verbosity + ) + return f"Callable[[{args}], {return_type}]" + else: + # Use a simple representation for function types; proper + # function types may result in long and difficult-to-read + # error messages. + return "overloaded function" + elif isinstance(typ, UnboundType): + return typ.accept(TypeStrVisitor(options=options)) + elif isinstance(typ, Parameters): + args = format_callable_args(typ.arg_types, typ.arg_kinds, typ.arg_names, format, verbosity) + return f"[{args}]" + elif typ is None: + raise RuntimeError("Type is None") + else: + # Default case; we simply have to return something meaningful here. + return "object" + + +def collect_all_named_types(t: Type) -> list[Type]: + """Return all instances/aliases/type variables that `t` contains (including `t`). + + This is similar to collect_all_inner_types from typeanal but only + returns instances and will recurse into fallbacks. + """ + visitor = CollectAllNamedTypesQuery() + t.accept(visitor) + return visitor.types + + +class CollectAllNamedTypesQuery(TypeTraverserVisitor): + def __init__(self) -> None: + self.types: list[Type] = [] + + def visit_instance(self, t: Instance) -> None: + self.types.append(t) + super().visit_instance(t) + + def visit_type_alias_type(self, t: TypeAliasType) -> None: + if t.alias and not t.is_recursive: + get_proper_type(t).accept(self) + else: + self.types.append(t) + super().visit_type_alias_type(t) + + def visit_type_var(self, t: TypeVarType) -> None: + self.types.append(t) + super().visit_type_var(t) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> None: + self.types.append(t) + super().visit_type_var_tuple(t) + + def visit_param_spec(self, t: ParamSpecType) -> None: + self.types.append(t) + super().visit_param_spec(t) + + +def scoped_type_var_name(t: TypeVarLikeType) -> str: + if not t.id.namespace: + return t.name + # TODO: support rare cases when both TypeVar name and namespace suffix coincide. + *_, suffix = t.id.namespace.split(".") + return f"{t.name}@{suffix}" + + +def find_type_overlaps(*types: Type) -> set[str]: + """Return a set of fullnames that share a short name and appear in either type. + + This is used to ensure that distinct types with the same short name are printed + with their fullname. + """ + d: dict[str, set[str]] = {} + for type in types: + for t in collect_all_named_types(type): + if isinstance(t, ProperType) and isinstance(t, Instance): + d.setdefault(t.type.name, set()).add(t.type.fullname) + elif isinstance(t, TypeAliasType) and t.alias: + d.setdefault(t.alias.name, set()).add(t.alias.fullname) + else: + assert isinstance(t, TypeVarLikeType) + d.setdefault(t.name, set()).add(scoped_type_var_name(t)) + for shortname in d.keys(): + if f"typing.{shortname}" in TYPES_FOR_UNIMPORTED_HINTS: + d[shortname].add(f"typing.{shortname}") + + overlaps: set[str] = set() + for fullnames in d.values(): + if len(fullnames) > 1: + overlaps.update(fullnames) + return overlaps + + +def format_type( + typ: Type, options: Options, verbosity: int = 0, module_names: bool = False +) -> str: + """ + Convert a type to a relatively short string suitable for error messages. + + `verbosity` is a coarse-grained control on the verbosity of the type + + This function returns a string appropriate for unmodified use in error + messages; this means that it will be quoted in most cases. If + modification of the formatted string is required, callers should use + format_type_bare. + """ + return quote_type_string(format_type_bare(typ, options, verbosity, module_names)) + + +def format_type_bare( + typ: Type, options: Options, verbosity: int = 0, module_names: bool = False +) -> str: + """ + Convert a type to a relatively short string suitable for error messages. + + `verbosity` is a coarse-grained control on the verbosity of the type + `fullnames` specifies a set of names that should be printed in full + + This function will return an unquoted string. If a caller doesn't need to + perform post-processing on the string output, format_type should be used + instead. (The caller may want to use quote_type_string after + processing has happened, to maintain consistent quoting in messages.) + """ + return format_type_inner(typ, verbosity, options, find_type_overlaps(typ), module_names) + + +def format_type_distinctly(*types: Type, options: Options, bare: bool = False) -> tuple[str, ...]: + """Jointly format types to distinct strings. + + Increase the verbosity of the type strings until they become distinct + while also requiring that distinct types with the same short name are + formatted distinctly. + + By default, the returned strings are created using format_type() and will be + quoted accordingly. If ``bare`` is True, the returned strings will not + be quoted; callers who need to do post-processing of the strings before + quoting them (such as prepending * or **) should use this. + """ + overlapping = find_type_overlaps(*types) + + def format_single(arg: Type) -> str: + return format_type_inner(arg, verbosity=0, options=options, fullnames=overlapping) + + min_verbosity = 0 + # Prevent emitting weird errors like: + # ... has incompatible type "Callable[[int], Child]"; expected "Callable[[int], Parent]" + if len(types) == 2: + left, right = types + left = get_proper_type(left) + right = get_proper_type(right) + # If the right type has named arguments, they may be the reason for incompatibility. + # This excludes cases when right is Callable[[Something], None] without named args, + # because that's usually the right thing to do. + if ( + isinstance(left, CallableType) + and isinstance(right, CallableType) + and any(right.arg_names) + and is_subtype(left, right, ignore_pos_arg_names=True) + ): + min_verbosity = 1 + + for verbosity in range(min_verbosity, 2): + strs = [ + format_type_inner(type, verbosity=verbosity, options=options, fullnames=overlapping) + for type in types + ] + if len(set(strs)) == len(strs): + break + if bare: + return tuple(strs) + else: + return tuple(quote_type_string(s) for s in strs) + + +def pretty_class_or_static_decorator(tp: CallableType) -> str | None: + """Return @classmethod or @staticmethod, if any, for the given callable type.""" + definition = get_func_def(tp) + if definition is not None and isinstance(definition, SYMBOL_FUNCBASE_TYPES): + if definition.is_class: + return "@classmethod" + if definition.is_static: + return "@staticmethod" + return None + + +def pretty_callable(tp: CallableType, options: Options, skip_self: bool = False) -> str: + """Return a nice easily-readable representation of a callable type. + For example: + def [T <: int] f(self, x: int, y: T) -> None + + If skip_self is True, print an actual callable type, as it would appear + when bound on an instance/class, rather than how it would appear in the + defining statement. + """ + s = "" + asterisk = False + slash = False + for i in range(len(tp.arg_types)): + if s: + s += ", " + if tp.arg_kinds[i].is_named() and not asterisk: + s += "*, " + asterisk = True + if tp.arg_kinds[i] == ARG_STAR: + s += "*" + asterisk = True + if tp.arg_kinds[i] == ARG_STAR2: + s += "**" + name = tp.arg_names[i] + if not name and not options.reveal_verbose_types: + # Avoid ambiguous (and weird) formatting for anonymous args/kwargs. + if tp.arg_kinds[i] == ARG_STAR and isinstance(tp.arg_types[i], UnpackType): + name = "args" + elif tp.arg_kinds[i] == ARG_STAR2 and tp.unpack_kwargs: + name = "kwargs" + if name: + s += name + ": " + type_str = format_type_bare(tp.arg_types[i], options) + if tp.arg_kinds[i] == ARG_STAR2 and tp.unpack_kwargs: + if options.reveal_verbose_types: + type_str = f"Unpack[{type_str}]" + else: + type_str = f"**{type_str}" + s += type_str + if tp.arg_kinds[i].is_optional(): + s += " = ..." + if ( + not slash + and tp.arg_kinds[i].is_positional() + and name is None + and ( + i == len(tp.arg_types) - 1 + or (tp.arg_names[i + 1] is not None or not tp.arg_kinds[i + 1].is_positional()) + ) + ): + s += ", /" + slash = True + + definition = get_func_def(tp) + + # Extract function name, prefer the "human-readable" name if available. + func_name = None + if tp.name: + func_name = tp.name.split()[0] # skip "of Class" part + elif isinstance(definition, FuncDef): + func_name = definition.name + + # If we got a "special arg" (i.e: self, cls, etc...), prepend it to the arg list + first_arg = None + if ( + isinstance(definition, FuncDef) + and hasattr(definition, "arguments") + and not tp.from_concatenate + ): + definition_arg_names = [arg.variable.name for arg in definition.arguments] + if len(definition_arg_names) > len(tp.arg_names) and definition_arg_names[0]: + first_arg = definition_arg_names[0] + else: + # TODO: avoid different logic for incremental runs. + first_arg = get_first_arg(tp) + + if tp.is_type_obj(): + skip_self = True + if first_arg and not skip_self: + if s: + s = ", " + s + s = first_arg + s + if func_name: + s = f"{func_name}({s})" + else: + s = f"({s})" + + s += " -> " + if tp.type_guard is not None: + s += f"TypeGuard[{format_type_bare(tp.type_guard, options)}]" + elif tp.type_is is not None: + s += f"TypeIs[{format_type_bare(tp.type_is, options)}]" + else: + s += format_type_bare(tp.ret_type, options) + + if tp.variables: + tvars = [] + for tvar in tp.variables: + if isinstance(tvar, TypeVarType): + upper_bound = get_proper_type(tvar.upper_bound) + if not ( + isinstance(upper_bound, Instance) + and upper_bound.type.fullname == "builtins.object" + ): + tvars.append(f"{tvar.name}: {format_type_bare(upper_bound, options)}") + elif tvar.values: + tvars.append( + "{}: ({})".format( + tvar.name, + ", ".join([format_type_bare(tp, options) for tp in tvar.values]), + ) + ) + else: + tvars.append(tvar.name) + else: + # For other TypeVarLikeTypes, just use the repr + tvars.append(repr(tvar)) + s = f"[{', '.join(tvars)}] {s}" + return f"def {s}" + + +def get_first_arg(tp: CallableType) -> str | None: + definition = get_func_def(tp) + if not isinstance(definition, FuncDef) or not definition.info or definition.is_static: + return None + return definition.original_first_arg + + +def variance_string(variance: int) -> str: + if variance == COVARIANT: + return "covariant" + elif variance == CONTRAVARIANT: + return "contravariant" + else: + return "invariant" + + +def get_missing_protocol_members(left: Instance, right: Instance, skip: list[str]) -> list[str]: + """Find all protocol members of 'right' that are not implemented + (i.e. completely missing) in 'left'. + """ + assert right.type.is_protocol + missing: list[str] = [] + for member in right.type.protocol_members: + if member in skip: + continue + if not find_member(member, left, left): + missing.append(member) + return missing + + +def get_conflict_protocol_types( + left: Instance, right: Instance, class_obj: bool = False, options: Options | None = None +) -> list[tuple[str, Type, Type, bool]]: + """Find members that are defined in 'left' but have incompatible types. + Return them as a list of ('member', 'got', 'expected', 'is_lvalue'). + """ + assert right.type.is_protocol + conflicts: list[tuple[str, Type, Type, bool]] = [] + for member in right.type.protocol_members: + if member in ("__init__", "__new__"): + continue + supertype = find_member(member, right, left) + assert supertype is not None + subtype = mypy.typeops.get_protocol_member(left, member, class_obj) + if not subtype: + continue + is_compat = is_subtype(subtype, supertype, ignore_pos_arg_names=True, options=options) + if not is_compat: + conflicts.append((member, subtype, supertype, False)) + superflags = get_member_flags(member, right) + if IS_SETTABLE not in superflags: + continue + different_setter = False + if IS_EXPLICIT_SETTER in superflags: + set_supertype = find_member(member, right, left, is_lvalue=True) + if set_supertype and not is_same_type(set_supertype, supertype): + different_setter = True + supertype = set_supertype + if IS_EXPLICIT_SETTER in get_member_flags(member, left): + set_subtype = mypy.typeops.get_protocol_member(left, member, class_obj, is_lvalue=True) + if set_subtype and not is_same_type(set_subtype, subtype): + different_setter = True + subtype = set_subtype + if not is_compat and not different_setter: + # We already have this conflict listed, avoid duplicates. + continue + assert supertype is not None and subtype is not None + is_compat = is_subtype(supertype, subtype, options=options) + if not is_compat: + conflicts.append((member, subtype, supertype, different_setter)) + return conflicts + + +def get_bad_protocol_flags( + left: Instance, right: Instance, class_obj: bool = False +) -> list[tuple[str, set[int], set[int]]]: + """Return all incompatible attribute flags for members that are present in both + 'left' and 'right'. + """ + assert right.type.is_protocol + all_flags: list[tuple[str, set[int], set[int]]] = [] + for member in right.type.protocol_members: + if find_member(member, left, left, class_obj=class_obj): + all_flags.append( + ( + member, + get_member_flags(member, left, class_obj=class_obj), + get_member_flags(member, right), + ) + ) + bad_flags = [] + for name, subflags, superflags in all_flags: + if ( + IS_CLASSVAR in subflags + and IS_CLASSVAR not in superflags + and IS_SETTABLE in superflags + or IS_CLASSVAR in superflags + and IS_CLASSVAR not in subflags + or IS_SETTABLE in superflags + and IS_SETTABLE not in subflags + or IS_CLASS_OR_STATIC in superflags + and IS_CLASS_OR_STATIC not in subflags + or class_obj + and IS_VAR in superflags + and IS_CLASSVAR not in subflags + or class_obj + and IS_CLASSVAR in superflags + ): + bad_flags.append((name, subflags, superflags)) + return bad_flags + + +def capitalize(s: str) -> str: + """Capitalize the first character of a string.""" + if s == "": + return "" + else: + return s[0].upper() + s[1:] + + +def extract_type(name: str) -> str: + """If the argument is the name of a method (of form C.m), return + the type portion in quotes (e.g. "y"). Otherwise, return the string + unmodified. + """ + name = re.sub('^"[a-zA-Z0-9_]+" of ', "", name) + return name + + +def strip_quotes(s: str) -> str: + """Strip a double quote at the beginning and end of the string, if any.""" + s = re.sub('^"', "", s) + s = re.sub('"$', "", s) + return s + + +def format_string_list(lst: list[str]) -> str: + assert lst + if len(lst) == 1: + return lst[0] + elif len(lst) <= 5: + return f"{', '.join(lst[:-1])} and {lst[-1]}" + else: + return "%s, ... and %s (%i methods suppressed)" % ( + ", ".join(lst[:2]), + lst[-1], + len(lst) - 3, + ) + + +def format_item_name_list(s: Iterable[str]) -> str: + lst = list(s) + if len(lst) <= 5: + return "(" + ", ".join([f'"{name}"' for name in lst]) + ")" + else: + return "(" + ", ".join([f'"{name}"' for name in lst[:5]]) + ", ...)" + + +def callable_name(type: FunctionLike) -> str | None: + name = type.get_name() + if name is not None and name[0] != "<": + return f'"{name}"'.replace(" of ", '" of "') + return name + + +def for_function(callee: CallableType) -> str: + name = callable_name(callee) + if name is not None: + return f" for {name}" + return "" + + +def wrong_type_arg_count(low: int, high: int, act: str, name: str) -> str: + if low == high: + s = f"{low} type arguments" + if low == 0: + s = "no type arguments" + elif low == 1: + s = "1 type argument" + else: + s = f"between {low} and {high} type arguments" + if act == "0": + act = "none" + return f'"{name}" expects {s}, but {act} given' + + +def find_defining_module(modules: dict[str, MypyFile], typ: CallableType) -> MypyFile | None: + if not typ.definition: + return None + fullname = typ.definition.fullname + if "." in fullname: + for i in range(fullname.count(".")): + module_name = fullname.rsplit(".", i + 1)[0] + try: + return modules[module_name] + except KeyError: + pass + assert False, "Couldn't determine module from CallableType" + return None + + +# For hard-coding suggested missing member alternatives. +COMMON_MISTAKES: Final[dict[str, Sequence[str]]] = {"add": ("append", "extend")} + + +def _real_quick_ratio(a: str, b: str) -> float: + # this is an upper bound on difflib.SequenceMatcher.ratio + # similar to difflib.SequenceMatcher.real_quick_ratio, but faster since we don't instantiate + al = len(a) + bl = len(b) + return 2.0 * min(al, bl) / (al + bl) + + +def best_matches(current: str, options: Collection[str], n: int) -> list[str]: + if not current: + return [] + # narrow down options cheaply + options = [o for o in options if _real_quick_ratio(current, o) > 0.75] + if len(options) >= 50: + options = [o for o in options if abs(len(o) - len(current)) <= 1] + + ratios = {option: difflib.SequenceMatcher(a=current, b=option).ratio() for option in options} + options = [option for option, ratio in ratios.items() if ratio > 0.75] + return sorted(options, key=lambda v: (-ratios[v], v))[:n] + + +def pretty_seq(args: Sequence[str], conjunction: str) -> str: + quoted = ['"' + a + '"' for a in args] + if len(quoted) == 1: + return quoted[0] + if len(quoted) == 2: + return f"{quoted[0]} {conjunction} {quoted[1]}" + last_sep = ", " + conjunction + " " + return ", ".join(quoted[:-1]) + last_sep + quoted[-1] + + +def append_invariance_notes( + notes: list[str], arg_type: Instance, expected_type: Instance +) -> list[str]: + """Explain that the type is invariant and give notes for how to solve the issue.""" + invariant_type = "" + covariant_suggestion = "" + if ( + arg_type.type.fullname == "builtins.list" + and expected_type.type.fullname == "builtins.list" + and is_subtype(arg_type.args[0], expected_type.args[0]) + ): + invariant_type = "list" + covariant_suggestion = 'Consider using "Sequence" instead, which is covariant' + elif ( + arg_type.type.fullname == "builtins.dict" + and expected_type.type.fullname == "builtins.dict" + and is_same_type(arg_type.args[0], expected_type.args[0]) + and is_subtype(arg_type.args[1], expected_type.args[1]) + ): + invariant_type = "dict" + covariant_suggestion = ( + 'Consider using "Mapping" instead, which is covariant in the value type' + ) + if invariant_type and covariant_suggestion: + notes.append( + f'"{invariant_type}" is invariant -- see ' + + "https://mypy.readthedocs.io/en/stable/common_issues.html#variance" + ) + notes.append(covariant_suggestion) + return notes + + +def append_union_note( + notes: list[str], arg_type: UnionType, expected_type: UnionType, options: Options +) -> list[str]: + """Point to specific union item(s) that may cause failure in subtype check.""" + non_matching = [] + items = flatten_nested_unions(arg_type.items) + if len(items) < MAX_UNION_ITEMS: + return notes + for item in items: + if not is_subtype(item, expected_type): + non_matching.append(item) + if non_matching: + types = ", ".join([format_type(typ, options) for typ in non_matching]) + notes.append(f"Item{plural_s(non_matching)} in the first union not in the second: {types}") + return notes + + +def append_numbers_notes( + notes: list[str], arg_type: Instance, expected_type: Instance +) -> list[str]: + """Explain if an unsupported type from "numbers" is used in a subtype check.""" + if expected_type.type.fullname in UNSUPPORTED_NUMBERS_TYPES: + notes.append('Types from "numbers" are not supported for static type checking') + notes.append("See https://peps.python.org/pep-0484/#the-numeric-tower") + notes.append("Consider using a protocol instead, such as typing.SupportsFloat") + return notes + + +def make_inferred_type_note( + context: Context, subtype: Type, supertype: Type, supertype_str: str +) -> str: + """Explain that the user may have forgotten to type a variable. + + The user does not expect an error if the inferred container type is the same as the return + type of a function and the argument type(s) are a subtype of the argument type(s) of the + return type. This note suggests that they add a type annotation with the return type instead + of relying on the inferred type. + """ + subtype = get_proper_type(subtype) + supertype = get_proper_type(supertype) + if ( + isinstance(subtype, Instance) + and isinstance(supertype, Instance) + and subtype.type.fullname == supertype.type.fullname + and subtype.args + and supertype.args + and isinstance(context, ReturnStmt) + and isinstance(context.expr, NameExpr) + and isinstance(context.expr.node, Var) + and context.expr.node.is_inferred + ): + for subtype_arg, supertype_arg in zip(subtype.args, supertype.args): + if not is_subtype(subtype_arg, supertype_arg): + return "" + var_name = context.expr.name + return 'Perhaps you need a type annotation for "{}"? Suggestion: {}'.format( + var_name, supertype_str + ) + return "" + + +def format_key_list(keys: list[str], *, short: bool = False) -> str: + formatted_keys = [f'"{key}"' for key in keys] + td = "" if short else "TypedDict " + if len(keys) == 0: + return f"no {td}keys" + elif len(keys) == 1: + return f"{td}key {formatted_keys[0]}" + else: + return f"{td}keys ({', '.join(formatted_keys)})" + + +def ignore_last_known_values(t: UnionType) -> Type: + """This will avoid types like str | str in error messages. + + last_known_values are kept during union simplification, but may cause + weird formatting for e.g. tuples of literals. + """ + union_items: list[Type] = [] + seen_instances = set() + for item in t.items: + if isinstance(item, ProperType) and isinstance(item, Instance): + erased = item.copy_modified(last_known_value=None) + if erased in seen_instances: + continue + seen_instances.add(erased) + union_items.append(erased) + else: + union_items.append(item) + return UnionType.make_union(union_items, t.line, t.column) diff --git a/micromamba_root/Lib/site-packages/mypy/metastore.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/metastore.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..b6646c70f021deed6dd7d8a9f738c0c8e4761b67 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/metastore.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/metastore.py b/micromamba_root/Lib/site-packages/mypy/metastore.py new file mode 100644 index 0000000000000000000000000000000000000000..e12c0e26588302c36952791a74bb5c4ab0732942 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/metastore.py @@ -0,0 +1,243 @@ +"""Interfaces for accessing metadata. + +We provide two implementations. + * The "classic" file system implementation, which uses a directory + structure of files. + * A hokey sqlite backed implementation, which basically simulates + the file system in an effort to work around poor file system performance + on OS X. +""" + +from __future__ import annotations + +import binascii +import os +import time +from abc import abstractmethod +from collections.abc import Iterable +from typing import TYPE_CHECKING, Any + +from mypy.util import os_path_join + +if TYPE_CHECKING: + # We avoid importing sqlite3 unless we are using it so we can mostly work + # on semi-broken pythons that are missing it. + import sqlite3 + + +class MetadataStore: + """Generic interface for metadata storage.""" + + @abstractmethod + def getmtime(self, name: str) -> float: + """Read the mtime of a metadata entry. + + Raises FileNotFound if the entry does not exist. + """ + + @abstractmethod + def read(self, name: str) -> bytes: + """Read the contents of a metadata entry. + + Raises FileNotFound if the entry does not exist. + """ + + @abstractmethod + def write(self, name: str, data: bytes, mtime: float | None = None) -> bool: + """Write a metadata entry. + + If mtime is specified, set it as the mtime of the entry. Otherwise, + the current time is used. + + Returns True if the entry is successfully written, False otherwise. + """ + + @abstractmethod + def remove(self, name: str) -> None: + """Delete a metadata entry""" + + @abstractmethod + def commit(self) -> None: + """If the backing store requires a commit, do it. + + But N.B. that this is not *guaranteed* to do anything, and + there is no guarantee that changes are not made until it is + called. + """ + + @abstractmethod + def list_all(self) -> Iterable[str]: ... + + @abstractmethod + def close(self) -> None: + """Release any resources held by the backing store.""" + + +def random_string() -> str: + return binascii.hexlify(os.urandom(8)).decode("ascii") + + +class FilesystemMetadataStore(MetadataStore): + def __init__(self, cache_dir_prefix: str) -> None: + # We check startswith instead of equality because the version + # will have already been appended by the time the cache dir is + # passed here. + if cache_dir_prefix.startswith(os.devnull): + self.cache_dir_prefix = None + else: + self.cache_dir_prefix = cache_dir_prefix + + def getmtime(self, name: str) -> float: + if not self.cache_dir_prefix: + raise FileNotFoundError() + + return int(os.path.getmtime(os_path_join(self.cache_dir_prefix, name))) + + def read(self, name: str) -> bytes: + assert not os.path.isabs(name), "Don't use absolute paths!" + + if not self.cache_dir_prefix: + raise FileNotFoundError() + + with open(os_path_join(self.cache_dir_prefix, name), "rb", buffering=0) as f: + return f.read() + + def write(self, name: str, data: bytes, mtime: float | None = None) -> bool: + assert not os.path.isabs(name), "Don't use absolute paths!" + + if not self.cache_dir_prefix: + return False + + path = os_path_join(self.cache_dir_prefix, name) + tmp_filename = path + "." + random_string() + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(tmp_filename, "wb") as f: + f.write(data) + os.replace(tmp_filename, path) + if mtime is not None: + os.utime(path, times=(mtime, mtime)) + + except OSError: + return False + return True + + def remove(self, name: str) -> None: + if not self.cache_dir_prefix: + raise FileNotFoundError() + + os.remove(os_path_join(self.cache_dir_prefix, name)) + + def commit(self) -> None: + pass + + def list_all(self) -> Iterable[str]: + if not self.cache_dir_prefix: + return + + for dir, _, files in os.walk(self.cache_dir_prefix): + dir = os.path.relpath(dir, self.cache_dir_prefix) + for file in files: + yield os.path.normpath(os_path_join(dir, file)) + + def close(self) -> None: + pass + + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS files2 ( + path TEXT UNIQUE NOT NULL, + mtime REAL, + data BLOB +); +CREATE INDEX IF NOT EXISTS path_idx on files2(path); +""" + + +def connect_db(db_file: str, set_journal_mode: bool) -> sqlite3.Connection: + import sqlite3.dbapi2 + + db = sqlite3.dbapi2.connect(db_file) + # This is a bit unfortunate (as we may get corrupt cache after e.g. Ctrl + C), + # but without this flag, commits are *very* slow, especially when using HDDs, + # see https://www.sqlite.org/faq.html#q19 for details. + db.execute("PRAGMA synchronous=OFF") + if set_journal_mode: + db.execute("PRAGMA journal_mode=WAL") + db.executescript(SCHEMA) + return db + + +class SqliteMetadataStore(MetadataStore): + def __init__(self, cache_dir_prefix: str, set_journal_mode: bool = False) -> None: + # We check startswith instead of equality because the version + # will have already been appended by the time the cache dir is + # passed here. + self.db = None + if cache_dir_prefix.startswith(os.devnull): + return + + os.makedirs(cache_dir_prefix, exist_ok=True) + self.db = connect_db(os_path_join(cache_dir_prefix, "cache.db"), set_journal_mode) + + def _query(self, name: str, field: str) -> Any: + # Raises FileNotFound for consistency with the file system version + if not self.db: + raise FileNotFoundError() + + cur = self.db.execute(f"SELECT {field} FROM files2 WHERE path = ?", (name,)) + results = cur.fetchall() + if not results: + raise FileNotFoundError() + assert len(results) == 1 + return results[0][0] + + def getmtime(self, name: str) -> float: + mtime = self._query(name, "mtime") + assert isinstance(mtime, float) + return mtime + + def read(self, name: str) -> bytes: + data = self._query(name, "data") + assert isinstance(data, bytes) + return data + + def write(self, name: str, data: bytes, mtime: float | None = None) -> bool: + import sqlite3 + + if not self.db: + return False + try: + if mtime is None: + mtime = time.time() + self.db.execute( + "INSERT OR REPLACE INTO files2(path, mtime, data) VALUES(?, ?, ?)", + (name, mtime, data), + ) + except sqlite3.OperationalError: + return False + return True + + def remove(self, name: str) -> None: + if not self.db: + raise FileNotFoundError() + + self.db.execute("DELETE FROM files2 WHERE path = ?", (name,)) + + def commit(self) -> None: + if self.db: + self.db.commit() + + def list_all(self) -> Iterable[str]: + if self.db: + for row in self.db.execute("SELECT path FROM files2"): + yield row[0] + + def close(self) -> None: + if self.db: + db = self.db + self.db = None + db.close() + + def __del__(self) -> None: + self.close() diff --git a/micromamba_root/Lib/site-packages/mypy/mixedtraverser.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/mixedtraverser.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..3a19c7d89cd56ffd6f3b966e3083a5ac50cf55aa Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/mixedtraverser.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/mixedtraverser.py b/micromamba_root/Lib/site-packages/mypy/mixedtraverser.py new file mode 100644 index 0000000000000000000000000000000000000000..535391886b0205936b98cc559b581e3263e98df1 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/mixedtraverser.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +from mypy.nodes import ( + AssertTypeExpr, + AssignmentStmt, + CastExpr, + ClassDef, + ForStmt, + FuncItem, + NamedTupleExpr, + NewTypeExpr, + PromoteExpr, + TypeAlias, + TypeAliasExpr, + TypeAliasStmt, + TypeApplication, + TypedDictExpr, + TypeFormExpr, + TypeVarExpr, + Var, + WithStmt, +) +from mypy.traverser import TraverserVisitor +from mypy.types import Type +from mypy.typetraverser import TypeTraverserVisitor + + +class MixedTraverserVisitor(TraverserVisitor, TypeTraverserVisitor): + """Recursive traversal of both Node and Type objects.""" + + def __init__(self) -> None: + self.in_type_alias_expr = False + + # Symbol nodes + + def visit_var(self, var: Var, /) -> None: + self.visit_optional_type(var.type) + + def visit_func(self, o: FuncItem, /) -> None: + super().visit_func(o) + self.visit_optional_type(o.type) + + def visit_class_def(self, o: ClassDef, /) -> None: + # TODO: Should we visit generated methods/variables as well, either here or in + # TraverserVisitor? + super().visit_class_def(o) + info = o.info + if info: + for base in info.bases: + base.accept(self) + if info.special_alias: + info.special_alias.accept(self) + + def visit_type_alias_expr(self, o: TypeAliasExpr, /) -> None: + super().visit_type_alias_expr(o) + o.node.accept(self) + + def visit_type_var_expr(self, o: TypeVarExpr, /) -> None: + super().visit_type_var_expr(o) + o.upper_bound.accept(self) + o.default.accept(self) + for value in o.values: + value.accept(self) + + def visit_typeddict_expr(self, o: TypedDictExpr, /) -> None: + super().visit_typeddict_expr(o) + self.visit_optional_type(o.info.typeddict_type) + + def visit_namedtuple_expr(self, o: NamedTupleExpr, /) -> None: + super().visit_namedtuple_expr(o) + assert o.info.tuple_type + o.info.tuple_type.accept(self) + + def visit__promote_expr(self, o: PromoteExpr, /) -> None: + super().visit__promote_expr(o) + o.type.accept(self) + + def visit_newtype_expr(self, o: NewTypeExpr, /) -> None: + super().visit_newtype_expr(o) + self.visit_optional_type(o.old_type) + + # Statements + + def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None: + super().visit_assignment_stmt(o) + self.visit_optional_type(o.type) + + def visit_type_alias_stmt(self, o: TypeAliasStmt, /) -> None: + super().visit_type_alias_stmt(o) + if o.alias_node is not None: + o.alias_node.accept(self) + + def visit_type_alias(self, o: TypeAlias, /) -> None: + super().visit_type_alias(o) + self.in_type_alias_expr = True + o.target.accept(self) + self.in_type_alias_expr = False + + def visit_for_stmt(self, o: ForStmt, /) -> None: + super().visit_for_stmt(o) + self.visit_optional_type(o.index_type) + + def visit_with_stmt(self, o: WithStmt, /) -> None: + super().visit_with_stmt(o) + for typ in o.analyzed_types: + typ.accept(self) + + # Expressions + + def visit_cast_expr(self, o: CastExpr, /) -> None: + super().visit_cast_expr(o) + o.type.accept(self) + + def visit_type_form_expr(self, o: TypeFormExpr, /) -> None: + super().visit_type_form_expr(o) + o.type.accept(self) + + def visit_assert_type_expr(self, o: AssertTypeExpr, /) -> None: + super().visit_assert_type_expr(o) + o.type.accept(self) + + def visit_type_application(self, o: TypeApplication, /) -> None: + super().visit_type_application(o) + for t in o.types: + t.accept(self) + + # Helpers + + def visit_optional_type(self, t: Type | None, /) -> None: + if t: + t.accept(self) diff --git a/micromamba_root/Lib/site-packages/mypy/modulefinder.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/modulefinder.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ee72216908be37b06636224f7409c5a0030aefc5 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/modulefinder.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/modulefinder.py b/micromamba_root/Lib/site-packages/mypy/modulefinder.py new file mode 100644 index 0000000000000000000000000000000000000000..b3b88e5aac65772bfec64be94ce5b2954e283dc4 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/modulefinder.py @@ -0,0 +1,1002 @@ +"""Low-level infrastructure to find modules. + +This builds on fscache.py; find_sources.py builds on top of this. +""" + +from __future__ import annotations + +import ast +import collections +import functools +import os +import re +import subprocess +import sys +from enum import Enum, unique +from typing import Final, TypeAlias as _TypeAlias + +from pathspec import PathSpec +from pathspec.patterns.gitignore import GitIgnorePatternError + +from mypy import pyinfo +from mypy.errors import CompileError +from mypy.fscache import FileSystemCache +from mypy.nodes import MypyFile +from mypy.options import Options +from mypy.stubinfo import stub_distribution_name +from mypy.util import os_path_join + + +# Paths to be searched in find_module(). +class SearchPaths: + def __init__( + self, + python_path: tuple[str, ...], + mypy_path: tuple[str, ...], + package_path: tuple[str, ...], + typeshed_path: tuple[str, ...], + ) -> None: + # where user code is found + self.python_path = tuple(map(os.path.abspath, python_path)) + # from $MYPYPATH or config variable + self.mypy_path = tuple(map(os.path.abspath, mypy_path)) + # from get_site_packages_dirs() + self.package_path = tuple(map(os.path.abspath, package_path)) + # paths in typeshed + self.typeshed_path = tuple(map(os.path.abspath, typeshed_path)) + + def asdict(self) -> dict[str, tuple[str, ...]]: + return { + "python_path": self.python_path, + "mypy_path": self.mypy_path, + "package_path": self.package_path, + "typeshed_path": self.typeshed_path, + } + + +# Package dirs are a two-tuple of path to search and whether to verify the module +OnePackageDir = tuple[str, bool] +PackageDirs = list[OnePackageDir] + +# Minimum and maximum Python versions for modules in stdlib as (major, minor) +StdlibVersions: _TypeAlias = dict[str, tuple[tuple[int, int], tuple[int, int] | None]] + +PYTHON_EXTENSIONS: Final = [".pyi", ".py"] + + +# TODO: Consider adding more reasons here? +# E.g. if we deduce a module would likely be found if the user were +# to set the --namespace-packages flag. +@unique +class ModuleNotFoundReason(Enum): + # The module was not found: we found neither stubs nor a plausible code + # implementation (with or without a py.typed file). + NOT_FOUND = 0 + + # The implementation for this module plausibly exists (e.g. we + # found a matching folder or *.py file), but either the parent package + # did not contain a py.typed file or we were unable to find a + # corresponding *-stubs package. + FOUND_WITHOUT_TYPE_HINTS = 1 + + # The module was not found in the current working directory, but + # was able to be found in the parent directory. + WRONG_WORKING_DIRECTORY = 2 + + # Stub PyPI package (typically types-pkgname) known to exist but not installed. + APPROVED_STUBS_NOT_INSTALLED = 3 + + def error_message_templates(self, daemon: bool) -> tuple[str, list[str]]: + doc_link = "See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports" + if self is ModuleNotFoundReason.NOT_FOUND: + msg = 'Cannot find implementation or library stub for module named "{module}"' + notes = [doc_link] + elif self is ModuleNotFoundReason.WRONG_WORKING_DIRECTORY: + msg = 'Cannot find implementation or library stub for module named "{module}"' + notes = [ + "You may be running mypy in a subpackage, mypy should be run on the package root" + ] + elif self is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: + msg = ( + 'Skipping analyzing "{module}": module is installed, but missing library stubs ' + "or py.typed marker" + ) + notes = [doc_link] + elif self is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED: + msg = 'Library stubs not installed for "{module}"' + notes = ['Hint: "python3 -m pip install {stub_dist}"'] + if not daemon: + notes.append( + '(or run "mypy --install-types" to install all missing stub packages)' + ) + notes.append(doc_link) + else: + assert False + return msg, notes + + +# If we found the module, returns the path to the module as a str. +# Otherwise, returns the reason why the module wasn't found. +ModuleSearchResult = str | ModuleNotFoundReason + + +class BuildSource: + """A single source file.""" + + def __init__( + self, + path: str | None, + module: str | None, + text: str | None = None, + base_dir: str | None = None, + followed: bool = False, + ) -> None: + self.path = path # File where it's found (e.g. 'xxx/yyy/foo/bar.py') + self.module = module or "__main__" # Module name (e.g. 'foo.bar') + self.text = text # Source code, if initially supplied, else None + self.base_dir = base_dir # Directory where the package is rooted (e.g. 'xxx/yyy') + self.followed = followed # Was this found by following imports? + + def __repr__(self) -> str: + return ( + "BuildSource(path={!r}, module={!r}, has_text={}, base_dir={!r}, followed={})".format( + self.path, self.module, self.text is not None, self.base_dir, self.followed + ) + ) + + +class BuildSourceSet: + """Helper to efficiently test a file's membership in a set of build sources.""" + + def __init__(self, sources: list[BuildSource]) -> None: + self.source_text_present = False + self.source_modules: dict[str, str] = {} + self.source_paths: set[str] = set() + + for source in sources: + if source.text is not None: + self.source_text_present = True + if source.path: + self.source_paths.add(source.path) + if source.module: + self.source_modules[source.module] = source.path or "" + + def is_source(self, file: MypyFile) -> bool: + return ( + (file.path and file.path in self.source_paths) + or file._fullname in self.source_modules + or self.source_text_present + ) + + +class FindModuleCache: + """Module finder with integrated cache. + + Module locations and some intermediate results are cached internally + and can be cleared with the clear() method. + + All file system accesses are performed through a FileSystemCache, + which is not ever cleared by this class. If necessary it must be + cleared by client code. + """ + + def __init__( + self, + search_paths: SearchPaths, + fscache: FileSystemCache | None, + options: Options | None, + stdlib_py_versions: StdlibVersions | None = None, + source_set: BuildSourceSet | None = None, + ) -> None: + self.search_paths = search_paths + self.source_set = source_set + self.fscache = fscache or FileSystemCache() + # Cache for get_toplevel_possibilities: + # search_paths -> (toplevel_id -> list(package_dirs)) + self.initial_components: dict[tuple[str, ...], dict[str, list[str]]] = {} + # Cache find_module: id -> result + self.results: dict[str, ModuleSearchResult] = {} + self.ns_ancestors: dict[str, str] = {} + self.options = options + custom_typeshed_dir = None + if options: + custom_typeshed_dir = options.custom_typeshed_dir + self.stdlib_py_versions = stdlib_py_versions or load_stdlib_py_versions( + custom_typeshed_dir + ) + + def clear(self) -> None: + self.results.clear() + self.initial_components.clear() + self.ns_ancestors.clear() + + def find_module_via_source_set(self, id: str) -> ModuleSearchResult | None: + """Fast path to find modules by looking through the input sources + + This is only used when --fast-module-lookup is passed on the command line.""" + if not self.source_set: + return None + + p = self.source_set.source_modules.get(id, None) + if p and self.fscache.isfile(p): + # We need to make sure we still have __init__.py all the way up + # otherwise we might have false positives compared to slow path + # in case of deletion of init files, which is covered by some tests. + # TODO: are there some combination of flags in which this check should be skipped? + d = os.path.dirname(p) + for _ in range(id.count(".")): + if not any( + self.fscache.isfile(os_path_join(d, "__init__" + x)) for x in PYTHON_EXTENSIONS + ): + return None + d = os.path.dirname(d) + return p + + idx = id.rfind(".") + if idx != -1: + # When we're looking for foo.bar.baz and can't find a matching module + # in the source set, look up for a foo.bar module. + parent = self.find_module_via_source_set(id[:idx]) + if parent is None or not isinstance(parent, str): + return None + + basename, ext = os.path.splitext(parent) + if not any(parent.endswith("__init__" + x) for x in PYTHON_EXTENSIONS) and ( + ext in PYTHON_EXTENSIONS and not self.fscache.isdir(basename) + ): + # If we do find such a *module* (and crucially, we don't want a package, + # hence the filtering out of __init__ files, and checking for the presence + # of a folder with a matching name), then we can be pretty confident that + # 'baz' will either be a top-level variable in foo.bar, or will not exist. + # + # Either way, spelunking in other search paths for another 'foo.bar.baz' + # module should be avoided because: + # 1. in the unlikely event that one were found, it's highly likely that + # it would be unrelated to the source being typechecked and therefore + # more likely to lead to erroneous results + # 2. as described in _find_module, in some cases the search itself could + # potentially waste significant amounts of time + return ModuleNotFoundReason.NOT_FOUND + return None + + def find_lib_path_dirs(self, id: str, lib_path: tuple[str, ...]) -> PackageDirs: + """Find which elements of a lib_path have the directory a module needs to exist.""" + components = id.split(".") + dir_chain = os.sep.join(components[:-1]) # e.g., 'foo/bar' + + dirs = [] + for pathitem in self.get_toplevel_possibilities(lib_path, components[0]): + # e.g., '/usr/lib/python3.4/foo/bar' + if dir_chain: + dir = os_path_join(pathitem, dir_chain) + else: + dir = pathitem + if self.fscache.isdir(dir): + dirs.append((dir, True)) + return dirs + + def get_toplevel_possibilities(self, lib_path: tuple[str, ...], id: str) -> list[str]: + """Find which elements of lib_path could contain a particular top-level module. + + In practice, almost all modules can be routed to the correct entry in + lib_path by looking at just the first component of the module name. + + We take advantage of this by enumerating the contents of all of the + directories on the lib_path and building a map of which entries in + the lib_path could contain each potential top-level module that appears. + """ + + if lib_path in self.initial_components: + return self.initial_components[lib_path].get(id, []) + + # Enumerate all the files in the directories on lib_path and produce the map + components: dict[str, list[str]] = {} + for dir in lib_path: + try: + contents = self.fscache.listdir(dir) + except OSError: + contents = [] + # False positives are fine for correctness here, since we will check + # precisely later, so we only look at the root of every filename without + # any concern for the exact details. + for name in contents: + name = os.path.splitext(name)[0] + components.setdefault(name, []).append(dir) + + self.initial_components[lib_path] = components + return components.get(id, []) + + def find_module(self, id: str, *, fast_path: bool = False) -> ModuleSearchResult: + """Return the path of the module source file or why it wasn't found. + + If fast_path is True, prioritize performance over generating detailed + error descriptions. + """ + if id not in self.results: + top_level = id.partition(".")[0] + use_typeshed = True + if id in self.stdlib_py_versions: + use_typeshed = self._typeshed_has_version(id) + elif top_level in self.stdlib_py_versions: + use_typeshed = self._typeshed_has_version(top_level) + result, should_cache = self._find_module(id, use_typeshed) + if should_cache: + if ( + not ( + fast_path or (self.options is not None and self.options.fast_module_lookup) + ) + and result is ModuleNotFoundReason.NOT_FOUND + and self._can_find_module_in_parent_dir(id) + ): + self.results[id] = ModuleNotFoundReason.WRONG_WORKING_DIRECTORY + else: + self.results[id] = result + return self.results[id] + else: + return result + return self.results[id] + + def _typeshed_has_version(self, module: str) -> bool: + if not self.options: + return True + version = typeshed_py_version(self.options) + min_version, max_version = self.stdlib_py_versions[module] + return version >= min_version and (max_version is None or version <= max_version) + + def _find_module_non_stub_helper( + self, id: str, pkg_dir: str + ) -> OnePackageDir | ModuleNotFoundReason: + plausible_match = False + dir_path = pkg_dir + components = id.split(".") + for index, component in enumerate(components): + dir_path = os_path_join(dir_path, component) + if self.fscache.isfile(os_path_join(dir_path, "py.typed")): + return os.path.join(pkg_dir, *components[:-1]), index == 0 + elif not plausible_match and ( + self.fscache.isdir(dir_path) or self.fscache.isfile(dir_path + ".py") + ): + plausible_match = True + # If this is not a directory then we can't traverse further into it + if not self.fscache.isdir(dir_path): + break + if plausible_match: + if self.options: + module_specific_options = self.options.clone_for_module(id) + if module_specific_options.follow_untyped_imports: + return os.path.join(pkg_dir, *components[:-1]), False + return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS + else: + return ModuleNotFoundReason.NOT_FOUND + + def _update_ns_ancestors(self, components: list[str], match: tuple[str, bool]) -> None: + path, verify = match + for i in range(1, len(components)): + pkg_id = ".".join(components[:-i]) + if pkg_id not in self.ns_ancestors and self.fscache.isdir(path): + self.ns_ancestors[pkg_id] = path + path = os.path.dirname(path) + + def _can_find_module_in_parent_dir(self, id: str) -> bool: + """Test if a module can be found by checking the parent directories + of the current working directory. + """ + working_dir = os.getcwd() + parent_search = FindModuleCache( + SearchPaths((), (), (), ()), + self.fscache, + self.options, + stdlib_py_versions=self.stdlib_py_versions, + ) + while any(is_init_file(file) for file in os.listdir(working_dir)): + working_dir = os.path.dirname(working_dir) + parent_search.search_paths = SearchPaths((working_dir,), (), (), ()) + if not isinstance(parent_search._find_module(id, False)[0], ModuleNotFoundReason): + return True + return False + + def _find_module(self, id: str, use_typeshed: bool) -> tuple[ModuleSearchResult, bool]: + """Try to find a module in all available sources. + + Returns: + ``(result, can_be_cached)`` pair. + """ + fscache = self.fscache + + # Fast path for any modules in the current source set. + # This is particularly important when there are a large number of search + # paths which share the first (few) component(s) due to the use of namespace + # packages, for instance: + # foo/ + # company/ + # __init__.py + # foo/ + # bar/ + # company/ + # __init__.py + # bar/ + # baz/ + # company/ + # __init__.py + # baz/ + # + # mypy gets [foo/company/foo, bar/company/bar, baz/company/baz, ...] as input + # and computes [foo, bar, baz, ...] as the module search path. + # + # This would result in O(n) search for every import of company.*, leading to + # O(n**2) behavior in load_graph as such imports are unsurprisingly present + # at least once, and usually many more times than that, in each and every file + # being parsed. + # + # Thankfully, such cases are efficiently handled by looking up the module path + # via BuildSourceSet. + p = ( + self.find_module_via_source_set(id) + if (self.options is not None and self.options.fast_module_lookup) + else None + ) + if p: + return p, True + + # If we're looking for a module like 'foo.bar.baz', it's likely that most of the + # many elements of lib_path don't even have a subdirectory 'foo/bar'. Discover + # that only once and cache it for when we look for modules like 'foo.bar.blah' + # that will require the same subdirectory. + components = id.split(".") + dir_chain = os.sep.join(components[:-1]) # e.g., 'foo/bar' + + # We have two sets of folders so that we collect *all* stubs folders and + # put them in the front of the search path + third_party_inline_dirs: PackageDirs = [] + third_party_stubs_dirs: PackageDirs = [] + found_possible_third_party_missing_type_hints = False + # Third-party stub/typed packages + candidate_package_dirs = { + package_dir[0] + for component in (components[0], components[0] + "-stubs") + for package_dir in self.find_lib_path_dirs(component, self.search_paths.package_path) + } + # Caching FOUND_WITHOUT_TYPE_HINTS is not always safe. That causes issues with + # typed subpackages in namespace packages. + can_cache_any_result = True + for pkg_dir in self.search_paths.package_path: + if pkg_dir not in candidate_package_dirs: + continue + stub_name = components[0] + "-stubs" + stub_dir = os_path_join(pkg_dir, stub_name) + if fscache.isdir(stub_dir): + stub_typed_file = os_path_join(stub_dir, "py.typed") + stub_components = [stub_name] + components[1:] + path = os.path.join(pkg_dir, *stub_components[:-1]) + if fscache.isdir(path): + if fscache.isfile(stub_typed_file): + # Stub packages can have a py.typed file, which must include + # 'partial\n' to make the package partial. + # Partial here means that mypy should look at the runtime + # package if installed. + if fscache.read(stub_typed_file).decode().strip() == "partial": + runtime_path = os_path_join(pkg_dir, dir_chain) + third_party_inline_dirs.append((runtime_path, True)) + # if the package is partial, we don't verify the module, as + # the partial stub package may not have a __init__.pyi + third_party_stubs_dirs.append((path, False)) + else: + # handle the edge case where people put a py.typed file + # in a stub package, but it isn't partial + third_party_stubs_dirs.append((path, True)) + else: + third_party_stubs_dirs.append((path, True)) + non_stub_match = self._find_module_non_stub_helper(id, pkg_dir) + if isinstance(non_stub_match, ModuleNotFoundReason): + if non_stub_match is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: + found_possible_third_party_missing_type_hints = True + can_cache_any_result = False + else: + third_party_inline_dirs.append(non_stub_match) + self._update_ns_ancestors(components, non_stub_match) + + if self.options and self.options.use_builtins_fixtures: + # Everything should be in fixtures. + third_party_inline_dirs.clear() + third_party_stubs_dirs.clear() + found_possible_third_party_missing_type_hints = False + python_mypy_path = self.search_paths.mypy_path + self.search_paths.python_path + candidate_base_dirs = self.find_lib_path_dirs(id, python_mypy_path) + if use_typeshed: + # Search for stdlib stubs in typeshed before installed + # stubs to avoid picking up backports (dataclasses, for + # example) when the library is included in stdlib. + candidate_base_dirs += self.find_lib_path_dirs(id, self.search_paths.typeshed_path) + candidate_base_dirs += third_party_stubs_dirs + third_party_inline_dirs + + # If we're looking for a module like 'foo.bar.baz', then candidate_base_dirs now + # contains just the subdirectories 'foo/bar' that actually exist under the + # elements of lib_path. This is probably much shorter than lib_path itself. + # Now just look for 'baz.pyi', 'baz/__init__.py', etc., inside those directories. + seplast = os.sep + components[-1] # so e.g. '/baz' + sepinit = os.sep + "__init__" + near_misses = [] # Collect near misses for namespace mode (see below). + for base_dir, verify in candidate_base_dirs: + base_path = base_dir + seplast # so e.g. '/usr/lib/python3.4/foo/bar/baz' + has_init = False + dir_prefix = base_dir + for _ in range(len(components) - 1): + dir_prefix = os.path.dirname(dir_prefix) + + # Stubs-only packages always take precedence over py.typed packages + path_stubs = f"{base_path}-stubs{sepinit}.pyi" + if fscache.isfile_case(path_stubs, dir_prefix): + if verify and not verify_module(fscache, id, path_stubs, dir_prefix): + near_misses.append((path_stubs, dir_prefix)) + else: + return path_stubs, True + + # Prefer package over module, i.e. baz/__init__.py* over baz.py*. + for extension in PYTHON_EXTENSIONS: + path = base_path + sepinit + extension + if fscache.isfile_case(path, dir_prefix): + has_init = True + if verify and not verify_module(fscache, id, path, dir_prefix): + near_misses.append((path, dir_prefix)) + continue + return path, True + + # In namespace mode, register a potential namespace package + if self.options and self.options.namespace_packages: + if ( + not has_init + and fscache.exists_case(base_path, dir_prefix) + and not fscache.isfile_case(base_path, dir_prefix) + ): + near_misses.append((base_path, dir_prefix)) + + # No package, look for module. + for extension in PYTHON_EXTENSIONS: + path = base_path + extension + if fscache.isfile_case(path, dir_prefix): + if verify and not verify_module(fscache, id, path, dir_prefix): + near_misses.append((path, dir_prefix)) + continue + return path, True + + # In namespace mode, re-check those entries that had 'verify'. + # Assume search path entries xxx, yyy and zzz, and we're + # looking for foo.bar.baz. Suppose near_misses has: + # + # - xxx/foo/bar/baz.py + # - yyy/foo/bar/baz/__init__.py + # - zzz/foo/bar/baz.pyi + # + # If any of the foo directories has __init__.py[i], it wins. + # Else, we look for foo/bar/__init__.py[i], etc. If there are + # none, the first hit wins. Note that this does not take into + # account whether the lowest-level module is a file (baz.py), + # a package (baz/__init__.py), or a stub file (baz.pyi) -- for + # these the first one encountered along the search path wins. + # + # The helper function highest_init_level() returns an int that + # indicates the highest level at which a __init__.py[i] file + # is found; if no __init__ was found it returns 0, if we find + # only foo/bar/__init__.py it returns 1, and if we have + # foo/__init__.py it returns 2 (regardless of what's in + # foo/bar). It doesn't look higher than that. + if self.options and self.options.namespace_packages and near_misses: + levels = [ + highest_init_level(fscache, id, path, dir_prefix) + for path, dir_prefix in near_misses + ] + index = levels.index(max(levels)) + return near_misses[index][0], True + + # Finally, we may be asked to produce an ancestor for an + # installed package with a py.typed marker that is a + # subpackage of a namespace package. We only fess up to these + # if we would otherwise return "not found". + ancestor = self.ns_ancestors.get(id) + if ancestor is not None: + return ancestor, True + + approved_dist_name = stub_distribution_name(id) + if approved_dist_name: + if len(components) == 1: + return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED, True + # If we're a missing submodule of an already installed approved stubs, we don't want to + # error with APPROVED_STUBS_NOT_INSTALLED, but rather want to return NOT_FOUND. + for i in range(1, len(components)): + parent_id = ".".join(components[:i]) + if stub_distribution_name(parent_id) == approved_dist_name: + break + else: + return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED, True + if self.find_module(parent_id) is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED: + return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED, True + return ModuleNotFoundReason.NOT_FOUND, True + + if found_possible_third_party_missing_type_hints: + return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS, can_cache_any_result + return ModuleNotFoundReason.NOT_FOUND, True + + def find_modules_recursive(self, module: str) -> list[BuildSource]: + module_path = self.find_module(module, fast_path=True) + if isinstance(module_path, ModuleNotFoundReason): + return [] + sources = [BuildSource(module_path, module, None)] + + package_path = None + if is_init_file(module_path): + package_path = os.path.dirname(module_path) + elif self.fscache.isdir(module_path): + package_path = module_path + if package_path is None: + return sources + + # This logic closely mirrors that in find_sources. One small but important difference is + # that we do not sort names with keyfunc. The recursive call to find_modules_recursive + # calls find_module, which will handle the preference between packages, pyi and py. + # Another difference is it doesn't handle nested search paths / package roots. + + seen: set[str] = set() + names = sorted(self.fscache.listdir(package_path)) + for name in names: + # Skip certain names altogether + if name in ("__pycache__", "site-packages", "node_modules") or name.startswith("."): + continue + subpath = os_path_join(package_path, name) + + if self.options and matches_exclude( + subpath, self.options.exclude, self.fscache, self.options.verbosity >= 2 + ): + continue + if ( + self.options + and self.options.exclude_gitignore + and matches_gitignore(subpath, self.fscache, self.options.verbosity >= 2) + ): + continue + + if self.fscache.isdir(subpath): + # Only recurse into packages + if (self.options and self.options.namespace_packages) or ( + self.fscache.isfile(os_path_join(subpath, "__init__.py")) + or self.fscache.isfile(os_path_join(subpath, "__init__.pyi")) + ): + seen.add(name) + sources.extend(self.find_modules_recursive(module + "." + name)) + else: + stem, suffix = os.path.splitext(name) + if stem == "__init__": + continue + if stem not in seen and "." not in stem and suffix in PYTHON_EXTENSIONS: + # (If we sorted names by keyfunc) we could probably just make the BuildSource + # ourselves, but this ensures compatibility with find_module / the cache + seen.add(stem) + sources.extend(self.find_modules_recursive(module + "." + stem)) + return sources + + +def matches_exclude( + subpath: str, excludes: list[str], fscache: FileSystemCache, verbose: bool +) -> bool: + if not excludes: + return False + subpath_str = os.path.relpath(subpath).replace(os.sep, "/") + if fscache.isdir(subpath): + subpath_str += "/" + for exclude in excludes: + try: + if re.search(exclude, subpath_str): + if verbose: + print( + f"TRACE: Excluding {subpath_str} (matches pattern {exclude})", + file=sys.stderr, + ) + return True + except re.error as e: + print( + f"error: The exclude {exclude} is an invalid regular expression, because: {e}" + + ( + "\n(Hint: use / as a path separator, even if you're on Windows!)" + if "\\" in exclude + else "" + ) + + "\nFor more information on Python's flavor of regex, see:" + + " https://docs.python.org/3/library/re.html", + file=sys.stderr, + ) + sys.exit(2) + return False + + +def matches_gitignore(subpath: str, fscache: FileSystemCache, verbose: bool) -> bool: + dir, _ = os.path.split(subpath) + for gi_path, gi_spec in find_gitignores(dir): + relative_path = os.path.relpath(subpath, gi_path) + if fscache.isdir(relative_path): + relative_path = relative_path + "/" + if gi_spec.match_file(relative_path): + if verbose: + print( + f"TRACE: Excluding {relative_path} (matches .gitignore) in {gi_path}", + file=sys.stderr, + ) + return True + return False + + +@functools.lru_cache +def find_gitignores(dir: str) -> list[tuple[str, PathSpec]]: + parent_dir = os.path.dirname(dir) + if parent_dir == dir or os.path.exists(os.path.join(dir, ".git")): + parent_gitignores = [] + else: + parent_gitignores = find_gitignores(parent_dir) + + gitignore = os.path.join(dir, ".gitignore") + if os.path.isfile(gitignore): + with open(gitignore) as f: + lines = f.readlines() + try: + return parent_gitignores + [(dir, PathSpec.from_lines("gitignore", lines))] + except GitIgnorePatternError: + print(f"error: could not parse {gitignore}", file=sys.stderr) + return parent_gitignores + return parent_gitignores + + +def is_init_file(path: str) -> bool: + return os.path.basename(path) in ("__init__.py", "__init__.pyi") + + +def verify_module(fscache: FileSystemCache, id: str, path: str, prefix: str) -> bool: + """Check that all packages containing id have a __init__ file.""" + if is_init_file(path): + path = os.path.dirname(path) + for i in range(id.count(".")): + path = os.path.dirname(path) + if not any( + fscache.isfile_case(os_path_join(path, f"__init__{extension}"), prefix) + for extension in PYTHON_EXTENSIONS + ): + return False + return True + + +def highest_init_level(fscache: FileSystemCache, id: str, path: str, prefix: str) -> int: + """Compute the highest level where an __init__ file is found.""" + if is_init_file(path): + path = os.path.dirname(path) + level = 0 + for i in range(id.count(".")): + path = os.path.dirname(path) + if any( + fscache.isfile_case(os_path_join(path, f"__init__{extension}"), prefix) + for extension in PYTHON_EXTENSIONS + ): + level = i + 1 + return level + + +def mypy_path() -> list[str]: + path_env = os.getenv("MYPYPATH") + if not path_env: + return [] + return path_env.split(os.pathsep) + + +def default_lib_path( + data_dir: str, pyversion: tuple[int, int], custom_typeshed_dir: str | None +) -> list[str]: + """Return default standard library search paths. Guaranteed to be normalised.""" + + data_dir = os.path.abspath(data_dir) + path: list[str] = [] + + if custom_typeshed_dir: + custom_typeshed_dir = os.path.abspath(custom_typeshed_dir) + typeshed_dir = os.path.join(custom_typeshed_dir, "stdlib") + mypy_extensions_dir = os.path.join(custom_typeshed_dir, "stubs", "mypy-extensions") + librt_dir = os.path.join(custom_typeshed_dir, "stubs", "librt") + versions_file = os.path.join(typeshed_dir, "VERSIONS") + if not os.path.isdir(typeshed_dir) or not os.path.isfile(versions_file): + print( + "error: --custom-typeshed-dir does not point to a valid typeshed ({})".format( + custom_typeshed_dir + ), + file=sys.stderr, + ) + sys.exit(2) + else: + auto = os.path.join(data_dir, "stubs-auto") + if os.path.isdir(auto): + data_dir = auto + typeshed_dir = os.path.join(data_dir, "typeshed", "stdlib") + mypy_extensions_dir = os.path.join(data_dir, "typeshed", "stubs", "mypy-extensions") + librt_dir = os.path.join(data_dir, "typeshed", "stubs", "librt") + path.append(typeshed_dir) + + # Get mypy-extensions and librt stubs from typeshed, since we treat them as + # "internal" libraries, similar to typing and typing-extensions. + path.append(mypy_extensions_dir) + path.append(librt_dir) + + # Add fallback path that can be used if we have a broken installation. + if sys.platform != "win32": + path.append("/usr/local/lib/mypy") + if not path: + print( + "Could not resolve typeshed subdirectories. Your mypy install is broken.\n" + "Python executable is located at {}.\nMypy located at {}".format( + sys.executable, data_dir + ), + file=sys.stderr, + ) + sys.exit(1) + return path + + +@functools.cache +def get_search_dirs(python_executable: str | None) -> tuple[list[str], list[str]]: + """Find package directories for given python. Guaranteed to return absolute paths. + + This runs a subprocess call, which generates a list of the directories in sys.path. + To avoid repeatedly calling a subprocess (which can be slow!) we + lru_cache the results. + """ + + if python_executable is None: + return ([], []) + elif python_executable == sys.executable: + # Use running Python's package dirs + sys_path, site_packages = pyinfo.getsearchdirs() + else: + # Use subprocess to get the package directory of given Python + # executable + env = {**dict(os.environ), "PYTHONSAFEPATH": "1"} + try: + sys_path, site_packages = ast.literal_eval( + subprocess.check_output( + [python_executable, pyinfo.__file__, "getsearchdirs"], + env=env, + stderr=subprocess.PIPE, + ).decode() + ) + except subprocess.CalledProcessError as err: + print(err.stderr) + print(err.stdout) + raise + except OSError as err: + assert err.errno is not None + reason = os.strerror(err.errno) + raise CompileError( + [f"mypy: Invalid python executable '{python_executable}': {reason}"] + ) from err + return sys_path, site_packages + + +def compute_search_paths( + sources: list[BuildSource], options: Options, data_dir: str, alt_lib_path: str | None = None +) -> SearchPaths: + """Compute the search paths as specified in PEP 561. + + There are the following 4 members created: + - User code (from `sources`) + - MYPYPATH (set either via config or environment variable) + - installed package directories (which will later be split into stub-only and inline) + - typeshed + """ + # Determine the default module search path. + lib_path = collections.deque( + default_lib_path( + data_dir, options.python_version, custom_typeshed_dir=options.custom_typeshed_dir + ) + ) + + if options.use_builtins_fixtures: + # Use stub builtins (to speed up test cases and to make them easier to + # debug). This is a test-only feature, so assume our files are laid out + # as in the source tree. + # We also need to allow overriding where to look for it. Argh. + root_dir = os.getenv("MYPY_TEST_PREFIX", None) + if not root_dir: + root_dir = os.path.dirname(os.path.dirname(__file__)) + root_dir = os.path.abspath(root_dir) + lib_path.appendleft(os.path.join(root_dir, "test-data", "unit", "lib-stub")) + # alt_lib_path is used by some tests to bypass the normal lib_path mechanics. + # If we don't have one, grab directories of source files. + python_path: list[str] = [] + if not alt_lib_path: + for source in sources: + # Include directory of the program file in the module search path. + if source.base_dir: + dir = source.base_dir + if dir not in python_path: + python_path.append(dir) + + # Do this even if running as a file, for sanity (mainly because with + # multiple builds, there could be a mix of files/modules, so its easier + # to just define the semantics that we always add the current director + # to the lib_path + # TODO: Don't do this in some cases; for motivation see see + # https://github.com/python/mypy/issues/4195#issuecomment-341915031 + if options.bazel: + dir = "." + else: + dir = os.getcwd() + if dir not in lib_path: + python_path.insert(0, dir) + + # Start with a MYPYPATH environment variable at the front of the mypy_path, if defined. + mypypath = mypy_path() + + # Add a config-defined mypy path. + mypypath.extend(options.mypy_path) + + # If provided, insert the caller-supplied extra module path to the + # beginning (highest priority) of the search path. + if alt_lib_path: + mypypath.insert(0, alt_lib_path) + + sys_path, site_packages = get_search_dirs(options.python_executable) + # We only use site packages for this check + for site in site_packages: + assert site not in lib_path + if ( + site in mypypath + or any(p.startswith(site + os.path.sep) for p in mypypath) + or (os.path.altsep and any(p.startswith(site + os.path.altsep) for p in mypypath)) + ): + print(f"{site} is in the MYPYPATH. Please remove it.", file=sys.stderr) + print( + "See https://mypy.readthedocs.io/en/stable/running_mypy.html" + "#how-mypy-handles-imports for more info", + file=sys.stderr, + ) + sys.exit(1) + + return SearchPaths( + python_path=tuple(reversed(python_path)), + mypy_path=tuple(mypypath), + package_path=tuple(sys_path + site_packages), + typeshed_path=tuple(lib_path), + ) + + +def load_stdlib_py_versions(custom_typeshed_dir: str | None) -> StdlibVersions: + """Return dict with minimum and maximum Python versions of stdlib modules. + + The contents look like + {..., 'secrets': ((3, 6), None), 'symbol': ((2, 7), (3, 9)), ...} + + None means there is no maximum version. + """ + typeshed_dir = custom_typeshed_dir or os_path_join(os.path.dirname(__file__), "typeshed") + stdlib_dir = os_path_join(typeshed_dir, "stdlib") + result = {} + + versions_path = os_path_join(stdlib_dir, "VERSIONS") + assert os.path.isfile(versions_path), (custom_typeshed_dir, versions_path, __file__) + with open(versions_path) as f: + for line in f: + line = line.split("#")[0].strip() + if line == "": + continue + module, version_range = line.split(":") + versions = version_range.split("-") + min_version = parse_version(versions[0]) + max_version = ( + parse_version(versions[1]) if len(versions) >= 2 and versions[1].strip() else None + ) + result[module] = min_version, max_version + return result + + +def parse_version(version: str) -> tuple[int, int]: + major, minor = version.strip().split(".") + return int(major), int(minor) + + +def typeshed_py_version(options: Options) -> tuple[int, int]: + """Return Python version used for checking whether module supports typeshed.""" + # Typeshed no longer covers Python 3.x versions before 3.9, so 3.9 is + # the earliest we can support. + return max(options.python_version, (3, 9)) diff --git a/micromamba_root/Lib/site-packages/mypy/moduleinspect.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/moduleinspect.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..cba6dd08ff927423326b2e60f98994f9a9b856f0 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/moduleinspect.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/moduleinspect.py b/micromamba_root/Lib/site-packages/mypy/moduleinspect.py new file mode 100644 index 0000000000000000000000000000000000000000..35db2132f66c6a199c1003b6269e7974bb54e448 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/moduleinspect.py @@ -0,0 +1,184 @@ +"""Basic introspection of modules.""" + +from __future__ import annotations + +import importlib +import inspect +import os +import pkgutil +import queue +import sys +from multiprocessing import Queue, get_context +from types import ModuleType + + +class ModuleProperties: + # Note that all __init__ args must have default values + def __init__( + self, + name: str = "", + file: str | None = None, + path: list[str] | None = None, + all: list[str] | None = None, + is_c_module: bool = False, + subpackages: list[str] | None = None, + ) -> None: + self.name = name # __name__ attribute + self.file = file # __file__ attribute + self.path = path # __path__ attribute + self.all = all # __all__ attribute + self.is_c_module = is_c_module + self.subpackages = subpackages or [] + + +def is_c_module(module: ModuleType) -> bool: + if module.__dict__.get("__file__") is None: + # Could be a namespace package. These must be handled through + # introspection, since there is no source file. + return True + return os.path.splitext(module.__dict__["__file__"])[-1] in [".so", ".pyd", ".dll"] + + +def is_pyc_only(file: str | None) -> bool: + return bool(file and file.endswith(".pyc") and not os.path.exists(file[:-1])) + + +class InspectError(Exception): + pass + + +def get_package_properties(package_id: str) -> ModuleProperties: + """Use runtime introspection to get information about a module/package.""" + try: + package = importlib.import_module(package_id) + except BaseException as e: + raise InspectError(str(e)) from e + name = getattr(package, "__name__", package_id) + file = getattr(package, "__file__", None) + path: list[str] | None = getattr(package, "__path__", None) + if not isinstance(path, list): + path = None + pkg_all = getattr(package, "__all__", None) + if pkg_all is not None: + try: + pkg_all = list(pkg_all) + except Exception: + pkg_all = None + is_c = is_c_module(package) + + if path is None: + # Object has no path; this means it's either a module inside a package + # (and thus no sub-packages), or it could be a C extension package. + if is_c: + # This is a C extension module, now get the list of all sub-packages + # using the inspect module + subpackages = [ + package.__name__ + "." + name + for name, val in inspect.getmembers(package) + if inspect.ismodule(val) and val.__name__ == package.__name__ + "." + name + ] + else: + # It's a module inside a package. There's nothing else to walk/yield. + subpackages = [] + else: + all_packages = pkgutil.walk_packages( + path, prefix=package.__name__ + ".", onerror=lambda r: None + ) + subpackages = [qualified_name for importer, qualified_name, ispkg in all_packages] + return ModuleProperties( + name=name, file=file, path=path, all=pkg_all, is_c_module=is_c, subpackages=subpackages + ) + + +def worker(tasks: Queue[str], results: Queue[str | ModuleProperties], sys_path: list[str]) -> None: + """The main loop of a worker introspection process.""" + sys.path = sys_path + while True: + mod = tasks.get() + try: + prop = get_package_properties(mod) + except InspectError as e: + results.put(str(e)) + continue + results.put(prop) + + +class ModuleInspect: + """Perform runtime introspection of modules in a separate process. + + Reuse the process for multiple modules for efficiency. However, if there is an + error, retry using a fresh process to avoid cross-contamination of state between + modules. + + We use a separate process to isolate us from many side effects. For example, the + import of a module may kill the current process, and we want to recover from that. + + Always use in a with statement for proper clean-up: + + with ModuleInspect() as m: + p = m.get_package_properties('urllib.parse') + """ + + def __init__(self) -> None: + self._start() + + def _start(self) -> None: + if sys.platform == "linux": + ctx = get_context("forkserver") + else: + ctx = get_context("spawn") + self.tasks: Queue[str] = ctx.Queue() + self.results: Queue[ModuleProperties | str] = ctx.Queue() + self.proc = ctx.Process(target=worker, args=(self.tasks, self.results, sys.path)) + self.proc.start() + self.counter = 0 # Number of successful roundtrips + + def close(self) -> None: + """Free any resources used.""" + self.proc.terminate() + + def get_package_properties(self, package_id: str) -> ModuleProperties: + """Return some properties of a module/package using runtime introspection. + + Raise InspectError if the target couldn't be imported. + """ + self.tasks.put(package_id) + res = self._get_from_queue() + if res is None: + # The process died; recover and report error. + self._start() + raise InspectError(f"Process died when importing {package_id!r}") + if isinstance(res, str): + # Error importing module + if self.counter > 0: + # Also try with a fresh process. Maybe one of the previous imports has + # corrupted some global state. + self.close() + self._start() + return self.get_package_properties(package_id) + raise InspectError(res) + self.counter += 1 + return res + + def _get_from_queue(self) -> ModuleProperties | str | None: + """Get value from the queue. + + Return the value read from the queue, or None if the process unexpectedly died. + """ + max_iter = 600 + n = 0 + while True: + if n == max_iter: + raise RuntimeError("Timeout waiting for subprocess") + try: + return self.results.get(timeout=0.05) + except queue.Empty: + if not self.proc.is_alive(): + return None + n += 1 + + def __enter__(self) -> ModuleInspect: + return self + + def __exit__(self, *args: object) -> None: + self.close() diff --git a/micromamba_root/Lib/site-packages/mypy/mro.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/mro.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..666431530069a080caca0190a601a8304d0c4618 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/mro.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/mro.py b/micromamba_root/Lib/site-packages/mypy/mro.py new file mode 100644 index 0000000000000000000000000000000000000000..b5b38cd1bedef725ee8b4c1ce79fc3092b0474a9 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/mro.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from collections.abc import Callable + +from mypy.nodes import TypeInfo +from mypy.types import Instance +from mypy.typestate import type_state + + +def calculate_mro(info: TypeInfo, obj_type: Callable[[], Instance] | None = None) -> None: + """Calculate and set mro (method resolution order). + + Raise MroError if cannot determine mro. + """ + mro = linearize_hierarchy(info, obj_type) + assert mro, f"Could not produce a MRO at all for {info}" + info.mro = mro + # The property of falling back to Any is inherited. + info.fallback_to_any = any(baseinfo.fallback_to_any for baseinfo in info.mro) + type_state.reset_all_subtype_caches_for(info) + + +class MroError(Exception): + """Raised if a consistent mro cannot be determined for a class.""" + + +def linearize_hierarchy( + info: TypeInfo, obj_type: Callable[[], Instance] | None = None +) -> list[TypeInfo]: + # TODO describe + if info.mro: + return info.mro + bases = info.direct_base_classes() + if not bases and info.fullname != "builtins.object" and obj_type is not None: + # Probably an error, add a dummy `object` base class, + # otherwise MRO calculation may spuriously fail. + bases = [obj_type().type] + lin_bases = [] + for base in bases: + assert base is not None, f"Cannot linearize bases for {info.fullname} {bases}" + lin_bases.append(linearize_hierarchy(base, obj_type)) + lin_bases.append(bases) + return [info] + merge(lin_bases) + + +def merge(seqs: list[list[TypeInfo]]) -> list[TypeInfo]: + seqs = [s.copy() for s in seqs] + result: list[TypeInfo] = [] + while True: + seqs = [s for s in seqs if s] + if not seqs: + return result + for seq in seqs: + head = seq[0] + if not [s for s in seqs if head in s[1:]]: + break + else: + raise MroError() + result.append(head) + for s in seqs: + if s[0] is head: + del s[0] diff --git a/micromamba_root/Lib/site-packages/mypy/nativeparse.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/nativeparse.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..5dfd9996e5926b7455160a09c022e2ef65455c9d Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/nativeparse.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/nativeparse.py b/micromamba_root/Lib/site-packages/mypy/nativeparse.py new file mode 100644 index 0000000000000000000000000000000000000000..3ff184155bac244c97be58957694fe41856d660e --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/nativeparse.py @@ -0,0 +1,2094 @@ +# mypy: allow-redefinition-new, local-partial-types +"""Python parser that directly constructs a native AST (when compiled). + +Use a Rust extension to generate a serialized AST, and deserialize the AST directly +to a mypy AST. + +NOTE: This is work in progress. To use this, you need to manually build the + ast_serialize Rust extension. See the README at https://github.com/mypyc/ast_serialize. + +Expected benefits over mypy.fastparse: + * No intermediate non-mypyc Python-level AST created, to improve performance + * Parsing doesn't need GIL => use multithreading to construct serialized ASTs in parallel + * Produce import dependencies without having to build an AST => helps parallel type checking + * Support all Python syntax even if mypy is running on an older Python version + * Generate an AST even if there are syntax errors + * Potential to support incremental parsing (quickly process modified sections in a file) + * Stripping function bodies in third-party code can happen earlier, for extra performance +""" + +from __future__ import annotations + +import os +from typing import Any, Final, cast + +import ast_serialize # type: ignore[import-untyped, import-not-found, unused-ignore] +from librt.internal import ( + read_float as read_float_bare, + read_int as read_int_bare, + read_str as read_str_bare, +) + +from mypy import message_registry, nodes, types +from mypy.cache import ( + DICT_STR_GEN, + END_TAG, + LIST_GEN, + LIST_INT, + LITERAL_FLOAT, + LITERAL_NONE, + LITERAL_STR, + LOCATION, + ReadBuffer, + Tag, + read_bool, + read_int, + read_str, + read_str_opt, + read_tag, +) +from mypy.nodes import ( + ARG_KINDS, + ARG_POS, + IMPORT_METADATA, + IMPORTALL_METADATA, + IMPORTFROM_METADATA, + MISSING_FALLBACK, + Argument, + AssertStmt, + AssignmentExpr, + AssignmentStmt, + AwaitExpr, + Block, + BreakStmt, + BytesExpr, + CallExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + Context, + ContinueStmt, + Decorator, + DelStmt, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + Expression, + ExpressionStmt, + FileRawData, + FloatExpr, + ForStmt, + FuncDef, + GeneratorExpr, + GlobalDecl, + IfStmt, + Import, + ImportAll, + ImportBase, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MatchStmt, + MemberExpr, + MypyFile, + NameExpr, + NonlocalDecl, + OperatorAssignmentStmt, + OpExpr, + OverloadedFuncDef, + OverloadPart, + PassStmt, + RaiseStmt, + RefExpr, + ReturnStmt, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + Statement, + StrExpr, + SuperExpr, + TemplateStrExpr, + TempNode, + TryStmt, + TupleExpr, + TypeAliasStmt, + TypeParam, + UnaryExpr, + Var, + WhileStmt, + WithStmt, + YieldExpr, + YieldFromExpr, +) +from mypy.options import Options +from mypy.patterns import ( + AsPattern, + ClassPattern, + MappingPattern, + OrPattern, + Pattern, + SequencePattern, + SingletonPattern, + StarredPattern, + ValuePattern, +) +from mypy.reachability import infer_reachability_of_if_statement +from mypy.sharedparse import special_function_elide_names +from mypy.types import ( + AnyType, + CallableArgument, + CallableType, + EllipsisType, + Instance, + ProperType, + RawExpressionType, + TupleType, + Type, + TypedDictType, + TypeList, + TypeOfAny, + UnboundType, + UnionType, + UnpackType, +) +from mypy.util import unnamed_function + +TypeIgnores = list[tuple[int, list[str]]] + +# There is no way to create reasonable fallbacks at this stage, +# they must be patched later. +_dummy_fallback: Final = Instance(MISSING_FALLBACK, [], -1) + + +class State: + def __init__(self, options: Options) -> None: + self.options = options + self.errors: list[dict[str, Any]] = [] + self.num_funcs = 0 + + def add_error( + self, + message: str, + line: int, + column: int, + *, + blocker: bool = False, + code: str | None = None, + ) -> None: + """Report an error at a specific location. + + Args: + message: Error message to display + line: Line number where error occurred + column: Column number where error occurred + blocker: If True, this error blocks further analysis + code: Error code for categorization + """ + self.errors.append( + {"line": line, "column": column, "message": message, "blocker": blocker, "code": code} + ) + + +def native_parse( + filename: str, options: Options, skip_function_bodies: bool = False, imports_only: bool = False +) -> tuple[MypyFile, list[dict[str, Any]], TypeIgnores]: + """Parse a Python file using the native Rust-based parser. + + Uses the ast_serialize Rust extension to parse Python code and deserialize + the resulting AST directly into mypy's native AST representation. + + Args: + filename: Path to the Python source file to parse + options: Mypy options affecting parsing behavior (e.g., Python version) + skip_function_bodies: If True, many function and method bodies are omitted from + the AST, useful for parsing stubs or extracting signatures without full + implementation details + imports_only: If True create an empty MypyFile with actual serialized defs + stored in binary_data. + + Returns: + A tuple containing: + - MypyFile: The parsed AST as a mypy AST node + - list[dict[str, Any]]: List of parse errors and deserialization errors + - TypeIgnores: List of (line_number, ignored_codes) tuples for type: ignore comments + """ + # If the path is a directory, return empty AST (matching fastparse behavior) + # This can happen for packages that only contain .pyc files without source + if os.path.isdir(filename): + node = MypyFile([], []) + node.path = filename + return node, [], [] + + b, errors, ignores, import_bytes, is_partial_package, uses_template_strings = ( + parse_to_binary_ast(filename, options, skip_function_bodies) + ) + data = ReadBuffer(b) + n = read_int(data) + state = State(options) + if imports_only: + defs = [] + else: + defs = read_statements(state, data, n) + + imports = deserialize_imports(import_bytes) + + node = MypyFile(defs, imports) + node.path = filename + node.is_partial_stub_package = is_partial_package + if imports_only: + node.raw_data = FileRawData( + b, import_bytes, errors, dict(ignores), is_partial_package, uses_template_strings + ) + node.uses_template_strings = uses_template_strings + # Merge deserialization errors with parsing errors + all_errors = errors + state.errors + return node, all_errors, ignores + + +def expect_end_tag(data: ReadBuffer) -> None: + assert read_tag(data) == END_TAG + + +def expect_tag(data: ReadBuffer, tag: Tag) -> None: + assert (actual := read_tag(data)) == tag, actual + + +def read_statements(state: State, data: ReadBuffer, n: int) -> list[Statement]: + defs: list[Statement] = [] + old_num_funcs = state.num_funcs + for _ in range(n): + stmt = read_statement(state, data) + defs.append(stmt) + if state.num_funcs > old_num_funcs + 1: + # There were at least two functions, so we may need to merge overloads. + defs = fix_function_overloads(state, defs) + return defs + + +def parse_to_binary_ast( + filename: str, options: Options, skip_function_bodies: bool = False +) -> tuple[bytes, list[dict[str, Any]], TypeIgnores, bytes, bool, bool]: + ast_bytes, errors, ignores, import_bytes, ast_data = ast_serialize.parse( + filename, + skip_function_bodies=skip_function_bodies, + python_version=options.python_version, + platform=options.platform, + always_true=options.always_true, + always_false=options.always_false, + ) + return ( + ast_bytes, + cast("list[dict[str, Any]]", errors), + ignores, + import_bytes, + ast_data["is_partial_package"], + ast_data["uses_template_strings"], + ) + + +def read_statement(state: State, data: ReadBuffer) -> Statement: + tag = read_tag(data) + stmt: Statement + if tag == nodes.FUNC_DEF_STMT: + return read_func_def(state, data) + elif tag == nodes.DECORATOR: + expect_tag(data, LIST_GEN) + n_decorators = read_int_bare(data) + decorators = [read_expression(state, data) for i in range(n_decorators)] + line = read_int(data) + column = read_int(data) + fdef = read_statement(state, data) + assert isinstance(fdef, FuncDef) + fdef.is_decorated = True + var = Var(fdef.name) + var.line = fdef.line + var.is_ready = False + stmt = Decorator(fdef, decorators, var) + stmt.line = line + stmt.column = column + stmt.end_line = fdef.end_line + stmt.end_column = fdef.end_column + # TODO: Adjust funcdef location to start after decorator? + expect_end_tag(data) + return stmt + elif tag == nodes.EXPR_STMT: + es = ExpressionStmt(read_expression(state, data)) + set_line_column_range(es, es.expr) + expect_end_tag(data) + return es + elif tag == nodes.ASSIGNMENT_STMT: + lvalues = read_expression_list(state, data) + rvalue = read_expression(state, data) + has_type = read_bool(data) + if has_type: + type_annotation = read_type(state, data) + else: + type_annotation = None + new_syntax = read_bool(data) + a = AssignmentStmt(lvalues, rvalue, type=type_annotation, new_syntax=new_syntax) + read_loc(data, a) + # If rvalue is TempNode, copy location from AssignmentStmt + if isinstance(rvalue, TempNode): + set_line_column_range(rvalue, a) + expect_end_tag(data) + return a + elif tag == nodes.OPERATOR_ASSIGNMENT_STMT: + # Read operator string + op = read_str(data) + # Read lvalue (target) + lvalue = read_expression(state, data) + # Read rvalue (value) + rvalue = read_expression(state, data) + stmt = OperatorAssignmentStmt(op, lvalue, rvalue) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.IF_STMT: + # Read the main if condition and body + expr = read_expression(state, data) + body = read_block(state, data) + + # Read elif clauses + num_elif = read_int(data) + elif_exprs = [] + elif_bodies = [] + for i in range(num_elif): + elif_exprs.append(read_expression(state, data)) + elif_bodies.append(read_block(state, data)) + + has_else = read_bool(data) + if has_else: + else_body = read_block(state, data) + else: + else_body = None + + # Normalize elif into nested if/else statements + # Build from the bottom up, starting with the final else body + current_else = else_body + + # Process elif clauses in reverse order + for i in range(len(elif_exprs) - 1, -1, -1): + elif_stmt = IfStmt([elif_exprs[i]], [elif_bodies[i]], current_else) + # Set location from the elif expression + elif_stmt.line = elif_exprs[i].line + elif_stmt.column = elif_exprs[i].column + # Set end location based on what follows + if current_else is not None: + elif_stmt.end_line = current_else.end_line + elif_stmt.end_column = current_else.end_column + else: + elif_stmt.end_line = elif_bodies[i].end_line + elif_stmt.end_column = elif_bodies[i].end_column + + # Wrap in a Block to become the else clause for the outer if + current_else = Block([elif_stmt]) + set_line_column_range(current_else, elif_stmt) + + if_stmt = IfStmt([expr], [body], current_else) + read_loc(data, if_stmt) + expect_end_tag(data) + return if_stmt + elif tag == nodes.RETURN_STMT: + has_value = read_bool(data) + if has_value: + value = read_expression(state, data) + else: + value = None + stmt = ReturnStmt(value) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.RAISE_STMT: + has_exc = read_bool(data) + if has_exc: + exc = read_expression(state, data) + else: + exc = None + has_from = read_bool(data) + if has_from: + from_expr = read_expression(state, data) + else: + from_expr = None + stmt = RaiseStmt(exc, from_expr) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.ASSERT_STMT: + test = read_expression(state, data) + has_msg = read_bool(data) + if has_msg: + msg = read_expression(state, data) + else: + msg = None + stmt = AssertStmt(test, msg) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.WHILE_STMT: + expr = read_expression(state, data) + body = read_block(state, data) + else_body = read_optional_block(state, data) + stmt = WhileStmt(expr, body, else_body) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.FOR_STMT: + index = read_expression(state, data) + expr = read_expression(state, data) + body = read_block(state, data) + else_body = read_optional_block(state, data) + is_async = read_bool(data) + stmt = ForStmt(index, expr, body, else_body) + stmt.is_async = is_async + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.WITH_STMT: + n = read_int(data) + expr_list = [] + target_list: list[Expression | None] = [] + for _ in range(n): + context_expr = read_expression(state, data) + expr_list.append(context_expr) + has_target = read_bool(data) + if has_target: + target = read_expression(state, data) + target_list.append(target) + else: + target_list.append(None) + body = read_block(state, data) + is_async = read_bool(data) + stmt = WithStmt(expr_list, target_list, body) + stmt.is_async = is_async + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.PASS_STMT: + stmt = PassStmt() + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.BREAK_STMT: + stmt = BreakStmt() + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.CONTINUE_STMT: + stmt = ContinueStmt() + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.IMPORT: + n = read_int(data) + ids = [] + for _ in range(n): + name = read_str(data) + has_asname = read_bool(data) + if has_asname: + asname = read_str(data) + else: + asname = None + ids.append((name, asname)) + stmt = Import(ids) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.IMPORT_FROM: + relative = read_int(data) + module_id = read_str(data) # Empty string for "from . import x" + n = read_int(data) + names = [] + for _ in range(n): + name = read_str(data) + has_asname = read_bool(data) + if has_asname: + asname = read_str(data) + else: + asname = None + names.append((name, asname)) + + stmt = ImportFrom(module_id, relative, names) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.IMPORT_ALL: + module_id = read_str(data) # Empty string for "from . import *" + relative = read_int(data) + + stmt = ImportAll(module_id, relative) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.CLASS_DEF: + return read_class_def(state, data) + elif tag == nodes.TYPE_ALIAS_STMT: + return read_type_alias_stmt(state, data) + elif tag == nodes.TRY_STMT: + return read_try_stmt(state, data) + elif tag == nodes.DEL_STMT: + expr = read_expression(state, data) + stmt = DelStmt(expr) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.GLOBAL_DECL: + n = read_int(data) + decl_names = [] + for _ in range(n): + decl_names.append(read_str(data)) + stmt = GlobalDecl(decl_names) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.NONLOCAL_DECL: + n = read_int(data) + decl_names = [] + for _ in range(n): + decl_names.append(read_str(data)) + stmt = NonlocalDecl(decl_names) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + elif tag == nodes.MATCH_STMT: + subject = read_expression(state, data) + n_cases = read_int(data) + patterns = [] + guards: list[Expression | None] = [] + bodies = [] + for _ in range(n_cases): + pattern = read_pattern(state, data) + patterns.append(pattern) + has_guard = read_bool(data) + if has_guard: + guard = read_expression(state, data) + guards.append(guard) + else: + guards.append(None) + body = read_block(state, data) + bodies.append(body) + stmt = MatchStmt(subject, patterns, guards, bodies) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + else: + assert False, tag + + +def read_parameters(state: State, data: ReadBuffer) -> tuple[list[Argument], bool]: + """Read function/lambda parameters from the buffer. + + Returns: + A tuple of (arguments list, has_annotations flag) + """ + expect_tag(data, LIST_GEN) + n_args = read_int_bare(data) + arguments = [] + has_ann = False + for _ in range(n_args): + arg_name = read_str(data) + arg_kind_int = read_int(data) + arg_kind = ARG_KINDS[arg_kind_int] + has_type = read_bool(data) + if has_type: + ann = read_type(state, data) + has_ann = True + else: + ann = None + has_default = read_bool(data) + if has_default: + default = read_expression(state, data) + else: + default = None + pos_only = read_bool(data) + + # Apply implicit_optional if enabled and default is None + if state.options.implicit_optional and ann is not None: + optional = isinstance(default, NameExpr) and default.name == "None" + if isinstance(ann, UnboundType): + ann.optional = optional + + var = Var(arg_name, ann) + var.is_inferred = False + var.is_argument = True + arg = Argument(var, ann, default, arg_kind, pos_only) + read_loc(data, arg) + set_line_column_range(var, arg) + arguments.append(arg) + + return arguments, has_ann + + +def read_type_params(state: State, data: ReadBuffer) -> list[TypeParam]: + """Read type parameters (PEP 695 generics).""" + type_params: list[TypeParam] = [] + n = read_int_bare(data) + for _ in range(n): + kind = read_int(data) + name = read_str(data) + has_bound = read_bool(data) + if has_bound: + upper_bound = read_type(state, data) + else: + upper_bound = None + + expect_tag(data, LIST_GEN) + n_values = read_int_bare(data) + values = [read_type(state, data) for _ in range(n_values)] + + has_default = read_bool(data) + if has_default: + default = read_type(state, data) + else: + default = None + + type_params.append(TypeParam(name, kind, upper_bound, values, default)) + + return type_params + + +def read_func_def(state: State, data: ReadBuffer) -> FuncDef: + state.num_funcs += 1 + + name = read_str(data) + arguments, has_ann = read_parameters(state, data) + + if special_function_elide_names(name): + for arg in arguments: + arg.pos_only = True + + body = read_block(state, data) + is_async = read_bool(data) + + # Type parameters (PEP 695) + has_type_params = read_bool(data) + if has_type_params: + type_params = read_type_params(state, data) + else: + type_params = None + + has_return_type = read_bool(data) + if has_return_type: + return_type = read_type(state, data) + has_ann = True + else: + return_type = None + + if has_ann: + typ = CallableType( + [ + arg.type_annotation if arg.type_annotation else AnyType(TypeOfAny.unannotated) + for arg in arguments + ], + [arg.kind for arg in arguments], + [None if arg.pos_only else arg.variable.name for arg in arguments], + return_type if return_type else AnyType(TypeOfAny.unannotated), + _dummy_fallback, + ) + else: + typ = None + + func_def = FuncDef(name, arguments, body, typ=typ, type_args=type_params) + if is_async: + func_def.is_coroutine = True + read_loc(data, func_def) + if typ: + typ.line = func_def.line + typ.column = func_def.column + typ.definition = func_def + # TODO: This seems wasteful, can we avoid it? + func_def.unanalyzed_type = typ.copy_modified() + expect_end_tag(data) + return func_def + + +def read_class_def(state: State, data: ReadBuffer) -> ClassDef: + name = read_str(data) + body = read_block(state, data) + base_type_exprs = read_expression_list(state, data) + + expect_tag(data, LIST_GEN) + n_decorators = read_int_bare(data) + decorators = [read_expression(state, data) for _ in range(n_decorators)] + + # Type parameters (PEP 695) + has_type_params = read_bool(data) + if has_type_params: + type_params = read_type_params(state, data) + else: + type_params = None + + # Keywords (all keyword arguments including metaclass) + expect_tag(data, DICT_STR_GEN) + n_keywords = read_int_bare(data) + keywords = [] + for _ in range(n_keywords): + key = read_str(data) + value = read_expression(state, data) + keywords.append((key, value)) + + # Extract metaclass from keywords if present + metaclass = dict(keywords).get("metaclass") if keywords else None + # Remove metaclass from keywords since it's passed as a separate field + filtered_keywords = [(k, v) for k, v in keywords if k != "metaclass"] if keywords else None + + class_def = ClassDef( + name, + body, + base_type_exprs=base_type_exprs if base_type_exprs else None, + metaclass=metaclass, + keywords=filtered_keywords, + type_args=type_params, + ) + class_def.decorators = decorators + read_loc(data, class_def) + expect_end_tag(data) + return class_def + + +def read_type_alias_stmt(state: State, data: ReadBuffer) -> TypeAliasStmt: + """Read PEP 695 type alias statement.""" + name = read_expression(state, data) + assert isinstance(name, NameExpr), f"Expected NameExpr for type alias name, got {type(name)}" + + n_type_params = read_int_bare(data) + if n_type_params > 0: + type_params = [] + for _ in range(n_type_params): + kind = read_int(data) + param_name = read_str(data) + has_bound = read_bool(data) + if has_bound: + upper_bound = read_type(state, data) + else: + upper_bound = None + + # Read values (for constrained TypeVar) + expect_tag(data, LIST_GEN) + n_values = read_int_bare(data) + values = [read_type(state, data) for _ in range(n_values)] + + has_default = read_bool(data) + if has_default: + default = read_type(state, data) + else: + default = None + + type_params.append(TypeParam(param_name, kind, upper_bound, values, default)) + else: + type_params = [] + + value_expr = read_expression(state, data) + + # Wrap the value expression in a LambdaExpr as expected by TypeAliasStmt + # The LambdaExpr body is a Block with a single ReturnStmt + return_stmt = ReturnStmt(value_expr) + set_line_column_range(return_stmt, value_expr) + + block = Block([return_stmt]) + block.line = -1 # Synthetic block + block.column = 0 + block.end_line = -1 + block.end_column = 0 + + lambda_expr = LambdaExpr([], block) + set_line_column_range(lambda_expr, value_expr) + + stmt = TypeAliasStmt(name, type_params, lambda_expr) + read_loc(data, stmt) + expect_end_tag(data) + return stmt + + +def read_try_stmt(state: State, data: ReadBuffer) -> TryStmt: + body = read_block(state, data) + num_handlers = read_int(data) + + types_list: list[Expression | None] = [] + for _ in range(num_handlers): + has_type = read_bool(data) + if has_type: + exc_type = read_expression(state, data) + types_list.append(exc_type) + else: + types_list.append(None) + + vars_list: list[NameExpr | None] = [] + for _ in range(num_handlers): + has_name = read_bool(data) + if has_name: + var_name = read_str(data) + var_expr = NameExpr(var_name) + vars_list.append(var_expr) + else: + vars_list.append(None) + + handlers = [] + for _ in range(num_handlers): + handler_body = read_block(state, data) + handlers.append(handler_body) + + has_else = read_bool(data) + if has_else: + else_body = read_block(state, data) + else: + else_body = None + + has_finally = read_bool(data) + if has_finally: + finally_body = read_block(state, data) + else: + finally_body = None + + # Read is_star flag (for except* in Python 3.11+) + is_star = read_bool(data) + + stmt = TryStmt(body, vars_list, types_list, handlers, else_body, finally_body) + stmt.is_star = is_star + read_loc(data, stmt) + expect_end_tag(data) + return stmt + + +def read_type(state: State, data: ReadBuffer) -> Type: + tag = read_tag(data) + if tag == types.UNBOUND_TYPE: + name = read_str(data) + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + args = tuple(read_type(state, data) for i in range(n)) + empty_tuple_index = read_bool(data) + # Read optional original_str_expr + t = read_tag(data) + if t == LITERAL_NONE: + original_str_expr = None + elif t == LITERAL_STR: + original_str_expr = read_str_bare(data) + else: + assert False, f"Unexpected tag for original_str_expr: {t}" + # Read optional original_str_fallback + t = read_tag(data) + if t == LITERAL_NONE: + original_str_fallback = None + elif t == LITERAL_STR: + original_str_fallback = read_str_bare(data) + else: + assert False, f"Unexpected tag for original_str_fallback: {t}" + unbound = UnboundType( + name, + args, + empty_tuple_index=empty_tuple_index, + original_str_expr=original_str_expr, + original_str_fallback=original_str_fallback, + ) + read_loc(data, unbound) + expect_end_tag(data) + return unbound + elif tag == types.UNION_TYPE: + # Read items list + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + items = [read_type(state, data) for i in range(n)] + # Read uses_pep604_syntax flag + uses_pep604_syntax = read_bool(data) + # Read optional original_str_expr + t = read_tag(data) + if t == LITERAL_NONE: + original_str_expr = None + elif t == LITERAL_STR: + original_str_expr = read_str_bare(data) + else: + assert False, f"Unexpected tag for original_str_expr: {t}" + # Read optional original_str_fallback + t = read_tag(data) + if t == LITERAL_NONE: + original_str_fallback = None + elif t == LITERAL_STR: + original_str_fallback = read_str_bare(data) + else: + assert False, f"Unexpected tag for original_str_fallback: {t}" + union = UnionType(items, uses_pep604_syntax=uses_pep604_syntax) + union.original_str_expr = original_str_expr + union.original_str_fallback = original_str_fallback + union.is_evaluated = read_bool(data) + read_loc(data, union) + expect_end_tag(data) + return union + elif tag == types.LIST_TYPE: + # Read items list + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + items = [read_type(state, data) for i in range(n)] + type_list = TypeList(items) + read_loc(data, type_list) + expect_end_tag(data) + return type_list + elif tag == types.TUPLE_TYPE: + # Read items list + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + items = [read_type(state, data) for i in range(n)] + implicit = read_bool(data) + tuple_type = TupleType(items, _dummy_fallback, implicit=implicit) + read_loc(data, tuple_type) + expect_end_tag(data) + return tuple_type + elif tag == types.TYPED_DICT_TYPE: + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + keys = [read_str_opt(data) for i in range(n)] + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + values = [read_type(state, data) for i in range(n)] + td_items = {} + extra_items_from = [] + for key, val in zip(keys, values): + if key is None: + assert isinstance(val, ProperType) + extra_items_from.append(val) + else: + td_items[key] = val + typeddict_type = TypedDictType(td_items, set(), set(), _dummy_fallback) + typeddict_type.extra_items_from = extra_items_from + read_loc(data, typeddict_type) + expect_end_tag(data) + return typeddict_type + elif tag == types.ELLIPSIS_TYPE: + # EllipsisType has no attributes + ellipsis_type = EllipsisType() + read_loc(data, ellipsis_type) + expect_end_tag(data) + return ellipsis_type + elif tag == types.RAW_EXPRESSION_TYPE: + type_name = read_str(data) + value: types.LiteralValue | str | None + if type_name == "builtins.bool": + value = read_bool(data) + elif type_name == "builtins.int": + value = read_int(data) + elif type_name == "builtins.str": + value = read_str(data) + elif type_name == "builtins.bytes": + # Bytes literals are serialized as escaped strings + value = read_str(data) + elif type_name == "typing.Any": + # Invalid type - read None value + tag = read_tag(data) + assert tag == LITERAL_NONE, f"Expected LITERAL_NONE for invalid type, got {tag}" + value = None + else: + assert False, f"Unsupported RawExpressionType: {type_name}" + raw_type = RawExpressionType(value, type_name) + read_loc(data, raw_type) + expect_end_tag(data) + return raw_type + elif tag == types.UNPACK_TYPE: + inner_type = read_type(state, data) + from_star_syntax = read_bool(data) + unpack = UnpackType(inner_type, from_star_syntax=from_star_syntax) + read_loc(data, unpack) + expect_end_tag(data) + return unpack + elif tag == types.CALL_TYPE: + return read_call_type(state, data) + else: + assert False, tag + + +def stringify_type_name(typ: Type) -> str | None: + """Extract qualified name from a type (for Arg constructor detection).""" + if isinstance(typ, UnboundType): + return typ.name + return None + + +def extract_arg_name(typ: Type) -> str | None: + """Extract argument name from a type (for Arg name parameter).""" + if isinstance(typ, RawExpressionType) and typ.base_type_name == "builtins.str": + return typ.literal_value # type: ignore[return-value] + elif isinstance(typ, UnboundType): + # String literals in type context are parsed as UnboundType (forward references) + # For Arg names, these are typically simple names without dots + if typ.name == "None": + return None + # Return the name as-is (it's the argument name) + return typ.name + return None # Invalid, but let validation handle it + + +def read_call_type(state: State, data: ReadBuffer) -> Type: + """Read Call in type context - check if it's an Arg/DefaultArg/VarArg/KwArg constructor. + + This performs validation and error reporting similar to mypy/fastparse.py. + """ + callee_type = read_type(state, data) + + # Read positional arguments + expect_tag(data, LIST_GEN) + n_args = read_int_bare(data) + args = [read_type(state, data) for _ in range(n_args)] + + # Read keyword arguments + expect_tag(data, LIST_GEN) + n_kwargs = read_int_bare(data) + kwargs = [] + for _ in range(n_kwargs): + tag_kw = read_tag(data) + if tag_kw == LITERAL_NONE: + kw_name = None + elif tag_kw == LITERAL_STR: + kw_name = read_str_bare(data) + else: + assert False, f"Unexpected tag for keyword name: {tag_kw}" + kw_value = read_type(state, data) + kwargs.append((kw_name, kw_value)) + + # Try to detect Arg/DefaultArg/VarArg/KwArg pattern + constructor = stringify_type_name(callee_type) + + # We'll read location before processing errors so we can report them correctly + invalid = AnyType(TypeOfAny.from_error) + read_loc(data, invalid) + expect_end_tag(data) + + if not constructor: + # ARG_CONSTRUCTOR_NAME_EXPECTED + state.add_error( + message_registry.ARG_CONSTRUCTOR_NAME_EXPECTED.value, + invalid.line, + invalid.column, + blocker=True, + code="misc", + ) + return invalid + + # Extract type and name from arguments + name: str | None = None + name_set_from_positional = False + default_type = AnyType(TypeOfAny.special_form) + typ: Type = default_type + typ_set_from_positional = False + + # Process positional arguments + for i, arg in enumerate(args): + if i == 0: + typ = arg + typ_set_from_positional = True + elif i == 1: + name = extract_arg_name(arg) + name_set_from_positional = True + else: + # ARG_CONSTRUCTOR_TOO_MANY_ARGS + state.add_error( + message_registry.ARG_CONSTRUCTOR_TOO_MANY_ARGS.value, + invalid.line, + invalid.column, + blocker=True, + code="misc", + ) + + # Process keyword arguments + for kw_name, kw_value in kwargs: + if kw_name == "name": + # MULTIPLE_VALUES_FOR_NAME_KWARG + if name is not None and name_set_from_positional: + state.add_error( + message_registry.MULTIPLE_VALUES_FOR_NAME_KWARG.format(constructor).value, + invalid.line, + invalid.column, + blocker=True, + code="misc", + ) + name = extract_arg_name(kw_value) + elif kw_name == "type": + # MULTIPLE_VALUES_FOR_TYPE_KWARG + if typ is not default_type and typ_set_from_positional: + state.add_error( + message_registry.MULTIPLE_VALUES_FOR_TYPE_KWARG.format(constructor).value, + invalid.line, + invalid.column, + blocker=True, + code="misc", + ) + typ = kw_value + else: + # ARG_CONSTRUCTOR_UNEXPECTED_ARG + state.add_error( + message_registry.ARG_CONSTRUCTOR_UNEXPECTED_ARG.format(kw_name).value, + invalid.line, + invalid.column, + blocker=True, + code="misc", + ) + + # Create CallableArgument + call_arg = CallableArgument(typ, name, constructor) + set_line_column_range(call_arg, invalid) + return call_arg + + +def read_pattern(state: State, data: ReadBuffer) -> Pattern: + """Read a pattern node from the buffer.""" + tag = read_tag(data) + if tag == nodes.AS_PATTERN: + has_pattern = read_bool(data) + if has_pattern: + pattern = read_pattern(state, data) + else: + pattern = None + has_name = read_bool(data) + if has_name: + name_str = read_str(data) + name = NameExpr(name_str) + read_loc(data, name) + else: + name = None + as_pattern = AsPattern(pattern, name) + read_loc(data, as_pattern) + expect_end_tag(data) + return as_pattern + elif tag == nodes.OR_PATTERN: + n = read_int(data) + patterns = [read_pattern(state, data) for _ in range(n)] + or_pattern = OrPattern(patterns) + read_loc(data, or_pattern) + expect_end_tag(data) + return or_pattern + elif tag == nodes.VALUE_PATTERN: + expr = read_expression(state, data) + value_pattern = ValuePattern(expr) + read_loc(data, value_pattern) + expect_end_tag(data) + return value_pattern + elif tag == nodes.SINGLETON_PATTERN: + singleton_tag = read_tag(data) + if singleton_tag == LITERAL_NONE: + value = None + else: + # It's a boolean + value = singleton_tag == 1 # TAG_LITERAL_TRUE + singleton_pattern = SingletonPattern(value) + read_loc(data, singleton_pattern) + expect_end_tag(data) + return singleton_pattern + elif tag == nodes.SEQUENCE_PATTERN: + n = read_int(data) + patterns = [read_pattern(state, data) for _ in range(n)] + sequence_pattern = SequencePattern(patterns) + read_loc(data, sequence_pattern) + expect_end_tag(data) + return sequence_pattern + elif tag == nodes.STARRED_PATTERN: + # Read optional capture name + has_name = read_bool(data) + if has_name: + name_str = read_str(data) + name = NameExpr(name_str) + read_loc(data, name) + else: + name = None + starred_pattern = StarredPattern(name) + read_loc(data, starred_pattern) + expect_end_tag(data) + return starred_pattern + elif tag == nodes.MAPPING_PATTERN: + n = read_int(data) + keys = [] + values = [] + for _ in range(n): + key = read_expression(state, data) + value = read_pattern(state, data) + keys.append(key) + values.append(value) + has_rest = read_bool(data) + if has_rest: + rest_str = read_str(data) + rest = NameExpr(rest_str) + read_loc(data, rest) + else: + rest = None + mapping_pattern = MappingPattern(keys, values, rest) + read_loc(data, mapping_pattern) + expect_end_tag(data) + return mapping_pattern + elif tag == nodes.CLASS_PATTERN: + class_ref = cast(RefExpr, read_expression(state, data)) + n_positional = read_int(data) + positionals = [read_pattern(state, data) for _ in range(n_positional)] + n_keywords = read_int(data) + keyword_keys = [] + keyword_values = [] + for _ in range(n_keywords): + key = read_str(data) + value = read_pattern(state, data) + keyword_keys.append(key) + keyword_values.append(value) + class_pattern = ClassPattern(class_ref, positionals, keyword_keys, keyword_values) + read_loc(data, class_pattern) + expect_end_tag(data) + return class_pattern + else: + assert False, f"Unknown pattern tag: {tag}" + + +def read_block(state: State, data: ReadBuffer) -> Block: + expect_tag(data, nodes.BLOCK) + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + is_unreachable = read_bool(data) + if n == 0: + # Empty block - read explicit location + b = Block([], is_unreachable=is_unreachable) + read_loc(data, b) + expect_end_tag(data) + return b + else: + # Non-empty block - read statements and set location from them + a = read_statements(state, data, n) + expect_end_tag(data) + b = Block(a, is_unreachable=is_unreachable) + b.line = a[0].line + b.column = a[0].column + b.end_line = a[-1].end_line + b.end_column = a[-1].end_column + return b + + +def read_optional_block(state: State, data: ReadBuffer) -> Block | None: + expect_tag(data, nodes.BLOCK) + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + is_unreachable = read_bool(data) + if n == 0: + b = None + else: + a = [read_statement(state, data) for i in range(n)] + b = Block(a, is_unreachable=is_unreachable) + b.line = a[0].line + b.column = a[0].column + b.end_line = a[-1].end_line + b.end_column = a[-1].end_column + expect_end_tag(data) + return b + + +bin_ops: Final = ["+", "-", "*", "@", "/", "%", "**", "<<", ">>", "|", "^", "&", "//"] +bool_ops: Final = ["and", "or"] +cmp_ops: Final = ["==", "!=", "<", "<=", ">", ">=", "is", "is not", "in", "not in"] +unary_ops: Final = ["~", "not", "+", "-"] + + +def read_expression(state: State, data: ReadBuffer) -> Expression: + tag = read_tag(data) + expr: Expression + if tag == nodes.CALL_EXPR: + callee = read_expression(state, data) + args = read_expression_list(state, data) + # Read argument kinds + expect_tag(data, LIST_INT) + n_kinds = read_int_bare(data) + arg_kinds = [ARG_KINDS[read_int_bare(data)] for _ in range(n_kinds)] + # Read argument names + expect_tag(data, LIST_GEN) + n_names = read_int_bare(data) + arg_names: list[str | None] = [] + for _ in range(n_names): + tag = read_tag(data) + if tag == LITERAL_NONE: + arg_names.append(None) + elif tag == LITERAL_STR: + arg_names.append(read_str_bare(data)) + else: + assert False, f"Unexpected tag for arg_name: {tag}" + ce = CallExpr(callee, args, arg_kinds, arg_names) + read_loc(data, ce) + expect_end_tag(data) + return ce + elif tag == nodes.NAME_EXPR: + s = read_str(data) + ne = NameExpr(s) + read_loc(data, ne) + expect_end_tag(data) + return ne + elif tag == nodes.MEMBER_EXPR: + e = read_expression(state, data) + attr = read_str(data) + m = MemberExpr(e, attr) + # Check if this is a super() call - if so, convert to SuperExpr + if isinstance(e, CallExpr) and isinstance(e.callee, NameExpr) and e.callee.name == "super": + result: Expression = SuperExpr(attr, e) + else: + result = m + read_loc(data, result) + expect_end_tag(data) + return result + elif tag == nodes.STR_EXPR: + se = StrExpr(read_str(data)) + read_loc(data, se) + expect_end_tag(data) + return se + elif tag == nodes.INT_EXPR: + ie = IntExpr(read_int(data)) + read_loc(data, ie) + expect_end_tag(data) + return ie + elif tag == nodes.FLOAT_EXPR: + expect_tag(data, LITERAL_FLOAT) + value = read_float_bare(data) + fe = FloatExpr(value) + read_loc(data, fe) + expect_end_tag(data) + return fe + elif tag == nodes.LIST_EXPR: + items = read_expression_list(state, data) + expr = ListExpr(items) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.TUPLE_EXPR: + items = read_expression_list(state, data) + t = TupleExpr(items) + read_loc(data, t) + expect_end_tag(data) + return t + elif tag == nodes.SET_EXPR: + items = read_expression_list(state, data) + expr = SetExpr(items) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.GENERATOR_EXPR: + expr = read_generator_expr(state, data) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.LIST_COMPREHENSION: + generator = read_generator_expr(state, data) + expr = ListComprehension(generator) + read_loc(data, expr) + # Also copy location to the inner generator + set_line_column_range(generator, expr) + expect_end_tag(data) + return expr + elif tag == nodes.SET_COMPREHENSION: + generator = read_generator_expr(state, data) + expr = SetComprehension(generator) + read_loc(data, expr) + # Also copy location to the inner generator + set_line_column_range(generator, expr) + expect_end_tag(data) + return expr + elif tag == nodes.DICT_COMPREHENSION: + key = read_expression(state, data) + value = read_expression(state, data) + n_generators = read_int(data) + indices = [read_expression(state, data) for _ in range(n_generators)] + sequences = [read_expression(state, data) for _ in range(n_generators)] + condlists = [read_expression_list(state, data) for _ in range(n_generators)] + is_async = [read_bool(data) for _ in range(n_generators)] + expr = DictionaryComprehension(key, value, indices, sequences, condlists, is_async) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.YIELD_EXPR: + has_value = read_bool(data) + if has_value: + value = read_expression(state, data) + else: + value = None + expr = YieldExpr(value) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.YIELD_FROM_EXPR: + value = read_expression(state, data) + expr = YieldFromExpr(value) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.OP_EXPR: + op = bin_ops[read_int(data)] + left = read_expression(state, data) + right = read_expression(state, data) + o = OpExpr(op, left, right) + # TODO: Store these explicitly? + o.line = left.line + o.column = left.column + o.end_line = right.end_line + o.end_column = right.end_column + expect_end_tag(data) + return o + elif tag == nodes.INDEX_EXPR: + base = read_expression(state, data) + index = read_expression(state, data) + expr = IndexExpr(base, index) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.BOOL_OP_EXPR: + op = bool_ops[read_int(data)] + values = read_expression_list(state, data) + # Convert list of values to nested OpExpr nodes + # E.g., [a, b, c] with "and" becomes OpExpr("and", OpExpr("and", a, b), c) + assert len(values) >= 2 + result = values[0] + for val in values[1:]: + result = OpExpr(op, result, val) + result.line = values[0].line + result.column = values[0].column + result.end_line = val.end_line + result.end_column = val.end_column + read_loc(data, result) + expect_end_tag(data) + return result + elif tag == nodes.COMPARISON_EXPR: + left = read_expression(state, data) + expect_tag(data, LIST_INT) + n_ops = read_int_bare(data) + ops = [cmp_ops[read_int_bare(data)] for _ in range(n_ops)] + comparators = read_expression_list(state, data) + assert len(ops) == len(comparators) + expr = ComparisonExpr(ops, [left] + comparators) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.UNARY_EXPR: + op = unary_ops[read_int(data)] + operand = read_expression(state, data) + expr = UnaryExpr(op, operand) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.DICT_EXPR: + expect_tag(data, LIST_GEN) + n_keys = read_int_bare(data) + keys: list[Expression | None] = [] + for _ in range(n_keys): + has_key = read_bool(data) + if has_key: + keys.append(read_expression(state, data)) + else: + keys.append(None) + values = read_expression_list(state, data) + # Zip keys and values into items + items = list(zip(keys, values)) + expr = DictExpr(items) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.COMPLEX_EXPR: + expect_tag(data, LITERAL_FLOAT) + real = read_float_bare(data) + expect_tag(data, LITERAL_FLOAT) + imag = read_float_bare(data) + value = complex(real, imag) + expr = ComplexExpr(value) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.SLICE_EXPR: + has_begin = read_bool(data) + begin_index = read_expression(state, data) if has_begin else None + has_end = read_bool(data) + end_index = read_expression(state, data) if has_end else None + has_stride = read_bool(data) + stride = read_expression(state, data) if has_stride else None + expr = SliceExpr(begin_index, end_index, stride) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.TEMP_NODE: + # TempNode with no attributes + temp = TempNode(AnyType(TypeOfAny.special_form), no_rhs=True) + expect_end_tag(data) + return temp + elif tag == nodes.ELLIPSIS_EXPR: + expr = EllipsisExpr() + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.CONDITIONAL_EXPR: + if_expr = read_expression(state, data) + cond = read_expression(state, data) + else_expr = read_expression(state, data) + expr = ConditionalExpr(cond, if_expr, else_expr) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.FSTRING_EXPR: + # F-strings are converted into nodes representing "".join([...]), to match + # pre-existing behavior. + nparts = read_int(data) + fitems = [] + for _ in range(nparts): + b = read_bool(data) + if b: + n = read_int(data) + for i in range(n): + fitems.append(read_fstring_item(state, data)) + else: + s = StrExpr(read_str(data)) + read_loc(data, s) + fitems.append(s) + expr = build_fstring_join(state, data, fitems) + expect_end_tag(data) + return expr + elif tag == nodes.TSTRING_EXPR: + nparts = read_int(data) + titems: list[Expression | tuple[Expression, str, str | None, Expression | None]] = [] + for _ in range(nparts): + if read_bool(data): + e = read_expression(state, data) + s = read_str(data) + if read_bool(data): + conv = read_str(data) + else: + conv = None + if read_bool(data): + # Parse format spec as a JoinedStr, this matches the old parser behavior. + format_spec = read_fstring_items(state, data) + else: + format_spec = None + titems.append((e, s, conv, format_spec)) + else: + s = StrExpr(read_str(data)) + read_loc(data, s) + titems.append(s) + expr = TemplateStrExpr(titems) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.LAMBDA_EXPR: + arguments, has_ann = read_parameters(state, data) + body = read_block(state, data) + + if has_ann: + typ = CallableType( + [ + arg.type_annotation if arg.type_annotation else AnyType(TypeOfAny.unannotated) + for arg in arguments + ], + [arg.kind for arg in arguments], + [None if arg.pos_only else arg.variable.name for arg in arguments], + AnyType(TypeOfAny.unannotated), + _dummy_fallback, + ) + else: + typ = None + + expr = LambdaExpr(arguments, body) + expr.type = typ + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.NAMED_EXPR: + target = read_expression(state, data) + value = read_expression(state, data) + # AssignmentExpr expects target to be a NameExpr + if not isinstance(target, NameExpr): + # In case target is not a NameExpr, we need to handle this + # For now, we'll assert since the grammar should ensure it's a NameExpr + assert isinstance( + target, NameExpr + ), f"Expected NameExpr for target, got {type(target)}" + expr = AssignmentExpr(target, value) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.STAR_EXPR: + wrapped_expr = read_expression(state, data) + expr = StarExpr(wrapped_expr) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.BYTES_EXPR: + # Read bytes literal as string + value = read_str(data) + expr = BytesExpr(value) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.AWAIT_EXPR: + value = read_expression(state, data) + expr = AwaitExpr(value) + read_loc(data, expr) + expect_end_tag(data) + return expr + elif tag == nodes.BIG_INT_EXPR: + strval = read_str(data) + ie = IntExpr(int(strval, base=0)) + read_loc(data, ie) + expect_end_tag(data) + return ie + else: + assert False, tag + + +def read_fstring_items(state: State, data: ReadBuffer) -> Expression: + items = [] + n = read_int(data) + items = [read_fstring_item(state, data) for i in range(n)] + return build_fstring_join(state, data, items) + + +def build_fstring_join(state: State, data: ReadBuffer, items: list[Expression]) -> Expression: + if len(items) == 1: + expr = items[0] + read_loc(data, expr) + return expr + if all(isinstance(item, StrExpr) for item in items): + s = "".join([cast(StrExpr, item).value for item in items]) + expr = StrExpr(s) + read_loc(data, expr) + return expr + args = ListExpr(items) + str_expr = StrExpr("") + member = MemberExpr(str_expr, "join") + call = CallExpr(member, [args], [ARG_POS], [None]) + read_loc(data, call) + set_line_column(args, call) + set_line_column(str_expr, call) + set_line_column(member, call) + return call + + +def read_fstring_item(state: State, data: ReadBuffer) -> Expression: + t = read_tag(data) + if t == LITERAL_STR: + str_expr = StrExpr(read_str_bare(data)) + read_loc(data, str_expr) + return str_expr + elif t == nodes.FSTRING_INTERPOLATION: + expr = read_expression(state, data) + + # Read conversion flag such as !r + has_conv = read_bool(data) + if has_conv: + c = read_str(data) + fmt = "{" + c + ":{}}" + else: + fmt = "{:{}}" + + # Read format spec such as <30 (which may have nested {...}) + has_spec = read_bool(data) + if has_spec: + spec = read_fstring_items(state, data) + else: + spec = StrExpr("") + + member = MemberExpr(StrExpr(fmt), "format") + set_line_column(member, expr) + call = CallExpr(member, [expr, spec], [ARG_POS, ARG_POS], [None, None]) + set_line_column(call, expr) + expect_end_tag(data) + return call + else: + raise ValueError(f"Unexpected tag {t}") + + +def set_line_column(target: Context, src: Context) -> None: + target.line = src.line + target.column = src.column + + +def set_line_column_range(target: Context, src: Context) -> None: + target.line = src.line + target.column = src.column + target.end_line = src.end_line + target.end_column = src.end_column + + +def read_expression_list(state: State, data: ReadBuffer) -> list[Expression]: + expect_tag(data, LIST_GEN) + n = read_int_bare(data) + return [read_expression(state, data) for i in range(n)] + + +def read_generator_expr(state: State, data: ReadBuffer) -> GeneratorExpr: + """Helper function to read comprehension data (shared by Generator, ListComp, SetComp)""" + left_expr = read_expression(state, data) + n_generators = read_int(data) + indices = [read_expression(state, data) for _ in range(n_generators)] + sequences = [read_expression(state, data) for _ in range(n_generators)] + condlists = [read_expression_list(state, data) for _ in range(n_generators)] + is_async = [read_bool(data) for _ in range(n_generators)] + return GeneratorExpr(left_expr, indices, sequences, condlists, is_async) + + +def read_loc(data: ReadBuffer, node: Context) -> None: + expect_tag(data, LOCATION) + line = read_int_bare(data) + node.line = line + column = read_int_bare(data) + node.column = column + node.end_line = line + read_int_bare(data) + node.end_column = column + read_int_bare(data) + + +def strip_contents_from_if_stmt(stmt: IfStmt) -> None: + """Remove contents from IfStmt. + + Needed to still be able to check the conditions after the contents + have been merged with the surrounding function overloads. + """ + if len(stmt.body) == 1: + stmt.body[0].body = [] + if stmt.else_body and len(stmt.else_body.body) == 1: + if isinstance(stmt.else_body.body[0], IfStmt): + strip_contents_from_if_stmt(stmt.else_body.body[0]) + else: + stmt.else_body.body = [] + + +def is_stripped_if_stmt(stmt: Statement) -> bool: + """Check stmt to make sure it is a stripped IfStmt. + + See also: strip_contents_from_if_stmt + """ + if not isinstance(stmt, IfStmt): + return False + + if not (len(stmt.body) == 1 and len(stmt.body[0].body) == 0): + # Body not empty + return False + + if not stmt.else_body or len(stmt.else_body.body) == 0: + # No or empty else_body + return True + + # For elif, IfStmt are stored recursively in else_body + return is_stripped_if_stmt(stmt.else_body.body[0]) + + +def fail_merge_overload(state: State, node: IfStmt) -> None: + """Report an error when overloads cannot be merged due to unknown condition.""" + state.add_error( + message_registry.FAILED_TO_MERGE_OVERLOADS.value, + node.line, + node.column, + blocker=False, + code="misc", + ) + + +def check_ifstmt_for_overloads( + stmt: IfStmt, current_overload_name: str | None = None +) -> str | None: + """Check if IfStmt contains only overloads with the same name. + Return overload_name if found, None otherwise. + """ + # Check that block only contains a single Decorator, FuncDef, or OverloadedFuncDef. + # Multiple overloads have already been merged as OverloadedFuncDef. + if not ( + len(stmt.body[0].body) == 1 + and ( + isinstance(stmt.body[0].body[0], (Decorator, OverloadedFuncDef)) + or current_overload_name is not None + and isinstance(stmt.body[0].body[0], FuncDef) + ) + or len(stmt.body[0].body) > 1 + and isinstance(stmt.body[0].body[-1], OverloadedFuncDef) + and all(is_stripped_if_stmt(if_stmt) for if_stmt in stmt.body[0].body[:-1]) + ): + return None + + overload_name = cast(Decorator | FuncDef | OverloadedFuncDef, stmt.body[0].body[-1]).name + if stmt.else_body is None or stmt.else_body.is_unreachable: + return overload_name + + if len(stmt.else_body.body) == 1: + # For elif: else_body contains an IfStmt itself -> do a recursive check. + if ( + isinstance(stmt.else_body.body[0], (Decorator, FuncDef, OverloadedFuncDef)) + and stmt.else_body.body[0].name == overload_name + ): + return overload_name + if ( + isinstance(stmt.else_body.body[0], IfStmt) + and check_ifstmt_for_overloads(stmt.else_body.body[0], current_overload_name) + == overload_name + ): + return overload_name + + return None + + +def get_executable_if_block_with_overloads( + stmt: IfStmt, options: Options +) -> tuple[Block | None, IfStmt | None]: + """Return block from IfStmt that will get executed. + + Return + 0 -> A block if sure that alternative blocks are unreachable. + 1 -> An IfStmt if the reachability of it can't be inferred, + i.e. the truth value is unknown. + """ + infer_reachability_of_if_statement(stmt, options) + if stmt.else_body is None and stmt.body[0].is_unreachable is True: + # always False condition with no else + return None, None + if ( + stmt.else_body is None + or stmt.body[0].is_unreachable is False + and stmt.else_body.is_unreachable is False + ): + # The truth value is unknown, thus not conclusive + return None, stmt + if stmt.else_body.is_unreachable: + # else_body will be set unreachable if condition is always True + return stmt.body[0], None + if stmt.body[0].is_unreachable is True: + # body will be set unreachable if condition is always False + # else_body can contain an IfStmt itself (for elif) -> do a recursive check + if isinstance(stmt.else_body.body[0], IfStmt): + return get_executable_if_block_with_overloads(stmt.else_body.body[0], options) + return stmt.else_body, None + return None, stmt + + +def fix_function_overloads(state: State, stmts: list[Statement]) -> list[Statement]: + """Merge consecutive function overloads into OverloadedFuncDef nodes. + + This function processes a list of statements and combines function overloads + (marked with @overload decorator) that have the same name into a single + OverloadedFuncDef node. It also handles conditional overloads (overloads + inside if statements) when the condition can be evaluated. + """ + ret: list[Statement] = [] + current_overload: list[OverloadPart] = [] + current_overload_name: str | None = None + last_unconditional_func_def: str | None = None + last_if_stmt: IfStmt | None = None + last_if_overload: Decorator | FuncDef | OverloadedFuncDef | None = None + last_if_stmt_overload_name: str | None = None + last_if_unknown_truth_value: IfStmt | None = None + skipped_if_stmts: list[IfStmt] = [] + for stmt in stmts: + if_overload_name: str | None = None + if_block_with_overload: Block | None = None + if_unknown_truth_value: IfStmt | None = None + if isinstance(stmt, IfStmt): + # Check IfStmt block to determine if function overloads can be merged + if_overload_name = check_ifstmt_for_overloads(stmt, current_overload_name) + if if_overload_name is not None: + if_block_with_overload, if_unknown_truth_value = ( + get_executable_if_block_with_overloads(stmt, state.options) + ) + + if ( + current_overload_name is not None + and isinstance(stmt, (Decorator, FuncDef)) + and stmt.name == current_overload_name + ): + if last_if_stmt is not None: + skipped_if_stmts.append(last_if_stmt) + if last_if_overload is not None: + # Last stmt was an IfStmt with same overload name + # Add overloads to current_overload + if isinstance(last_if_overload, OverloadedFuncDef): + current_overload.extend(last_if_overload.items) + else: + current_overload.append(last_if_overload) + last_if_stmt, last_if_overload = None, None + if last_if_unknown_truth_value: + fail_merge_overload(state, last_if_unknown_truth_value) + last_if_unknown_truth_value = None + current_overload.append(stmt) + if isinstance(stmt, FuncDef): + # This is, strictly speaking, wrong: there might be a decorated + # implementation. However, it only affects the error message we show: + # ideally it's "already defined", but "implementation must come last" + # is also reasonable. + # TODO: can we get rid of this completely and just always emit + # "implementation must come last" instead? + last_unconditional_func_def = stmt.name + elif ( + current_overload_name is not None + and isinstance(stmt, IfStmt) + and if_overload_name == current_overload_name + and last_unconditional_func_def != current_overload_name + ): + # IfStmt only contains stmts relevant to current_overload. + # Check if stmts are reachable and add them to current_overload, + # otherwise skip IfStmt to allow subsequent overload + # or function definitions. + skipped_if_stmts.append(stmt) + if if_block_with_overload is None: + if if_unknown_truth_value is not None: + fail_merge_overload(state, if_unknown_truth_value) + continue + if last_if_overload is not None: + # Last stmt was an IfStmt with same overload name + # Add overloads to current_overload + if isinstance(last_if_overload, OverloadedFuncDef): + current_overload.extend(last_if_overload.items) + else: + current_overload.append(last_if_overload) + last_if_stmt, last_if_overload = None, None + if isinstance(if_block_with_overload.body[-1], OverloadedFuncDef): + skipped_if_stmts.extend(cast(list[IfStmt], if_block_with_overload.body[:-1])) + current_overload.extend(if_block_with_overload.body[-1].items) + else: + current_overload.append(cast(Decorator | FuncDef, if_block_with_overload.body[0])) + else: + if last_if_stmt is not None: + ret.append(last_if_stmt) + last_if_stmt_overload_name = current_overload_name + last_if_stmt, last_if_overload = None, None + last_if_unknown_truth_value = None + + if current_overload and current_overload_name == last_if_stmt_overload_name: + # Remove last stmt (IfStmt) from ret if the overload names matched + # Only happens if no executable block had been found in IfStmt + popped = ret.pop() + assert isinstance(popped, IfStmt) + skipped_if_stmts.append(popped) + if current_overload and skipped_if_stmts: + # Add bare IfStmt (without overloads) to ret + # Required for mypy to be able to still check conditions + for if_stmt in skipped_if_stmts: + strip_contents_from_if_stmt(if_stmt) + ret.append(if_stmt) + skipped_if_stmts = [] + if len(current_overload) == 1: + ret.append(current_overload[0]) + elif len(current_overload) > 1: + ret.append(OverloadedFuncDef(current_overload)) + + # If we have multiple decorated functions named "_" next to each, we want to treat + # them as a series of regular FuncDefs instead of one OverloadedFuncDef because + # most of mypy/mypyc assumes that all the functions in an OverloadedFuncDef are + # related, but multiple underscore functions next to each other aren't necessarily + # related + last_unconditional_func_def = None + if isinstance(stmt, Decorator) and not unnamed_function(stmt.name): + current_overload = [stmt] + current_overload_name = stmt.name + elif isinstance(stmt, IfStmt) and if_overload_name is not None: + current_overload = [] + current_overload_name = if_overload_name + last_if_stmt = stmt + last_if_stmt_overload_name = None + if if_block_with_overload is not None: + skipped_if_stmts.extend(cast(list[IfStmt], if_block_with_overload.body[:-1])) + last_if_overload = cast( + Decorator | FuncDef | OverloadedFuncDef, if_block_with_overload.body[-1] + ) + last_if_unknown_truth_value = if_unknown_truth_value + else: + current_overload = [] + current_overload_name = None + ret.append(stmt) + + if current_overload and skipped_if_stmts: + # Add bare IfStmt (without overloads) to ret + # Required for mypy to be able to still check conditions + for if_stmt in skipped_if_stmts: + strip_contents_from_if_stmt(if_stmt) + ret.append(if_stmt) + if len(current_overload) == 1: + ret.append(current_overload[0]) + elif len(current_overload) > 1: + ret.append(OverloadedFuncDef(current_overload)) + elif last_if_overload is not None: + ret.append(last_if_overload) + elif last_if_stmt is not None: + ret.append(last_if_stmt) + return ret + + +def deserialize_imports(import_bytes: bytes) -> list[ImportBase]: + """Deserialize import metadata from bytes into mypy AST nodes. + + Args: + import_bytes: Serialized import metadata from the Rust parser + + Returns: + List of Import and ImportFrom AST nodes with location and metadata + """ + if not import_bytes: + return [] + + data = ReadBuffer(import_bytes) + + expect_tag(data, LIST_GEN) + n_imports = read_int_bare(data) + + imports: list[ImportBase] = [] + + for _ in range(n_imports): + tag = read_tag(data) + + if tag == IMPORT_METADATA: + name = read_str(data) + relative = read_int(data) + + has_asname = read_bool(data) + if has_asname: + asname = read_str(data) + else: + asname = None + + # Note: relative imports are handled via ImportFrom, so relative should be 0 here + stmt = Import([(name, asname)]) + _read_and_set_import_metadata(data, stmt) + imports.append(stmt) + + elif tag == IMPORTFROM_METADATA: + module = read_str(data) + relative = read_int(data) + + expect_tag(data, LIST_GEN) + n_names = read_int_bare(data) + names: list[tuple[str, str | None]] = [] + + for _ in range(n_names): + name = read_str(data) + has_asname = read_bool(data) + if has_asname: + asname = read_str(data) + else: + asname = None + names.append((name, asname)) + + stmt = ImportFrom(module, relative, names) + _read_and_set_import_metadata(data, stmt) + imports.append(stmt) + + elif tag == IMPORTALL_METADATA: + module = read_str(data) + relative = read_int(data) + + stmt = ImportAll(module, relative) + _read_and_set_import_metadata(data, stmt) + imports.append(stmt) + + else: + raise ValueError(f"Unexpected tag in import metadata: {tag}") + + return imports + + +def _read_and_set_import_metadata(data: ReadBuffer, stmt: Import | ImportFrom | ImportAll) -> None: + """Read location and metadata flags from buffer and set them on the import statement. + + Args: + data: Buffer containing serialized data + stmt: Import, ImportFrom, or ImportAll statement to populate with location and metadata + """ + read_loc(data, stmt) + + # Metadata flags as a single integer bitfield + flags = read_int(data) + + # Extract individual flags using bitwise operations + # Bit 0: is_top_level + # Bit 1: is_unreachable + # Bit 2: is_mypy_only + stmt.is_top_level = (flags & 0x01) != 0 + stmt.is_unreachable = (flags & 0x02) != 0 + stmt.is_mypy_only = (flags & 0x04) != 0 diff --git a/micromamba_root/Lib/site-packages/mypy/nodes.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/nodes.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..2cf1b2fef6cfe16979750b9a12d0f27114b56b25 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/nodes.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/nodes.py b/micromamba_root/Lib/site-packages/mypy/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..37ea4d3b0d56108482e96e9eb2c409836fd4c6a7 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/nodes.py @@ -0,0 +1,5367 @@ +"""Abstract syntax tree node classes (i.e. parse tree).""" + +from __future__ import annotations + +import os +from abc import abstractmethod +from collections import defaultdict +from collections.abc import Callable, Iterator, Sequence +from contextlib import contextmanager +from enum import Enum, unique +from typing import ( + TYPE_CHECKING, + Any, + Final, + Optional, + TypeAlias as _TypeAlias, + TypeGuard, + TypeVar, + Union, + cast, +) + +from librt.internal import ( + read_float as read_float_bare, + read_int as read_int_bare, + read_str as read_str_bare, + write_int as write_int_bare, + write_str as write_str_bare, +) +from mypy_extensions import trait + +import mypy.strconv +from mypy.cache import ( + DICT_INT_GEN, + DICT_STR_GEN, + DT_SPEC, + END_TAG, + LIST_GEN, + LIST_STR, + LITERAL_COMPLEX, + LITERAL_NONE, + ReadBuffer, + Tag, + WriteBuffer, + read_bool, + read_bytes, + read_int, + read_int_list, + read_int_opt, + read_json, + read_literal, + read_str, + read_str_list, + read_str_opt, + read_str_opt_list, + read_tag, + write_bool, + write_bytes, + write_int, + write_int_list, + write_int_opt, + write_json, + write_literal, + write_str, + write_str_list, + write_str_opt, + write_str_opt_list, + write_tag, +) +from mypy.options import Options +from mypy.util import is_sunder, is_typeshed_file, short_type +from mypy.visitor import ExpressionVisitor, NodeVisitor, StatementVisitor + +if TYPE_CHECKING: + from mypy.patterns import Pattern + + +@unique +class NotParsed(Enum): + VALUE = "NotParsed" + + +class Context: + """Base type for objects that are valid as error message locations.""" + + __slots__ = ("line", "column", "end_line", "end_column") + + def __init__(self, line: int = -1, column: int = -1) -> None: + self.line = line + self.column = column + self.end_line: int | None = None + self.end_column: int | None = None + + def set_line( + self, + target: Context | int, + column: int | None = None, + end_line: int | None = None, + end_column: int | None = None, + ) -> None: + """If target is a node, pull line (and column) information + into this node. If column is specified, this will override any column + information coming from a node. + """ + if isinstance(target, int): + self.line = target + else: + self.line = target.line + self.column = target.column + self.end_line = target.end_line + self.end_column = target.end_column + + if column is not None: + self.column = column + + if end_line is not None: + self.end_line = end_line + + if end_column is not None: + self.end_column = end_column + + +if TYPE_CHECKING: + # break import cycle only needed for mypy + import mypy.types + + +T = TypeVar("T") + +JsonDict: _TypeAlias = dict[str, Any] + + +# Symbol table node kinds +# +# TODO rename to use more descriptive names + +LDEF: Final = 0 +GDEF: Final = 1 +MDEF: Final = 2 + +# Placeholder for a name imported via 'from ... import'. Second phase of +# semantic will replace this the actual imported reference. This is +# needed so that we can detect whether a name has been imported during +# XXX what? +UNBOUND_IMPORTED: Final = 3 + +# RevealExpr node kinds +REVEAL_TYPE: Final = 0 +REVEAL_LOCALS: Final = 1 + +# Kinds of 'literal' expressions. +# +# Use the function mypy.literals.literal to calculate these. +# +# TODO: Can we make these less confusing? +LITERAL_YES: Final = 2 # Value of expression known statically +LITERAL_TYPE: Final = 1 # Type of expression can be narrowed (e.g. variable reference) +LITERAL_NO: Final = 0 # None of the above + +node_kinds: Final = {LDEF: "Ldef", GDEF: "Gdef", MDEF: "Mdef", UNBOUND_IMPORTED: "UnboundImported"} +inverse_node_kinds: Final = {_kind: _name for _name, _kind in node_kinds.items()} + + +implicit_module_attrs: Final = { + "__name__": "__builtins__.str", + "__doc__": None, # depends on Python version, see semanal.py + "__path__": None, # depends on if the module is a package + "__file__": "__builtins__.str", + "__package__": "__builtins__.str", + "__annotations__": None, # dict[str, Any] bounded in add_implicit_module_attrs() + "__spec__": None, # importlib.machinery.ModuleSpec bounded in add_implicit_module_attrs() +} + + +# These aliases exist because built-in class objects are not subscriptable. +# For example `list[int]` fails at runtime. Instead List[int] should be used. +type_aliases: Final = { + "typing.List": "builtins.list", + "typing.Dict": "builtins.dict", + "typing.Set": "builtins.set", + "typing.FrozenSet": "builtins.frozenset", + "typing.ChainMap": "collections.ChainMap", + "typing.Counter": "collections.Counter", + "typing.DefaultDict": "collections.defaultdict", + "typing.Deque": "collections.deque", + "typing.OrderedDict": "collections.OrderedDict", + # HACK: a lie in lieu of actual support for PEP 675 + "typing.LiteralString": "builtins.str", +} + +# This keeps track of the oldest supported Python version where the corresponding +# alias source is available. +type_aliases_source_versions: Final = {"typing.LiteralString": (3, 11)} + +# This keeps track of aliases in `typing_extensions`, which we treat specially. +typing_extensions_aliases: Final = { + # See: https://github.com/python/mypy/issues/11528 + "typing_extensions.OrderedDict": "collections.OrderedDict", + # HACK: a lie in lieu of actual support for PEP 675 + "typing_extensions.LiteralString": "builtins.str", +} + +reverse_builtin_aliases: Final = { + "builtins.list": "typing.List", + "builtins.dict": "typing.Dict", + "builtins.set": "typing.Set", + "builtins.frozenset": "typing.FrozenSet", +} + + +RUNTIME_PROTOCOL_DECOS: Final = ( + "typing.runtime_checkable", + "typing_extensions.runtime", + "typing_extensions.runtime_checkable", +) + +LAMBDA_NAME: Final = "" + + +class Node(Context): + """Common base class for all non-type parse tree nodes.""" + + __slots__ = () + + def __str__(self) -> str: + return self.accept(mypy.strconv.StrConv(options=Options())) + + def str_with_options(self, options: Options) -> str: + a = self.accept(mypy.strconv.StrConv(options=options)) + assert a + return a + + def accept(self, visitor: NodeVisitor[T]) -> T: + raise RuntimeError("Not implemented", type(self)) + + +@trait +class Statement(Node): + """A statement node.""" + + __slots__ = () + + def accept(self, visitor: StatementVisitor[T]) -> T: + raise RuntimeError("Not implemented", type(self)) + + +@trait +class Expression(Node): + """An expression node.""" + + __slots__ = () + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + raise RuntimeError("Not implemented", type(self)) + + +class FakeExpression(Expression): + """A dummy expression. + + We need a dummy expression in one place, and can't instantiate Expression + because it is a trait and mypyc barfs. + """ + + __slots__ = () + + +# TODO: +# Lvalue = Union['NameExpr', 'MemberExpr', 'IndexExpr', 'SuperExpr', 'StarExpr' +# 'TupleExpr']; see #1783. +Lvalue: _TypeAlias = Expression + + +@trait +class SymbolNode(Node): + """Nodes that can be stored in a symbol table.""" + + __slots__ = () + + @property + @abstractmethod + def name(self) -> str: + pass + + # Fully qualified name + @property + @abstractmethod + def fullname(self) -> str: + pass + + @abstractmethod + def serialize(self) -> JsonDict: + pass + + @classmethod + def deserialize(cls, data: JsonDict) -> SymbolNode: + classname = data[".class"] + method = deserialize_map.get(classname) + if method is not None: + return method(data) + raise NotImplementedError(f"unexpected .class {classname}") + + def write(self, data: WriteBuffer) -> None: + raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance") + + @classmethod + def read(cls, data: ReadBuffer) -> SymbolNode: + raise NotImplementedError(f"Cannot deserialize {cls.__name__} instance") + + +# Items: fullname, related symbol table node, surrounding type (if any) +Definition: _TypeAlias = tuple[str, "SymbolTableNode", Optional["TypeInfo"]] + + +class FileRawData: + """Raw (binary) data representing parsed, but not deserialized file.""" + + __slots__ = ( + "defs", + "imports", + "raw_errors", + "ignored_lines", + "is_partial_stub_package", + "uses_template_strings", + ) + + defs: bytes + imports: bytes + raw_errors: list[dict[str, Any]] # TODO: switch to more precise type here. + ignored_lines: dict[int, list[str]] + is_partial_stub_package: bool + uses_template_strings: bool + + def __init__( + self, + defs: bytes, + imports: bytes, + raw_errors: list[dict[str, Any]], + ignored_lines: dict[int, list[str]], + is_partial_stub_package: bool, + uses_template_strings: bool, + ) -> None: + self.defs = defs + self.imports = imports + self.raw_errors = raw_errors + self.ignored_lines = ignored_lines + self.is_partial_stub_package = is_partial_stub_package + self.uses_template_strings = uses_template_strings + + def write(self, data: WriteBuffer) -> None: + write_bytes(data, self.defs) + write_bytes(data, self.imports) + write_tag(data, LIST_GEN) + write_int_bare(data, len(self.raw_errors)) + for err in self.raw_errors: + write_json(data, err) + write_tag(data, DICT_INT_GEN) + write_int_bare(data, len(self.ignored_lines)) + for line, codes in self.ignored_lines.items(): + write_int(data, line) + write_str_list(data, codes) + write_bool(data, self.is_partial_stub_package) + write_bool(data, self.uses_template_strings) + + @classmethod + def read(cls, data: ReadBuffer) -> FileRawData: + defs = read_bytes(data) + imports = read_bytes(data) + assert read_tag(data) == LIST_GEN + raw_errors = [read_json(data) for _ in range(read_int_bare(data))] + assert read_tag(data) == DICT_INT_GEN + ignored_lines = {read_int(data): read_str_list(data) for _ in range(read_int_bare(data))} + return FileRawData( + defs, imports, raw_errors, ignored_lines, read_bool(data), read_bool(data) + ) + + +class MypyFile(SymbolNode): + """The abstract syntax tree of a single source file.""" + + __slots__ = ( + "_fullname", + "path", + "defs", + "alias_deps", + "module_refs", + "is_bom", + "names", + "imports", + "ignored_lines", + "skipped_lines", + "is_stub", + "is_cache_skeleton", + "is_partial_stub_package", + "uses_template_strings", + "plugin_deps", + "future_import_flags", + "_is_typeshed_file", + "raw_data", + ) + + __match_args__ = ("name", "path", "defs") + + # Fully qualified module name + _fullname: str + # Path to the file (empty string if not known) + path: str + # Top-level definitions and statements + defs: list[Statement] + # Type alias dependencies as mapping from target to set of alias full names + alias_deps: defaultdict[str, set[str]] + # The set of all dependencies (suppressed or not) that this module accesses, either + # directly or indirectly. + module_refs: set[str] + # Is there a UTF-8 BOM at the start? + is_bom: bool + names: SymbolTable + # All import nodes within the file (also ones within functions etc.) + imports: list[ImportBase] + # Lines on which to ignore certain errors when checking. + # If the value is empty, ignore all errors; otherwise, the list contains all + # error codes to ignore. + ignored_lines: dict[int, list[str]] + # Lines that were skipped during semantic analysis e.g. due to ALWAYS_FALSE, MYPY_FALSE, + # or platform/version checks. Those lines would not be type-checked. + skipped_lines: set[int] + # Is this file represented by a stub file (.pyi)? + is_stub: bool + # Is this loaded from the cache and thus missing the actual body of the file? + is_cache_skeleton: bool + # Does this represent an __init__.pyi stub with a module __getattr__ + # (i.e. a partial stub package), for such packages we suppress any missing + # module errors in addition to missing attribute errors. + is_partial_stub_package: bool + # True if module contains at least one t-string (PEP 750 TemplateStr). + uses_template_strings: bool + # Plugin-created dependencies + plugin_deps: dict[str, set[str]] + # Future imports defined in this file. Populated during semantic analysis. + future_import_flags: set[str] + _is_typeshed_file: bool | None + # For native parser store actual serialized data here. + raw_data: FileRawData | None + + def __init__( + self, + defs: list[Statement], + imports: list[ImportBase], + is_bom: bool = False, + ignored_lines: dict[int, list[str]] | None = None, + ) -> None: + super().__init__() + self.defs = defs + self.line = 1 # Dummy line number + self.column = 0 # Dummy column + self.imports = imports + self.is_bom = is_bom + self.alias_deps = defaultdict(set) + self.module_refs = set() + self.plugin_deps = {} + if ignored_lines: + self.ignored_lines = ignored_lines + else: + self.ignored_lines = {} + self.skipped_lines = set() + + self.path = "" + self.is_stub = False + self.is_cache_skeleton = False + self.is_partial_stub_package = False + self.uses_template_strings = False + self.future_import_flags = set() + self._is_typeshed_file = None + self.raw_data = None + + def local_definitions(self) -> Iterator[Definition]: + """Return all definitions within the module (including nested). + + This doesn't include imported definitions. + """ + return local_definitions(self.names, self.fullname) + + @property + def name(self) -> str: + return "" if not self._fullname else self._fullname.split(".")[-1] + + @property + def fullname(self) -> str: + return self._fullname + + def accept(self, visitor: NodeVisitor[T]) -> T: + return visitor.visit_mypy_file(self) + + def is_package_init_file(self) -> bool: + return len(self.path) != 0 and os.path.basename(self.path).startswith("__init__.") + + def is_future_flag_set(self, flag: str) -> bool: + return flag in self.future_import_flags + + def is_typeshed_file(self, options: Options) -> bool: + # Cache result since this is called a lot + if self._is_typeshed_file is None: + self._is_typeshed_file = is_typeshed_file(options.abs_custom_typeshed_dir, self.path) + return self._is_typeshed_file + + def serialize(self) -> JsonDict: + return { + ".class": "MypyFile", + "_fullname": self._fullname, + "names": self.names.serialize(self._fullname), + "is_stub": self.is_stub, + "path": self.path, + "is_partial_stub_package": self.is_partial_stub_package, + "future_import_flags": sorted(self.future_import_flags), + } + + @classmethod + def deserialize(cls, data: JsonDict) -> MypyFile: + assert data[".class"] == "MypyFile", data + tree = MypyFile([], []) + tree._fullname = data["_fullname"] + tree.names = SymbolTable.deserialize(data["names"]) + tree.is_stub = data["is_stub"] + tree.path = data["path"] + tree.is_partial_stub_package = data["is_partial_stub_package"] + tree.is_cache_skeleton = True + tree.future_import_flags = set(data["future_import_flags"]) + return tree + + def write(self, data: WriteBuffer) -> None: + write_tag(data, MYPY_FILE) + write_str(data, self._fullname) + self.names.write(data, self._fullname) + write_bool(data, self.is_stub) + write_str(data, self.path) + write_bool(data, self.is_partial_stub_package) + write_str_list(data, sorted(self.future_import_flags)) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> MypyFile: + assert read_tag(data) == MYPY_FILE + tree = MypyFile([], []) + tree._fullname = read_str(data) + tree.names = SymbolTable.read(data) + tree.is_stub = read_bool(data) + tree.path = read_str(data) + tree.is_partial_stub_package = read_bool(data) + tree.future_import_flags = set(read_str_list(data)) + tree.is_cache_skeleton = True + assert read_tag(data) == END_TAG + return tree + + +class ImportBase(Statement): + """Base class for all import statements.""" + + __slots__ = ("is_unreachable", "is_top_level", "is_mypy_only", "assignments") + + is_unreachable: bool # Set by semanal.SemanticAnalyzerPass1 if inside `if False` etc. + is_top_level: bool # Ditto if outside any class or def + is_mypy_only: bool # Ditto if inside `if TYPE_CHECKING` or `if MYPY` + + # If an import replaces existing definitions, we construct dummy assignment + # statements that assign the imported names to the names in the current scope, + # for type checking purposes. Example: + # + # x = 1 + # from m import x <-- add assignment representing "x = m.x" + assignments: list[AssignmentStmt] + + def __init__(self) -> None: + super().__init__() + self.assignments = [] + self.is_unreachable = False + self.is_top_level = False + self.is_mypy_only = False + + +class Import(ImportBase): + """import m [as n]""" + + __slots__ = ("ids",) + + __match_args__ = ("ids",) + + ids: list[tuple[str, str | None]] # (module id, as id) + + def __init__(self, ids: list[tuple[str, str | None]]) -> None: + super().__init__() + self.ids = ids + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_import(self) + + +class ImportFrom(ImportBase): + """from m import x [as y], ...""" + + __slots__ = ("id", "names", "relative") + + __match_args__ = ("id", "names", "relative") + + id: str + relative: int + names: list[tuple[str, str | None]] # Tuples (name, as name) + + def __init__(self, id: str, relative: int, names: list[tuple[str, str | None]]) -> None: + super().__init__() + self.id = id + self.names = names + self.relative = relative + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_import_from(self) + + +class ImportAll(ImportBase): + """from m import *""" + + __slots__ = ("id", "relative") + + __match_args__ = ("id", "relative") + + id: str + relative: int + + def __init__(self, id: str, relative: int) -> None: + super().__init__() + self.id = id + self.relative = relative + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_import_all(self) + + +FUNCBASE_FLAGS: Final = ["is_property", "is_class", "is_static", "is_final"] + + +class FuncBase(Node): + """Abstract base class for function-like nodes. + + N.B: Although this has SymbolNode subclasses (FuncDef, + OverloadedFuncDef), avoid calling isinstance(..., FuncBase) on + something that is typed as SymbolNode. This is to work around + mypy bug #3603, in which mypy doesn't understand multiple + inheritance very well, and will assume that a SymbolNode + cannot be a FuncBase. + + Instead, test against SYMBOL_FUNCBASE_TYPES, which enumerates + SymbolNode subclasses that are also FuncBase subclasses. + """ + + __slots__ = ( + "type", + "unanalyzed_type", + "info", + "is_property", + "is_class", # Uses "@classmethod" (explicit or implicit) + "is_static", # Uses "@staticmethod" (explicit or implicit) + "is_final", # Uses "@final" + "is_explicit_override", # Uses "@override" + "is_type_check_only", # Uses "@type_check_only" + "def_or_infer_vars", + "_fullname", + ) + + def __init__(self) -> None: + super().__init__() + # Type signature. This is usually CallableType or Overloaded, but it can be + # something else for decorated functions. + self.type: mypy.types.ProperType | None = None + # Original, not semantically analyzed type (used for reprocessing) + self.unanalyzed_type: mypy.types.ProperType | None = None + # If method, reference to TypeInfo + self.info = FUNC_NO_INFO + self.is_property = False + self.is_class = False + # Is this a `@staticmethod` (explicit or implicit)? + # Note: use has_self_or_cls_argument to check if there is `self` or `cls` argument + self.is_static = False + self.is_final = False + self.is_explicit_override = False + self.is_type_check_only = False + # Can this function/method define variables or infer variables defined outside? + # In particular, we set this in cases like: + # x = None + # def foo() -> None: + # global x + # x = 1 + # and + # class C: + # x = None + # def foo(self) -> None: + # self.x = 1 + self.def_or_infer_vars = False + # Name with module prefix + self._fullname = "" + + @property + @abstractmethod + def name(self) -> str: + pass + + @property + def fullname(self) -> str: + return self._fullname + + @property + def has_self_or_cls_argument(self) -> bool: + """If used as a method, does it have an argument for method binding (`self`, `cls`)? + + This is true for `__new__` even though `__new__` does not undergo method binding, + because we still usually assume that `cls` corresponds to the enclosing class. + """ + return not self.is_static or self.name == "__new__" + + +OverloadPart: _TypeAlias = Union["FuncDef", "Decorator"] + + +class OverloadedFuncDef(FuncBase, SymbolNode, Statement): + """A logical node representing all the variants of a multi-declaration function. + + A multi-declaration function is often an @overload, but can also be a + @property with a setter and a/or a deleter. + + This node has no explicit representation in the source program. + Overloaded variants must be consecutive in the source file. + """ + + __slots__ = ( + "items", + "unanalyzed_items", + "impl", + "deprecated", + "setter_index", + "_is_trivial_self", + ) + + items: list[OverloadPart] + unanalyzed_items: list[OverloadPart] + impl: OverloadPart | None + deprecated: str | None + setter_index: int | None + + def __init__(self, items: list[OverloadPart]) -> None: + super().__init__() + self.items = items + self.unanalyzed_items = items.copy() + self.impl = None + self.deprecated = None + self.setter_index = None + self._is_trivial_self: bool | None = None + if items: + # TODO: figure out how to reliably set end position (we don't know the impl here). + self.set_line(items[0].line, items[0].column) + + @property + def name(self) -> str: + if self.items: + return self.items[0].name + else: + # This may happen for malformed overload + assert self.impl is not None + return self.impl.name + + @property + def is_trivial_self(self) -> bool: + """Check we can use bind_self() fast path for this overload. + + This will return False if at least one overload: + * Has an explicit self annotation, or Self in signature. + * Has a non-trivial decorator. + """ + if self._is_trivial_self is not None: + return self._is_trivial_self + for i, item in enumerate(self.items): + # Note: bare @property is removed in visit_decorator(). + trivial = 1 if i > 0 or not self.is_property else 0 + if isinstance(item, FuncDef): + if not item.is_trivial_self: + self._is_trivial_self = False + return False + elif len(item.decorators) > trivial or not item.func.is_trivial_self: + self._is_trivial_self = False + return False + self._is_trivial_self = True + return True + + @property + def setter(self) -> Decorator: + # Do some consistency checks first. + first_item = self.items[0] + assert isinstance(first_item, Decorator) + assert first_item.var.is_settable_property + assert self.setter_index is not None + item = self.items[self.setter_index] + assert isinstance(item, Decorator) + return item + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_overloaded_func_def(self) + + def serialize(self) -> JsonDict: + return { + ".class": "OverloadedFuncDef", + "items": [i.serialize() for i in self.items], + "type": None if self.type is None else self.type.serialize(), + "fullname": self._fullname, + "impl": None if self.impl is None else self.impl.serialize(), + "flags": get_flags(self, FUNCBASE_FLAGS), + "deprecated": self.deprecated, + "setter_index": self.setter_index, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> OverloadedFuncDef: + assert data[".class"] == "OverloadedFuncDef" + res = OverloadedFuncDef( + [cast(OverloadPart, SymbolNode.deserialize(d)) for d in data["items"]] + ) + if data.get("impl") is not None: + res.impl = cast(OverloadPart, SymbolNode.deserialize(data["impl"])) + # set line for empty overload items, as not set in __init__ + if len(res.items) > 0: + res.set_line(res.impl.line) + if data.get("type") is not None: + typ = mypy.types.deserialize_type(data["type"]) + assert isinstance(typ, mypy.types.ProperType) + res.type = typ + res._fullname = data["fullname"] + set_flags(res, data["flags"]) + res.deprecated = data["deprecated"] + res.setter_index = data["setter_index"] + # NOTE: res.info will be set in the fixup phase. + return res + + def write(self, data: WriteBuffer) -> None: + write_tag(data, OVERLOADED_FUNC_DEF) + write_tag(data, LIST_GEN) + write_int_bare(data, len(self.items)) + for item in self.items: + item.write(data) + mypy.types.write_type_opt(data, self.type) + write_str(data, self._fullname) + if self.impl is None: + write_tag(data, LITERAL_NONE) + else: + self.impl.write(data) + write_flags(data, [self.is_property, self.is_class, self.is_static, self.is_final]) + write_str_opt(data, self.deprecated) + write_int_opt(data, self.setter_index) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> OverloadedFuncDef: + assert read_tag(data) == LIST_GEN + res = OverloadedFuncDef([read_overload_part(data) for _ in range(read_int_bare(data))]) + typ = mypy.types.read_type_opt(data) + if typ is not None: + assert isinstance(typ, mypy.types.ProperType) + res.type = typ + res._fullname = read_str(data) + tag = read_tag(data) + if tag != LITERAL_NONE: + res.impl = read_overload_part(data, tag) + # set line for empty overload items, as not set in __init__ + if len(res.items) > 0: + res.set_line(res.impl.line) + res.is_property, res.is_class, res.is_static, res.is_final = read_flags(data, num_flags=4) + res.deprecated = read_str_opt(data) + res.setter_index = read_int_opt(data) + # NOTE: res.info will be set in the fixup phase. + assert read_tag(data) == END_TAG + return res + + def is_dynamic(self) -> bool: + return all(item.is_dynamic() for item in self.items) + + +class Argument(Node): + """A single argument in a FuncItem.""" + + __slots__ = ("variable", "type_annotation", "initializer", "kind", "pos_only") + + __match_args__ = ("variable", "type_annotation", "initializer", "kind", "pos_only") + + def __init__( + self, + variable: Var, + type_annotation: mypy.types.Type | None, + initializer: Expression | None, + kind: ArgKind, + pos_only: bool = False, + ) -> None: + super().__init__() + self.variable = variable + self.type_annotation = type_annotation + self.initializer = initializer + self.kind = kind # must be an ARG_* constant + self.pos_only = pos_only + + def set_line( + self, + target: Context | int, + column: int | None = None, + end_line: int | None = None, + end_column: int | None = None, + ) -> None: + super().set_line(target, column, end_line, end_column) + + if self.initializer and self.initializer.line < 0: + self.initializer.set_line(self.line, self.column, self.end_line, self.end_column) + + self.variable.set_line(self.line, self.column, self.end_line, self.end_column) + + +# These specify the kind of a TypeParam +TYPE_VAR_KIND: Final = 0 +PARAM_SPEC_KIND: Final = 1 +TYPE_VAR_TUPLE_KIND: Final = 2 + + +class TypeParam: + __slots__ = ("name", "kind", "upper_bound", "values", "default") + + def __init__( + self, + name: str, + kind: int, + upper_bound: mypy.types.Type | None, + values: list[mypy.types.Type], + default: mypy.types.Type | None, + ) -> None: + self.name = name + self.kind = kind + self.upper_bound = upper_bound + self.values = values + self.default = default + + +FUNCITEM_FLAGS: Final = FUNCBASE_FLAGS + [ + "is_overload", + "is_generator", + "is_coroutine", + "is_async_generator", + "is_awaitable_coroutine", +] + + +class FuncItem(FuncBase): + """Base class for nodes usable as overloaded function items.""" + + __slots__ = ( + "arguments", # Note that can be unset if deserialized (type is a lie!) + "arg_names", # Names of arguments + "arg_kinds", # Kinds of arguments + "min_args", # Minimum number of arguments + "max_pos", # Maximum number of positional arguments, -1 if no explicit + # limit (*args not included) + "type_args", # New-style type parameters (PEP 695) + "body", # Body of the function + "is_overload", # Is this an overload variant of function with more than + # one overload variant? + "is_generator", # Contains a yield statement? + "is_coroutine", # Defined using 'async def' syntax? + "is_async_generator", # Is an async def generator? + "is_awaitable_coroutine", # Decorated with '@{typing,asyncio}.coroutine'? + "expanded", # Variants of function with type variables with values expanded + ) + + __deletable__ = ("arguments", "max_pos", "min_args") + + def __init__( + self, + arguments: list[Argument] | None = None, + body: Block | None = None, + typ: mypy.types.FunctionLike | None = None, + type_args: list[TypeParam] | None = None, + ) -> None: + super().__init__() + self.arguments = arguments or [] + self.arg_names = [None if arg.pos_only else arg.variable.name for arg in self.arguments] + self.arg_kinds: list[ArgKind] = [arg.kind for arg in self.arguments] + self.max_pos: int = self.arg_kinds.count(ARG_POS) + self.arg_kinds.count(ARG_OPT) + self.type_args: list[TypeParam] | None = type_args + self.body: Block = body or Block([]) + self.type = typ + self.unanalyzed_type = typ + self.is_overload: bool = False + self.is_generator: bool = False + self.is_coroutine: bool = False + self.is_async_generator: bool = False + self.is_awaitable_coroutine: bool = False + self.expanded: list[FuncItem] = [] + + self.min_args = 0 + for i in range(len(self.arguments)): + if self.arguments[i] is None and i < self.max_fixed_argc(): + self.min_args = i + 1 + + def max_fixed_argc(self) -> int: + return self.max_pos + + def is_dynamic(self) -> bool: + return self.type is None + + +FUNCDEF_FLAGS: Final = FUNCITEM_FLAGS + [ + "is_decorated", + "is_conditional", + "is_trivial_body", + "is_trivial_self", + "is_mypy_only", +] + +# Abstract status of a function +NOT_ABSTRACT: Final = 0 +# Explicitly abstract (with @abstractmethod or overload without implementation) +IS_ABSTRACT: Final = 1 +# Implicitly abstract: used for functions with trivial bodies defined in Protocols +IMPLICITLY_ABSTRACT: Final = 2 + + +class FuncDef(FuncItem, SymbolNode, Statement): + """Function definition. + + This is a non-lambda function defined using 'def'. + """ + + __slots__ = ( + "_name", + "is_decorated", + "is_conditional", + "abstract_status", + "original_def", + "is_trivial_body", + "is_trivial_self", + "is_mypy_only", + # Present only when a function is decorated with @typing.dataclass_transform or similar + "dataclass_transform_spec", + "docstring", + "deprecated", + "original_first_arg", + ) + + __match_args__ = ("name", "arguments", "type", "body") + + # Note that all __init__ args must have default values + def __init__( + self, + name: str = "", # Function name + arguments: list[Argument] | None = None, + body: Block | None = None, + typ: mypy.types.FunctionLike | None = None, + type_args: list[TypeParam] | None = None, + ) -> None: + super().__init__(arguments, body, typ, type_args) + self._name = name + self.is_decorated = False + self.is_conditional = False # Defined conditionally (within block)? + self.abstract_status = NOT_ABSTRACT + # Is this an abstract method with trivial body? + # Such methods can't be called via super(). + self.is_trivial_body = False + # Original conditional definition + self.original_def: None | FuncDef | Var | Decorator = None + # Definitions that appear in if TYPE_CHECKING are marked with this flag. + self.is_mypy_only = False + self.dataclass_transform_spec: DataclassTransformSpec | None = None + self.docstring: str | None = None + self.deprecated: str | None = None + # This is used to simplify bind_self() logic in trivial cases (which are + # the majority). In cases where self is not annotated and there are no Self + # in the signature we can simply drop the first argument. + self.is_trivial_self = False + # This is needed because for positional-only arguments the name is set to None, + # but we sometimes still want to show it in error messages. + if arguments: + self.original_first_arg: str | None = arguments[0].variable.name + else: + self.original_first_arg = None + + @property + def name(self) -> str: + return self._name + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_func_def(self) + + def serialize(self) -> JsonDict: + # We're deliberating omitting arguments and storing only arg_names and + # arg_kinds for space-saving reasons (arguments is not used in later + # stages of mypy). + # TODO: After a FuncDef is deserialized, the only time we use `arg_names` + # and `arg_kinds` is when `type` is None and we need to infer a type. Can + # we store the inferred type ahead of time? + return { + ".class": "FuncDef", + "name": self._name, + "fullname": self._fullname, + "arg_names": self.arg_names, + "arg_kinds": [int(x.value) for x in self.arg_kinds], + "type": None if self.type is None else self.type.serialize(), + "flags": get_flags(self, FUNCDEF_FLAGS), + "abstract_status": self.abstract_status, + # TODO: Do we need expanded, original_def? + "dataclass_transform_spec": ( + None + if self.dataclass_transform_spec is None + else self.dataclass_transform_spec.serialize() + ), + "deprecated": self.deprecated, + "original_first_arg": self.original_first_arg, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> FuncDef: + assert data[".class"] == "FuncDef" + body = Block([]) + ret = FuncDef( + data["name"], + [], + body, + ( + None + if data["type"] is None + else cast(mypy.types.FunctionLike, mypy.types.deserialize_type(data["type"])) + ), + ) + ret._fullname = data["fullname"] + set_flags(ret, data["flags"]) + # NOTE: ret.info is set in the fixup phase. + ret.arg_names = data["arg_names"] + ret.original_first_arg = data.get("original_first_arg") + ret.arg_kinds = [ARG_KINDS[x] for x in data["arg_kinds"]] + ret.abstract_status = data["abstract_status"] + ret.dataclass_transform_spec = ( + DataclassTransformSpec.deserialize(data["dataclass_transform_spec"]) + if data["dataclass_transform_spec"] is not None + else None + ) + ret.deprecated = data["deprecated"] + # Leave these uninitialized so that future uses will trigger an error + del ret.arguments + del ret.max_pos + del ret.min_args + return ret + + def write(self, data: WriteBuffer) -> None: + write_tag(data, FUNC_DEF) + write_str(data, self._name) + mypy.types.write_type_opt(data, self.type) + write_str(data, self._fullname) + write_flags( + data, + [ + self.is_property, + self.is_class, + self.is_static, + self.is_final, + self.is_overload, + self.is_generator, + self.is_coroutine, + self.is_async_generator, + self.is_awaitable_coroutine, + self.is_decorated, + self.is_conditional, + self.is_trivial_body, + self.is_trivial_self, + self.is_mypy_only, + ], + ) + write_str_opt_list(data, self.arg_names) + write_int_list(data, [int(ak.value) for ak in self.arg_kinds]) + write_int(data, self.abstract_status) + if self.dataclass_transform_spec is None: + write_tag(data, LITERAL_NONE) + else: + self.dataclass_transform_spec.write(data) + write_str_opt(data, self.deprecated) + write_str_opt(data, self.original_first_arg) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> FuncDef: + name = read_str(data) + typ: mypy.types.FunctionLike | None = None + tag = read_tag(data) + if tag != LITERAL_NONE: + typ = mypy.types.read_function_like(data, tag) + ret = FuncDef(name, [], Block([]), typ) + ret._fullname = read_str(data) + ( + ret.is_property, + ret.is_class, + ret.is_static, + ret.is_final, + ret.is_overload, + ret.is_generator, + ret.is_coroutine, + ret.is_async_generator, + ret.is_awaitable_coroutine, + ret.is_decorated, + ret.is_conditional, + ret.is_trivial_body, + ret.is_trivial_self, + ret.is_mypy_only, + ) = read_flags(data, num_flags=14) + # NOTE: ret.info is set in the fixup phase. + ret.arg_names = read_str_opt_list(data) + ret.arg_kinds = [ARG_KINDS[ak] for ak in read_int_list(data)] + ret.abstract_status = read_int(data) + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == DT_SPEC + ret.dataclass_transform_spec = DataclassTransformSpec.read(data) + ret.deprecated = read_str_opt(data) + ret.original_first_arg = read_str_opt(data) + # Leave these uninitialized so that future uses will trigger an error + del ret.arguments + del ret.max_pos + del ret.min_args + assert read_tag(data) == END_TAG + return ret + + +# All types that are both SymbolNodes and FuncBases. See the FuncBase +# docstring for the rationale. +# See https://github.com/python/mypy/pull/13607#issuecomment-1236357236 +# TODO: we want to remove this at some point and just use `FuncBase` ideally. +SYMBOL_FUNCBASE_TYPES: Final = (OverloadedFuncDef, FuncDef) + + +class Decorator(SymbolNode, Statement): + """A decorated function. + + A single Decorator object can include any number of function decorators. + """ + + __slots__ = ("func", "decorators", "original_decorators", "var", "is_overload") + + __match_args__ = ("decorators", "var", "func") + + func: FuncDef # Decorated function + decorators: list[Expression] # Decorators (may be empty) + # Some decorators are removed by semanal, keep the original here. + original_decorators: list[Expression] + # TODO: This is mostly used for the type; consider replacing with a 'type' attribute + var: Var # Represents the decorated function obj + is_overload: bool + + def __init__(self, func: FuncDef, decorators: list[Expression], var: Var) -> None: + super().__init__() + self.func = func + self.decorators = decorators + self.original_decorators = decorators.copy() + self.var = var + self.is_overload = False + + @property + def name(self) -> str: + return self.func.name + + @property + def fullname(self) -> str: + return self.func.fullname + + @property + def is_final(self) -> bool: + return self.func.is_final + + @property + def info(self) -> TypeInfo: + return self.func.info + + @property + def type(self) -> mypy.types.Type | None: + return self.var.type + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_decorator(self) + + def serialize(self) -> JsonDict: + return { + ".class": "Decorator", + "func": self.func.serialize(), + "var": self.var.serialize(), + "is_overload": self.is_overload, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> Decorator: + assert data[".class"] == "Decorator" + dec = Decorator(FuncDef.deserialize(data["func"]), [], Var.deserialize(data["var"])) + dec.is_overload = data["is_overload"] + return dec + + def write(self, data: WriteBuffer) -> None: + write_tag(data, DECORATOR) + self.func.write(data) + self.var.write(data) + write_bool(data, self.is_overload) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> Decorator: + assert read_tag(data) == FUNC_DEF + func = FuncDef.read(data) + assert read_tag(data) == VAR + var = Var.read(data) + dec = Decorator(func, [], var) + dec.is_overload = read_bool(data) + assert read_tag(data) == END_TAG + return dec + + def is_dynamic(self) -> bool: + return self.func.is_dynamic() + + +VAR_FLAGS: Final = [ + "is_self", + "is_cls", + "is_initialized_in_class", + "is_staticmethod", + "is_classmethod", + "is_property", + "is_settable_property", + "is_suppressed_import", + "is_classvar", + "is_abstract_var", + "is_final", + "is_index_var", + "final_unset_in_class", + "final_set_in_init", + "explicit_self_type", + "is_ready", + "is_inferred", + "invalid_partial_type", + "from_module_getattr", + "has_explicit_value", + "allow_incompatible_override", +] + + +class Var(SymbolNode): + """A variable. + + It can refer to global/local variable or a data attribute. + """ + + __slots__ = ( + "_name", + "_fullname", + "info", + "type", + "setter_type", + "final_value", + "is_self", + "is_cls", + "is_ready", + "is_inferred", + "is_initialized_in_class", + "is_staticmethod", + "is_classmethod", + "is_property", + "is_settable_property", + "is_classvar", + "is_abstract_var", + "is_final", + "is_index_var", + "final_unset_in_class", + "final_set_in_init", + "is_suppressed_import", + "explicit_self_type", + "from_module_getattr", + "has_explicit_value", + "allow_incompatible_override", + "invalid_partial_type", + "is_argument", + ) + + __match_args__ = ("name", "type", "final_value") + + def __init__(self, name: str, type: mypy.types.Type | None = None) -> None: + super().__init__() + self._name = name # Name without module prefix + # TODO: Should be Optional[str] + self._fullname = "" # Name with module prefix + # TODO: Should be Optional[TypeInfo] + self.info = VAR_NO_INFO + self.type: mypy.types.Type | None = type # Declared or inferred type, or None + # The setter type for settable properties. + self.setter_type: mypy.types.CallableType | None = None + # Is this the first argument to an ordinary method (usually "self")? + self.is_self = False + # Is this the first argument to a classmethod (typically "cls")? + self.is_cls = False + self.is_ready = True # If inferred, is the inferred type available? + self.is_inferred = self.type is None + # Is this variable declared in class body? The name is confusing, but it + # is a very old attribute, and changing will break some plugins. + self.is_initialized_in_class = False + self.is_staticmethod = False + self.is_classmethod = False + self.is_property = False + self.is_settable_property = False + self.is_classvar = False + self.is_abstract_var = False + self.is_index_var = False + # Set to true when this variable refers to a module we were unable to + # parse for some reason (eg a silenced module) + self.is_suppressed_import = False + # Was this "variable" (rather a constant) defined as Final[...]? + self.is_final = False + # If constant value is a simple literal, + # store the literal value (unboxed) for the benefit of + # tools like mypyc. + self.final_value: int | float | complex | bool | str | None = None + # Where the value was set (only for class attributes) + self.final_unset_in_class = False + self.final_set_in_init = False + # This is True for a variable that was declared on self with an explicit type: + # class C: + # def __init__(self) -> None: + # self.x: int + # This case is important because this defines a new Var, even if there is one + # present in a superclass (without explicit type this doesn't create a new Var). + # See SemanticAnalyzer.analyze_member_lvalue() for details. + self.explicit_self_type = False + # If True, this is an implicit Var created due to module-level __getattr__. + self.from_module_getattr = False + # Var can be created with an explicit value `a = 1` or without one `a: int`, + # we need a way to tell which one is which. + self.has_explicit_value = False + # If True, subclasses can override this with an incompatible type. + self.allow_incompatible_override = False + # If True, this means we didn't manage to infer full type and fall back to + # something like list[Any]. We may decide to not use such types as context. + self.invalid_partial_type = False + # Is it a variable symbol for a function argument? + self.is_argument = False + + @property + def name(self) -> str: + return self._name + + @property + def fullname(self) -> str: + return self._fullname + + def __repr__(self) -> str: + name = self.fullname or self.name + return f"" + + def accept(self, visitor: NodeVisitor[T]) -> T: + return visitor.visit_var(self) + + def serialize(self) -> JsonDict: + # TODO: Leave default values out? + # NOTE: Sometimes self.is_ready is False here, but we don't care. + data: JsonDict = { + ".class": "Var", + "name": self._name, + "fullname": self._fullname, + "type": None if self.type is None else self.type.serialize(), + "setter_type": None if self.setter_type is None else self.setter_type.serialize(), + "flags": get_flags(self, VAR_FLAGS), + } + if self.final_value is not None: + data["final_value"] = self.final_value + return data + + @classmethod + def deserialize(cls, data: JsonDict) -> Var: + assert data[".class"] == "Var" + name = data["name"] + type = None if data["type"] is None else mypy.types.deserialize_type(data["type"]) + setter_type = ( + None + if data["setter_type"] is None + else mypy.types.deserialize_type(data["setter_type"]) + ) + v = Var(name, type) + assert ( + setter_type is None + or isinstance(setter_type, mypy.types.ProperType) + and isinstance(setter_type, mypy.types.CallableType) + ) + v.setter_type = setter_type + v.is_ready = False # Override True default set in __init__ + v._fullname = data["fullname"] + set_flags(v, data["flags"]) + v.final_value = data.get("final_value") + return v + + def write(self, data: WriteBuffer) -> None: + write_tag(data, VAR) + write_str(data, self._name) + mypy.types.write_type_opt(data, self.type) + mypy.types.write_type_opt(data, self.setter_type) + write_str(data, self._fullname) + write_flags( + data, + [ + self.is_initialized_in_class, + self.is_staticmethod, + self.is_classmethod, + self.is_property, + self.is_settable_property, + self.is_suppressed_import, + self.is_classvar, + self.is_abstract_var, + self.is_final, + self.is_index_var, + self.final_unset_in_class, + self.final_set_in_init, + self.explicit_self_type, + self.is_ready, + self.is_inferred, + self.invalid_partial_type, + self.from_module_getattr, + self.has_explicit_value, + self.allow_incompatible_override, + ], + ) + write_literal(data, self.final_value) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> Var: + name = read_str(data) + typ = mypy.types.read_type_opt(data) + v = Var(name, typ) + setter_type: mypy.types.CallableType | None = None + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == mypy.types.CALLABLE_TYPE + setter_type = mypy.types.CallableType.read(data) + v.setter_type = setter_type + v._fullname = read_str(data) + ( + v.is_initialized_in_class, + v.is_staticmethod, + v.is_classmethod, + v.is_property, + v.is_settable_property, + v.is_suppressed_import, + v.is_classvar, + v.is_abstract_var, + v.is_final, + v.is_index_var, + v.final_unset_in_class, + v.final_set_in_init, + v.explicit_self_type, + v.is_ready, + v.is_inferred, + v.invalid_partial_type, + v.from_module_getattr, + v.has_explicit_value, + v.allow_incompatible_override, + ) = read_flags(data, num_flags=19) + tag = read_tag(data) + if tag == LITERAL_COMPLEX: + v.final_value = complex(read_float_bare(data), read_float_bare(data)) + elif tag != LITERAL_NONE: + v.final_value = read_literal(data, tag) + assert read_tag(data) == END_TAG + return v + + +class ClassDef(Statement): + """Class definition""" + + __slots__ = ( + "name", + "_fullname", + "defs", + "type_args", + "type_vars", + "base_type_exprs", + "removed_base_type_exprs", + "info", + "metaclass", + "decorators", + "keywords", + "analyzed", + "has_incompatible_baseclass", + "docstring", + "removed_statements", + ) + + __match_args__ = ("name", "defs") + + name: str # Name of the class without module prefix + _fullname: str # Fully qualified name of the class + defs: Block + # New-style type parameters (PEP 695), unanalyzed + type_args: list[TypeParam] | None + # Semantically analyzed type parameters (all syntax variants) + type_vars: list[mypy.types.TypeVarLikeType] + # Base class expressions (not semantically analyzed -- can be arbitrary expressions) + base_type_exprs: list[Expression] + # Special base classes like Generic[...] get moved here during semantic analysis + removed_base_type_exprs: list[Expression] + info: TypeInfo # Related TypeInfo + metaclass: Expression | None + decorators: list[Expression] + keywords: dict[str, Expression] + analyzed: Expression | None + has_incompatible_baseclass: bool + # Used by special forms like NamedTuple and TypedDict to store invalid statements + removed_statements: list[Statement] + + def __init__( + self, + name: str, + defs: Block, + type_vars: list[mypy.types.TypeVarLikeType] | None = None, + base_type_exprs: list[Expression] | None = None, + metaclass: Expression | None = None, + keywords: list[tuple[str, Expression]] | None = None, + type_args: list[TypeParam] | None = None, + ) -> None: + super().__init__() + self.name = name + self._fullname = "" + self.defs = defs + self.type_vars = type_vars or [] + self.type_args = type_args + self.base_type_exprs = base_type_exprs or [] + self.removed_base_type_exprs = [] + self.info = CLASSDEF_NO_INFO + self.metaclass = metaclass + self.decorators = [] + self.keywords = dict(keywords) if keywords else {} + self.analyzed = None + self.has_incompatible_baseclass = False + self.docstring: str | None = None + self.removed_statements = [] + + @property + def fullname(self) -> str: + return self._fullname + + @fullname.setter + def fullname(self, v: str) -> None: + self._fullname = v + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_class_def(self) + + def is_generic(self) -> bool: + return self.info.is_generic() + + def serialize(self) -> JsonDict: + # Not serialized: defs, base_type_exprs, metaclass, decorators, + # analyzed (for named tuples etc.) + return { + ".class": "ClassDef", + "name": self.name, + "fullname": self.fullname, + "type_vars": [v.serialize() for v in self.type_vars], + } + + @classmethod + def deserialize(cls, data: JsonDict) -> ClassDef: + assert data[".class"] == "ClassDef" + res = ClassDef( + data["name"], + Block([]), + # https://github.com/python/mypy/issues/12257 + [ + cast(mypy.types.TypeVarLikeType, mypy.types.deserialize_type(v)) + for v in data["type_vars"] + ], + ) + res.fullname = data["fullname"] + return res + + def write(self, data: WriteBuffer) -> None: + write_tag(data, CLASS_DEF) + write_str(data, self.name) + mypy.types.write_type_list(data, self.type_vars) + write_str(data, self.fullname) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> ClassDef: + res = ClassDef(read_str(data), Block([]), mypy.types.read_type_var_likes(data)) + res.fullname = read_str(data) + assert read_tag(data) == END_TAG + return res + + +class GlobalDecl(Statement): + """Declaration global x, y, ...""" + + __slots__ = ("names",) + + __match_args__ = ("names",) + + names: list[str] + + def __init__(self, names: list[str]) -> None: + super().__init__() + self.names = names + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_global_decl(self) + + +class NonlocalDecl(Statement): + """Declaration nonlocal x, y, ...""" + + __slots__ = ("names",) + + __match_args__ = ("names",) + + names: list[str] + + def __init__(self, names: list[str]) -> None: + super().__init__() + self.names = names + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_nonlocal_decl(self) + + +class Block(Statement): + __slots__ = ("body", "is_unreachable") + + __match_args__ = ("body", "is_unreachable") + + def __init__(self, body: list[Statement], *, is_unreachable: bool = False) -> None: + super().__init__() + self.body = body + # True if we can determine that this block is not executed during semantic + # analysis. For example, this applies to blocks that are protected by + # something like "if PY3:" when using Python 2. However, some code is + # only considered unreachable during type checking and this is not true + # in those cases. + self.is_unreachable = is_unreachable + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_block(self) + + +# Statements + + +class ExpressionStmt(Statement): + """An expression as a statement, such as print(s).""" + + __slots__ = ("expr",) + + __match_args__ = ("expr",) + + expr: Expression + + def __init__(self, expr: Expression) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_expression_stmt(self) + + +class AssignmentStmt(Statement): + """Assignment statement. + + The same node class is used for single assignment, multiple assignment + (e.g. x, y = z) and chained assignment (e.g. x = y = z), assignments + that define new names, and assignments with explicit types ("# type: t" + or "x: t [= ...]"). + + An lvalue can be NameExpr, TupleExpr, ListExpr, MemberExpr, or IndexExpr. + """ + + __slots__ = ( + "lvalues", + "rvalue", + "type", + "unanalyzed_type", + "new_syntax", + "is_alias_def", + "is_final_def", + "invalid_recursive_alias", + ) + + __match_args__ = ("lvalues", "rvalues", "type") + + lvalues: list[Lvalue] + # This is a TempNode if and only if no rvalue (x: t). + rvalue: Expression + # Declared type in a comment, may be None. + type: mypy.types.Type | None + # Original, not semantically analyzed type in annotation (used for reprocessing) + unanalyzed_type: mypy.types.Type | None + # This indicates usage of PEP 526 type annotation syntax in assignment. + new_syntax: bool + # Does this assignment define a type alias? + is_alias_def: bool + # Is this a final definition? + # Final attributes can't be re-assigned once set, and can't be overridden + # in a subclass. This flag is not set if an attempted declaration was found to + # be invalid during semantic analysis. It is still set to `True` if + # a final declaration overrides another final declaration (this is checked + # during type checking when MROs are known). + is_final_def: bool + # Stop further processing of this assignment, to prevent flipping back and forth + # during semantic analysis passes. + invalid_recursive_alias: bool + + def __init__( + self, + lvalues: list[Lvalue], + rvalue: Expression, + type: mypy.types.Type | None = None, + new_syntax: bool = False, + ) -> None: + super().__init__() + self.lvalues = lvalues + self.rvalue = rvalue + self.type = type + self.unanalyzed_type = type + self.new_syntax = new_syntax + self.is_alias_def = False + self.is_final_def = False + self.invalid_recursive_alias = False + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_assignment_stmt(self) + + +class OperatorAssignmentStmt(Statement): + """Operator assignment statement such as x += 1""" + + __slots__ = ("op", "lvalue", "rvalue") + + __match_args__ = ("lvalue", "op", "rvalue") + + op: str # TODO: Enum? + lvalue: Lvalue + rvalue: Expression + + def __init__(self, op: str, lvalue: Lvalue, rvalue: Expression) -> None: + super().__init__() + self.op = op + self.lvalue = lvalue + self.rvalue = rvalue + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_operator_assignment_stmt(self) + + +class WhileStmt(Statement): + __slots__ = ("expr", "body", "else_body") + + __match_args__ = ("expr", "body", "else_body") + + expr: Expression + body: Block + else_body: Block | None + + def __init__(self, expr: Expression, body: Block, else_body: Block | None) -> None: + super().__init__() + self.expr = expr + self.body = body + self.else_body = else_body + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_while_stmt(self) + + +class ForStmt(Statement): + __slots__ = ( + "index", + "index_type", + "unanalyzed_index_type", + "inferred_item_type", + "inferred_iterator_type", + "expr", + "body", + "else_body", + "is_async", + ) + + __match_args__ = ("index", "index_type", "expr", "body", "else_body") + + # Index variables + index: Lvalue + # Type given by type comments for index, can be None + index_type: mypy.types.Type | None + # Original, not semantically analyzed type in annotation (used for reprocessing) + unanalyzed_index_type: mypy.types.Type | None + # Inferred iterable item type + inferred_item_type: mypy.types.Type | None + # Inferred iterator type + inferred_iterator_type: mypy.types.Type | None + # Expression to iterate + expr: Expression + body: Block + else_body: Block | None + is_async: bool # True if `async for ...` (PEP 492, Python 3.5) + + def __init__( + self, + index: Lvalue, + expr: Expression, + body: Block, + else_body: Block | None, + index_type: mypy.types.Type | None = None, + ) -> None: + super().__init__() + self.index = index + self.index_type = index_type + self.unanalyzed_index_type = index_type + self.inferred_item_type = None + self.inferred_iterator_type = None + self.expr = expr + self.body = body + self.else_body = else_body + self.is_async = False + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_for_stmt(self) + + +class ReturnStmt(Statement): + __slots__ = ("expr",) + + __match_args__ = ("expr",) + + expr: Expression | None + + def __init__(self, expr: Expression | None) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_return_stmt(self) + + +class AssertStmt(Statement): + __slots__ = ("expr", "msg") + + __match_args__ = ("expr", "msg") + + expr: Expression + msg: Expression | None + + def __init__(self, expr: Expression, msg: Expression | None = None) -> None: + super().__init__() + self.expr = expr + self.msg = msg + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_assert_stmt(self) + + +class DelStmt(Statement): + __slots__ = ("expr",) + + __match_args__ = ("expr",) + + expr: Lvalue + + def __init__(self, expr: Lvalue) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_del_stmt(self) + + +class BreakStmt(Statement): + __slots__ = () + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_break_stmt(self) + + +class ContinueStmt(Statement): + __slots__ = () + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_continue_stmt(self) + + +class PassStmt(Statement): + __slots__ = () + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_pass_stmt(self) + + +class IfStmt(Statement): + __slots__ = ("expr", "body", "else_body", "unreachable_else") + + __match_args__ = ("expr", "body", "else_body", "unreachable_else") + + expr: list[Expression] + body: list[Block] + else_body: Block | None + # (If there is actually no else statement, semantic analysis may nevertheless create an + # empty else block and mark it permanently as unreachable to tell that the control flow + # must always go through the if block.) + unreachable_else: bool + # (Type checking may modify this flag repeatedly to indicate whether an actually available + # or unavailable else block is unreachable, considering the current type information.) + + def __init__(self, expr: list[Expression], body: list[Block], else_body: Block | None) -> None: + super().__init__() + self.expr = expr + self.body = body + self.else_body = else_body + self.unreachable_else = False + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_if_stmt(self) + + +class RaiseStmt(Statement): + __slots__ = ("expr", "from_expr") + + __match_args__ = ("expr", "from_expr") + + # Plain 'raise' is a valid statement. + expr: Expression | None + from_expr: Expression | None + + def __init__(self, expr: Expression | None, from_expr: Expression | None) -> None: + super().__init__() + self.expr = expr + self.from_expr = from_expr + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_raise_stmt(self) + + +class TryStmt(Statement): + __slots__ = ("body", "types", "vars", "handlers", "else_body", "finally_body", "is_star") + + __match_args__ = ("body", "types", "vars", "handlers", "else_body", "finally_body", "is_star") + + body: Block # Try body + # Plain 'except:' also possible + types: list[Expression | None] # Except type expressions + vars: list[NameExpr | None] # Except variable names + handlers: list[Block] # Except bodies + else_body: Block | None + finally_body: Block | None + # Whether this is try ... except* (added in Python 3.11) + is_star: bool + + def __init__( + self, + body: Block, + vars: list[NameExpr | None], + types: list[Expression | None], + handlers: list[Block], + else_body: Block | None, + finally_body: Block | None, + ) -> None: + super().__init__() + self.body = body + self.vars = vars + self.types = types + self.handlers = handlers + self.else_body = else_body + self.finally_body = finally_body + self.is_star = False + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_try_stmt(self) + + +class WithStmt(Statement): + __slots__ = ("expr", "target", "unanalyzed_type", "analyzed_types", "body", "is_async") + + __match_args__ = ("expr", "target", "body") + + expr: list[Expression] + target: list[Lvalue | None] + # Type given by type comments for target, can be None + unanalyzed_type: mypy.types.Type | None + # Semantically analyzed types from type comment (TypeList type expanded) + analyzed_types: list[mypy.types.Type] + body: Block + is_async: bool # True if `async with ...` (PEP 492, Python 3.5) + + def __init__( + self, + expr: list[Expression], + target: list[Lvalue | None], + body: Block, + target_type: mypy.types.Type | None = None, + ) -> None: + super().__init__() + self.expr = expr + self.target = target + self.unanalyzed_type = target_type + self.analyzed_types = [] + self.body = body + self.is_async = False + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_with_stmt(self) + + +class MatchStmt(Statement): + __slots__ = ("subject", "subject_dummy", "patterns", "guards", "bodies") + + __match_args__ = ("subject", "patterns", "guards", "bodies") + + subject: Expression + subject_dummy: NameExpr | None + patterns: list[Pattern] + guards: list[Expression | None] + bodies: list[Block] + + def __init__( + self, + subject: Expression, + patterns: list[Pattern], + guards: list[Expression | None], + bodies: list[Block], + ) -> None: + super().__init__() + assert len(patterns) == len(guards) == len(bodies) + self.subject = subject + self.subject_dummy = None + self.patterns = patterns + self.guards = guards + self.bodies = bodies + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_match_stmt(self) + + +class TypeAliasStmt(Statement): + __slots__ = ("name", "type_args", "value", "invalid_recursive_alias", "alias_node") + + __match_args__ = ("name", "type_args", "value") + + name: NameExpr + type_args: list[TypeParam] + value: LambdaExpr # Return value will get translated into a type + invalid_recursive_alias: bool + alias_node: TypeAlias | None + + def __init__(self, name: NameExpr, type_args: list[TypeParam], value: LambdaExpr) -> None: + super().__init__() + self.name = name + self.type_args = type_args + self.value = value + self.invalid_recursive_alias = False + self.alias_node = None + + def accept(self, visitor: StatementVisitor[T]) -> T: + return visitor.visit_type_alias_stmt(self) + + +# Expressions + + +class IntExpr(Expression): + """Integer literal""" + + __slots__ = ("value",) + + __match_args__ = ("value",) + + value: int # 0 by default + + def __init__(self, value: int) -> None: + super().__init__() + self.value = value + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_int_expr(self) + + +# How mypy uses StrExpr and BytesExpr: +# +# b'x' -> BytesExpr +# 'x', u'x' -> StrExpr + + +class StrExpr(Expression): + """String literal""" + + __slots__ = ("value", "as_type") + + __match_args__ = ("value",) + + value: str # '' by default + # If this value expression can also be parsed as a valid type expression, + # represents the type denoted by the type expression. + # None means "is not a type expression". + as_type: NotParsed | mypy.types.Type | None + + def __init__(self, value: str) -> None: + super().__init__() + self.value = value + self.as_type = NotParsed.VALUE + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_str_expr(self) + + +def is_StrExpr_list(seq: list[Expression]) -> TypeGuard[list[StrExpr]]: # noqa: N802 + return all(isinstance(item, StrExpr) for item in seq) + + +class BytesExpr(Expression): + """Bytes literal""" + + __slots__ = ("value",) + + __match_args__ = ("value",) + + # Note: we deliberately do NOT use bytes here because it ends up + # unnecessarily complicating a lot of the result logic. For example, + # we'd have to worry about converting the bytes into a format we can + # easily serialize/deserialize to and from JSON, would have to worry + # about turning the bytes into a human-readable representation in + # error messages... + # + # It's more convenient to just store the human-readable representation + # from the very start. + value: str + + def __init__(self, value: str) -> None: + super().__init__() + self.value = value + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_bytes_expr(self) + + +class FloatExpr(Expression): + """Float literal""" + + __slots__ = ("value",) + + __match_args__ = ("value",) + + value: float # 0.0 by default + + def __init__(self, value: float) -> None: + super().__init__() + self.value = value + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_float_expr(self) + + +class ComplexExpr(Expression): + """Complex literal""" + + __slots__ = ("value",) + + __match_args__ = ("value",) + + value: complex + + def __init__(self, value: complex) -> None: + super().__init__() + self.value = value + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_complex_expr(self) + + +class EllipsisExpr(Expression): + """Ellipsis (...)""" + + __slots__ = () + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_ellipsis(self) + + +class StarExpr(Expression): + """Star expression""" + + __slots__ = ("expr", "valid") + + __match_args__ = ("expr", "valid") + + expr: Expression + valid: bool + + def __init__(self, expr: Expression) -> None: + super().__init__() + self.expr = expr + + # Whether this starred expression is used in a tuple/list and as lvalue + self.valid = False + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_star_expr(self) + + +class RefExpr(Expression): + """Abstract base class for name-like constructs""" + + __slots__ = ( + "kind", + "node", + "_fullname", + "is_new_def", + "is_inferred_def", + "is_alias_rvalue", + "type_guard", + "type_is", + ) + + def __init__(self) -> None: + super().__init__() + # LDEF/GDEF/MDEF/... (None if not available) + self.kind: int | None = None + # Var, FuncDef or TypeInfo that describes this + self.node: SymbolNode | None = None + # Fully qualified name (or name if not global) + self._fullname = "" + # Does this define a new name? + self.is_new_def = False + # Does this define a new name with inferred type? + # + # For members, after semantic analysis, this does not take base + # classes into consideration at all; the type checker deals with these. + self.is_inferred_def = False + # Is this expression appears as an rvalue of a valid type alias definition? + self.is_alias_rvalue = False + # Cache type guard from callable_type.type_guard + self.type_guard: mypy.types.Type | None = None + # And same for TypeIs + self.type_is: mypy.types.Type | None = None + + @property + def fullname(self) -> str: + return self._fullname + + @fullname.setter + def fullname(self, v: str) -> None: + self._fullname = v + + +class NameExpr(RefExpr): + """Name expression + + This refers to a local name, global name or a module. + """ + + __slots__ = ("name", "is_special_form") + + __match_args__ = ("name", "node") + + def __init__(self, name: str) -> None: + super().__init__() + self.name = name # Name referred to + # Is this a l.h.s. of a special form assignment like typed dict or type variable? + self.is_special_form = False + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_name_expr(self) + + def serialize(self) -> JsonDict: + assert False, f"Serializing NameExpr: {self}" + + +class MemberExpr(RefExpr): + """Member access expression x.y""" + + __slots__ = ("expr", "name", "def_var") + + __match_args__ = ("expr", "name", "node") + + def __init__(self, expr: Expression, name: str) -> None: + super().__init__() + self.expr = expr + self.name = name + # The variable node related to a definition through 'self.x = '. + # The nodes of other kinds of member expressions are resolved during type checking. + self.def_var: Var | None = None + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_member_expr(self) + + +# Kinds of arguments +@unique +class ArgKind(Enum): + # Positional argument + ARG_POS = 0 + # Positional, optional argument (functions only, not calls) + ARG_OPT = 1 + # *arg argument + ARG_STAR = 2 + # Keyword argument x=y in call, or keyword-only function arg + ARG_NAMED = 3 + # **arg argument + ARG_STAR2 = 4 + # In an argument list, keyword-only and also optional + ARG_NAMED_OPT = 5 + + def is_positional(self, star: bool = False) -> bool: + return self == ARG_POS or self == ARG_OPT or (star and self == ARG_STAR) + + def is_named(self, star: bool = False) -> bool: + return self == ARG_NAMED or self == ARG_NAMED_OPT or (star and self == ARG_STAR2) + + def is_required(self) -> bool: + return self == ARG_POS or self == ARG_NAMED + + def is_optional(self) -> bool: + return self == ARG_OPT or self == ARG_NAMED_OPT + + def is_star(self) -> bool: + return self == ARG_STAR or self == ARG_STAR2 + + +ARG_POS: Final = ArgKind.ARG_POS +ARG_OPT: Final = ArgKind.ARG_OPT +ARG_STAR: Final = ArgKind.ARG_STAR +ARG_NAMED: Final = ArgKind.ARG_NAMED +ARG_STAR2: Final = ArgKind.ARG_STAR2 +ARG_NAMED_OPT: Final = ArgKind.ARG_NAMED_OPT + +ARG_KINDS: Final = (ARG_POS, ARG_OPT, ARG_STAR, ARG_NAMED, ARG_STAR2, ARG_NAMED_OPT) + + +class CallExpr(Expression): + """Call expression. + + This can also represent several special forms that are syntactically calls + such as cast(...) and None # type: .... + """ + + __slots__ = ("callee", "args", "arg_kinds", "arg_names", "analyzed") + + __match_args__ = ("callee", "args", "arg_kinds", "arg_names") + + def __init__( + self, + callee: Expression, + args: list[Expression], + arg_kinds: list[ArgKind], + arg_names: list[str | None], + analyzed: Expression | None = None, + ) -> None: + super().__init__() + if not arg_names: + arg_names = [None] * len(args) + + self.callee = callee + self.args = args + self.arg_kinds = arg_kinds # ARG_ constants + # Each name can be None if not a keyword argument. + self.arg_names: list[str | None] = arg_names + # If not None, the node that represents the meaning of the CallExpr. For + # cast(...) this is a CastExpr. + self.analyzed = analyzed + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_call_expr(self) + + +class YieldFromExpr(Expression): + __slots__ = ("expr",) + + __match_args__ = ("expr",) + + expr: Expression + + def __init__(self, expr: Expression) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_yield_from_expr(self) + + +class YieldExpr(Expression): + __slots__ = ("expr",) + + __match_args__ = ("expr",) + + expr: Expression | None + + def __init__(self, expr: Expression | None) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_yield_expr(self) + + +class IndexExpr(Expression): + """Index expression x[y]. + + Also wraps type application such as List[int] as a special form. + """ + + __slots__ = ("base", "index", "method_type", "analyzed", "as_type") + + __match_args__ = ("base", "index") + + base: Expression + index: Expression + # Inferred __getitem__ method type + method_type: mypy.types.Type | None + # If not None, this is actually semantically a type application + # Class[type, ...] or a type alias initializer. + analyzed: TypeApplication | TypeAliasExpr | None + # If this value expression can also be parsed as a valid type expression, + # represents the type denoted by the type expression. + # None means "is not a type expression". + as_type: NotParsed | mypy.types.Type | None + + def __init__(self, base: Expression, index: Expression) -> None: + super().__init__() + self.base = base + self.index = index + self.method_type = None + self.analyzed = None + self.as_type = NotParsed.VALUE + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_index_expr(self) + + +class UnaryExpr(Expression): + """Unary operation""" + + __slots__ = ("op", "expr", "method_type") + + __match_args__ = ("op", "expr") + + op: str # TODO: Enum? + expr: Expression + # Inferred operator method type + method_type: mypy.types.Type | None + + def __init__(self, op: str, expr: Expression) -> None: + super().__init__() + self.op = op + self.expr = expr + self.method_type = None + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_unary_expr(self) + + +class AssignmentExpr(Expression): + """Assignment expressions in Python 3.8+, like "a := 2".""" + + __slots__ = ("target", "value") + + __match_args__ = ("target", "value") + + def __init__(self, target: NameExpr, value: Expression) -> None: + super().__init__() + self.target = target + self.value = value + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_assignment_expr(self) + + +class OpExpr(Expression): + """Binary operation. + + The dot (.), [] and comparison operators have more specific nodes. + """ + + __slots__ = ( + "op", + "left", + "right", + "method_type", + "right_always", + "right_unreachable", + "analyzed", + "as_type", + ) + + __match_args__ = ("left", "op", "right") + + op: str # TODO: Enum? + left: Expression + right: Expression + # Inferred type for the operator method type (when relevant). + method_type: mypy.types.Type | None + # Per static analysis only: Is the right side going to be evaluated every time? + right_always: bool + # Per static analysis only: Is the right side unreachable? + right_unreachable: bool + # Used for expressions that represent a type "X | Y" in some contexts + analyzed: TypeAliasExpr | None + # If this value expression can also be parsed as a valid type expression, + # represents the type denoted by the type expression. + # None means "is not a type expression". + as_type: NotParsed | mypy.types.Type | None + + def __init__( + self, op: str, left: Expression, right: Expression, analyzed: TypeAliasExpr | None = None + ) -> None: + super().__init__() + self.op = op + self.left = left + self.right = right + self.method_type = None + self.right_always = False + self.right_unreachable = False + self.analyzed = analyzed + self.as_type = NotParsed.VALUE + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_op_expr(self) + + +# Expression subtypes that could represent the root of a valid type expression. +# +# May have an "as_type" attribute to hold the type for a type expression parsed +# during the SemanticAnalyzer pass. +MaybeTypeExpression = (IndexExpr, MemberExpr, NameExpr, OpExpr, StrExpr) + + +class ComparisonExpr(Expression): + """Comparison expression (e.g. a < b > c < d).""" + + __slots__ = ("operators", "operands", "method_types") + + __match_args__ = ("operands", "operators") + + operators: list[str] + operands: list[Expression] + # Inferred type for the operator methods (when relevant; None for 'is'). + method_types: list[mypy.types.Type | None] + + def __init__(self, operators: list[str], operands: list[Expression]) -> None: + super().__init__() + self.operators = operators + self.operands = operands + self.method_types = [] + + def pairwise(self) -> Iterator[tuple[str, Expression, Expression]]: + """If this comparison expr is "a < b is c == d", yields the sequence + ("<", a, b), ("is", b, c), ("==", c, d) + """ + for i, operator in enumerate(self.operators): + yield operator, self.operands[i], self.operands[i + 1] + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_comparison_expr(self) + + +class SliceExpr(Expression): + """Slice expression (e.g. 'x:y', 'x:', '::2' or ':'). + + This is only valid as index in index expressions. + """ + + __slots__ = ("begin_index", "end_index", "stride") + + __match_args__ = ("begin_index", "end_index", "stride") + + begin_index: Expression | None + end_index: Expression | None + stride: Expression | None + + def __init__( + self, + begin_index: Expression | None, + end_index: Expression | None, + stride: Expression | None, + ) -> None: + super().__init__() + self.begin_index = begin_index + self.end_index = end_index + self.stride = stride + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_slice_expr(self) + + +class CastExpr(Expression): + """Cast expression cast(type, expr).""" + + __slots__ = ("expr", "type") + + __match_args__ = ("expr", "type") + + expr: Expression + type: mypy.types.Type + + def __init__(self, expr: Expression, typ: mypy.types.Type) -> None: + super().__init__() + self.expr = expr + self.type = typ + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_cast_expr(self) + + +class TypeFormExpr(Expression): + """TypeForm(type) expression.""" + + __slots__ = ("type",) + + __match_args__ = ("type",) + + type: mypy.types.Type + + def __init__(self, typ: mypy.types.Type) -> None: + super().__init__() + self.type = typ + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_type_form_expr(self) + + +class AssertTypeExpr(Expression): + """Represents a typing.assert_type(expr, type) call.""" + + __slots__ = ("expr", "type") + + __match_args__ = ("expr", "type") + + expr: Expression + type: mypy.types.Type + + def __init__(self, expr: Expression, typ: mypy.types.Type) -> None: + super().__init__() + self.expr = expr + self.type = typ + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_assert_type_expr(self) + + +class RevealExpr(Expression): + """Reveal type expression reveal_type(expr) or reveal_locals() expression.""" + + __slots__ = ("expr", "kind", "local_nodes", "is_imported") + + __match_args__ = ("expr", "kind", "local_nodes", "is_imported") + + expr: Expression | None + kind: int + local_nodes: list[Var] | None + + def __init__( + self, + kind: int, + expr: Expression | None = None, + local_nodes: list[Var] | None = None, + is_imported: bool = False, + ) -> None: + super().__init__() + self.expr = expr + self.kind = kind + self.local_nodes = local_nodes + self.is_imported = is_imported + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_reveal_expr(self) + + +class SuperExpr(Expression): + """Expression super().name""" + + __slots__ = ("name", "info", "call") + + __match_args__ = ("name", "call", "info") + + name: str + info: TypeInfo | None # Type that contains this super expression + call: CallExpr # The expression super(...) + + def __init__(self, name: str, call: CallExpr) -> None: + super().__init__() + self.name = name + self.call = call + self.info = None + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_super_expr(self) + + +class LambdaExpr(FuncItem, Expression): + """Lambda expression""" + + __match_args__ = ("arguments", "arg_names", "arg_kinds", "body") + + @property + def name(self) -> str: + return LAMBDA_NAME + + def expr(self) -> Expression: + """Return the expression (the body) of the lambda.""" + ret = self.body.body[-1] + assert isinstance(ret, ReturnStmt) + expr = ret.expr + assert expr is not None # lambda can't have empty body + return expr + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_lambda_expr(self) + + def is_dynamic(self) -> bool: + return False + + +class ListExpr(Expression): + """List literal expression [...].""" + + __slots__ = ("items",) + + __match_args__ = ("items",) + + items: list[Expression] + + def __init__(self, items: list[Expression]) -> None: + super().__init__() + self.items = items + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_list_expr(self) + + +class DictExpr(Expression): + """Dictionary literal expression {key: value, ...}.""" + + __slots__ = ("items",) + + __match_args__ = ("items",) + + items: list[tuple[Expression | None, Expression]] + + def __init__(self, items: list[tuple[Expression | None, Expression]]) -> None: + super().__init__() + self.items = items + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_dict_expr(self) + + +class TemplateStrExpr(Expression): + """Template string expression t'...'.""" + + __slots__ = ("items",) + __match_args__ = ("items",) + + # Each item is either: + # - a StrExpr (literal string segment), or + # - a tuple (value_expr, source_text, conversion, format_spec_expr) + # where conversion is str | None ("r", "s", "a", or None) + # and format_spec_expr is Expression | None + items: list[Expression | tuple[Expression, str, str | None, Expression | None]] + + def __init__( + self, items: list[Expression | tuple[Expression, str, str | None, Expression | None]] + ) -> None: + super().__init__() + self.items = items + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_template_str_expr(self) + + +class TupleExpr(Expression): + """Tuple literal expression (..., ...) + + Also lvalue sequences (..., ...) and [..., ...]""" + + __slots__ = ("items",) + + __match_args__ = ("items",) + + items: list[Expression] + + def __init__(self, items: list[Expression]) -> None: + super().__init__() + self.items = items + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_tuple_expr(self) + + +class SetExpr(Expression): + """Set literal expression {value, ...}.""" + + __slots__ = ("items",) + + __match_args__ = ("items",) + + items: list[Expression] + + def __init__(self, items: list[Expression]) -> None: + super().__init__() + self.items = items + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_set_expr(self) + + +class GeneratorExpr(Expression): + """Generator expression ... for ... in ... [ for ... in ... ] [ if ... ].""" + + __slots__ = ("left_expr", "sequences", "condlists", "is_async", "indices") + + __match_args__ = ("left_expr", "indices", "sequences", "condlists") + + left_expr: Expression + sequences: list[Expression] + condlists: list[list[Expression]] + is_async: list[bool] + indices: list[Lvalue] + + def __init__( + self, + left_expr: Expression, + indices: list[Lvalue], + sequences: list[Expression], + condlists: list[list[Expression]], + is_async: list[bool], + ) -> None: + super().__init__() + self.left_expr = left_expr + self.sequences = sequences + self.condlists = condlists + self.indices = indices + self.is_async = is_async + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_generator_expr(self) + + +class ListComprehension(Expression): + """List comprehension (e.g. [x + 1 for x in a])""" + + __slots__ = ("generator",) + + __match_args__ = ("generator",) + + generator: GeneratorExpr + + def __init__(self, generator: GeneratorExpr) -> None: + super().__init__() + self.generator = generator + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_list_comprehension(self) + + +class SetComprehension(Expression): + """Set comprehension (e.g. {x + 1 for x in a})""" + + __slots__ = ("generator",) + + __match_args__ = ("generator",) + + generator: GeneratorExpr + + def __init__(self, generator: GeneratorExpr) -> None: + super().__init__() + self.generator = generator + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_set_comprehension(self) + + +class DictionaryComprehension(Expression): + """Dictionary comprehension (e.g. {k: v for k, v in a}""" + + __slots__ = ("key", "value", "sequences", "condlists", "is_async", "indices") + + __match_args__ = ("key", "value", "indices", "sequences", "condlists") + + key: Expression + value: Expression + sequences: list[Expression] + condlists: list[list[Expression]] + is_async: list[bool] + indices: list[Lvalue] + + def __init__( + self, + key: Expression, + value: Expression, + indices: list[Lvalue], + sequences: list[Expression], + condlists: list[list[Expression]], + is_async: list[bool], + ) -> None: + super().__init__() + self.key = key + self.value = value + self.sequences = sequences + self.condlists = condlists + self.indices = indices + self.is_async = is_async + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_dictionary_comprehension(self) + + +class ConditionalExpr(Expression): + """Conditional expression (e.g. x if y else z)""" + + __slots__ = ("cond", "if_expr", "else_expr") + + __match_args__ = ("if_expr", "cond", "else_expr") + + cond: Expression + if_expr: Expression + else_expr: Expression + + def __init__(self, cond: Expression, if_expr: Expression, else_expr: Expression) -> None: + super().__init__() + self.cond = cond + self.if_expr = if_expr + self.else_expr = else_expr + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_conditional_expr(self) + + +class TypeApplication(Expression): + """Type application expr[type, ...]""" + + __slots__ = ("expr", "types") + + __match_args__ = ("expr", "types") + + expr: Expression + types: list[mypy.types.Type] + + def __init__(self, expr: Expression, types: list[mypy.types.Type]) -> None: + super().__init__() + self.expr = expr + self.types = types + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_type_application(self) + + +# Variance of a type variable. For example, T in the definition of +# List[T] is invariant, so List[int] is not a subtype of List[object], +# and also List[object] is not a subtype of List[int]. +# +# The T in Iterable[T] is covariant, so Iterable[int] is a subtype of +# Iterable[object], but not vice versa. +# +# If T is contravariant in Foo[T], Foo[object] is a subtype of +# Foo[int], but not vice versa. +INVARIANT: Final = 0 +COVARIANT: Final = 1 +CONTRAVARIANT: Final = 2 +VARIANCE_NOT_READY: Final = 3 # Variance hasn't been inferred (using Python 3.12 syntax) + + +class TypeVarLikeExpr(SymbolNode, Expression): + """Base class for TypeVarExpr, ParamSpecExpr and TypeVarTupleExpr. + + Note that they are constructed by the semantic analyzer. + """ + + __slots__ = ("_name", "_fullname", "upper_bound", "default", "variance", "is_new_style") + + _name: str + _fullname: str + # Upper bound: only subtypes of upper_bound are valid as values. By default + # this is 'object', meaning no restriction. + upper_bound: mypy.types.Type + # Default: used to resolve the TypeVar if the default is not explicitly given. + # By default this is 'AnyType(TypeOfAny.from_omitted_generics)'. See PEP 696. + default: mypy.types.Type + # Variance of the type variable. Invariant is the default. + # TypeVar(..., covariant=True) defines a covariant type variable. + # TypeVar(..., contravariant=True) defines a contravariant type + # variable. + variance: int + + def __init__( + self, + name: str, + fullname: str, + upper_bound: mypy.types.Type, + default: mypy.types.Type, + variance: int = INVARIANT, + is_new_style: bool = False, + line: int = -1, + ) -> None: + super().__init__(line=line) + self._name = name + self._fullname = fullname + self.upper_bound = upper_bound + self.default = default + self.variance = variance + self.is_new_style = is_new_style + + @property + def name(self) -> str: + return self._name + + @property + def fullname(self) -> str: + return self._fullname + + +# All types that are both SymbolNodes and Expressions. +# Use when common children of them are needed. +SYMBOL_NODE_EXPRESSION_TYPES: Final = (TypeVarLikeExpr,) + + +class TypeVarExpr(TypeVarLikeExpr): + """Type variable expression TypeVar(...). + + This is also used to represent type variables in symbol tables. + + A type variable is not valid as a type unless bound in a TypeVarLikeScope. + That happens within: + + 1. a generic class that uses the type variable as a type argument or + 2. a generic function that refers to the type variable in its signature. + """ + + __slots__ = ("values",) + + __match_args__ = ("name", "values", "upper_bound", "default") + + # Value restriction: only types in the list are valid as values. If the + # list is empty, there is no restriction. + values: list[mypy.types.Type] + + def __init__( + self, + name: str, + fullname: str, + values: list[mypy.types.Type], + upper_bound: mypy.types.Type, + default: mypy.types.Type, + variance: int = INVARIANT, + is_new_style: bool = False, + line: int = -1, + ) -> None: + super().__init__(name, fullname, upper_bound, default, variance, is_new_style, line=line) + self.values = values + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_type_var_expr(self) + + def serialize(self) -> JsonDict: + return { + ".class": "TypeVarExpr", + "name": self._name, + "fullname": self._fullname, + "values": [t.serialize() for t in self.values], + "upper_bound": self.upper_bound.serialize(), + "default": self.default.serialize(), + "variance": self.variance, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeVarExpr: + assert data[".class"] == "TypeVarExpr" + return TypeVarExpr( + data["name"], + data["fullname"], + [mypy.types.deserialize_type(v) for v in data["values"]], + mypy.types.deserialize_type(data["upper_bound"]), + mypy.types.deserialize_type(data["default"]), + data["variance"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_VAR_EXPR) + write_str(data, self._name) + write_str(data, self._fullname) + mypy.types.write_type_list(data, self.values) + self.upper_bound.write(data) + self.default.write(data) + write_int(data, self.variance) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeVarExpr: + ret = TypeVarExpr( + read_str(data), + read_str(data), + mypy.types.read_type_list(data), + mypy.types.read_type(data), + mypy.types.read_type(data), + read_int(data), + ) + assert read_tag(data) == END_TAG + return ret + + +class ParamSpecExpr(TypeVarLikeExpr): + __slots__ = () + + __match_args__ = ("name", "upper_bound", "default") + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_paramspec_expr(self) + + def serialize(self) -> JsonDict: + return { + ".class": "ParamSpecExpr", + "name": self._name, + "fullname": self._fullname, + "upper_bound": self.upper_bound.serialize(), + "default": self.default.serialize(), + "variance": self.variance, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> ParamSpecExpr: + assert data[".class"] == "ParamSpecExpr" + return ParamSpecExpr( + data["name"], + data["fullname"], + mypy.types.deserialize_type(data["upper_bound"]), + mypy.types.deserialize_type(data["default"]), + data["variance"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, PARAM_SPEC_EXPR) + write_str(data, self._name) + write_str(data, self._fullname) + self.upper_bound.write(data) + self.default.write(data) + write_int(data, self.variance) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> ParamSpecExpr: + ret = ParamSpecExpr( + read_str(data), + read_str(data), + mypy.types.read_type(data), + mypy.types.read_type(data), + read_int(data), + ) + assert read_tag(data) == END_TAG + return ret + + +class TypeVarTupleExpr(TypeVarLikeExpr): + """Type variable tuple expression TypeVarTuple(...).""" + + __slots__ = "tuple_fallback" + + tuple_fallback: mypy.types.Instance + + __match_args__ = ("name", "upper_bound", "default") + + def __init__( + self, + name: str, + fullname: str, + upper_bound: mypy.types.Type, + tuple_fallback: mypy.types.Instance, + default: mypy.types.Type, + variance: int = INVARIANT, + is_new_style: bool = False, + line: int = -1, + ) -> None: + super().__init__(name, fullname, upper_bound, default, variance, is_new_style, line=line) + self.tuple_fallback = tuple_fallback + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_type_var_tuple_expr(self) + + def serialize(self) -> JsonDict: + return { + ".class": "TypeVarTupleExpr", + "name": self._name, + "fullname": self._fullname, + "upper_bound": self.upper_bound.serialize(), + "tuple_fallback": self.tuple_fallback.serialize(), + "default": self.default.serialize(), + "variance": self.variance, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeVarTupleExpr: + assert data[".class"] == "TypeVarTupleExpr" + return TypeVarTupleExpr( + data["name"], + data["fullname"], + mypy.types.deserialize_type(data["upper_bound"]), + mypy.types.Instance.deserialize(data["tuple_fallback"]), + mypy.types.deserialize_type(data["default"]), + data["variance"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_VAR_TUPLE_EXPR) + self.tuple_fallback.write(data) + write_str(data, self._name) + write_str(data, self._fullname) + self.upper_bound.write(data) + self.default.write(data) + write_int(data, self.variance) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeVarTupleExpr: + assert read_tag(data) == mypy.types.INSTANCE + fallback = mypy.types.Instance.read(data) + ret = TypeVarTupleExpr( + read_str(data), + read_str(data), + mypy.types.read_type(data), + fallback, + mypy.types.read_type(data), + read_int(data), + ) + assert read_tag(data) == END_TAG + return ret + + +class TypeAliasExpr(Expression): + """Type alias expression (rvalue).""" + + __slots__ = ("node",) + + __match_args__ = ("node",) + + node: TypeAlias + + def __init__(self, node: TypeAlias) -> None: + super().__init__() + self.node = node + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_type_alias_expr(self) + + +class NamedTupleExpr(Expression): + """Named tuple expression namedtuple(...) or NamedTuple(...).""" + + __slots__ = ("info", "is_typed") + + __match_args__ = ("info",) + + # The class representation of this named tuple (its tuple_type attribute contains + # the tuple item types) + info: TypeInfo + is_typed: bool # whether this class was created with typing(_extensions).NamedTuple + + def __init__(self, info: TypeInfo, is_typed: bool = False) -> None: + super().__init__() + self.info = info + self.is_typed = is_typed + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_namedtuple_expr(self) + + +class TypedDictExpr(Expression): + """Typed dict expression TypedDict(...).""" + + __slots__ = ("info",) + + __match_args__ = ("info",) + + # The class representation of this typed dict + info: TypeInfo + + def __init__(self, info: TypeInfo) -> None: + super().__init__() + self.info = info + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_typeddict_expr(self) + + +class EnumCallExpr(Expression): + """Named tuple expression Enum('name', 'val1 val2 ...').""" + + __slots__ = ("info", "items", "values") + + __match_args__ = ("info", "items", "values") + + # The class representation of this enumerated type + info: TypeInfo + # The item names (for debugging) + items: list[str] + values: list[Expression | None] + + def __init__(self, info: TypeInfo, items: list[str], values: list[Expression | None]) -> None: + super().__init__() + self.info = info + self.items = items + self.values = values + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_enum_call_expr(self) + + +class PromoteExpr(Expression): + """Ducktype class decorator expression _promote(...).""" + + __slots__ = ("type",) + + type: mypy.types.ProperType + + def __init__(self, type: mypy.types.ProperType) -> None: + super().__init__() + self.type = type + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit__promote_expr(self) + + +class NewTypeExpr(Expression): + """NewType expression NewType(...).""" + + __slots__ = ("name", "old_type", "info") + + __match_args__ = ("name", "old_type", "info") + + name: str + # The base type (the second argument to NewType) + old_type: mypy.types.Type | None + # The synthesized class representing the new type (inherits old_type) + info: TypeInfo | None + + def __init__( + self, name: str, old_type: mypy.types.Type | None, line: int, column: int + ) -> None: + super().__init__(line=line, column=column) + self.name = name + self.old_type = old_type + self.info = None + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_newtype_expr(self) + + +class AwaitExpr(Expression): + """Await expression (await ...).""" + + __slots__ = ("expr",) + + __match_args__ = ("expr",) + + expr: Expression + + def __init__(self, expr: Expression) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_await_expr(self) + + +# Constants + + +class TempNode(Expression): + """Temporary dummy node used during type checking. + + This node is not present in the original program; it is just an artifact + of the type checker implementation. It only represents an opaque node with + some fixed type. + """ + + __slots__ = ("type", "no_rhs") + + type: mypy.types.Type + # Is this TempNode used to indicate absence of a right hand side in an annotated assignment? + # (e.g. for 'x: int' the rvalue is TempNode(AnyType(TypeOfAny.special_form), no_rhs=True)) + no_rhs: bool + + def __init__( + self, typ: mypy.types.Type, no_rhs: bool = False, *, context: Context | None = None + ) -> None: + """Construct a dummy node; optionally borrow line/column from context object.""" + super().__init__() + self.type = typ + self.no_rhs = no_rhs + if context is not None: + self.line = context.line + self.column = context.column + + def __repr__(self) -> str: + return "TempNode:%d(%s)" % (self.line, str(self.type)) + + def accept(self, visitor: ExpressionVisitor[T]) -> T: + return visitor.visit_temp_node(self) + + +# Special attributes not collected as protocol members by Python 3.12 +# See typing._SPECIAL_NAMES +EXCLUDED_PROTOCOL_ATTRIBUTES: Final = frozenset( + { + "__abstractmethods__", + "__annotations__", + "__dict__", + "__doc__", + "__init__", + "__module__", + "__new__", + "__slots__", + "__subclasshook__", + "__weakref__", + "__class_getitem__", # Since Python 3.9 + } +) + +# Attributes that can optionally be defined in the body of a subclass of +# enum.Enum but are removed from the class __dict__ by EnumMeta. +EXCLUDED_ENUM_ATTRIBUTES: Final = frozenset({"_ignore_", "_order_", "__order__"}) + + +class TypeInfo(SymbolNode): + """The type structure of a single class. + + Each TypeInfo corresponds one-to-one to a ClassDef, which + represents the AST of the class. + + In type-theory terms, this is a "type constructor", and if the + class is generic then it will be a type constructor of higher kind. + Where the class is used in an actual type, it's in the form of an + Instance, which amounts to a type application of the tycon to + the appropriate number of arguments. + """ + + __slots__ = ( + "_fullname", + "module_name", + "defn", + "mro", + "_mro_refs", + "bad_mro", + "is_final", + "is_disjoint_base", + "declared_metaclass", + "metaclass_type", + "names", + "is_abstract", + "is_protocol", + "runtime_protocol", + "abstract_attributes", + "deletable_attributes", + "slots", + "assuming", + "assuming_proper", + "inferring", + "is_enum", + "fallback_to_any", + "meta_fallback_to_any", + "type_vars", + "has_param_spec_type", + "bases", + "_promote", + "tuple_type", + "special_alias", + "is_named_tuple", + "typeddict_type", + "is_newtype", + "is_intersection", + "metadata", + "alt_promote", + "has_type_var_tuple_type", + "type_var_tuple_prefix", + "type_var_tuple_suffix", + "self_type", + "dataclass_transform_spec", + "is_type_check_only", + "deprecated", + "type_object_type", + ) + + _fullname: str # Fully qualified name + # Fully qualified name for the module this type was defined in. This + # information is also in the fullname, but is harder to extract in the + # case of nested class definitions. + module_name: str + defn: ClassDef # Corresponding ClassDef + # Method Resolution Order: the order of looking up attributes. The first + # value always to refers to this class. + mro: list[TypeInfo] + # Used to stash the names of the mro classes temporarily between + # deserialization and fixup. See deserialize() for why. + _mro_refs: list[str] | None + bad_mro: bool # Could not construct full MRO + is_final: bool + is_disjoint_base: bool + + declared_metaclass: mypy.types.Instance | None + metaclass_type: mypy.types.Instance | None + + names: SymbolTable # Names defined directly in this type + is_abstract: bool # Does the class have any abstract attributes? + is_protocol: bool # Is this a protocol class? + runtime_protocol: bool # Does this protocol support isinstance checks? + # List of names of abstract attributes together with their abstract status. + # The abstract status must be one of `NOT_ABSTRACT`, `IS_ABSTRACT`, `IMPLICITLY_ABSTRACT`. + abstract_attributes: list[tuple[str, int]] + deletable_attributes: list[str] # Used by mypyc only + # Does this type have concrete `__slots__` defined? + # If class does not have `__slots__` defined then it is `None`, + # if it has empty `__slots__` then it is an empty set. + slots: set[str] | None + + # The attributes 'assuming' and 'assuming_proper' represent structural subtype matrices. + # + # In languages with structural subtyping, one can keep a global subtype matrix like this: + # . A B C . + # A 1 0 0 + # B 1 1 1 + # C 1 0 1 + # . + # where 1 indicates that the type in corresponding row is a subtype of the type + # in corresponding column. This matrix typically starts filled with all 1's and + # a typechecker tries to "disprove" every subtyping relation using atomic (or nominal) types. + # However, we don't want to keep this huge global state. Instead, we keep the subtype + # information in the form of list of pairs (subtype, supertype) shared by all Instances + # with given supertype's TypeInfo. When we enter a subtype check we push a pair in this list + # thus assuming that we started with 1 in corresponding matrix element. Such algorithm allows + # to treat recursive and mutually recursive protocols and other kinds of complex situations. + # + # If concurrent/parallel type checking will be added in future, + # then there should be one matrix per thread/process to avoid false negatives + # during the type checking phase. + assuming: list[tuple[mypy.types.Instance, mypy.types.Instance]] + assuming_proper: list[tuple[mypy.types.Instance, mypy.types.Instance]] + # Ditto for temporary 'inferring' stack of recursive constraint inference. + # It contains Instances of protocol types that appeared as an argument to + # constraints.infer_constraints(). We need 'inferring' to avoid infinite recursion for + # recursive and mutually recursive protocols. + # + # We make 'assuming' and 'inferring' attributes here instead of passing they as kwargs, + # since this would require to pass them in many dozens of calls. In particular, + # there is a dependency infer_constraint -> is_subtype -> is_callable_subtype -> + # -> infer_constraints. + inferring: list[mypy.types.Instance] + # 'inferring' and 'assuming' can't be made sets, since we need to use + # is_same_type to correctly treat unions. + + # Classes inheriting from Enum shadow their true members with a __getattr__, so we + # have to treat them as a special case. + is_enum: bool + # If true, any unknown attributes should have type 'Any' instead + # of generating a type error. This would be true if there is a + # base class with type 'Any', but other use cases may be + # possible. This is similar to having __getattr__ that returns Any + # (and __setattr__), but without the __getattr__ method. + fallback_to_any: bool + + # Same as above but for cases where metaclass has type Any. This will suppress + # all attribute errors only for *class object* access. + meta_fallback_to_any: bool + + # Information related to type annotations. + + # Generic type variable names (full names) + type_vars: list[str] + + # Whether this class has a ParamSpec type variable + has_param_spec_type: bool + + # Direct base classes. + bases: list[mypy.types.Instance] + + # Another type which this type will be treated as a subtype of, + # even though it's not a subclass in Python. The non-standard + # `@_promote` decorator introduces this, and there are also + # several builtin examples, in particular `int` -> `float`. + _promote: list[mypy.types.ProperType] + + # This is used for promoting native integer types such as 'i64' to + # 'int'. (_promote is used for the other direction.) This only + # supports one-step promotions (e.g., i64 -> int, not + # i64 -> int -> float, and this isn't used to promote in joins. + # + # This results in some unintuitive results, such as that even + # though i64 is compatible with int and int is compatible with + # float, i64 is *not* compatible with float. + alt_promote: mypy.types.Instance | None + + # Representation of a Tuple[...] base class, if the class has any + # (e.g., for named tuples). If this is not None, the actual Type + # object used for this class is not an Instance but a TupleType; + # the corresponding Instance is set as the fallback type of the + # tuple type. + tuple_type: mypy.types.TupleType | None + + # Is this a named tuple type? + is_named_tuple: bool + + # If this class is defined by the TypedDict type constructor, + # then this is not None. + typeddict_type: mypy.types.TypedDictType | None + + # Is this a newtype type? + is_newtype: bool + + # Is this a synthesized intersection type? + is_intersection: bool + + # This is a dictionary that will be serialized and un-serialized as is. + # It is useful for plugins to add their data to save in the cache. + metadata: dict[str, JsonDict] + + # Store type alias representing this type (for named tuples and TypedDicts). + # Although definitions of these types are stored in symbol tables as TypeInfo, + # when a type analyzer will find them, it should construct a TupleType, or + # a TypedDict type. However, we can't use the plain types, since if the definition + # is recursive, this will create an actual recursive structure of types (i.e. as + # internal Python objects) causing infinite recursions everywhere during type checking. + # To overcome this, we create a TypeAlias node, that will point to these types. + # We store this node in the `special_alias` attribute, because it must be the same node + # in case we are doing multiple semantic analysis passes. + special_alias: TypeAlias | None + + # Shared type variable for typing.Self in this class (if used, otherwise None). + self_type: mypy.types.TypeVarType | None + + # Added if the corresponding class is directly decorated with `typing.dataclass_transform` + dataclass_transform_spec: DataclassTransformSpec | None + + # Is set to `True` when class is decorated with `@typing.type_check_only` + is_type_check_only: bool + + # The type's deprecation message (in case it is deprecated) + deprecated: str | None + + # Cached value of class constructor type, i.e. the type of class object when it + # appears in runtime context. + type_object_type: mypy.types.FunctionLike | None + + FLAGS: Final = [ + "is_abstract", + "is_enum", + "fallback_to_any", + "meta_fallback_to_any", + "is_named_tuple", + "is_newtype", + "is_protocol", + "runtime_protocol", + "is_final", + "is_disjoint_base", + "is_intersection", + ] + + def __init__(self, names: SymbolTable, defn: ClassDef, module_name: str) -> None: + """Initialize a TypeInfo.""" + super().__init__() + self._fullname = defn.fullname + self.names = names + self.defn = defn + self.module_name = module_name + self.type_vars = [] + self.has_param_spec_type = False + self.has_type_var_tuple_type = False + self.bases = [] + self.mro = [] + self._mro_refs = None + self.bad_mro = False + self.declared_metaclass = None + self.metaclass_type = None + self.is_abstract = False + self.abstract_attributes = [] + self.deletable_attributes = [] + self.slots = None + self.assuming = [] + self.assuming_proper = [] + self.inferring = [] + self.is_protocol = False + self.runtime_protocol = False + self.type_var_tuple_prefix: int | None = None + self.type_var_tuple_suffix: int | None = None + self.add_type_vars() + self.is_final = False + self.is_disjoint_base = False + self.is_enum = False + self.fallback_to_any = False + self.meta_fallback_to_any = False + self._promote = [] + self.alt_promote = None + self.tuple_type = None + self.special_alias = None + self.is_named_tuple = False + self.typeddict_type = None + self.is_newtype = False + self.is_intersection = False + self.metadata = {} + self.self_type = None + self.dataclass_transform_spec = None + self.is_type_check_only = False + self.deprecated = None + self.type_object_type = None + + def add_type_vars(self) -> None: + self.has_type_var_tuple_type = False + if self.defn.type_vars: + for i, vd in enumerate(self.defn.type_vars): + if isinstance(vd, mypy.types.ParamSpecType): + self.has_param_spec_type = True + if isinstance(vd, mypy.types.TypeVarTupleType): + assert not self.has_type_var_tuple_type + self.has_type_var_tuple_type = True + self.type_var_tuple_prefix = i + self.type_var_tuple_suffix = len(self.defn.type_vars) - i - 1 + self.type_vars.append(vd.name) + + @property + def name(self) -> str: + """Short name.""" + return self.defn.name + + @property + def fullname(self) -> str: + return self._fullname + + def is_generic(self) -> bool: + """Is the type generic (i.e. does it have type variables)?""" + return len(self.type_vars) > 0 + + def get(self, name: str) -> SymbolTableNode | None: + for cls in self.mro: + n = cls.names.get(name) + if n: + return n + return None + + def get_containing_type_info(self, name: str) -> TypeInfo | None: + for cls in self.mro: + if name in cls.names: + return cls + return None + + @property + def protocol_members(self) -> list[str]: + # Protocol members are names of all attributes/methods defined in a protocol + # and in all its supertypes (except for 'object'). + members: set[str] = set() + assert self.mro, "This property can be only accessed after MRO is (re-)calculated" + for base in self.mro[:-1]: # we skip "object" since everyone implements it + if base.is_protocol: + for name, node in base.names.items(): + if isinstance(node.node, (TypeAlias, TypeVarExpr, MypyFile)): + # These are auxiliary definitions (and type aliases are prohibited). + continue + if name in EXCLUDED_PROTOCOL_ATTRIBUTES: + continue + members.add(name) + return sorted(members) + + @property + def enum_members(self) -> list[str]: + # TODO: cache the results? + members = [] + for name, sym in self.names.items(): + # Case 1: + # + # class MyEnum(Enum): + # @member + # def some(self): ... + if isinstance(sym.node, Decorator): + if any( + dec.fullname == "enum.member" + for dec in sym.node.decorators + if isinstance(dec, RefExpr) + ): + members.append(name) + continue + # Case 2: + # + # class MyEnum(Enum): + # x = 1 + # + # Case 3: + # + # class MyEnum(Enum): + # class Other: ... + elif isinstance(sym.node, (Var, TypeInfo)): + if ( + # TODO: properly support ignored names from `_ignore_` + name in EXCLUDED_ENUM_ATTRIBUTES + or is_sunder(name) + or name.startswith("__") # dunder and private + ): + continue # name is excluded + + if isinstance(sym.node, Var): + if not sym.node.has_explicit_value: + continue # unannotated value not a member + + typ = mypy.types.get_proper_type(sym.node.type) + if ( + isinstance(typ, mypy.types.FunctionLike) and not typ.is_type_obj() + ) or ( # explicit `@member` is required + isinstance(typ, mypy.types.Instance) + and typ.type.fullname == "enum.nonmember" + ): + continue # name is not a member + + members.append(name) + return members + + def __getitem__(self, name: str) -> SymbolTableNode: + n = self.get(name) + if n: + return n + else: + raise KeyError(name) + + def __repr__(self) -> str: + return f"" + + def __bool__(self) -> bool: + # We defined this here instead of just overriding it in + # FakeInfo so that mypyc can generate a direct call instead of + # using the generic bool handling. + return not isinstance(self, FakeInfo) + + def has_readable_member(self, name: str) -> bool: + return self.get(name) is not None + + def get_method(self, name: str) -> FuncBase | Decorator | None: + for cls in self.mro: + if name in cls.names: + node = cls.names[name].node + elif possible_redefinitions := sorted( + [n for n in cls.names.keys() if n.startswith(f"{name}-redefinition")] + ): + node = cls.names[possible_redefinitions[-1]].node + else: + continue + if isinstance(node, SYMBOL_FUNCBASE_TYPES): + return node + elif isinstance(node, Decorator): # Two `if`s make `mypyc` happy + return node + else: + return None + return None + + def calculate_metaclass_type(self) -> mypy.types.Instance | None: + declared = self.declared_metaclass + if declared is not None and not declared.type.has_base("builtins.type"): + return declared + if self._fullname == "builtins.type": + return mypy.types.Instance(self, []) + + winner = declared + for super_class in self.mro[1:]: + super_meta = super_class.declared_metaclass + if super_meta is None or super_meta.type is None: + continue + if winner is None: + winner = super_meta + continue + if winner.type.has_base(super_meta.type.fullname): + continue + if super_meta.type.has_base(winner.type.fullname): + winner = super_meta + continue + # metaclass conflict + winner = None + break + + return winner + + def explain_metaclass_conflict(self) -> str | None: + # Compare to logic in calculate_metaclass_type + declared = self.declared_metaclass + if declared is not None and not declared.type.has_base("builtins.type"): + return None + if self._fullname == "builtins.type": + return None + + winner = declared + if declared is None: + resolution_steps = [] + else: + resolution_steps = [f'"{declared.type.fullname}" (metaclass of "{self.fullname}")'] + for super_class in self.mro[1:]: + super_meta = super_class.declared_metaclass + if super_meta is None or super_meta.type is None: + continue + if winner is None: + winner = super_meta + resolution_steps.append( + f'"{winner.type.fullname}" (metaclass of "{super_class.fullname}")' + ) + continue + if winner.type.has_base(super_meta.type.fullname): + continue + if super_meta.type.has_base(winner.type.fullname): + winner = super_meta + resolution_steps.append( + f'"{winner.type.fullname}" (metaclass of "{super_class.fullname}")' + ) + continue + # metaclass conflict + conflict = f'"{super_meta.type.fullname}" (metaclass of "{super_class.fullname}")' + return f"{' > '.join(resolution_steps)} conflicts with {conflict}" + + return None + + def is_metaclass(self, *, precise: bool = False) -> bool: + return ( + self.has_base("builtins.type") + or self.fullname == "abc.ABCMeta" + or (self.fallback_to_any and not precise) + ) + + def has_base(self, fullname: str) -> bool: + """Return True if type has a base type with the specified name. + + This can be either via extension or via implementation. + """ + for cls in self.mro: + if cls.fullname == fullname: + return True + return False + + def direct_base_classes(self) -> list[TypeInfo]: + """Return a direct base classes. + + Omit base classes of other base classes. + """ + return [base.type for base in self.bases] + + def update_tuple_type(self, typ: mypy.types.TupleType) -> None: + """Update tuple_type and special_alias as needed.""" + self.tuple_type = typ + alias = TypeAlias.from_tuple_type(self) + if not self.special_alias: + self.special_alias = alias + else: + self.special_alias.target = alias.target + # Invalidate recursive status cache in case it was previously set. + self.special_alias._is_recursive = None + + def update_typeddict_type(self, typ: mypy.types.TypedDictType) -> None: + """Update typeddict_type and special_alias as needed.""" + self.typeddict_type = typ + alias = TypeAlias.from_typeddict_type(self) + if not self.special_alias: + self.special_alias = alias + else: + self.special_alias.target = alias.target + # Invalidate recursive status cache in case it was previously set. + self.special_alias._is_recursive = None + + def __str__(self) -> str: + """Return a string representation of the type. + + This includes the most important information about the type. + """ + options = Options() + return self.dump( + str_conv=mypy.strconv.StrConv(options=options), + type_str_conv=mypy.types.TypeStrVisitor(options=options), + ) + + def dump( + self, str_conv: mypy.strconv.StrConv, type_str_conv: mypy.types.TypeStrVisitor + ) -> str: + """Return a string dump of the contents of the TypeInfo.""" + + base: str = "" + + def type_str(typ: mypy.types.Type) -> str: + return typ.accept(type_str_conv) + + head = "TypeInfo" + str_conv.format_id(self) + if self.bases: + base = f"Bases({', '.join(type_str(base) for base in self.bases)})" + mro = "Mro({})".format( + ", ".join(item.fullname + str_conv.format_id(item) for item in self.mro) + ) + names = [] + for name in sorted(self.names): + description = name + str_conv.format_id(self.names[name].node) + node = self.names[name].node + if isinstance(node, Var) and node.type: + description += f" ({type_str(node.type)})" + names.append(description) + items = [f"Name({self.fullname})", base, mro, ("Names", names)] + if self.declared_metaclass: + items.append(f"DeclaredMetaclass({type_str(self.declared_metaclass)})") + if self.metaclass_type: + items.append(f"MetaclassType({type_str(self.metaclass_type)})") + return mypy.strconv.dump_tagged(items, head, str_conv=str_conv) + + def serialize(self) -> JsonDict: + # NOTE: This is where all ClassDefs originate, so there shouldn't be duplicates. + data = { + ".class": "TypeInfo", + "module_name": self.module_name, + "fullname": self.fullname, + "names": self.names.serialize(self.fullname), + "defn": self.defn.serialize(), + "abstract_attributes": self.abstract_attributes, + "type_vars": self.type_vars, + "has_param_spec_type": self.has_param_spec_type, + "bases": [b.serialize() for b in self.bases], + "mro": [c.fullname for c in self.mro], + "_promote": [p.serialize() for p in self._promote], + "alt_promote": None if self.alt_promote is None else self.alt_promote.serialize(), + "declared_metaclass": ( + None if self.declared_metaclass is None else self.declared_metaclass.serialize() + ), + "metaclass_type": ( + None if self.metaclass_type is None else self.metaclass_type.serialize() + ), + "tuple_type": None if self.tuple_type is None else self.tuple_type.serialize(), + "typeddict_type": ( + None if self.typeddict_type is None else self.typeddict_type.serialize() + ), + "flags": get_flags(self, TypeInfo.FLAGS), + "metadata": self.metadata, + "slots": sorted(self.slots) if self.slots is not None else None, + "deletable_attributes": self.deletable_attributes, + "self_type": self.self_type.serialize() if self.self_type is not None else None, + "dataclass_transform_spec": ( + self.dataclass_transform_spec.serialize() + if self.dataclass_transform_spec is not None + else None + ), + "deprecated": self.deprecated, + } + return data + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeInfo: + names = SymbolTable.deserialize(data["names"]) + defn = ClassDef.deserialize(data["defn"]) + module_name = data["module_name"] + ti = TypeInfo(names, defn, module_name) + ti._fullname = data["fullname"] + ti.abstract_attributes = [(attr[0], attr[1]) for attr in data["abstract_attributes"]] + ti.type_vars = data["type_vars"] + ti.has_param_spec_type = data["has_param_spec_type"] + ti.bases = [mypy.types.Instance.deserialize(b) for b in data["bases"]] + _promote = [] + for p in data["_promote"]: + t = mypy.types.deserialize_type(p) + assert isinstance(t, mypy.types.ProperType) + _promote.append(t) + ti._promote = _promote + ti.alt_promote = ( + None + if data["alt_promote"] is None + else mypy.types.Instance.deserialize(data["alt_promote"]) + ) + ti.declared_metaclass = ( + None + if data["declared_metaclass"] is None + else mypy.types.Instance.deserialize(data["declared_metaclass"]) + ) + ti.metaclass_type = ( + None + if data["metaclass_type"] is None + else mypy.types.Instance.deserialize(data["metaclass_type"]) + ) + # NOTE: ti.mro will be set in the fixup phase based on these + # names. The reason we need to store the mro instead of just + # recomputing it from base classes has to do with a subtle + # point about fine-grained incremental: the cache files might + # not be loaded until after a class in the mro has changed its + # bases, which causes the mro to change. If we recomputed our + # mro, we would compute the *new* mro, which leaves us with no + # way to detect that the mro has changed! Thus we need to make + # sure to load the original mro so that once the class is + # rechecked, it can tell that the mro has changed. + ti._mro_refs = data["mro"] + ti.tuple_type = ( + None + if data["tuple_type"] is None + else mypy.types.TupleType.deserialize(data["tuple_type"]) + ) + ti.typeddict_type = ( + None + if data["typeddict_type"] is None + else mypy.types.TypedDictType.deserialize(data["typeddict_type"]) + ) + ti.metadata = data["metadata"] + ti.slots = set(data["slots"]) if data["slots"] is not None else None + ti.deletable_attributes = data["deletable_attributes"] + set_flags(ti, data["flags"]) + st = data["self_type"] + ti.self_type = mypy.types.TypeVarType.deserialize(st) if st is not None else None + if data.get("dataclass_transform_spec") is not None: + ti.dataclass_transform_spec = DataclassTransformSpec.deserialize( + data["dataclass_transform_spec"] + ) + ti.deprecated = data.get("deprecated") + return ti + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_INFO) + self.names.write(data, self.fullname) + self.defn.write(data) + write_str(data, self.module_name) + write_str(data, self.fullname) + write_str_list(data, [a for a, _ in self.abstract_attributes]) + write_int_list(data, [s for _, s in self.abstract_attributes]) + write_str_list(data, self.type_vars) + write_bool(data, self.has_param_spec_type) + mypy.types.write_type_list(data, self.bases) + write_str_list(data, [c.fullname for c in self.mro]) + mypy.types.write_type_list(data, self._promote) + mypy.types.write_type_opt(data, self.alt_promote) + mypy.types.write_type_opt(data, self.declared_metaclass) + mypy.types.write_type_opt(data, self.metaclass_type) + mypy.types.write_type_opt(data, self.tuple_type) + mypy.types.write_type_opt(data, self.typeddict_type) + write_flags( + data, + [ + self.is_abstract, + self.is_enum, + self.fallback_to_any, + self.meta_fallback_to_any, + self.is_named_tuple, + self.is_newtype, + self.is_protocol, + self.runtime_protocol, + self.is_final, + self.is_disjoint_base, + self.is_intersection, + ], + ) + write_json(data, self.metadata) + if self.slots is None: + write_tag(data, LITERAL_NONE) + else: + write_str_list(data, sorted(self.slots)) + write_str_list(data, self.deletable_attributes) + mypy.types.write_type_opt(data, self.self_type) + if self.dataclass_transform_spec is None: + write_tag(data, LITERAL_NONE) + else: + self.dataclass_transform_spec.write(data) + write_str_opt(data, self.deprecated) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeInfo: + names = SymbolTable.read(data) + assert read_tag(data) == CLASS_DEF + defn = ClassDef.read(data) + module_name = read_str(data) + ti = TypeInfo(names, defn, module_name) + ti._fullname = read_str(data) + attrs = read_str_list(data) + statuses = read_int_list(data) + ti.abstract_attributes = list(zip(attrs, statuses)) + ti.type_vars = read_str_list(data) + ti.has_param_spec_type = read_bool(data) + ti.bases = [] + assert read_tag(data) == LIST_GEN + for _ in range(read_int_bare(data)): + assert read_tag(data) == mypy.types.INSTANCE + ti.bases.append(mypy.types.Instance.read(data)) + # NOTE: ti.mro will be set in the fixup phase based on these + # names. The reason we need to store the mro instead of just + # recomputing it from base classes has to do with a subtle + # point about fine-grained incremental: the cache files might + # not be loaded until after a class in the mro has changed its + # bases, which causes the mro to change. If we recomputed our + # mro, we would compute the *new* mro, which leaves us with no + # way to detect that the mro has changed! Thus, we need to make + # sure to load the original mro so that once the class is + # rechecked, it can tell that the mro has changed. + ti._mro_refs = read_str_list(data) + ti._promote = cast(list[mypy.types.ProperType], mypy.types.read_type_list(data)) + if (tag := read_tag(data)) != LITERAL_NONE: + assert tag == mypy.types.INSTANCE + ti.alt_promote = mypy.types.Instance.read(data) + if (tag := read_tag(data)) != LITERAL_NONE: + assert tag == mypy.types.INSTANCE + ti.declared_metaclass = mypy.types.Instance.read(data) + if (tag := read_tag(data)) != LITERAL_NONE: + assert tag == mypy.types.INSTANCE + ti.metaclass_type = mypy.types.Instance.read(data) + if (tag := read_tag(data)) != LITERAL_NONE: + assert tag == mypy.types.TUPLE_TYPE + ti.tuple_type = mypy.types.TupleType.read(data) + if (tag := read_tag(data)) != LITERAL_NONE: + assert tag == mypy.types.TYPED_DICT_TYPE + ti.typeddict_type = mypy.types.TypedDictType.read(data) + ( + ti.is_abstract, + ti.is_enum, + ti.fallback_to_any, + ti.meta_fallback_to_any, + ti.is_named_tuple, + ti.is_newtype, + ti.is_protocol, + ti.runtime_protocol, + ti.is_final, + ti.is_disjoint_base, + ti.is_intersection, + ) = read_flags(data, num_flags=11) + ti.metadata = read_json(data) + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == LIST_STR + ti.slots = {read_str_bare(data) for _ in range(read_int_bare(data))} + ti.deletable_attributes = read_str_list(data) + if (tag := read_tag(data)) != LITERAL_NONE: + assert tag == mypy.types.TYPE_VAR_TYPE + ti.self_type = mypy.types.TypeVarType.read(data) + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == DT_SPEC + ti.dataclass_transform_spec = DataclassTransformSpec.read(data) + ti.deprecated = read_str_opt(data) + assert read_tag(data) == END_TAG + return ti + + +class FakeInfo(TypeInfo): + __slots__ = ("msg",) + + # types.py defines a single instance of this class, called types.NOT_READY. + # This instance is used as a temporary placeholder in the process of de-serialization + # of 'Instance' types. The de-serialization happens in two steps: In the first step, + # Instance.type is set to NOT_READY. In the second step (in fixup.py) it is replaced by + # an actual TypeInfo. If you see the assertion error below, then most probably something + # went wrong during the second step and an 'Instance' that raised this error was not fixed. + # Note: + # 'None' is not used as a dummy value for two reasons: + # 1. This will require around 80-100 asserts to make 'mypy --strict-optional mypy' + # pass cleanly. + # 2. If NOT_READY value is accidentally used somewhere, it will be obvious where the value + # is from, whereas a 'None' value could come from anywhere. + # + # Additionally, this serves as a more general-purpose placeholder + # for missing TypeInfos in a number of places where the excuses + # for not being Optional are a little weaker. + # + # TypeInfo defines a __bool__ method that returns False for FakeInfo + # so that it can be conveniently tested against in the same way that it + # would be if things were properly optional. + def __init__(self, msg: str) -> None: + self.msg = msg + + def __getattribute__(self, attr: str) -> type: + # Handle __class__ so that isinstance still works... + if attr == "__class__": + return object.__getattribute__(self, attr) # type: ignore[no-any-return] + raise AssertionError(object.__getattribute__(self, "msg")) + + +VAR_NO_INFO: Final[TypeInfo] = FakeInfo("Var is lacking info") +CLASSDEF_NO_INFO: Final[TypeInfo] = FakeInfo("ClassDef is lacking info") +FUNC_NO_INFO: Final[TypeInfo] = FakeInfo("FuncBase for non-methods lack info") +MISSING_FALLBACK: Final = FakeInfo("fallback can't be filled out until semanal") + + +class TypeAlias(SymbolNode): + """ + A symbol node representing a type alias. + + Type alias is a static concept, in contrast to variables with types + like Type[...]. Namely: + * type aliases + - can be used in type context (annotations) + - cannot be re-assigned + * variables with type Type[...] + - cannot be used in type context + - but can be re-assigned + + An alias can be defined only by an assignment to a name (not any other lvalues). + + Such assignment defines an alias by default. To define a variable, + an explicit Type[...] annotation is required. As an exception, + at non-global scope non-subscripted rvalue creates a variable even without + an annotation. This exception exists to accommodate the common use case of + class-valued attributes. See SemanticAnalyzerPass2.check_and_set_up_type_alias + for details. + + Aliases can be generic. We use bound type variables for generic aliases, similar + to classes. Essentially, type aliases work as macros that expand textually. + The definition and expansion rules are following: + + 1. An alias targeting a generic class without explicit variables act as + the given class (this doesn't apply to TypedDict, Tuple and Callable, which + are not proper classes but special type constructors): + + A = List + AA = List[Any] + + x: A # same as List[Any] + x: A[int] # same as List[int] + + x: AA # same as List[Any] + x: AA[int] # Error! + + C = Callable # Same as Callable[..., Any] + T = Tuple # Same as Tuple[Any, ...] + + 2. An alias using explicit type variables in its rvalue expects + replacements (type arguments) for these variables. If missing, they + are treated as Any, like for other generics: + + B = List[Tuple[T, T]] + + x: B # same as List[Tuple[Any, Any]] + x: B[int] # same as List[Tuple[int, int]] + + def f(x: B[T]) -> T: ... # without T, Any would be used here + + 3. An alias can be defined using another aliases. In the definition + rvalue the Any substitution doesn't happen for top level unsubscripted + generic classes: + + A = List + B = A # here A is expanded to List, _not_ List[Any], + # to match the Python runtime behaviour + x: B[int] # same as List[int] + C = List[A] # this expands to List[List[Any]] + + AA = List[T] + D = AA # here AA expands to List[Any] + x: D[int] # Error! + + Note: the fact that we support aliases like `A = List` means that the target + type will be initially an instance type with wrong number of type arguments. + Such instances are all fixed either during or after main semantic analysis passes. + We therefore store the difference between `List` and `List[Any]` rvalues (targets) + using the `no_args` flag. + + Meaning of other fields: + + target: The target type. For generic aliases contains bound type variables + as nested types (currently TypeVar and ParamSpec are supported). + _fullname: Qualified name of this type alias. This is used in particular + to track fine-grained dependencies from aliases. + module: Module where the alias was defined. + alias_tvars: Type variables used to define this alias. + normalized: Used to distinguish between `A = List`, and `A = list`. Both + are internally stored using `builtins.list` (because `typing.List` is + itself an alias), while the second cannot be subscripted because of + Python runtime limitation. + line and column: Line and column on the original alias definition. + eager: If True, immediately expand alias when referred to (useful for aliases + within functions that can't be looked up from the symbol table) + """ + + __slots__ = ( + "target", + "_fullname", + "module", + "alias_tvars", + "no_args", + "normalized", + "_is_recursive", + "eager", + "tvar_tuple_index", + "python_3_12_type_alias", + ) + + __match_args__ = ("name", "target", "alias_tvars", "no_args") + + def __init__( + self, + target: mypy.types.Type, + fullname: str, + module: str, + line: int, + column: int, + *, + alias_tvars: list[mypy.types.TypeVarLikeType] | None = None, + no_args: bool = False, + normalized: bool = False, + eager: bool = False, + python_3_12_type_alias: bool = False, + ) -> None: + self._fullname = fullname + self.module = module + self.target = target + if alias_tvars is None: + alias_tvars = [] + self.alias_tvars = alias_tvars + self.no_args = no_args + self.normalized = normalized + # This attribute is manipulated by TypeAliasType. If non-None, + # it is the cached value. + self._is_recursive: bool | None = None + self.eager = eager + self.python_3_12_type_alias = python_3_12_type_alias + self.tvar_tuple_index = None + for i, t in enumerate(alias_tvars): + if isinstance(t, mypy.types.TypeVarTupleType): + self.tvar_tuple_index = i + super().__init__(line, column) + + @classmethod + def from_tuple_type(cls, info: TypeInfo) -> TypeAlias: + """Generate an alias to the tuple type described by a given TypeInfo. + + NOTE: this doesn't set type alias type variables (for generic tuple types), + they must be set by the caller (when fully analyzed). + """ + assert info.tuple_type + # TODO: is it possible to refactor this to set the correct type vars here? + return TypeAlias( + info.tuple_type.copy_modified( + # Create an Instance similar to fill_typevars(). + fallback=mypy.types.Instance( + info, mypy.types.type_vars_as_args(info.defn.type_vars) + ) + ), + info.fullname, + info.module_name, + info.line, + info.column, + ) + + @classmethod + def from_typeddict_type(cls, info: TypeInfo) -> TypeAlias: + """Generate an alias to the TypedDict type described by a given TypeInfo. + + NOTE: this doesn't set type alias type variables (for generic TypedDicts), + they must be set by the caller (when fully analyzed). + """ + assert info.typeddict_type + # TODO: is it possible to refactor this to set the correct type vars here? + return TypeAlias( + info.typeddict_type.copy_modified( + # Create an Instance similar to fill_typevars(). + fallback=mypy.types.Instance( + info, mypy.types.type_vars_as_args(info.defn.type_vars) + ) + ), + info.fullname, + info.module_name, + info.line, + info.column, + ) + + @property + def name(self) -> str: + return self._fullname.split(".")[-1] + + @property + def fullname(self) -> str: + return self._fullname + + @property + def has_param_spec_type(self) -> bool: + return any(isinstance(v, mypy.types.ParamSpecType) for v in self.alias_tvars) + + def accept(self, visitor: NodeVisitor[T]) -> T: + return visitor.visit_type_alias(self) + + def serialize(self) -> JsonDict: + data: JsonDict = { + ".class": "TypeAlias", + "fullname": self._fullname, + "module": self.module, + "target": self.target.serialize(), + "alias_tvars": [v.serialize() for v in self.alias_tvars], + "no_args": self.no_args, + "normalized": self.normalized, + "python_3_12_type_alias": self.python_3_12_type_alias, + } + return data + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeAlias: + assert data[".class"] == "TypeAlias" + fullname = data["fullname"] + module = data["module"] + alias_tvars = [mypy.types.deserialize_type(v) for v in data["alias_tvars"]] + assert all(isinstance(t, mypy.types.TypeVarLikeType) for t in alias_tvars) + target = mypy.types.deserialize_type(data["target"]) + no_args = data["no_args"] + normalized = data["normalized"] + python_3_12_type_alias = data["python_3_12_type_alias"] + return cls( + target, + fullname, + module, + -1, + -1, + alias_tvars=cast(list[mypy.types.TypeVarLikeType], alias_tvars), + no_args=no_args, + normalized=normalized, + python_3_12_type_alias=python_3_12_type_alias, + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_ALIAS) + write_str(data, self._fullname) + write_str(data, self.module) + self.target.write(data) + mypy.types.write_type_list(data, self.alias_tvars) + write_bool(data, self.no_args) + write_bool(data, self.normalized) + write_bool(data, self.python_3_12_type_alias) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeAlias: + fullname = read_str(data) + module = read_str(data) + target = mypy.types.read_type(data) + alias_tvars = mypy.types.read_type_var_likes(data) + ret = TypeAlias( + target, + fullname, + module, + -1, + -1, + alias_tvars=alias_tvars, + no_args=read_bool(data), + normalized=read_bool(data), + python_3_12_type_alias=read_bool(data), + ) + assert read_tag(data) == END_TAG + return ret + + +class PlaceholderNode(SymbolNode): + """Temporary symbol node that will later become a real SymbolNode. + + These are only present during semantic analysis when using the new + semantic analyzer. These are created if some essential dependencies + of a definition are not yet complete. + + A typical use is for names imported from a module which is still + incomplete (within an import cycle): + + from m import f # Initially may create PlaceholderNode + + This is particularly important if the imported shadows a name from + an enclosing scope or builtins: + + from m import int # Placeholder avoids mixups with builtins.int + + Another case where this is useful is when there is another definition + or assignment: + + from m import f + def f() -> None: ... + + In the above example, the presence of PlaceholderNode allows us to + handle the second definition as a redefinition. + + They are also used to create PlaceholderType instances for types + that refer to incomplete types. Example: + + class C(Sequence[C]): ... + + We create a PlaceholderNode (with becomes_typeinfo=True) for C so + that the type C in Sequence[C] can be bound. + + Attributes: + + fullname: Full name of the PlaceholderNode. + node: AST node that contains the definition that caused this to + be created. This is useful for tracking order of incomplete definitions + and for debugging. + becomes_typeinfo: If True, this refers something that could later + become a TypeInfo. It can't be used with type variables, in + particular, as this would cause issues with class type variable + detection. + + The long-term purpose of placeholder nodes/types is to evolve into + something that can support general recursive types. + """ + + __slots__ = ("_fullname", "node", "becomes_typeinfo") + + def __init__( + self, fullname: str, node: Node, line: int, *, becomes_typeinfo: bool = False + ) -> None: + self._fullname = fullname + self.node = node + self.becomes_typeinfo = becomes_typeinfo + self.line = line + + @property + def name(self) -> str: + return self._fullname.split(".")[-1] + + @property + def fullname(self) -> str: + return self._fullname + + def serialize(self) -> JsonDict: + assert False, "PlaceholderNode can't be serialized" + + def accept(self, visitor: NodeVisitor[T]) -> T: + return visitor.visit_placeholder_node(self) + + +class SymbolTableNode: + """Description of a name binding in a symbol table. + + These are only used as values in module (global), function (local) + and class symbol tables (see SymbolTable). The name that is bound is + the key in SymbolTable. + + Symbol tables don't contain direct references to AST nodes primarily + because there can be multiple symbol table references to a single + AST node (due to imports and aliases), and different references can + behave differently. This class describes the unique properties of + each reference. + + The most fundamental attribute is 'node', which is the AST node that + the name refers to. + + The kind is usually one of LDEF, GDEF or MDEF, depending on the scope + of the definition. These three kinds can usually be used + interchangeably and the difference between local, global and class + scopes is mostly descriptive, with no semantic significance. + However, some tools that consume mypy ASTs may care about these so + they should be correct. + + Attributes: + node: AST node of definition. Among others, this can be one of + FuncDef, Var, TypeInfo, TypeVarExpr or MypyFile -- or None + for cross_ref that hasn't been fixed up yet. + kind: Kind of node. Possible values: + - LDEF: local definition + - GDEF: global (module-level) definition + - MDEF: class member definition + - UNBOUND_IMPORTED: temporary kind for imported names (we + don't know the final kind yet) + module_public: If False, this name won't be imported via + 'from import *'. This has no effect on names within + classes. + module_hidden: If True, the name will be never exported (needed for + stub files) + cross_ref: For deserialized MypyFile nodes, the referenced module + name; for other nodes, optionally the name of the referenced object. + implicit: Was this defined by assignment to self attribute? + plugin_generated: Was this symbol generated by a plugin? + (And therefore needs to be removed in aststrip.) + no_serialize: Do not serialize this node if True. This is used to prevent + keys in the cache that refer to modules on which this file does not + depend. Currently this can happen if there is a module not in build + used e.g. like this: + import a.b.c # type: ignore + This will add a submodule symbol to parent module `a` symbol table, + but `a.b` is _not_ added as its dependency. Therefore, we should + not serialize these symbols as they may not be found during fixup + phase, instead they will be re-added during subsequent patch parents + phase. + TODO: Refactor build.py to make dependency tracking more transparent + and/or refactor look-up functions to not require parent patching. + + NOTE: No other attributes should be added to this class unless they + are shared by all node kinds. + """ + + __slots__ = ( + "kind", + "node", + "module_public", + "module_hidden", + "cross_ref", + "implicit", + "plugin_generated", + "no_serialize", + ) + + def __init__( + self, + kind: int, + node: SymbolNode | None, + module_public: bool = True, + implicit: bool = False, + module_hidden: bool = False, + *, + plugin_generated: bool = False, + no_serialize: bool = False, + ) -> None: + self.kind = kind + self.node = node + self.module_public = module_public + self.implicit = implicit + self.module_hidden = module_hidden + self.cross_ref: str | None = None + self.plugin_generated = plugin_generated + self.no_serialize = no_serialize + + @property + def fullname(self) -> str | None: + if self.node is not None: + return self.node.fullname + else: + return None + + @property + def type(self) -> mypy.types.Type | None: + node = self.node + if isinstance(node, (Var, SYMBOL_FUNCBASE_TYPES)) and node.type is not None: + return node.type + elif isinstance(node, Decorator): + return node.var.type + else: + return None + + def copy(self) -> SymbolTableNode: + new = SymbolTableNode( + self.kind, self.node, self.module_public, self.implicit, self.module_hidden + ) + new.cross_ref = self.cross_ref + return new + + def __str__(self) -> str: + s = f"{node_kinds[self.kind]}/{short_type(self.node)}" + if isinstance(self.node, SymbolNode): + s += f" ({self.node.fullname})" + # Include declared type of variables and functions. + if self.type is not None: + s += f" : {self.type}" + if self.cross_ref: + s += f" cross_ref:{self.cross_ref}" + return s + + def serialize(self, prefix: str, name: str) -> JsonDict: + """Serialize a SymbolTableNode. + + Args: + prefix: full name of the containing module or class; or None + name: name of this object relative to the containing object + """ + data: JsonDict = {".class": "SymbolTableNode", "kind": node_kinds[self.kind]} + if self.module_hidden: + data["module_hidden"] = True + if not self.module_public: + data["module_public"] = False + if self.implicit: + data["implicit"] = True + if self.plugin_generated: + data["plugin_generated"] = True + if isinstance(self.node, MypyFile): + data["cross_ref"] = self.node.fullname + else: + assert self.node is not None, f"{prefix}:{name}" + if prefix is not None: + fullname = self.node.fullname + if ( + "." in fullname + and fullname != prefix + "." + name + and not (isinstance(self.node, Var) and self.node.from_module_getattr) + ): + assert not isinstance( + self.node, PlaceholderNode + ), f"Definition of {fullname} is unexpectedly incomplete" + data["cross_ref"] = fullname + return data + data["node"] = self.node.serialize() + return data + + @classmethod + def deserialize(cls, data: JsonDict) -> SymbolTableNode: + assert data[".class"] == "SymbolTableNode" + kind = inverse_node_kinds[data["kind"]] + if "cross_ref" in data: + # This will be fixed up later. + stnode = SymbolTableNode(kind, None) + stnode.cross_ref = data["cross_ref"] + else: + assert "node" in data, data + node = SymbolNode.deserialize(data["node"]) + stnode = SymbolTableNode(kind, node) + if "module_hidden" in data: + stnode.module_hidden = data["module_hidden"] + if "module_public" in data: + stnode.module_public = data["module_public"] + if "implicit" in data: + stnode.implicit = data["implicit"] + if "plugin_generated" in data: + stnode.plugin_generated = data["plugin_generated"] + return stnode + + def write(self, data: WriteBuffer, prefix: str, name: str) -> None: + write_tag(data, SYMBOL_TABLE_NODE) + write_int(data, self.kind) + write_bool(data, self.module_hidden) + write_bool(data, self.module_public) + write_bool(data, self.implicit) + write_bool(data, self.plugin_generated) + + cross_ref = None + if isinstance(self.node, MypyFile): + cross_ref = self.node.fullname + else: + assert self.node is not None, f"{prefix}:{name}" + if prefix is not None: + fullname = self.node.fullname + if ( + "." in fullname + and fullname != prefix + "." + name + and not (isinstance(self.node, Var) and self.node.from_module_getattr) + ): + assert not isinstance( + self.node, PlaceholderNode + ), f"Definition of {fullname} is unexpectedly incomplete" + cross_ref = fullname + + write_str_opt(data, cross_ref) + if cross_ref is None: + assert self.node is not None + self.node.write(data) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> SymbolTableNode: + assert read_tag(data) == SYMBOL_TABLE_NODE + sym = SymbolTableNode(read_int(data), None) + sym.module_hidden = read_bool(data) + sym.module_public = read_bool(data) + sym.implicit = read_bool(data) + sym.plugin_generated = read_bool(data) + cross_ref = read_str_opt(data) + if cross_ref is None: + sym.node = read_symbol(data) + else: + sym.cross_ref = cross_ref + assert read_tag(data) == END_TAG + return sym + + +class SymbolTable(dict[str, SymbolTableNode]): + """Static representation of a namespace dictionary. + + This is used for module, class and function namespaces. + """ + + __slots__ = () + + def __str__(self) -> str: + a: list[str] = [] + for key, value in self.items(): + # Filter out the implicit import of builtins. + if isinstance(value, SymbolTableNode): + if ( + value.fullname != "builtins" + and (value.fullname or "").split(".")[-1] not in implicit_module_attrs + ): + a.append(" " + str(key) + " : " + str(value)) + else: + # Used in debugging: + a.append(" ") # type: ignore[unreachable] + a = sorted(a) + a.insert(0, "SymbolTable(") + a[-1] += ")" + return "\n".join(a) + + def copy(self) -> SymbolTable: + return SymbolTable([(key, node.copy()) for key, node in self.items()]) + + def serialize(self, fullname: str) -> JsonDict: + data: JsonDict = {".class": "SymbolTable"} + for key, value in self.items(): + # Skip __builtins__: it's a reference to the builtins + # module that gets added to every module by + # SemanticAnalyzerPass2.visit_file(), but it shouldn't be + # accessed by users of the module. + if key == "__builtins__" or value.no_serialize: + continue + data[key] = value.serialize(fullname, key) + return data + + @classmethod + def deserialize(cls, data: JsonDict) -> SymbolTable: + assert data[".class"] == "SymbolTable" + st = SymbolTable() + for key, value in data.items(): + if key != ".class": + st[key] = SymbolTableNode.deserialize(value) + return st + + def write(self, data: WriteBuffer, fullname: str) -> None: + size = 0 + for key, value in self.items(): + # Skip __builtins__: it's a reference to the builtins + # module that gets added to every module by + # SemanticAnalyzerPass2.visit_file(), but it shouldn't be + # accessed by users of the module. + if key == "__builtins__" or value.no_serialize: + continue + size += 1 + # We intentionally tag SymbolTable as a simple dictionary str -> SymbolTableNode. + write_tag(data, DICT_STR_GEN) + write_int_bare(data, size) + for key in sorted(self): + value = self[key] + if key == "__builtins__" or value.no_serialize: + continue + write_str_bare(data, key) + value.write(data, fullname, key) + + @classmethod + def read(cls, data: ReadBuffer) -> SymbolTable: + assert read_tag(data) == DICT_STR_GEN + size = read_int_bare(data) + return SymbolTable( + [(read_str_bare(data), SymbolTableNode.read(data)) for _ in range(size)] + ) + + +class DataclassTransformSpec: + """Specifies how a dataclass-like transform should be applied. The fields here are based on the + parameters accepted by `typing.dataclass_transform`.""" + + __slots__ = ( + "eq_default", + "order_default", + "kw_only_default", + "frozen_default", + "field_specifiers", + ) + + def __init__( + self, + *, + eq_default: bool | None = None, + order_default: bool | None = None, + kw_only_default: bool | None = None, + field_specifiers: tuple[str, ...] | None = None, + # Specified outside of PEP 681: + # frozen_default was added to CPythonin https://github.com/python/cpython/pull/99958 citing + # positive discussion in typing-sig + frozen_default: bool | None = None, + ) -> None: + self.eq_default = eq_default if eq_default is not None else True + self.order_default = order_default if order_default is not None else False + self.kw_only_default = kw_only_default if kw_only_default is not None else False + self.frozen_default = frozen_default if frozen_default is not None else False + self.field_specifiers = field_specifiers if field_specifiers is not None else () + + def serialize(self) -> JsonDict: + return { + "eq_default": self.eq_default, + "order_default": self.order_default, + "kw_only_default": self.kw_only_default, + "frozen_default": self.frozen_default, + "field_specifiers": list(self.field_specifiers), + } + + @classmethod + def deserialize(cls, data: JsonDict) -> DataclassTransformSpec: + return DataclassTransformSpec( + eq_default=data.get("eq_default"), + order_default=data.get("order_default"), + kw_only_default=data.get("kw_only_default"), + frozen_default=data.get("frozen_default"), + field_specifiers=tuple(data.get("field_specifiers", [])), + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, DT_SPEC) + write_bool(data, self.eq_default) + write_bool(data, self.order_default) + write_bool(data, self.kw_only_default) + write_bool(data, self.frozen_default) + write_str_list(data, self.field_specifiers) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> DataclassTransformSpec: + ret = DataclassTransformSpec( + eq_default=read_bool(data), + order_default=read_bool(data), + kw_only_default=read_bool(data), + frozen_default=read_bool(data), + field_specifiers=tuple(read_str_list(data)), + ) + assert read_tag(data) == END_TAG + return ret + + +@trait +class SplittingVisitor: + # If True, process function definitions. If False, don't. This is used + # for processing module top levels in fine-grained incremental mode. + recurse_into_functions: bool + + @contextmanager + def set_recurse_into_functions(self) -> Iterator[None]: + """Temporarily set recurse_into_functions to True. + + This is used to process top-level functions/methods as a whole. + """ + old_recurse_into_functions = self.recurse_into_functions + self.recurse_into_functions = True + try: + yield + finally: + self.recurse_into_functions = old_recurse_into_functions + + +def get_flags(node: Node, names: list[str]) -> list[str]: + return [name for name in names if getattr(node, name)] + + +def set_flags(node: Node, flags: list[str]) -> None: + for name in flags: + setattr(node, name, True) + + +def write_flags(data: WriteBuffer, flags: list[bool]) -> None: + assert len(flags) <= 26, "This many flags not supported yet" + packed = 0 + for i, flag in enumerate(flags): + if flag: + packed |= 1 << i + write_int(data, packed) + + +def read_flags(data: ReadBuffer, num_flags: int) -> list[bool]: + packed = read_int(data) + return [(packed & (1 << i)) != 0 for i in range(num_flags)] + + +def get_member_expr_fullname(expr: MemberExpr) -> str | None: + """Return the qualified name representation of a member expression. + + Return a string of form foo.bar, foo.bar.baz, or similar, or None if the + argument cannot be represented in this form. + """ + initial: str | None = None + if isinstance(expr.expr, NameExpr): + initial = expr.expr.name + elif isinstance(expr.expr, MemberExpr): + initial = get_member_expr_fullname(expr.expr) + if initial is None: + return None + return f"{initial}.{expr.name}" + + +deserialize_map: Final = { + key: obj.deserialize + for key, obj in globals().items() + if type(obj) is not FakeInfo + and isinstance(obj, type) + and issubclass(obj, SymbolNode) + and obj is not SymbolNode +} + + +def check_arg_kinds( + arg_kinds: list[ArgKind], nodes: list[T], fail: Callable[[str, T], None] +) -> None: + is_var_arg = False + is_kw_arg = False + seen_named = False + seen_opt = False + for kind, node in zip(arg_kinds, nodes): + if kind == ARG_POS: + if is_var_arg or is_kw_arg or seen_named or seen_opt: + fail( + "Required positional args may not appear after default, named or var args", + node, + ) + break + elif kind == ARG_OPT: + if is_var_arg or is_kw_arg or seen_named: + fail("Positional default args may not appear after named or var args", node) + break + seen_opt = True + elif kind == ARG_STAR: + if is_var_arg or is_kw_arg or seen_named: + fail("Var args may not appear after named or var args", node) + break + is_var_arg = True + elif kind == ARG_NAMED or kind == ARG_NAMED_OPT: + seen_named = True + if is_kw_arg: + fail("A **kwargs argument must be the last argument", node) + break + elif kind == ARG_STAR2: + if is_kw_arg: + fail("You may only have one **kwargs argument", node) + break + is_kw_arg = True + + +def check_param_names( + names: Sequence[str | None], + nodes: list[T], + fail: Callable[[str, T], None], + description: str = "function definition", +) -> None: + seen_names: set[str | None] = set() + for name, node in zip(names, nodes): + if name is not None and name in seen_names: + fail(f'Duplicate parameter "{name}" in {description}', node) + break + seen_names.add(name) + + +def is_class_var(expr: NameExpr) -> bool: + """Return whether the expression is ClassVar[...]""" + if isinstance(expr.node, Var): + return expr.node.is_classvar + return False + + +def is_final_node(node: SymbolNode | None) -> bool: + """Check whether `node` corresponds to a final attribute.""" + return isinstance(node, (Var, FuncDef, OverloadedFuncDef, Decorator)) and node.is_final + + +def get_func_def(typ: mypy.types.CallableType) -> SymbolNode | None: + definition = typ.definition + if isinstance(definition, Decorator): + definition = definition.func + return definition + + +def local_definitions( + names: SymbolTable, name_prefix: str, info: TypeInfo | None = None +) -> Iterator[Definition]: + """Iterate over local definitions (not imported) in a symbol table. + + Recursively iterate over class members and nested classes. + """ + # TODO: What should the name be? Or maybe remove it? + for name, symnode in names.items(): + shortname = name + if "-redef" in name: + # Restore original name from mangled name of multiply defined function + shortname = name.split("-redef")[0] + fullname = name_prefix + "." + shortname + node = symnode.node + if node and node.fullname == fullname: + yield fullname, symnode, info + if isinstance(node, TypeInfo): + yield from local_definitions(node.names, fullname, node) + + +# See docstring for mypy/cache.py for reserved tag ranges. +MYPY_FILE: Final[Tag] = 50 +OVERLOADED_FUNC_DEF: Final[Tag] = 51 +FUNC_DEF: Final[Tag] = 52 +DECORATOR: Final[Tag] = 53 +VAR: Final[Tag] = 54 +TYPE_VAR_EXPR: Final[Tag] = 55 +PARAM_SPEC_EXPR: Final[Tag] = 56 +TYPE_VAR_TUPLE_EXPR: Final[Tag] = 57 +TYPE_INFO: Final[Tag] = 58 +TYPE_ALIAS: Final[Tag] = 59 +CLASS_DEF: Final[Tag] = 60 +SYMBOL_TABLE_NODE: Final[Tag] = 61 + +EXPR_STMT: Final[Tag] = 160 +CALL_EXPR: Final[Tag] = 161 +NAME_EXPR: Final[Tag] = 162 +STR_EXPR: Final[Tag] = 163 +IMPORT: Final[Tag] = 164 +MEMBER_EXPR: Final[Tag] = 165 +OP_EXPR: Final[Tag] = 166 +INT_EXPR: Final[Tag] = 167 +IF_STMT: Final[Tag] = 168 +ASSIGNMENT_STMT: Final[Tag] = 169 +TUPLE_EXPR: Final[Tag] = 170 +BLOCK: Final[Tag] = 171 +INDEX_EXPR: Final[Tag] = 172 +LIST_EXPR: Final[Tag] = 173 +SET_EXPR: Final[Tag] = 174 +RETURN_STMT: Final[Tag] = 175 +WHILE_STMT: Final[Tag] = 176 +COMPARISON_EXPR: Final[Tag] = 177 +BOOL_OP_EXPR: Final[Tag] = 178 +FUNC_DEF_STMT: Final[Tag] = 179 +PASS_STMT: Final[Tag] = 180 +FLOAT_EXPR: Final[Tag] = 181 +UNARY_EXPR: Final[Tag] = 182 +DICT_EXPR: Final[Tag] = 183 +COMPLEX_EXPR: Final[Tag] = 184 +SLICE_EXPR: Final[Tag] = 185 +TEMP_NODE: Final[Tag] = 186 +RAISE_STMT: Final[Tag] = 187 +BREAK_STMT: Final[Tag] = 188 +CONTINUE_STMT: Final[Tag] = 189 +GENERATOR_EXPR: Final[Tag] = 190 +YIELD_EXPR: Final[Tag] = 191 +YIELD_FROM_EXPR: Final[Tag] = 192 +LIST_COMPREHENSION: Final[Tag] = 193 +SET_COMPREHENSION: Final[Tag] = 194 +DICT_COMPREHENSION: Final[Tag] = 195 +IMPORT_FROM: Final[Tag] = 196 +ASSERT_STMT: Final[Tag] = 197 +FOR_STMT: Final[Tag] = 198 +WITH_STMT: Final[Tag] = 199 +OPERATOR_ASSIGNMENT_STMT: Final[Tag] = 200 +TRY_STMT: Final[Tag] = 201 +ELLIPSIS_EXPR: Final[Tag] = 202 +CONDITIONAL_EXPR: Final[Tag] = 203 +DEL_STMT: Final[Tag] = 204 +FSTRING_EXPR: Final[Tag] = 205 +FSTRING_INTERPOLATION: Final[Tag] = 206 +LAMBDA_EXPR: Final[Tag] = 207 +NAMED_EXPR: Final[Tag] = 208 +STAR_EXPR: Final[Tag] = 209 +BYTES_EXPR: Final[Tag] = 210 +GLOBAL_DECL: Final[Tag] = 211 +NONLOCAL_DECL: Final[Tag] = 212 +AWAIT_EXPR: Final[Tag] = 213 +BIG_INT_EXPR: Final[Tag] = 214 +IMPORT_ALL: Final[Tag] = 215 +MATCH_STMT: Final[Tag] = 216 +AS_PATTERN: Final[Tag] = 217 +OR_PATTERN: Final[Tag] = 218 +VALUE_PATTERN: Final[Tag] = 219 +SINGLETON_PATTERN: Final[Tag] = 220 +SEQUENCE_PATTERN: Final[Tag] = 221 +STARRED_PATTERN: Final[Tag] = 222 +MAPPING_PATTERN: Final[Tag] = 223 +CLASS_PATTERN: Final[Tag] = 224 +TYPE_ALIAS_STMT: Final[Tag] = 225 +IMPORT_METADATA: Final[Tag] = 226 +IMPORTFROM_METADATA: Final[Tag] = 227 +IMPORTALL_METADATA: Final[Tag] = 228 +TSTRING_EXPR: Final[Tag] = 229 + + +def read_symbol(data: ReadBuffer) -> SymbolNode: + tag = read_tag(data) + # The branches here are ordered manually by type "popularity". + if tag == VAR: + return Var.read(data) + if tag == FUNC_DEF: + return FuncDef.read(data) + if tag == DECORATOR: + return Decorator.read(data) + if tag == TYPE_INFO: + return TypeInfo.read(data) + if tag == OVERLOADED_FUNC_DEF: + return OverloadedFuncDef.read(data) + if tag == TYPE_VAR_EXPR: + return TypeVarExpr.read(data) + if tag == TYPE_ALIAS: + return TypeAlias.read(data) + if tag == PARAM_SPEC_EXPR: + return ParamSpecExpr.read(data) + if tag == TYPE_VAR_TUPLE_EXPR: + return TypeVarTupleExpr.read(data) + assert False, f"Unknown symbol tag {tag}" + + +def read_overload_part(data: ReadBuffer, tag: Tag | None = None) -> OverloadPart: + if tag is None: + tag = read_tag(data) + if tag == DECORATOR: + return Decorator.read(data) + if tag == FUNC_DEF: + return FuncDef.read(data) + assert False, f"Invalid tag for an OverloadPart {tag}" diff --git a/micromamba_root/Lib/site-packages/mypy/operators.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/operators.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..f74a8cbd3256b9ecae37bdd983e71a3dc13892ae Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/operators.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/operators.py b/micromamba_root/Lib/site-packages/mypy/operators.py new file mode 100644 index 0000000000000000000000000000000000000000..d1f050b58faeb5171c54b7de8b4cf5fc97b9bf6e --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/operators.py @@ -0,0 +1,126 @@ +"""Information about Python operators""" + +from __future__ import annotations + +from typing import Final + +# Map from binary operator id to related method name (in Python 3). +op_methods: Final = { + "+": "__add__", + "-": "__sub__", + "*": "__mul__", + "/": "__truediv__", + "%": "__mod__", + "divmod": "__divmod__", + "//": "__floordiv__", + "**": "__pow__", + "@": "__matmul__", + "&": "__and__", + "|": "__or__", + "^": "__xor__", + "<<": "__lshift__", + ">>": "__rshift__", + "==": "__eq__", + "!=": "__ne__", + "<": "__lt__", + ">=": "__ge__", + ">": "__gt__", + "<=": "__le__", + "in": "__contains__", +} + +op_methods_to_symbols: Final = {v: k for (k, v) in op_methods.items()} + +ops_falling_back_to_cmp: Final = {"__ne__", "__eq__", "__lt__", "__le__", "__gt__", "__ge__"} + + +ops_with_inplace_method: Final = { + "+", + "-", + "*", + "/", + "%", + "//", + "**", + "@", + "&", + "|", + "^", + "<<", + ">>", +} + +inplace_operator_methods: Final = {"__i" + op_methods[op][2:] for op in ops_with_inplace_method} + +reverse_op_methods: Final = { + "__add__": "__radd__", + "__sub__": "__rsub__", + "__mul__": "__rmul__", + "__truediv__": "__rtruediv__", + "__mod__": "__rmod__", + "__divmod__": "__rdivmod__", + "__floordiv__": "__rfloordiv__", + "__pow__": "__rpow__", + "__matmul__": "__rmatmul__", + "__and__": "__rand__", + "__or__": "__ror__", + "__xor__": "__rxor__", + "__lshift__": "__rlshift__", + "__rshift__": "__rrshift__", + "__eq__": "__eq__", + "__ne__": "__ne__", + "__lt__": "__gt__", + "__ge__": "__le__", + "__gt__": "__lt__", + "__le__": "__ge__", +} + +reverse_op_method_names: Final = set(reverse_op_methods.values()) + +# Suppose we have some class A. When we do A() + A(), Python will only check +# the output of A().__add__(A()) and skip calling the __radd__ method entirely. +# This shortcut is used only for the following methods: +op_methods_that_shortcut: Final = { + "__add__", + "__sub__", + "__mul__", + "__truediv__", + "__mod__", + "__divmod__", + "__floordiv__", + "__pow__", + "__matmul__", + "__and__", + "__or__", + "__xor__", + "__lshift__", + "__rshift__", +} + +normal_from_reverse_op: Final = {m: n for n, m in reverse_op_methods.items()} +reverse_op_method_set: Final = set(reverse_op_methods.values()) + +unary_op_methods: Final = {"-": "__neg__", "+": "__pos__", "~": "__invert__"} + +int_op_to_method: Final = { + "==": int.__eq__, + "is": int.__eq__, + "<": int.__lt__, + "<=": int.__le__, + "!=": int.__ne__, + "is not": int.__ne__, + ">": int.__gt__, + ">=": int.__ge__, +} + +flip_ops: Final = {"<": ">", "<=": ">=", ">": "<", ">=": "<="} +neg_ops: Final = { + "==": "!=", + "!=": "==", + "is": "is not", + "is not": "is", + "<": ">=", + "<=": ">", + ">": "<=", + ">=": "<", +} diff --git a/micromamba_root/Lib/site-packages/mypy/options.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/options.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..32dfc376a27860c144c76715b525c25d2434156d Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/options.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/options.py b/micromamba_root/Lib/site-packages/mypy/options.py new file mode 100644 index 0000000000000000000000000000000000000000..79ca75c58be6fb3440038278292db37f26bc370d --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/options.py @@ -0,0 +1,651 @@ +from __future__ import annotations + +import pprint +import re +import sys +import sysconfig +from collections.abc import Callable +from re import Pattern +from typing import Any, Final + +from librt.internal import WriteBuffer, write_bool, write_str + +from mypy import defaults +from mypy.errorcodes import ErrorCode, error_codes +from mypy.util import get_class_descriptors, replace_object_state + + +class BuildType: + STANDARD: Final = 0 + MODULE: Final = 1 + PROGRAM_TEXT: Final = 2 + + +PER_MODULE_OPTIONS: Final = { + # Please keep this list sorted + "allow_redefinition_old", + "allow_redefinition_new", + "allow_untyped_globals", + "always_false", + "always_true", + "check_untyped_defs", + "debug_cache", + "disable_error_code", + "disabled_error_codes", + "disallow_any_decorated", + "disallow_any_explicit", + "disallow_any_expr", + "disallow_any_generics", + "disallow_any_unimported", + "disallow_incomplete_defs", + "disallow_subclassing_any", + "disallow_untyped_calls", + "disallow_untyped_decorators", + "disallow_untyped_defs", + "enable_error_code", + "enabled_error_codes", + "extra_checks", + "follow_imports_for_stubs", + "follow_imports", + "follow_untyped_imports", + "ignore_errors", + "ignore_missing_imports", + "implicit_optional", + "implicit_reexport", + "local_partial_types", + "mypyc", + "strict_concatenate", + "strict_equality", + "strict_equality_for_none", + "strict_optional", + "warn_no_return", + "warn_return_any", + "warn_unreachable", + "warn_unused_ignores", +} + +OPTIONS_AFFECTING_CACHE: Final = ( + PER_MODULE_OPTIONS + | { + "platform", + "bazel", + "native_parser", + "old_type_inference", + "plugins", + "disable_bytearray_promotion", + "disable_memoryview_promotion", + "strict_bytes", + "fixed_format_cache", + "untyped_calls_exclude", + "enable_incomplete_feature", + } +) - {"debug_cache"} + +# OPTIONS_AFFECTING_CACHE without "platform", as a sorted tuple for fast iteration. +# "platform" is handled separately in options_snapshot(). +OPTIONS_AFFECTING_CACHE_NO_PLATFORM: Final = tuple(sorted(OPTIONS_AFFECTING_CACHE - {"platform"})) + +# Features that are currently (or were recently) incomplete/experimental +TYPE_VAR_TUPLE: Final = "TypeVarTuple" +UNPACK: Final = "Unpack" +PRECISE_TUPLE_TYPES: Final = "PreciseTupleTypes" +NEW_GENERIC_SYNTAX: Final = "NewGenericSyntax" +INLINE_TYPEDDICT: Final = "InlineTypedDict" +TYPE_FORM: Final = "TypeForm" +INCOMPLETE_FEATURES: Final = frozenset((PRECISE_TUPLE_TYPES, INLINE_TYPEDDICT, TYPE_FORM)) +COMPLETE_FEATURES: Final = frozenset((TYPE_VAR_TUPLE, UNPACK, NEW_GENERIC_SYNTAX)) + + +class Options: + """Options collected from flags.""" + + def __init__(self) -> None: + # Cache for clone_for_module() + self._per_module_cache: dict[str, Options] | None = None + + # -- build options -- + self.build_type = BuildType.STANDARD + self.python_version: tuple[int, int] = sys.version_info[:2] + # The executable used to search for PEP 561 packages. If this is None, + # then mypy does not search for PEP 561 packages. + self.python_executable: str | None = sys.executable + + # When cross compiling to emscripten, we need to rely on MACHDEP because + # sys.platform is the host build platform, not emscripten. + MACHDEP = sysconfig.get_config_var("MACHDEP") + if MACHDEP == "emscripten": + self.platform = MACHDEP + else: + self.platform = sys.platform + + self.custom_typing_module: str | None = None + self.custom_typeshed_dir: str | None = None + # The abspath() version of the above, we compute it once as an optimization. + self.abs_custom_typeshed_dir: str | None = None + self.mypy_path: list[str] = [] + self.report_dirs: dict[str, str] = {} + # Show errors in PEP 561 packages/site-packages modules + self.no_silence_site_packages = False + self.no_site_packages = False + self.ignore_missing_imports = False + # Is ignore_missing_imports set in a per-module section + self.ignore_missing_imports_per_module = False + # Typecheck modules without stubs or py.typed marker + self.follow_untyped_imports = False + self.follow_imports = "normal" # normal|silent|skip|error + # Whether to respect the follow_imports setting even for stub files. + # Intended to be used for disabling specific stubs. + self.follow_imports_for_stubs = False + # PEP 420 namespace packages + # This allows definitions of packages without __init__.py and allows packages to span + # multiple directories. This flag affects both import discovery and the association of + # input files/modules/packages to the relevant file and fully qualified module name. + self.namespace_packages = True + # Use current directory and MYPYPATH to determine fully qualified module names of files + # passed by automatically considering their subdirectories as packages. This is only + # relevant if namespace packages are enabled, since otherwise examining __init__.py's is + # sufficient to determine module names for files. As a possible alternative, add a single + # top-level __init__.py to your packages. + self.explicit_package_bases = False + # File names, directory names or subpaths to avoid checking + self.exclude: list[str] = [] + self.exclude_gitignore: bool = False + + # disallow_any options + self.disallow_any_generics = False + self.disallow_any_unimported = False + self.disallow_any_expr = False + self.disallow_any_decorated = False + self.disallow_any_explicit = False + + # Disallow calling untyped functions from typed ones + self.disallow_untyped_calls = False + + # Always allow untyped calls for function coming from modules/packages + # in this list (each item effectively acts as a prefix match) + self.untyped_calls_exclude: list[str] = [] + + # Disallow defining untyped (or incompletely typed) functions + self.disallow_untyped_defs = False + + # Disallow defining incompletely typed functions + self.disallow_incomplete_defs = False + + # Type check unannotated functions + self.check_untyped_defs = False + + # Disallow decorating typed functions with untyped decorators + self.disallow_untyped_decorators = False + + # Disallow subclassing values of type 'Any' + self.disallow_subclassing_any = False + + # Also check typeshed for missing annotations + self.warn_incomplete_stub = False + + # Warn about casting an expression to its inferred type + self.warn_redundant_casts = False + + # Warn about falling off the end of a function returning non-None + self.warn_no_return = True + + # Warn about returning objects of type Any when the function is + # declared with a precise type + self.warn_return_any = False + + # Report importing or using deprecated features as errors instead of notes. + self.report_deprecated_as_note = False + + # Allow deprecated calls from function coming from modules/packages + # in this list (each item effectively acts as a prefix match) + self.deprecated_calls_exclude: list[str] = [] + + # Warn about unused '# type: ignore' comments + self.warn_unused_ignores = False + + # Warn about unused '[mypy-]' or '[[tool.mypy.overrides]]' config sections + self.warn_unused_configs = False + + # Files in which to ignore all non-fatal errors + self.ignore_errors = False + + # Apply strict None checking + self.strict_optional = True + + # Show "note: In function "foo":" messages. + self.show_error_context = False + + # Use nicer output (when possible). + self.color_output = True + self.error_summary = True + + # Assume arguments with default values of None are Optional + self.implicit_optional = False + + # Don't re-export names unless they are imported with `from ... as ...` + self.implicit_reexport = True + + # Suppress toplevel errors caused by missing annotations + self.allow_untyped_globals = False + + # Allow variable to be redefined with an arbitrary type in the same block + # and the same nesting level as the initialization + self.allow_redefinition_old = False + + # Allow flexible variable redefinition with an arbitrary type, in different + # blocks and at different nesting levels + self.allow_redefinition_new = False + + # Prohibit equality, identity, and container checks for non-overlapping types. + # This makes 1 == '1', 1 in ['1'], and 1 is '1' errors. + self.strict_equality = False + + # Extend the logic of `strict_equality` to comparisons with `None`. + self.strict_equality_for_none = False + + # Disable treating bytearray and memoryview as subtypes of bytes + self.strict_bytes = False + + # Deprecated, use extra_checks instead. + self.strict_concatenate = False + + # Enable additional checks that are technically correct but impractical. + self.extra_checks = False + + # Report an error for any branches inferred to be unreachable as a result of + # type analysis. + self.warn_unreachable = False + + # Variable names considered True + self.always_true: list[str] = [] + + # Variable names considered False + self.always_false: list[str] = [] + + # Error codes to disable + self.disable_error_code: list[str] = [] + self.disabled_error_codes: set[ErrorCode] = set() + + # Error codes to enable + self.enable_error_code: list[str] = [] + self.enabled_error_codes: set[ErrorCode] = set() + + # Use script name instead of __main__ + self.scripts_are_modules = False + + # Config file name + self.config_file: str | None = None + + # A filename containing a JSON mapping from filenames to + # mtime/size/hash arrays, used to avoid having to recalculate + # source hashes as often. + self.quickstart_file: str | None = None + + # A comma-separated list of files/directories for mypy to type check; + # supports globbing + self.files: list[str] | None = None + + # A list of packages for mypy to type check + self.packages: list[str] | None = None + + # A list of modules for mypy to type check + self.modules: list[str] | None = None + + # Write junit.xml to given file + self.junit_xml: str | None = None + + self.junit_format: str = "global" # global|per_file + + # Caching and incremental checking options + self.incremental = True + self.cache_dir = defaults.CACHE_DIR + self.sqlite_cache = True + self.fixed_format_cache = True + self.debug_cache = False + self.skip_version_check = False + self.skip_cache_mtime_checks = False + self.fine_grained_incremental = False + # Include fine-grained dependencies in written cache files + self.cache_fine_grained = False + # Read cache files in fine-grained incremental mode (cache must include dependencies) + self.use_fine_grained_cache = False + + # Run tree.serialize() even if cache generation is disabled + self.debug_serialize = False + + # Tune certain behaviors when being used as a front-end to mypyc. Set per-module + # in modules being compiled. Not in the config file or command line. + self.mypyc = False + + # An internal flag to modify some type-checking logic while + # running inspections (e.g. don't expand function definitions). + # Not in the config file or command line. + self.inspections = False + + # Disable the memory optimization of freeing ASTs when + # possible. This isn't exposed as a command line option + # because it is intended for software integrating with + # mypy. (Like mypyc.) + self.preserve_asts = False + + # If True, function and class docstrings will be extracted and retained. + # This isn't exposed as a command line option + # because it is intended for software integrating with + # mypy. (Like stubgen.) + self.include_docstrings = False + + # Paths of user plugins + self.plugins: list[str] = [] + + # Per-module options (raw) + self.per_module_options: dict[str, dict[str, object]] = {} + self._glob_options: list[tuple[str, Pattern[str]]] = [] + self.unused_configs: set[str] = set() + + # -- development options -- + self.verbosity = 0 # More verbose messages (for troubleshooting) + self.pdb = False + self.show_traceback = False + self.raise_exceptions = False + self.dump_type_stats = False + self.dump_inference_stats = False + self.dump_build_stats = False + self.enable_incomplete_feature: list[str] = [] + self.timing_stats: str | None = None + self.line_checking_stats: str | None = None + + # -- test options -- + # Stop after the semantic analysis phase + self.semantic_analysis_only = False + + # Use stub builtins fixtures to speed up tests + self.use_builtins_fixtures = False + + # This should only be set when running certain mypy tests. + # Use this sparingly to avoid tests diverging from non-test behavior. + self.test_env = False + + # -- experimental options -- + self.num_workers: int = 0 + self.shadow_file: list[list[str]] | None = None + self.show_column_numbers: bool = False + self.show_error_end: bool = False + self.hide_error_codes = False + self.show_error_code_links = False + # This is an internal-only flag to simplify migrating test output. + self.reveal_verbose_types = False + # Use soft word wrap and show trimmed source snippets with error location markers. + self.pretty = False + self.dump_graph = False + self.dump_deps = False + self.logical_deps = False + # If True, partial types can't span a module top level and a function + self.local_partial_types = False + # If True, use the native parser (experimental) + self.native_parser = False + # Some behaviors are changed when using Bazel (https://bazel.build). + self.bazel = False + # If True, export inferred types for all expressions as BuildResult.types + self.export_types = False + # List of package roots -- directories under these are packages even + # if they don't have __init__.py. + self.package_root: list[str] = [] + self.cache_map: dict[str, tuple[str, str]] = {} + # Don't properly free objects on exit, just kill the current process. + self.fast_exit = True + # fast path for finding modules from source set + self.fast_module_lookup = False + # Allow empty function bodies even if it is not safe, used for testing only. + self.allow_empty_bodies = False + # Used to transform source code before parsing if not None + # TODO: Make the type precise (AnyStr -> AnyStr) + self.transform_source: Callable[[Any], Any] | None = None + # Print full path to each file in the report. + self.show_absolute_path: bool = False + # Install missing stub packages if True + self.install_types = False + # Install missing stub packages in non-interactive mode (don't prompt for + # confirmation, and don't show any errors) + self.non_interactive = False + # When we encounter errors that may cause many additional errors, + # skip most errors after this many messages have been reported. + # -1 means unlimited. + self.many_errors_threshold = defaults.MANY_ERRORS_THRESHOLD + # Disable new type inference algorithm. + self.old_type_inference = False + # Disable expression cache (for debugging). + self.disable_expression_cache = False + # Export line-level, limited, fine-grained dependency information in cache data + # (undocumented feature). + self.export_ref_info = False + # Treat special methods as being implicitly positional-only. + # Set to False when running stubtest. + self.pos_only_special_methods = True + + self.disable_bytearray_promotion = False + self.disable_memoryview_promotion = False + + # Sets custom output format + self.output: str | None = None + + # Output html file for mypyc -a + self.mypyc_annotation_file: str | None = None + # Skip writing C output files, but perform all other steps of a build (allows + # preserving manual tweaks to generated C file) + self.mypyc_skip_c_generation = False + + def use_star_unpack(self) -> bool: + return self.python_version >= (3, 11) or not self.reveal_verbose_types + + def snapshot(self) -> dict[str, object]: + """Produce a comparable snapshot of this Option""" + # Under mypyc, we don't have a __dict__, so we need to do worse things. + d = dict(getattr(self, "__dict__", ())) + for k in get_class_descriptors(Options): + if hasattr(self, k): + d[k] = getattr(self, k) + # Remove private attributes from snapshot + d = {k: v for k, v in d.items() if not k.startswith("_")} + return d + + def __repr__(self) -> str: + return f"Options({pprint.pformat(self.snapshot())})" + + def process_error_codes(self, *, error_callback: Callable[[str], Any]) -> None: + """Process `--enable-error-code` and `--disable-error-code` flags.""" + disabled_code_names = set(self.disable_error_code) + enabled_code_names = set(self.enable_error_code) + + valid_error_code_names = set(error_codes.keys()) + + invalid_code_names_here = ( + enabled_code_names | disabled_code_names + ) - valid_error_code_names + if invalid_code_names_here: + error_callback(f"Invalid error code(s): {', '.join(sorted(invalid_code_names_here))}") + + self.disabled_error_codes |= {error_codes[code] for code in disabled_code_names} + self.enabled_error_codes |= {error_codes[code] for code in enabled_code_names} + + # Enabling an error code always overrides disabling + self.disabled_error_codes -= self.enabled_error_codes + + def process_incomplete_features( + self, *, error_callback: Callable[[str], Any], warning_callback: Callable[[str], Any] + ) -> None: + # Validate incomplete features. + for feature in self.enable_incomplete_feature: + if feature not in INCOMPLETE_FEATURES | COMPLETE_FEATURES: + error_callback(f"Unknown incomplete feature: {feature}") + if feature in COMPLETE_FEATURES: + warning_callback(f"Warning: {feature} is already enabled by default") + + def process_strict_bytes(self) -> None: + # Sync `--strict-bytes` and `--disable-{bytearray,memoryview}-promotion` + if self.strict_bytes: + # backwards compatibility + self.disable_bytearray_promotion = True + self.disable_memoryview_promotion = True + elif self.disable_bytearray_promotion and self.disable_memoryview_promotion: + # forwards compatibility + self.strict_bytes = True + + def apply_changes(self, changes: dict[str, object]) -> Options: + # Note: effects of this method *must* be idempotent. + new_options = Options() + # Under mypyc, we don't have a __dict__, so we need to do worse things. + replace_object_state(new_options, self, copy_dict=True) + for key, value in changes.items(): + setattr(new_options, key, value) + if changes.get("ignore_missing_imports"): + # This is the only option for which a per-module and a global + # option sometimes beheave differently. + new_options.ignore_missing_imports_per_module = True + + # These two act as overrides, so apply them when cloning. + # Similar to global codes enabling overrides disabling, so we start from latter. + new_options.disabled_error_codes = self.disabled_error_codes.copy() + new_options.enabled_error_codes = self.enabled_error_codes.copy() + for code_str in new_options.disable_error_code: + code = error_codes[code_str] + new_options.disabled_error_codes.add(code) + new_options.enabled_error_codes.discard(code) + for code_str in new_options.enable_error_code: + code = error_codes[code_str] + new_options.enabled_error_codes.add(code) + new_options.disabled_error_codes.discard(code) + return new_options + + def compare_stable(self, other_snapshot: dict[str, object]) -> bool: + """Compare options in a way that is stable for snapshot() -> apply_changes() roundtrip. + + This is needed because apply_changes() has non-trivial effects for some flags, so + Options().apply_changes(options.snapshot()) may result in a (slightly) different object. + """ + return ( + Options().apply_changes(self.snapshot()).snapshot() + == Options().apply_changes(other_snapshot).snapshot() + ) + + def build_per_module_cache(self) -> None: + self._per_module_cache = {} + + # Config precedence is as follows: + # 1. Concrete section names: foo.bar.baz + # 2. "Unstructured" glob patterns: foo.*.baz, in the order + # they appear in the file (last wins) + # 3. "Well-structured" wildcard patterns: foo.bar.*, in specificity order. + + # Since structured configs inherit from structured configs above them in the hierarchy, + # we need to process per-module configs in a careful order. + # We have to process foo.* before foo.bar.* before foo.bar, + # and we need to apply *.bar to foo.bar but not to foo.bar.*. + # To do this, process all well-structured glob configs before non-glob configs and + # exploit the fact that foo.* sorts earlier ASCIIbetically (unicodebetically?) + # than foo.bar.*. + # (A section being "processed last" results in its config "winning".) + # Unstructured glob configs are stored and are all checked for each module. + unstructured_glob_keys = [k for k in self.per_module_options.keys() if "*" in k[:-1]] + structured_keys = [k for k in self.per_module_options.keys() if "*" not in k[:-1]] + wildcards = sorted(k for k in structured_keys if k.endswith(".*")) + concrete = [k for k in structured_keys if not k.endswith(".*")] + + for glob in unstructured_glob_keys: + self._glob_options.append((glob, self.compile_glob(glob))) + + # We (for ease of implementation) treat unstructured glob + # sections as used if any real modules use them or if any + # concrete config sections use them. This means we need to + # track which get used while constructing. + self.unused_configs = set(unstructured_glob_keys) + + for key in wildcards + concrete: + # Find what the options for this key would be, just based + # on inheriting from parent configs. + options = self.clone_for_module(key) + # And then update it with its per-module options. + self._per_module_cache[key] = options.apply_changes(self.per_module_options[key]) + + # Add the more structured sections into unused configs, since + # they only count as used if actually used by a real module. + self.unused_configs.update(structured_keys) + + def clone_for_module(self, module: str) -> Options: + """Create an Options object that incorporates per-module options. + + NOTE: Once this method is called all Options objects should be + considered read-only, else the caching might be incorrect. + """ + if self._per_module_cache is None: + self.build_per_module_cache() + assert self._per_module_cache is not None + + # If the module just directly has a config entry, use it. + if module in self._per_module_cache: + self.unused_configs.discard(module) + return self._per_module_cache[module] + + # If not, search for glob paths at all the parents. So if we are looking for + # options for foo.bar.baz, we search foo.bar.baz.*, foo.bar.*, foo.*, + # in that order, looking for an entry. + # This is technically quadratic in the length of the path, but module paths + # don't actually get all that long. + options = self + path = module.split(".") + for i in range(len(path), 0, -1): + key = ".".join(path[:i] + ["*"]) + if key in self._per_module_cache: + self.unused_configs.discard(key) + options = self._per_module_cache[key] + break + + # OK and *now* we need to look for unstructured glob matches. + # We only do this for concrete modules, not structured wildcards. + if not module.endswith(".*"): + for key, pattern in self._glob_options: + if pattern.match(module): + self.unused_configs.discard(key) + options = options.apply_changes(self.per_module_options[key]) + + # We could update the cache to directly point to modules once + # they have been looked up, but in testing this made things + # slower and not faster, so we don't bother. + + return options + + def compile_glob(self, s: str) -> Pattern[str]: + # Compile one of the glob patterns to a regex so that '.*' can + # match *zero or more* module sections. This means we compile + # '.*' into '(\..*)?'. + parts = s.split(".") + expr = re.escape(parts[0]) if parts[0] != "*" else ".*" + for part in parts[1:]: + expr += re.escape("." + part) if part != "*" else r"(\..*)?" + return re.compile(expr + "\\Z") + + def select_options_affecting_cache(self) -> tuple[str, list[object]]: + """Return (platform, [values...]) for options that affect the cache. + + The list contains values for OPTIONS_AFFECTING_CACHE_NO_PLATFORM + in sorted attribute name order. Keys are omitted since the cache + is invalidated when the mypy version changes, and keys are constant + on any specific mypy version. + """ + result: list[object] = [] + for opt in OPTIONS_AFFECTING_CACHE_NO_PLATFORM: + val = getattr(self, opt) + if opt in ("disabled_error_codes", "enabled_error_codes"): + val = sorted([code.code for code in val]) + result.append(val) + return self.platform, result + + def dep_import_options(self) -> bytes: + """Return opaque bytes with options that can affect dependent modules as well. + + The value can be compared for equality to detect changed options. + """ + buf = WriteBuffer() + write_bool(buf, self.ignore_missing_imports) + write_str(buf, self.follow_imports) + write_bool(buf, self.follow_imports_for_stubs) + return buf.getvalue() diff --git a/micromamba_root/Lib/site-packages/mypy/parse.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/parse.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..718249e1b815d0e930065e816565b81f8e4ae8c2 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/parse.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/parse.py b/micromamba_root/Lib/site-packages/mypy/parse.py new file mode 100644 index 0000000000000000000000000000000000000000..093653553137fb315250b1450916b8413d305555 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/parse.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +import os +import re + +from librt.internal import ReadBuffer + +from mypy import errorcodes as codes +from mypy.cache import read_int +from mypy.errors import Errors +from mypy.nodes import FileRawData, MypyFile +from mypy.options import Options + + +def parse( + source: str | bytes, + fnam: str, + module: str | None, + errors: Errors, + options: Options, + raise_on_error: bool = False, + imports_only: bool = False, +) -> MypyFile: + """Parse a source file, without doing any semantic analysis. + + Return the parse tree. If errors is not provided, raise ParseError + on failure. Otherwise, use the errors object to report parse errors. + + The python_version (major, minor) option determines the Python syntax variant. + """ + if options.native_parser: + # Native parser only works with actual files on disk + # Fall back to fastparse for in-memory source or non-existent files + if os.path.exists(fnam): + import mypy.nativeparse + + ignore_errors = options.ignore_errors or fnam in errors.ignored_files + # If errors are ignored, we can drop many function bodies to speed up type checking. + strip_function_bodies = ignore_errors and not options.preserve_asts + + errors.set_file(fnam, module, options=options) + tree, parse_errors, type_ignores = mypy.nativeparse.native_parse( + fnam, + options, + skip_function_bodies=strip_function_bodies, + imports_only=imports_only, + ) + # Convert type ignores list to dict + tree.ignored_lines = dict(type_ignores) + # Set is_stub based on file extension + tree.is_stub = fnam.endswith(".pyi") + # Note: tree.imports is populated directly by native_parse with deserialized + # import metadata, so we don't need to collect imports via AST traversal + + # Report parse errors + for error in parse_errors: + message = error["message"] + # Standardize error message by capitalizing the first word + message = re.sub(r"^(\s*\w)", lambda m: m.group(1).upper(), message) + # Respect blocker status from error, default to True for syntax errors + is_blocker = error.get("blocker", True) + error_code = error.get("code") + if error_code is None: + error_code = codes.SYNTAX + else: + # Fallback to [syntax] for backwards compatibility. + error_code = codes.error_codes.get(error_code) or codes.SYNTAX + errors.report( + error["line"], error["column"], message, blocker=is_blocker, code=error_code + ) + if raise_on_error and errors.is_errors(): + errors.raise_error() + return tree + # Fall through to fastparse for non-existent files + + assert not imports_only + if options.transform_source is not None: + source = options.transform_source(source) + import mypy.fastparse + + tree = mypy.fastparse.parse(source, fnam=fnam, module=module, errors=errors, options=options) + if raise_on_error and errors.is_errors(): + errors.raise_error() + return tree + + +def load_from_raw( + fnam: str, module: str | None, raw_data: FileRawData, errors: Errors, options: Options +) -> MypyFile: + """Load AST from parsed binary data. + + This essentially replicates parse() above but expects FileRawData instead of actually + parsing the source code in the file. + """ + from mypy.nativeparse import State, deserialize_imports, read_statements + + # This part mimics the logic in native_parse(). + data = ReadBuffer(raw_data.defs) + n = read_int(data) + state = State(options) + defs = read_statements(state, data, n) + imports = deserialize_imports(raw_data.imports) + + tree = MypyFile(defs, imports) + tree.path = fnam + tree.ignored_lines = raw_data.ignored_lines + tree.is_partial_stub_package = raw_data.is_partial_stub_package + tree.uses_template_strings = raw_data.uses_template_strings + tree.is_stub = fnam.endswith(".pyi") + + # Report parse errors, this replicates the logic in parse(). + all_errors = raw_data.raw_errors + state.errors + errors.set_file(fnam, module, options=options) + for error in all_errors: + message = error["message"] + message = re.sub(r"^(\s*\w)", lambda m: m.group(1).upper(), message) + is_blocker = error.get("blocker", True) + error_code = error.get("code") + if error_code is None: + error_code = codes.SYNTAX + else: + error_code = codes.error_codes.get(error_code) or codes.SYNTAX + # Note we never raise in this function, so it should not be called in coordinator. + errors.report(error["line"], error["column"], message, blocker=is_blocker, code=error_code) + return tree diff --git a/micromamba_root/Lib/site-packages/mypy/partially_defined.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/partially_defined.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..26a7e601ed5d3e220d830deafc9325e96e68bbbc Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/partially_defined.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/partially_defined.py b/micromamba_root/Lib/site-packages/mypy/partially_defined.py new file mode 100644 index 0000000000000000000000000000000000000000..2bff1669becbb5928efe70cf4cb9f7ef5c6ba4a5 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/partially_defined.py @@ -0,0 +1,703 @@ +from __future__ import annotations + +from enum import Enum + +from mypy import checker, errorcodes +from mypy.messages import MessageBuilder +from mypy.nodes import ( + AssertStmt, + AssignmentExpr, + AssignmentStmt, + BreakStmt, + ClassDef, + Context, + ContinueStmt, + DictionaryComprehension, + Expression, + ExpressionStmt, + ForStmt, + FuncDef, + FuncItem, + GeneratorExpr, + GlobalDecl, + IfStmt, + Import, + ImportFrom, + LambdaExpr, + ListExpr, + Lvalue, + MatchStmt, + MypyFile, + NameExpr, + NonlocalDecl, + RaiseStmt, + ReturnStmt, + StarExpr, + SymbolTable, + TryStmt, + TupleExpr, + TypeAliasStmt, + WhileStmt, + WithStmt, + implicit_module_attrs, +) +from mypy.options import Options +from mypy.patterns import AsPattern, StarredPattern +from mypy.reachability import ALWAYS_TRUE, infer_pattern_value +from mypy.traverser import ExtendedTraverserVisitor +from mypy.types import Type, UninhabitedType, get_proper_type + + +class BranchState: + """BranchState contains information about variable definition at the end of a branching statement. + `if` and `match` are examples of branching statements. + + `may_be_defined` contains variables that were defined in only some branches. + `must_be_defined` contains variables that were defined in all branches. + """ + + def __init__( + self, + must_be_defined: set[str] | None = None, + may_be_defined: set[str] | None = None, + skipped: bool = False, + ) -> None: + if may_be_defined is None: + may_be_defined = set() + if must_be_defined is None: + must_be_defined = set() + + self.may_be_defined = set(may_be_defined) + self.must_be_defined = set(must_be_defined) + self.skipped = skipped + + def copy(self) -> BranchState: + return BranchState( + must_be_defined=set(self.must_be_defined), + may_be_defined=set(self.may_be_defined), + skipped=self.skipped, + ) + + +class BranchStatement: + def __init__(self, initial_state: BranchState | None = None) -> None: + if initial_state is None: + initial_state = BranchState() + self.initial_state = initial_state + self.branches: list[BranchState] = [ + BranchState( + must_be_defined=self.initial_state.must_be_defined, + may_be_defined=self.initial_state.may_be_defined, + ) + ] + + def copy(self) -> BranchStatement: + result = BranchStatement(self.initial_state) + result.branches = [b.copy() for b in self.branches] + return result + + def next_branch(self) -> None: + self.branches.append( + BranchState( + must_be_defined=self.initial_state.must_be_defined, + may_be_defined=self.initial_state.may_be_defined, + ) + ) + + def record_definition(self, name: str) -> None: + assert len(self.branches) > 0 + self.branches[-1].must_be_defined.add(name) + self.branches[-1].may_be_defined.discard(name) + + def delete_var(self, name: str) -> None: + assert len(self.branches) > 0 + self.branches[-1].must_be_defined.discard(name) + self.branches[-1].may_be_defined.discard(name) + + def record_nested_branch(self, state: BranchState) -> None: + assert len(self.branches) > 0 + current_branch = self.branches[-1] + if state.skipped: + current_branch.skipped = True + return + current_branch.must_be_defined.update(state.must_be_defined) + current_branch.may_be_defined.update(state.may_be_defined) + current_branch.may_be_defined.difference_update(current_branch.must_be_defined) + + def skip_branch(self) -> None: + assert len(self.branches) > 0 + self.branches[-1].skipped = True + + def is_possibly_undefined(self, name: str) -> bool: + assert len(self.branches) > 0 + return name in self.branches[-1].may_be_defined + + def is_undefined(self, name: str) -> bool: + assert len(self.branches) > 0 + branch = self.branches[-1] + return name not in branch.may_be_defined and name not in branch.must_be_defined + + def is_defined_in_a_branch(self, name: str) -> bool: + assert len(self.branches) > 0 + for b in self.branches: + if name in b.must_be_defined or name in b.may_be_defined: + return True + return False + + def done(self) -> BranchState: + # First, compute all vars, including skipped branches. We include skipped branches + # because our goal is to capture all variables that semantic analyzer would + # consider defined. + all_vars = set() + for b in self.branches: + all_vars.update(b.may_be_defined) + all_vars.update(b.must_be_defined) + # For the rest of the things, we only care about branches that weren't skipped. + non_skipped_branches = [b for b in self.branches if not b.skipped] + if non_skipped_branches: + must_be_defined = non_skipped_branches[0].must_be_defined + for b in non_skipped_branches[1:]: + must_be_defined.intersection_update(b.must_be_defined) + else: + must_be_defined = set() + # Everything that wasn't defined in all branches but was defined + # in at least one branch should be in `may_be_defined`! + may_be_defined = all_vars.difference(must_be_defined) + return BranchState( + must_be_defined=must_be_defined, + may_be_defined=may_be_defined, + skipped=len(non_skipped_branches) == 0, + ) + + +class ScopeType(Enum): + Global = 1 + Class = 2 + Func = 3 + Generator = 4 + + +class Scope: + def __init__(self, stmts: list[BranchStatement], scope_type: ScopeType) -> None: + self.branch_stmts: list[BranchStatement] = stmts + self.scope_type = scope_type + self.undefined_refs: dict[str, set[NameExpr]] = {} + + def copy(self) -> Scope: + result = Scope([s.copy() for s in self.branch_stmts], self.scope_type) + result.undefined_refs = self.undefined_refs.copy() + return result + + def record_undefined_ref(self, o: NameExpr) -> None: + if o.name not in self.undefined_refs: + self.undefined_refs[o.name] = set() + self.undefined_refs[o.name].add(o) + + def pop_undefined_ref(self, name: str) -> set[NameExpr]: + return self.undefined_refs.pop(name, set()) + + +class DefinedVariableTracker: + """DefinedVariableTracker manages the state and scope for the UndefinedVariablesVisitor.""" + + def __init__(self) -> None: + # There's always at least one scope. Within each scope, there's at least one "global" BranchingStatement. + self.scopes: list[Scope] = [Scope([BranchStatement()], ScopeType.Global)] + # disable_branch_skip is used to disable skipping a branch due to a return/raise/etc. This is useful + # in things like try/except/finally statements. + self.disable_branch_skip = False + self.in_finally = False + + def copy(self) -> DefinedVariableTracker: + result = DefinedVariableTracker() + result.scopes = [s.copy() for s in self.scopes] + result.disable_branch_skip = self.disable_branch_skip + result.in_finally = self.in_finally + return result + + def _scope(self) -> Scope: + assert len(self.scopes) > 0 + return self.scopes[-1] + + def enter_scope(self, scope_type: ScopeType) -> None: + assert len(self._scope().branch_stmts) > 0 + initial_state = None + if scope_type == ScopeType.Generator: + # Generators are special because they inherit the outer scope. + initial_state = self._scope().branch_stmts[-1].branches[-1] + self.scopes.append(Scope([BranchStatement(initial_state)], scope_type)) + + def exit_scope(self) -> None: + self.scopes.pop() + + def in_scope(self, scope_type: ScopeType) -> bool: + return self._scope().scope_type == scope_type + + def start_branch_statement(self) -> None: + assert len(self._scope().branch_stmts) > 0 + self._scope().branch_stmts.append( + BranchStatement(self._scope().branch_stmts[-1].branches[-1]) + ) + + def next_branch(self) -> None: + assert len(self._scope().branch_stmts) > 1 + self._scope().branch_stmts[-1].next_branch() + + def end_branch_statement(self) -> None: + assert len(self._scope().branch_stmts) > 1 + result = self._scope().branch_stmts.pop().done() + self._scope().branch_stmts[-1].record_nested_branch(result) + + def skip_branch(self) -> None: + # Only skip branch if we're outside of "root" branch statement. + if len(self._scope().branch_stmts) > 1 and not self.disable_branch_skip: + self._scope().branch_stmts[-1].skip_branch() + + def record_definition(self, name: str) -> None: + assert len(self.scopes) > 0 + assert len(self.scopes[-1].branch_stmts) > 0 + self._scope().branch_stmts[-1].record_definition(name) + + def delete_var(self, name: str) -> None: + assert len(self.scopes) > 0 + assert len(self.scopes[-1].branch_stmts) > 0 + self._scope().branch_stmts[-1].delete_var(name) + + def record_undefined_ref(self, o: NameExpr) -> None: + """Records an undefined reference. These can later be retrieved via `pop_undefined_ref`.""" + assert len(self.scopes) > 0 + self._scope().record_undefined_ref(o) + + def pop_undefined_ref(self, name: str) -> set[NameExpr]: + """If name has previously been reported as undefined, the NameExpr that was called will be returned.""" + assert len(self.scopes) > 0 + return self._scope().pop_undefined_ref(name) + + def is_possibly_undefined(self, name: str) -> bool: + assert len(self._scope().branch_stmts) > 0 + # A variable is undefined if it's in a set of `may_be_defined` but not in `must_be_defined`. + return self._scope().branch_stmts[-1].is_possibly_undefined(name) + + def is_defined_in_different_branch(self, name: str) -> bool: + """This will return true if a variable is defined in a branch that's not the current branch.""" + assert len(self._scope().branch_stmts) > 0 + stmt = self._scope().branch_stmts[-1] + if not stmt.is_undefined(name): + return False + for stmt in self._scope().branch_stmts: + if stmt.is_defined_in_a_branch(name): + return True + return False + + def is_undefined(self, name: str) -> bool: + assert len(self._scope().branch_stmts) > 0 + return self._scope().branch_stmts[-1].is_undefined(name) + + +class Loop: + def __init__(self) -> None: + self.has_break = False + # variables defined in every loop branch with `break` + self.break_vars: set[str] | None = None + + +class PossiblyUndefinedVariableVisitor(ExtendedTraverserVisitor): + """Detects the following cases: + - A variable that's defined only part of the time. + - If a variable is used before definition + + An example of a partial definition: + if foo(): + x = 1 + print(x) # Error: "x" may be undefined. + + Example of a used before definition: + x = y + y: int = 2 + + Note that this code does not detect variables not defined in any of the branches -- that is + handled by the semantic analyzer. + """ + + def __init__( + self, + msg: MessageBuilder, + type_map: dict[Expression, Type], + options: Options, + names: SymbolTable, + ) -> None: + self.msg = msg + self.type_map = type_map + self.options = options + self.builtins = SymbolTable() + builtins_mod = names.get("__builtins__", None) + if builtins_mod: + assert isinstance(builtins_mod.node, MypyFile) + self.builtins = builtins_mod.node.names + self.loops: list[Loop] = [] + self.try_depth = 0 + self.tracker = DefinedVariableTracker() + for name in implicit_module_attrs: + self.tracker.record_definition(name) + + def var_used_before_def(self, name: str, context: Context) -> None: + if self.msg.errors.is_error_code_enabled(errorcodes.USED_BEFORE_DEF): + self.msg.var_used_before_def(name, context) + + def variable_may_be_undefined(self, name: str, context: Context) -> None: + if self.msg.errors.is_error_code_enabled(errorcodes.POSSIBLY_UNDEFINED): + self.msg.variable_may_be_undefined(name, context) + + def process_definition(self, name: str) -> None: + # Was this name previously used? If yes, it's a used-before-definition error. + if not self.tracker.in_scope(ScopeType.Class): + refs = self.tracker.pop_undefined_ref(name) + for ref in refs: + if self.loops: + self.variable_may_be_undefined(name, ref) + else: + self.var_used_before_def(name, ref) + else: + # Errors in class scopes are caught by the semantic analyzer. + pass + self.tracker.record_definition(name) + + def visit_global_decl(self, o: GlobalDecl) -> None: + for name in o.names: + self.process_definition(name) + super().visit_global_decl(o) + + def visit_nonlocal_decl(self, o: NonlocalDecl) -> None: + for name in o.names: + self.process_definition(name) + super().visit_nonlocal_decl(o) + + def process_lvalue(self, lvalue: Lvalue | None) -> None: + if isinstance(lvalue, NameExpr): + self.process_definition(lvalue.name) + elif isinstance(lvalue, StarExpr): + self.process_lvalue(lvalue.expr) + elif isinstance(lvalue, (ListExpr, TupleExpr)): + for item in lvalue.items: + self.process_lvalue(item) + + def visit_assignment_stmt(self, o: AssignmentStmt) -> None: + for lvalue in o.lvalues: + self.process_lvalue(lvalue) + super().visit_assignment_stmt(o) + + def visit_assignment_expr(self, o: AssignmentExpr) -> None: + o.value.accept(self) + self.process_lvalue(o.target) + + def visit_if_stmt(self, o: IfStmt) -> None: + for e in o.expr: + e.accept(self) + self.tracker.start_branch_statement() + for b in o.body: + if b.is_unreachable: + continue + b.accept(self) + self.tracker.next_branch() + if o.unreachable_else: + self.tracker.skip_branch() + elif o.else_body: + if o.else_body.is_unreachable: + self.tracker.skip_branch() + else: + o.else_body.accept(self) + self.tracker.end_branch_statement() + + def visit_match_stmt(self, o: MatchStmt) -> None: + o.subject.accept(self) + self.tracker.start_branch_statement() + for i in range(len(o.patterns)): + pattern = o.patterns[i] + pattern.accept(self) + guard = o.guards[i] + if guard is not None: + guard.accept(self) + if not o.bodies[i].is_unreachable: + o.bodies[i].accept(self) + else: + self.tracker.skip_branch() + is_catchall = infer_pattern_value(pattern) == ALWAYS_TRUE + if not is_catchall: + self.tracker.next_branch() + self.tracker.end_branch_statement() + + def visit_func_def(self, o: FuncDef) -> None: + self.process_definition(o.name) + super().visit_func_def(o) + + def visit_func(self, o: FuncItem) -> None: + if o.is_dynamic() and not self.options.check_untyped_defs: + return + + args = o.arguments or [] + # Process initializers (defaults) outside the function scope. + for arg in args: + if arg.initializer is not None: + arg.initializer.accept(self) + + self.tracker.enter_scope(ScopeType.Func) + for arg in args: + self.process_definition(arg.variable.name) + super().visit_var(arg.variable) + o.body.accept(self) + self.tracker.exit_scope() + + def visit_generator_expr(self, o: GeneratorExpr) -> None: + self.tracker.enter_scope(ScopeType.Generator) + for idx in o.indices: + self.process_lvalue(idx) + super().visit_generator_expr(o) + self.tracker.exit_scope() + + def visit_dictionary_comprehension(self, o: DictionaryComprehension) -> None: + self.tracker.enter_scope(ScopeType.Generator) + for idx in o.indices: + self.process_lvalue(idx) + super().visit_dictionary_comprehension(o) + self.tracker.exit_scope() + + def visit_for_stmt(self, o: ForStmt) -> None: + o.expr.accept(self) + self.process_lvalue(o.index) + o.index.accept(self) + self.tracker.start_branch_statement() + loop = Loop() + self.loops.append(loop) + o.body.accept(self) + self.tracker.next_branch() + self.tracker.end_branch_statement() + if o.else_body is not None: + # If the loop has a `break` inside, `else` is executed conditionally. + # If the loop doesn't have a `break` either the function will return or + # execute the `else`. + has_break = loop.has_break + if has_break: + self.tracker.start_branch_statement() + if loop.break_vars is not None: + for bv in loop.break_vars: + self.tracker.record_definition(bv) + self.tracker.next_branch() + o.else_body.accept(self) + if has_break: + self.tracker.end_branch_statement() + self.loops.pop() + + def visit_return_stmt(self, o: ReturnStmt) -> None: + super().visit_return_stmt(o) + self.tracker.skip_branch() + + def visit_lambda_expr(self, o: LambdaExpr) -> None: + self.tracker.enter_scope(ScopeType.Func) + super().visit_lambda_expr(o) + self.tracker.exit_scope() + + def visit_assert_stmt(self, o: AssertStmt) -> None: + super().visit_assert_stmt(o) + if checker.is_false_literal(o.expr): + self.tracker.skip_branch() + + def visit_raise_stmt(self, o: RaiseStmt) -> None: + super().visit_raise_stmt(o) + self.tracker.skip_branch() + + def visit_continue_stmt(self, o: ContinueStmt) -> None: + super().visit_continue_stmt(o) + self.tracker.skip_branch() + + def visit_break_stmt(self, o: BreakStmt) -> None: + super().visit_break_stmt(o) + if self.loops: + self.loops[-1].has_break = True + # Track variables that are definitely defined at the point of break + if len(self.tracker._scope().branch_stmts) > 0: + branch = self.tracker._scope().branch_stmts[-1].branches[-1] + if self.loops[-1].break_vars is None: + self.loops[-1].break_vars = set(branch.must_be_defined) + else: + # we only want variables that have been defined in each branch + self.loops[-1].break_vars.intersection_update(branch.must_be_defined) + self.tracker.skip_branch() + + def visit_expression_stmt(self, o: ExpressionStmt) -> None: + typ = self.type_map.get(o.expr) + if typ is None or isinstance(get_proper_type(typ), UninhabitedType): + self.tracker.skip_branch() + super().visit_expression_stmt(o) + + def visit_try_stmt(self, o: TryStmt) -> None: + """ + Note that finding undefined vars in `finally` requires different handling from + the rest of the code. In particular, we want to disallow skipping branches due to jump + statements in except/else clauses for finally but not for other cases. Imagine a case like: + def f() -> int: + try: + x = 1 + except: + # This jump statement needs to be handled differently depending on whether or + # not we're trying to process `finally` or not. + return 0 + finally: + # `x` may be undefined here. + pass + # `x` is always defined here. + return x + """ + self.try_depth += 1 + if o.finally_body is not None: + # In order to find undefined vars in `finally`, we need to + # process try/except with branch skipping disabled. However, for the rest of the code + # after finally, we need to process try/except with branch skipping enabled. + # Therefore, we need to process try/finally twice. + # Because processing is not idempotent, we should make a copy of the tracker. + old_tracker = self.tracker.copy() + self.tracker.disable_branch_skip = True + self.process_try_stmt(o) + self.tracker = old_tracker + self.process_try_stmt(o) + self.try_depth -= 1 + + def process_try_stmt(self, o: TryStmt) -> None: + """ + Processes try statement decomposing it into the following: + if ...: + body + else_body + elif ...: + except 1 + elif ...: + except 2 + else: + except n + finally + """ + self.tracker.start_branch_statement() + o.body.accept(self) + if o.else_body is not None: + o.else_body.accept(self) + if len(o.handlers) > 0: + assert len(o.handlers) == len(o.vars) == len(o.types) + for i in range(len(o.handlers)): + self.tracker.next_branch() + exc_type = o.types[i] + if exc_type is not None: + exc_type.accept(self) + var = o.vars[i] + if var is not None: + self.process_definition(var.name) + var.accept(self) + o.handlers[i].accept(self) + if var is not None: + self.tracker.delete_var(var.name) + self.tracker.end_branch_statement() + + if o.finally_body is not None: + self.tracker.in_finally = True + o.finally_body.accept(self) + self.tracker.in_finally = False + + def visit_while_stmt(self, o: WhileStmt) -> None: + o.expr.accept(self) + self.tracker.start_branch_statement() + loop = Loop() + self.loops.append(loop) + o.body.accept(self) + has_break = loop.has_break + if not checker.is_true_literal(o.expr): + # If this is a loop like `while True`, we can consider the body to be + # a single branch statement (we're guaranteed that the body is executed at least once). + # If not, call next_branch() to make all variables defined there conditional. + self.tracker.next_branch() + self.tracker.end_branch_statement() + if o.else_body is not None: + # If the loop has a `break` inside, `else` is executed conditionally. + # If the loop doesn't have a `break` either the function will return or + # execute the `else`. + if has_break: + self.tracker.start_branch_statement() + self.tracker.next_branch() + if o.else_body: + o.else_body.accept(self) + if has_break: + self.tracker.end_branch_statement() + self.loops.pop() + + def visit_as_pattern(self, o: AsPattern) -> None: + if o.name is not None: + self.process_lvalue(o.name) + super().visit_as_pattern(o) + + def visit_starred_pattern(self, o: StarredPattern) -> None: + if o.capture is not None: + self.process_lvalue(o.capture) + super().visit_starred_pattern(o) + + def visit_name_expr(self, o: NameExpr) -> None: + if o.name in self.builtins and self.tracker.in_scope(ScopeType.Global): + return + if ( + self.tracker.is_possibly_undefined(o.name) + and self.tracker.in_finally == self.tracker.disable_branch_skip + ): + # A variable is only defined in some branches. + self.variable_may_be_undefined(o.name, o) + # We don't want to report the error on the same variable multiple times. + self.tracker.record_definition(o.name) + elif self.tracker.is_defined_in_different_branch(o.name): + # A variable is defined in one branch but used in a different branch. + if self.loops or self.try_depth > 0: + # If we're in a loop or in a try, we can't be sure that this variable + # is undefined. Report it as "may be undefined". + self.variable_may_be_undefined(o.name, o) + else: + self.var_used_before_def(o.name, o) + elif self.tracker.is_undefined(o.name): + # A variable is undefined. It could be due to two things: + # 1. A variable is just totally undefined + # 2. The variable is defined later in the code. + # Case (1) will be caught by semantic analyzer. Case (2) is a forward ref that should + # be caught by this visitor. Save the ref for later, so that if we see a definition, + # we know it's a used-before-definition scenario. + self.tracker.record_undefined_ref(o) + super().visit_name_expr(o) + + def visit_with_stmt(self, o: WithStmt) -> None: + for expr, idx in zip(o.expr, o.target): + expr.accept(self) + self.process_lvalue(idx) + o.body.accept(self) + + def visit_class_def(self, o: ClassDef) -> None: + self.process_definition(o.name) + self.tracker.enter_scope(ScopeType.Class) + super().visit_class_def(o) + self.tracker.exit_scope() + + def visit_import(self, o: Import) -> None: + for mod, alias in o.ids: + if alias is not None: + self.tracker.record_definition(alias) + else: + # When you do `import x.y`, only `x` becomes defined. + names = mod.split(".") + if names: + # `names` should always be nonempty, but we don't want mypy + # to crash on invalid code. + self.tracker.record_definition(names[0]) + super().visit_import(o) + + def visit_import_from(self, o: ImportFrom) -> None: + for mod, alias in o.names: + name = alias + if name is None: + name = mod + self.tracker.record_definition(name) + super().visit_import_from(o) + + def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None: + # Type alias target may contain forward references + self.tracker.record_definition(o.name.name) diff --git a/micromamba_root/Lib/site-packages/mypy/patterns.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/patterns.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..0c7fa1a4e9bf5b43f3a0221908b384676e109052 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/patterns.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/patterns.py b/micromamba_root/Lib/site-packages/mypy/patterns.py new file mode 100644 index 0000000000000000000000000000000000000000..a01bf6acc87669fb1c9a990437c8209f193d2eae --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/patterns.py @@ -0,0 +1,150 @@ +"""Classes for representing match statement patterns.""" + +from __future__ import annotations + +from typing import TypeVar + +from mypy_extensions import trait + +from mypy.nodes import Expression, NameExpr, Node, RefExpr +from mypy.visitor import PatternVisitor + +T = TypeVar("T") + + +@trait +class Pattern(Node): + """A pattern node.""" + + __slots__ = () + + def accept(self, visitor: PatternVisitor[T]) -> T: + raise RuntimeError("Not implemented", type(self)) + + +class AsPattern(Pattern): + """The pattern as """ + + # The python ast, and therefore also our ast merges capture, wildcard and as patterns into one + # for easier handling. + # If pattern is None this is a capture pattern. If name and pattern are both none this is a + # wildcard pattern. + # Only name being None should not happen but also won't break anything. + pattern: Pattern | None + name: NameExpr | None + + def __init__(self, pattern: Pattern | None, name: NameExpr | None) -> None: + super().__init__() + self.pattern = pattern + self.name = name + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_as_pattern(self) + + +class OrPattern(Pattern): + """The pattern | | ...""" + + patterns: list[Pattern] + + def __init__(self, patterns: list[Pattern]) -> None: + super().__init__() + self.patterns = patterns + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_or_pattern(self) + + +class ValuePattern(Pattern): + """The pattern x.y (or x.y.z, ...)""" + + expr: Expression + + def __init__(self, expr: Expression) -> None: + super().__init__() + self.expr = expr + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_value_pattern(self) + + +class SingletonPattern(Pattern): + # This can be exactly True, False or None + value: bool | None + + def __init__(self, value: bool | None) -> None: + super().__init__() + self.value = value + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_singleton_pattern(self) + + +class SequencePattern(Pattern): + """The pattern [, ...]""" + + patterns: list[Pattern] + + def __init__(self, patterns: list[Pattern]) -> None: + super().__init__() + self.patterns = patterns + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_sequence_pattern(self) + + +class StarredPattern(Pattern): + # None corresponds to *_ in a list pattern. It will match multiple items but won't bind them to + # a name. + capture: NameExpr | None + + def __init__(self, capture: NameExpr | None) -> None: + super().__init__() + self.capture = capture + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_starred_pattern(self) + + +class MappingPattern(Pattern): + keys: list[Expression] + values: list[Pattern] + rest: NameExpr | None + + def __init__( + self, keys: list[Expression], values: list[Pattern], rest: NameExpr | None + ) -> None: + super().__init__() + assert len(keys) == len(values) + self.keys = keys + self.values = values + self.rest = rest + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_mapping_pattern(self) + + +class ClassPattern(Pattern): + """The pattern Cls(...)""" + + class_ref: RefExpr + positionals: list[Pattern] + keyword_keys: list[str] + keyword_values: list[Pattern] + + def __init__( + self, + class_ref: RefExpr, + positionals: list[Pattern], + keyword_keys: list[str], + keyword_values: list[Pattern], + ) -> None: + super().__init__() + assert len(keyword_keys) == len(keyword_values) + self.class_ref = class_ref + self.positionals = positionals + self.keyword_keys = keyword_keys + self.keyword_values = keyword_values + + def accept(self, visitor: PatternVisitor[T]) -> T: + return visitor.visit_class_pattern(self) diff --git a/micromamba_root/Lib/site-packages/mypy/plugin.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/plugin.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..de9839bafd04786d9509294791c0ddabce73ae83 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/plugin.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/plugin.py b/micromamba_root/Lib/site-packages/mypy/plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..383b07af87c0dbb313caf55efcb76c443318d290 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/plugin.py @@ -0,0 +1,928 @@ +"""Plugin system for extending mypy. + +At large scale the plugin system works as following: + +* Plugins are collected from the corresponding mypy config file option + (either via paths to Python files, or installed Python modules) + and imported using importlib. + +* Every module should get an entry point function (called 'plugin' by default, + but may be overridden in the config file) that should accept a single string + argument that is a full mypy version (includes git commit hash for dev + versions) and return a subclass of mypy.plugins.Plugin. + +* All plugin class constructors should match the signature of mypy.plugin.Plugin + (i.e. should accept an mypy.options.Options object), and *must* call + super().__init__(). + +* At several steps during semantic analysis and type checking mypy calls + special `get_xxx` methods on user plugins with a single string argument that + is a fully qualified name (full name) of a relevant definition + (see mypy.plugin.Plugin method docstrings for details). + +* The plugins are called in the order they are passed in the config option. + Every plugin must decide whether to act on a given full name. The first + plugin that returns non-None object will be used. + +* The above decision should be made using the limited common API specified by + mypy.plugin.CommonPluginApi. + +* The callback returned by the plugin will be called with a larger context that + includes relevant current state (e.g. a default return type, or a default + attribute type) and a wider relevant API provider (e.g. + SemanticAnalyzerPluginInterface or CheckerPluginInterface). + +* The result of this is used for further processing. See various `XxxContext` + named tuples for details about which information is given to each hook. + +Plugin developers should ensure that their plugins work well in incremental and +daemon modes. In particular, plugins should not hold global state, and should +always call add_plugin_dependency() in plugin hooks called during semantic +analysis. See the method docstring for more details. + +There is no dedicated cache storage for plugins, but plugins can store +per-TypeInfo data in a special .metadata attribute that is serialized to the +mypy caches between incremental runs. To avoid collisions between plugins, they +are encouraged to store their state under a dedicated key coinciding with +plugin name in the metadata dictionary. Every value stored there must be +JSON-serializable. + +## Notes about the semantic analyzer + +Mypy 0.710 introduced a new semantic analyzer that changed how plugins are +expected to work in several notable ways (from mypy 0.730 the old semantic +analyzer is no longer available): + +1. The order of processing AST nodes in modules is different. The old semantic + analyzer processed modules in textual order, one module at a time. The new + semantic analyzer first processes the module top levels, including bodies of + any top-level classes and classes nested within classes. ("Top-level" here + means "not nested within a function/method".) Functions and methods are + processed only after module top levels have been finished. If there is an + import cycle, all module top levels in the cycle are processed before + processing any functions or methods. Each unit of processing (a module top + level or a function/method) is called a *target*. + + This also means that function signatures in the same module have not been + analyzed yet when analyzing the module top level. If you need access to + a function signature, you'll need to explicitly analyze the signature first + using `anal_type()`. + +2. Each target can be processed multiple times. This may happen if some forward + references are not ready yet, for example. This means that semantic analyzer + related plugin hooks can be called multiple times for the same full name. + These plugin methods must thus be idempotent. + +3. The `anal_type` API function returns None if some part of the type is not + available yet. If this happens, the current target being analyzed will be + *deferred*, which means that it will be processed again soon, in the hope + that additional dependencies will be available. This may happen if there are + forward references to types or inter-module references to types within an + import cycle. + + Note that if there is a circular definition, mypy may decide to stop + processing to avoid an infinite number of iterations. When this happens, + `anal_type` will generate an error and return an `AnyType` type object + during the final iteration (instead of None). + +4. There is a new API method `defer()`. This can be used to explicitly request + the current target to be reprocessed one more time. You don't need this + to call this if `anal_type` returns None, however. + +5. There is a new API property `final_iteration`, which is true once mypy + detected no progress during the previous iteration or if the maximum + semantic analysis iteration count has been reached. You must never + defer during the final iteration, as it will cause a crash. + +6. The `node` attribute of SymbolTableNode objects may contain a reference to + a PlaceholderNode object. This object means that this definition has not + been fully processed yet. If you encounter a PlaceholderNode, you should + defer unless it's the final iteration. If it's the final iteration, you + should generate an error message. It usually means that there's a cyclic + definition that cannot be resolved by mypy. PlaceholderNodes can only refer + to references inside an import cycle. If you are looking up things from + another module, such as the builtins, that is outside the current module or + import cycle, you can safely assume that you won't receive a placeholder. + +When testing your plugin, you should have a test case that forces a module top +level to be processed multiple times. The easiest way to do this is to include +a forward reference to a class in a top-level annotation. Example: + + c: C # Forward reference causes second analysis pass + class C: pass + +Note that a forward reference in a function signature won't trigger another +pass, since all functions are processed only after the top level has been fully +analyzed. +""" + +from __future__ import annotations + +from abc import abstractmethod +from collections.abc import Callable +from typing import TYPE_CHECKING, Any, NamedTuple, TypeVar + +from mypy_extensions import mypyc_attr, trait + +from mypy.errorcodes import ErrorCode +from mypy.errors import ErrorInfo +from mypy.lookup import lookup_fully_qualified +from mypy.message_registry import ErrorMessage +from mypy.nodes import ( + ArgKind, + CallExpr, + ClassDef, + Context, + Expression, + MypyFile, + SymbolTableNode, + TypeInfo, +) +from mypy.options import Options +from mypy.types import ( + CallableType, + FunctionLike, + Instance, + ProperType, + Type, + TypeList, + UnboundType, +) + +if TYPE_CHECKING: + from mypy.messages import MessageBuilder + from mypy.tvar_scope import TypeVarLikeScope + + +@trait +class TypeAnalyzerPluginInterface: + """Interface for accessing semantic analyzer functionality in plugins. + + Methods docstrings contain only basic info. Look for corresponding implementation + docstrings in typeanal.py for more details. + """ + + # An options object. Note: these are the cloned options for the current file. + # This might be different from Plugin.options (that contains default/global options) + # if there are per-file options in the config. This applies to all other interfaces + # in this file. + options: Options + + @abstractmethod + def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + """Emit an error message at given location.""" + raise NotImplementedError + + @abstractmethod + def named_type(self, fullname: str, args: list[Type], /) -> Instance: + """Construct an instance of a builtin type with given name.""" + raise NotImplementedError + + @abstractmethod + def analyze_type(self, typ: Type, /) -> Type: + """Analyze an unbound type using the default mypy logic.""" + raise NotImplementedError + + @abstractmethod + def analyze_callable_args( + self, arglist: TypeList + ) -> tuple[list[Type], list[ArgKind], list[str | None]] | None: + """Find types, kinds, and names of arguments from extended callable syntax.""" + raise NotImplementedError + + +# A context for a hook that semantically analyzes an unbound type. +class AnalyzeTypeContext(NamedTuple): + type: UnboundType # Type to analyze + context: Context # Relevant location context (e.g. for error messages) + api: TypeAnalyzerPluginInterface + + +@mypyc_attr(allow_interpreted_subclasses=True) +class CommonPluginApi: + """ + A common plugin API (shared between semantic analysis and type checking phases) + that all plugin hooks get independently of the context. + """ + + # Global mypy options. + # Per-file options can be only accessed on various + # XxxPluginInterface classes. + options: Options + + @abstractmethod + def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode | None: + """Lookup a symbol by its full name (including module). + + This lookup function available for all plugins. Return None if a name + is not found. This function doesn't support lookup from current scope. + Use SemanticAnalyzerPluginInterface.lookup_qualified() for this.""" + raise NotImplementedError + + +@trait +class CheckerPluginInterface: + """Interface for accessing type checker functionality in plugins. + + Methods docstrings contain only basic info. Look for corresponding implementation + docstrings in checker.py for more details. + """ + + msg: MessageBuilder + options: Options + path: str + + # Type context for type inference + @property + @abstractmethod + def type_context(self) -> list[Type | None]: + """Return the type context of the plugin""" + raise NotImplementedError + + @abstractmethod + def fail( + self, msg: str | ErrorMessage, ctx: Context, /, *, code: ErrorCode | None = None + ) -> ErrorInfo | None: + """Emit an error message at given location.""" + raise NotImplementedError + + @abstractmethod + def named_generic_type(self, name: str, args: list[Type]) -> Instance: + """Construct an instance of a generic type with given type arguments.""" + raise NotImplementedError + + @abstractmethod + def get_expression_type(self, node: Expression, type_context: Type | None = None) -> Type: + """Checks the type of the given expression.""" + raise NotImplementedError + + +@trait +class SemanticAnalyzerPluginInterface: + """Interface for accessing semantic analyzer functionality in plugins. + + Methods docstrings contain only basic info. Look for corresponding implementation + docstrings in semanal.py for more details. + + # TODO: clean-up lookup functions. + """ + + modules: dict[str, MypyFile] + # Options for current file. + options: Options + cur_mod_id: str + msg: MessageBuilder + + @abstractmethod + def named_type(self, fullname: str, args: list[Type] | None = None) -> Instance: + """Construct an instance of a builtin type with given type arguments.""" + raise NotImplementedError + + @abstractmethod + def builtin_type(self, fully_qualified_name: str) -> Instance: + """Legacy function -- use named_type() instead.""" + # NOTE: Do not delete this since many plugins may still use it. + raise NotImplementedError + + @abstractmethod + def named_type_or_none(self, fullname: str, args: list[Type] | None = None) -> Instance | None: + """Construct an instance of a type with given type arguments. + + Return None if a type could not be constructed for the qualified + type name. This is possible when the qualified name includes a + module name and the module has not been imported. + """ + raise NotImplementedError + + @abstractmethod + def basic_new_typeinfo(self, name: str, basetype_or_fallback: Instance, line: int) -> TypeInfo: + raise NotImplementedError + + @abstractmethod + def parse_bool(self, expr: Expression) -> bool | None: + """Parse True/False literals.""" + raise NotImplementedError + + @abstractmethod + def parse_str_literal(self, expr: Expression) -> str | None: + """Parse string literals.""" + + @abstractmethod + def fail( + self, + msg: str, + ctx: Context, + serious: bool = False, + *, + blocker: bool = False, + code: ErrorCode | None = None, + ) -> None: + """Emit an error message at given location.""" + raise NotImplementedError + + @abstractmethod + def anal_type( + self, + typ: Type, + /, + *, + tvar_scope: TypeVarLikeScope | None = None, + allow_tuple_literal: bool = False, + allow_unbound_tvars: bool = False, + report_invalid_types: bool = True, + ) -> Type | None: + """Analyze an unbound type. + + Return None if some part of the type is not ready yet. In this + case the current target being analyzed will be deferred and + analyzed again. + """ + raise NotImplementedError + + @abstractmethod + def class_type(self, self_type: Type) -> Type: + """Generate type of first argument of class methods from type of self.""" + raise NotImplementedError + + @abstractmethod + def lookup_fully_qualified(self, fullname: str, /) -> SymbolTableNode: + """Lookup a symbol by its fully qualified name. + + Raise an error if not found. + """ + raise NotImplementedError + + @abstractmethod + def lookup_fully_qualified_or_none(self, fullname: str, /) -> SymbolTableNode | None: + """Lookup a symbol by its fully qualified name. + + Return None if not found. + """ + raise NotImplementedError + + @abstractmethod + def lookup_qualified( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + """Lookup symbol using a name in current scope. + + This follows Python local->non-local->global->builtins rules. + """ + raise NotImplementedError + + @abstractmethod + def add_plugin_dependency(self, trigger: str, target: str | None = None) -> None: + """Specify semantic dependencies for generated methods/variables. + + If the symbol with full name given by trigger is found to be stale by mypy, + then the body of node with full name given by target will be re-checked. + By default, this is the node that is currently analyzed. + + For example, the dataclass plugin adds a generated __init__ method with + a signature that depends on types of attributes in ancestor classes. If any + attribute in an ancestor class gets stale (modified), we need to reprocess + the subclasses (and thus regenerate __init__ methods). + + This is used by fine-grained incremental mode (mypy daemon). See mypy/server/deps.py + for more details. + """ + raise NotImplementedError + + @abstractmethod + def add_symbol_table_node(self, name: str, symbol: SymbolTableNode) -> Any: + """Add node to global symbol table (or to nearest class if there is one).""" + raise NotImplementedError + + @abstractmethod + def qualified_name(self, name: str) -> str: + """Make qualified name using current module and enclosing class (if any).""" + raise NotImplementedError + + @abstractmethod + def defer(self) -> None: + """Call this to defer the processing of the current node. + + This will request an additional iteration of semantic analysis. + """ + raise NotImplementedError + + @property + @abstractmethod + def final_iteration(self) -> bool: + """Is this the final iteration of semantic analysis?""" + raise NotImplementedError + + @property + @abstractmethod + def is_stub_file(self) -> bool: + raise NotImplementedError + + @abstractmethod + def analyze_simple_literal_type(self, rvalue: Expression, is_final: bool) -> Type | None: + raise NotImplementedError + + +# A context for querying for configuration data about a module for +# cache invalidation purposes. +class ReportConfigContext(NamedTuple): + id: str # Module name + path: str # Module file path + is_check: bool # Is this invocation for checking whether the config matches + + +# A context for a function signature hook that infers a better signature for a +# function. Note that argument types aren't available yet. If you need them, +# you have to use a method hook instead. +class FunctionSigContext(NamedTuple): + args: list[list[Expression]] # Actual expressions for each formal argument + default_signature: CallableType # Original signature of the method + context: Context # Relevant location context (e.g. for error messages) + api: CheckerPluginInterface + + +# A context for a function hook that infers the return type of a function with +# a special signature. +# +# A no-op callback would just return the inferred return type, but a useful +# callback at least sometimes can infer a more precise type. +class FunctionContext(NamedTuple): + arg_types: list[list[Type]] # List of actual caller types for each formal argument + arg_kinds: list[list[ArgKind]] # Ditto for argument kinds, see nodes.ARG_* constants + # Names of formal parameters from the callee definition, + # these will be sufficient in most cases. + callee_arg_names: list[str | None] + # Names of actual arguments in the call expression. For example, + # in a situation like this: + # def func(**kwargs) -> None: + # pass + # func(kw1=1, kw2=2) + # callee_arg_names will be ['kwargs'] and arg_names will be [['kw1', 'kw2']]. + arg_names: list[list[str | None]] + default_return_type: Type # Return type inferred from signature + args: list[list[Expression]] # Actual expressions for each formal argument + context: Context # Relevant location context (e.g. for error messages) + api: CheckerPluginInterface + + +# A context for a method signature hook that infers a better signature for a +# method. Note that argument types aren't available yet. If you need them, +# you have to use a method hook instead. +# TODO: document ProperType in the plugin changelog/update issue. +class MethodSigContext(NamedTuple): + type: ProperType # Base object type for method call + args: list[list[Expression]] # Actual expressions for each formal argument + default_signature: CallableType # Original signature of the method + context: Context # Relevant location context (e.g. for error messages) + api: CheckerPluginInterface + + +# A context for a method hook that infers the return type of a method with a +# special signature. +# +# This is very similar to FunctionContext (only differences are documented). +class MethodContext(NamedTuple): + type: ProperType # Base object type for method call + arg_types: list[list[Type]] # List of actual caller types for each formal argument + # see FunctionContext for details about names and kinds + arg_kinds: list[list[ArgKind]] + callee_arg_names: list[str | None] + arg_names: list[list[str | None]] + default_return_type: Type # Return type inferred by mypy + args: list[list[Expression]] # Lists of actual expressions for every formal argument + context: Context + api: CheckerPluginInterface + + +# A context for an attribute type hook that infers the type of an attribute. +class AttributeContext(NamedTuple): + type: ProperType # Type of object with attribute + default_attr_type: Type # Original attribute type + is_lvalue: bool # Whether the attribute is the target of an assignment + context: Context # Relevant location context (e.g. for error messages) + api: CheckerPluginInterface + + +# A context for a class hook that modifies the class definition. +class ClassDefContext(NamedTuple): + cls: ClassDef # The class definition + reason: Expression # The expression being applied (decorator, metaclass, base class) + api: SemanticAnalyzerPluginInterface + + +# A context for dynamic class definitions like +# Base = declarative_base() +class DynamicClassDefContext(NamedTuple): + call: CallExpr # The r.h.s. of dynamic class definition + name: str # The name this class is being assigned to + api: SemanticAnalyzerPluginInterface + + +@mypyc_attr(allow_interpreted_subclasses=True) +class Plugin(CommonPluginApi): + """Base class of all type checker plugins. + + This defines a no-op plugin. Subclasses can override some methods to + provide some actual functionality. + + All get_ methods are treated as pure functions (you should assume that + results might be cached). A plugin should return None from a get_ method + to give way to other plugins. + + Look at the comments of various *Context objects for additional information on + various hooks. + """ + + def __init__(self, options: Options) -> None: + self.options = options + self.python_version = options.python_version + # This can't be set in __init__ because it is executed too soon in build.py. + # Therefore, build.py *must* set it later before graph processing starts + # by calling set_modules(). + self._modules: dict[str, MypyFile] | None = None + + def set_modules(self, modules: dict[str, MypyFile]) -> None: + self._modules = modules + + def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode | None: + assert self._modules is not None + return lookup_fully_qualified(fullname, self._modules) + + def report_config_data(self, ctx: ReportConfigContext) -> Any: + """Get representation of configuration data for a module. + + The data must be encodable as JSON and will be stored in the + cache metadata for the module. A mismatch between the cached + values and the returned will result in that module's cache + being invalidated and the module being rechecked. + + This can be called twice for each module, once after loading + the cache to check if it is valid and once while writing new + cache information. + + If is_check in the context is true, then the return of this + call will be checked against the cached version. Otherwise the + call is being made to determine what to put in the cache. This + can be used to allow consulting extra cache files in certain + complex situations. + + This can be used to incorporate external configuration information + that might require changes to typechecking. + """ + return None + + def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]: + """Customize dependencies for a module. + + This hook allows adding in new dependencies for a module. It + is called after parsing a file but before analysis. This can + be useful if a library has dependencies that are dynamic based + on configuration information, for example. + + Returns a list of (priority, module name, line number) tuples. + + The line number can be -1 when there is not a known real line number. + + Priorities are defined in mypy.build (but maybe shouldn't be). + 10 is a good choice for priority. + """ + return [] + + def get_type_analyze_hook(self, fullname: str) -> Callable[[AnalyzeTypeContext], Type] | None: + """Customize behaviour of the type analyzer for given full names. + + This method is called during the semantic analysis pass whenever mypy sees an + unbound type. For example, while analysing this code: + + from lib import Special, Other + + var: Special + def func(x: Other[int]) -> None: + ... + + this method will be called with 'lib.Special', and then with 'lib.Other'. + The callback returned by plugin must return an analyzed type, + i.e. an instance of `mypy.types.Type`. + """ + return None + + def get_function_signature_hook( + self, fullname: str + ) -> Callable[[FunctionSigContext], FunctionLike] | None: + """Adjust the signature of a function. + + This method is called before type checking a function call. Plugin + may infer a better type for the function. + + from lib import Class, do_stuff + + do_stuff(42) + Class() + + This method will be called with 'lib.do_stuff' and then with 'lib.Class'. + """ + return None + + def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None: + """Adjust the return type of a function call. + + This method is called after type checking a call. Plugin may adjust the return + type inferred by mypy, and/or emit some error messages. Note, this hook is also + called for class instantiation calls, so that in this example: + + from lib import Class, do_stuff + + do_stuff(42) + Class() + + This method will be called with 'lib.do_stuff' and then with 'lib.Class'. + """ + return None + + def get_method_signature_hook( + self, fullname: str + ) -> Callable[[MethodSigContext], FunctionLike] | None: + """Adjust the signature of a method. + + This method is called before type checking a method call. Plugin + may infer a better type for the method. The hook is also called for special + Python dunder methods except __init__ and __new__ (use get_function_hook to customize + class instantiation). This function is called with the method full name using + the class where it was _defined_. For example, in this code: + + from lib import Special + + class Base: + def method(self, arg: Any) -> Any: + ... + class Derived(Base): + ... + + var: Derived + var.method(42) + + x: Special + y = x[0] + + this method is called with '__main__.Base.method', and then with + 'lib.Special.__getitem__'. + """ + return None + + def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: + """Adjust return type of a method call. + + This is the same as get_function_hook(), but is called with the + method full name (again, using the class where the method is defined). + """ + return None + + def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None: + """Adjust type of an instance attribute. + + This method is called with attribute full name using the class of the instance where + the attribute was defined (or Var.info.fullname for generated attributes). + + For classes without __getattr__ or __getattribute__, this hook is only called for + names of fields/properties (but not methods) that exist in the instance MRO. + + For classes that implement __getattr__ or __getattribute__, this hook is called + for all fields/properties, including nonexistent ones (but still not methods). + + For example: + + class Base: + x: Any + def __getattr__(self, attr: str) -> Any: ... + + class Derived(Base): + ... + + var: Derived + var.x + var.y + + get_attribute_hook is called with '__main__.Base.x' and '__main__.Base.y'. + However, if we had not implemented __getattr__ on Base, you would only get + the callback for 'var.x'; 'var.y' would produce an error without calling the hook. + """ + return None + + def get_class_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None: + """ + Adjust type of a class attribute. + + This method is called with attribute full name using the class where the attribute was + defined (or Var.info.fullname for generated attributes). + + For example: + + class Cls: + x: Any + + Cls.x + + get_class_attribute_hook is called with '__main__.Cls.x' as fullname. + """ + return None + + def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + """Update class definition for given class decorators. + + The plugin can modify a TypeInfo _in place_ (for example add some generated + methods to the symbol table). This hook is called after the class body was + semantically analyzed, but *there may still be placeholders* (typically + caused by forward references). + + NOTE: Usually get_class_decorator_hook_2 is the better option, since it + guarantees that there are no placeholders. + + The hook is called with full names of all class decorators. + + The hook can be called multiple times per class, so it must be + idempotent. + """ + return None + + def get_class_decorator_hook_2( + self, fullname: str + ) -> Callable[[ClassDefContext], bool] | None: + """Update class definition for given class decorators. + + Similar to get_class_decorator_hook, but this runs in a later pass when + placeholders have been resolved. + + The hook can return False if some base class hasn't been + processed yet using class hooks. It causes all class hooks + (that are run in this same pass) to be invoked another time for + the file(s) currently being processed. + + The hook can be called multiple times per class, so it must be + idempotent. + """ + return None + + def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + """Update class definition for given declared metaclasses. + + Same as get_class_decorator_hook() but for metaclasses. Note: + this hook will be only called for explicit metaclasses, not for + inherited ones. + + TODO: probably it should also be called on inherited metaclasses. + """ + return None + + def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + """Update class definition for given base classes. + + Same as get_class_decorator_hook() but for base classes. Base classes + don't need to refer to TypeInfos, if a base class refers to a variable with + Any type, this hook will still be called. + """ + return None + + def get_customize_class_mro_hook( + self, fullname: str + ) -> Callable[[ClassDefContext], None] | None: + """Customize MRO for given classes. + + The plugin can modify the class MRO _in place_. This method is called + with the class full name before its body was semantically analyzed. + """ + return None + + def get_dynamic_class_hook( + self, fullname: str + ) -> Callable[[DynamicClassDefContext], None] | None: + """Semantically analyze a dynamic class definition. + + This plugin hook allows one to semantically analyze dynamic class definitions like: + + from lib import dynamic_class + + X = dynamic_class('X', []) + + For such definition, this hook will be called with 'lib.dynamic_class'. + The plugin should create the corresponding TypeInfo, and place it into a relevant + symbol table, e.g. using ctx.api.add_symbol_table_node(). + """ + return None + + +T = TypeVar("T") + + +class ChainedPlugin(Plugin): + """A plugin that represents a sequence of chained plugins. + + Each lookup method returns the hook for the first plugin that + reports a match. + + This class should not be subclassed -- use Plugin as the base class + for all plugins. + """ + + # TODO: Support caching of lookup results (through a LRU cache, for example). + + def __init__(self, options: Options, plugins: list[Plugin]) -> None: + """Initialize chained plugin. + + Assume that the child plugins aren't mutated (results may be cached). + """ + super().__init__(options) + self._plugins = plugins + + def set_modules(self, modules: dict[str, MypyFile]) -> None: + for plugin in self._plugins: + plugin.set_modules(modules) + + def report_config_data(self, ctx: ReportConfigContext) -> Any: + config_data = [plugin.report_config_data(ctx) for plugin in self._plugins] + return config_data if any(x is not None for x in config_data) else None + + def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]: + deps = [] + for plugin in self._plugins: + deps.extend(plugin.get_additional_deps(file)) + return deps + + def get_type_analyze_hook(self, fullname: str) -> Callable[[AnalyzeTypeContext], Type] | None: + # Micro-optimization: Inline iteration over plugins + for plugin in self._plugins: + hook = plugin.get_type_analyze_hook(fullname) + if hook is not None: + return hook + return None + + def get_function_signature_hook( + self, fullname: str + ) -> Callable[[FunctionSigContext], FunctionLike] | None: + # Micro-optimization: Inline iteration over plugins + for plugin in self._plugins: + hook = plugin.get_function_signature_hook(fullname) + if hook is not None: + return hook + return None + + def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None: + return self._find_hook(lambda plugin: plugin.get_function_hook(fullname)) + + def get_method_signature_hook( + self, fullname: str + ) -> Callable[[MethodSigContext], FunctionLike] | None: + # Micro-optimization: Inline iteration over plugins + for plugin in self._plugins: + hook = plugin.get_method_signature_hook(fullname) + if hook is not None: + return hook + return None + + def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: + # Micro-optimization: Inline iteration over plugins + for plugin in self._plugins: + hook = plugin.get_method_hook(fullname) + if hook is not None: + return hook + return None + + def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None: + # Micro-optimization: Inline iteration over plugins + for plugin in self._plugins: + hook = plugin.get_attribute_hook(fullname) + if hook is not None: + return hook + return None + + def get_class_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None: + return self._find_hook(lambda plugin: plugin.get_class_attribute_hook(fullname)) + + def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + return self._find_hook(lambda plugin: plugin.get_class_decorator_hook(fullname)) + + def get_class_decorator_hook_2( + self, fullname: str + ) -> Callable[[ClassDefContext], bool] | None: + return self._find_hook(lambda plugin: plugin.get_class_decorator_hook_2(fullname)) + + def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + return self._find_hook(lambda plugin: plugin.get_metaclass_hook(fullname)) + + def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + return self._find_hook(lambda plugin: plugin.get_base_class_hook(fullname)) + + def get_customize_class_mro_hook( + self, fullname: str + ) -> Callable[[ClassDefContext], None] | None: + return self._find_hook(lambda plugin: plugin.get_customize_class_mro_hook(fullname)) + + def get_dynamic_class_hook( + self, fullname: str + ) -> Callable[[DynamicClassDefContext], None] | None: + return self._find_hook(lambda plugin: plugin.get_dynamic_class_hook(fullname)) + + def _find_hook(self, lookup: Callable[[Plugin], T]) -> T | None: + for plugin in self._plugins: + hook = lookup(plugin) + if hook is not None: + return hook + return None diff --git a/micromamba_root/Lib/site-packages/mypy/py.typed b/micromamba_root/Lib/site-packages/mypy/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..9724ed562890af1d6c28c46865a752566e14f932 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. The mypy package uses inline types. diff --git a/micromamba_root/Lib/site-packages/mypy/pyinfo.py b/micromamba_root/Lib/site-packages/mypy/pyinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..98350f46363ca87905da28becf81220d46865e34 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/pyinfo.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +"""Utilities to find the site and prefix information of a Python executable. + +This file MUST remain compatible with all Python 3.9+ versions. Since we cannot make any +assumptions about the Python being executed, this module should not use *any* dependencies outside +of the standard library found in Python 3.9. This file is run each mypy run, so it should be kept +as fast as possible. +""" +import sys + +if __name__ == "__main__": + # HACK: We don't want to pick up mypy.types as the top-level types + # module. This could happen if this file is run as a script. + # This workaround fixes this for Python versions before 3.11. + if sys.version_info < (3, 11): + old_sys_path = sys.path + sys.path = sys.path[1:] + import types # noqa: F401 + + sys.path = old_sys_path + +import os +import site +import sysconfig + + +def getsitepackages() -> list[str]: + res = [] + if hasattr(site, "getsitepackages"): + res.extend(site.getsitepackages()) + + if hasattr(site, "getusersitepackages") and site.ENABLE_USER_SITE: + res.insert(0, site.getusersitepackages()) + else: + res = [sysconfig.get_paths()["purelib"]] + return res + + +def getsyspath() -> list[str]: + # Do not include things from the standard library + # because those should come from typeshed. + stdlib_zip = os.path.join( + sys.base_exec_prefix, + getattr(sys, "platlibdir", "lib"), + f"python{sys.version_info.major}{sys.version_info.minor}.zip", + ) + stdlib = sysconfig.get_path("stdlib") + stdlib_ext = os.path.join(stdlib, "lib-dynload") + excludes = {stdlib_zip, stdlib, stdlib_ext} + + # Drop the first entry of sys.path + # - If pyinfo.py is executed as a script (in a subprocess), this is the directory + # containing pyinfo.py + # - Otherwise, if mypy launched via console script, this is the directory of the script + # - Otherwise, if mypy launched via python -m mypy, this is the current directory + # In all these cases, it is desirable to drop the first entry + # Note that mypy adds the cwd to SearchPaths.python_path, so we still find things on the + # cwd consistently (the return value here sets SearchPaths.package_path) + + # Python 3.11 adds a "safe_path" flag wherein Python won't automatically prepend + # anything to sys.path. In this case, the first entry of sys.path is no longer special. + offset = 0 if sys.version_info >= (3, 11) and sys.flags.safe_path else 1 + + abs_sys_path = (os.path.abspath(p) for p in sys.path[offset:]) + return [p for p in abs_sys_path if p not in excludes] + + +def getsearchdirs() -> tuple[list[str], list[str]]: + return (getsyspath(), getsitepackages()) + + +if __name__ == "__main__": + sys.stdout.reconfigure(encoding="utf-8") # type: ignore[union-attr] + if sys.argv[-1] == "getsearchdirs": + print(repr(getsearchdirs())) + else: + print("ERROR: incorrect argument to pyinfo.py.", file=sys.stderr) + sys.exit(1) diff --git a/micromamba_root/Lib/site-packages/mypy/reachability.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/reachability.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..0587dce373b9df621c713cf4bd476d71deeec186 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/reachability.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/reachability.py b/micromamba_root/Lib/site-packages/mypy/reachability.py new file mode 100644 index 0000000000000000000000000000000000000000..37c7a9715600af82889cdc864aa4680bc8641a05 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/reachability.py @@ -0,0 +1,370 @@ +"""Utilities related to determining the reachability of code (in semantic analysis).""" + +from __future__ import annotations + +from typing import Final, TypeVar + +from mypy.literals import literal +from mypy.nodes import ( + LITERAL_YES, + AssertStmt, + Block, + CallExpr, + ComparisonExpr, + Expression, + FuncDef, + IfStmt, + Import, + ImportAll, + ImportFrom, + IndexExpr, + IntExpr, + MatchStmt, + MemberExpr, + NameExpr, + OpExpr, + SliceExpr, + StrExpr, + TupleExpr, + UnaryExpr, +) +from mypy.options import Options +from mypy.patterns import AsPattern, OrPattern, Pattern +from mypy.traverser import TraverserVisitor + +# Inferred truth value of an expression. +ALWAYS_TRUE: Final = 1 +MYPY_TRUE: Final = 2 # True in mypy, False at runtime +ALWAYS_FALSE: Final = 3 +MYPY_FALSE: Final = 4 # False in mypy, True at runtime +TRUTH_VALUE_UNKNOWN: Final = 5 + +inverted_truth_mapping: Final = { + ALWAYS_TRUE: ALWAYS_FALSE, + ALWAYS_FALSE: ALWAYS_TRUE, + TRUTH_VALUE_UNKNOWN: TRUTH_VALUE_UNKNOWN, + MYPY_TRUE: MYPY_FALSE, + MYPY_FALSE: MYPY_TRUE, +} + +reverse_op: Final = {"==": "==", "!=": "!=", "<": ">", ">": "<", "<=": ">=", ">=": "<="} + + +def infer_reachability_of_if_statement(s: IfStmt, options: Options) -> None: + for i in range(len(s.expr)): + result = infer_condition_value(s.expr[i], options) + if result in (ALWAYS_FALSE, MYPY_FALSE): + # The condition is considered always false, so we skip the if/elif body. + mark_block_unreachable(s.body[i]) + elif result in (ALWAYS_TRUE, MYPY_TRUE): + # This condition is considered always true, so all of the remaining + # elif/else bodies should not be checked. + if result == MYPY_TRUE: + # This condition is false at runtime; this will affect + # import priorities. + mark_block_mypy_only(s.body[i]) + for body in s.body[i + 1 :]: + mark_block_unreachable(body) + + # Make sure else body always exists and is marked as + # unreachable so the type checker always knows that + # all control flow paths will flow through the if + # statement body. + if not s.else_body: + s.else_body = Block([]) + mark_block_unreachable(s.else_body) + break + + +def infer_reachability_of_match_statement(s: MatchStmt, options: Options) -> None: + for i, guard in enumerate(s.guards): + pattern_value = infer_pattern_value(s.patterns[i]) + + if guard is not None: + guard_value = infer_condition_value(guard, options) + else: + guard_value = ALWAYS_TRUE + + if pattern_value in (ALWAYS_FALSE, MYPY_FALSE) or guard_value in ( + ALWAYS_FALSE, + MYPY_FALSE, + ): + # The case is considered always false, so we skip the case body. + mark_block_unreachable(s.bodies[i]) + elif pattern_value in (ALWAYS_TRUE, MYPY_TRUE) and guard_value in (ALWAYS_TRUE, MYPY_TRUE): + for body in s.bodies[i + 1 :]: + mark_block_unreachable(body) + + if guard_value == MYPY_TRUE: + # This condition is false at runtime; this will affect + # import priorities. + mark_block_mypy_only(s.bodies[i]) + + +def assert_will_always_fail(s: AssertStmt, options: Options) -> bool: + return infer_condition_value(s.expr, options) in (ALWAYS_FALSE, MYPY_FALSE) + + +def infer_condition_value(expr: Expression, options: Options) -> int: + """Infer whether the given condition is always true/false. + + Return ALWAYS_TRUE if always true, ALWAYS_FALSE if always false, + MYPY_TRUE if true under mypy and false at runtime, MYPY_FALSE if + false under mypy and true at runtime, else TRUTH_VALUE_UNKNOWN. + """ + if isinstance(expr, UnaryExpr) and expr.op == "not": + positive = infer_condition_value(expr.expr, options) + return inverted_truth_mapping[positive] + + pyversion = options.python_version + name = "" + + result = TRUTH_VALUE_UNKNOWN + if isinstance(expr, NameExpr): + name = expr.name + elif isinstance(expr, MemberExpr): + name = expr.name + elif isinstance(expr, OpExpr): + if expr.op not in ("or", "and"): + return TRUTH_VALUE_UNKNOWN + + left = infer_condition_value(expr.left, options) + right = infer_condition_value(expr.right, options) + results = {left, right} + if expr.op == "or": + if ALWAYS_TRUE in results: + return ALWAYS_TRUE + elif MYPY_TRUE in results: + return MYPY_TRUE + elif left == right == MYPY_FALSE: + return MYPY_FALSE + elif results <= {ALWAYS_FALSE, MYPY_FALSE}: + return ALWAYS_FALSE + elif expr.op == "and": + if ALWAYS_FALSE in results: + return ALWAYS_FALSE + elif MYPY_FALSE in results: + return MYPY_FALSE + elif left == right == ALWAYS_TRUE: + return ALWAYS_TRUE + elif results <= {ALWAYS_TRUE, MYPY_TRUE}: + return MYPY_TRUE + return TRUTH_VALUE_UNKNOWN + else: + result = consider_sys_version_info(expr, pyversion) + if result == TRUTH_VALUE_UNKNOWN: + result = consider_sys_platform(expr, options.platform) + if result == TRUTH_VALUE_UNKNOWN: + if name == "PY2": + result = ALWAYS_FALSE + elif name == "PY3": + result = ALWAYS_TRUE + elif name == "MYPY" or name == "TYPE_CHECKING": + result = MYPY_TRUE + elif name in options.always_true: + result = ALWAYS_TRUE + elif name in options.always_false: + result = ALWAYS_FALSE + return result + + +def infer_pattern_value(pattern: Pattern) -> int: + if isinstance(pattern, AsPattern) and pattern.pattern is None: + return ALWAYS_TRUE + elif isinstance(pattern, OrPattern) and any( + infer_pattern_value(p) == ALWAYS_TRUE for p in pattern.patterns + ): + return ALWAYS_TRUE + else: + return TRUTH_VALUE_UNKNOWN + + +def consider_sys_version_info(expr: Expression, pyversion: tuple[int, ...]) -> int: + """Consider whether expr is a comparison involving sys.version_info. + + Return ALWAYS_TRUE, ALWAYS_FALSE, or TRUTH_VALUE_UNKNOWN. + """ + # Cases supported: + # - sys.version_info[] + # - sys.version_info[:] + # - sys.version_info + # (in this case must be >, >=, <, <=, but cannot be ==, !=) + if not isinstance(expr, ComparisonExpr): + return TRUTH_VALUE_UNKNOWN + # Let's not yet support chained comparisons. + if len(expr.operators) > 1: + return TRUTH_VALUE_UNKNOWN + op = expr.operators[0] + if op not in ("==", "!=", "<=", ">=", "<", ">"): + return TRUTH_VALUE_UNKNOWN + + index = contains_sys_version_info(expr.operands[0]) + thing = contains_int_or_tuple_of_ints(expr.operands[1]) + if index is None or thing is None: + index = contains_sys_version_info(expr.operands[1]) + thing = contains_int_or_tuple_of_ints(expr.operands[0]) + op = reverse_op[op] + if isinstance(index, int) and isinstance(thing, int): + # sys.version_info[i] k + if 0 <= index <= 1: + return fixed_comparison(pyversion[index], op, thing) + else: + return TRUTH_VALUE_UNKNOWN + elif isinstance(index, tuple) and isinstance(thing, tuple): + lo, hi = index + if lo is None: + lo = 0 + if hi is None: + hi = 2 + if 0 <= lo < hi <= 2: + val = pyversion[lo:hi] + if len(val) == len(thing) or len(val) > len(thing) and op not in ("==", "!="): + return fixed_comparison(val, op, thing) + return TRUTH_VALUE_UNKNOWN + + +def consider_sys_platform(expr: Expression, platform: str) -> int: + """Consider whether expr is a comparison involving sys.platform. + + Return ALWAYS_TRUE, ALWAYS_FALSE, or TRUTH_VALUE_UNKNOWN. + """ + # Cases supported: + # - sys.platform == 'linux' + # - sys.platform != 'win32' + # - sys.platform.startswith('win') + if isinstance(expr, ComparisonExpr): + # Let's not yet support chained comparisons. + if len(expr.operators) > 1: + return TRUTH_VALUE_UNKNOWN + op = expr.operators[0] + if op not in ("==", "!="): + return TRUTH_VALUE_UNKNOWN + if not is_sys_attr(expr.operands[0], "platform"): + return TRUTH_VALUE_UNKNOWN + right = expr.operands[1] + if not isinstance(right, StrExpr): + return TRUTH_VALUE_UNKNOWN + return fixed_comparison(platform, op, right.value) + elif isinstance(expr, CallExpr): + if not isinstance(expr.callee, MemberExpr): + return TRUTH_VALUE_UNKNOWN + if len(expr.args) != 1 or not isinstance(expr.args[0], StrExpr): + return TRUTH_VALUE_UNKNOWN + if not is_sys_attr(expr.callee.expr, "platform"): + return TRUTH_VALUE_UNKNOWN + if expr.callee.name != "startswith": + return TRUTH_VALUE_UNKNOWN + if platform.startswith(expr.args[0].value): + return ALWAYS_TRUE + else: + return ALWAYS_FALSE + else: + return TRUTH_VALUE_UNKNOWN + + +Targ = TypeVar("Targ", int, str, tuple[int, ...]) + + +def fixed_comparison(left: Targ, op: str, right: Targ) -> int: + rmap = {False: ALWAYS_FALSE, True: ALWAYS_TRUE} + if op == "==": + return rmap[left == right] + if op == "!=": + return rmap[left != right] + if op == "<=": + return rmap[left <= right] + if op == ">=": + return rmap[left >= right] + if op == "<": + return rmap[left < right] + if op == ">": + return rmap[left > right] + return TRUTH_VALUE_UNKNOWN + + +def contains_int_or_tuple_of_ints(expr: Expression) -> None | int | tuple[int, ...]: + if isinstance(expr, IntExpr): + return expr.value + if isinstance(expr, TupleExpr): + if literal(expr) == LITERAL_YES: + thing = [] + for x in expr.items: + if not isinstance(x, IntExpr): + return None + thing.append(x.value) + return tuple(thing) + return None + + +def contains_sys_version_info(expr: Expression) -> None | int | tuple[int | None, int | None]: + if is_sys_attr(expr, "version_info"): + return (None, None) # Same as sys.version_info[:] + if isinstance(expr, IndexExpr) and is_sys_attr(expr.base, "version_info"): + index = expr.index + if isinstance(index, IntExpr): + return index.value + if isinstance(index, SliceExpr): + if index.stride is not None: + if not isinstance(index.stride, IntExpr) or index.stride.value != 1: + return None + begin = end = None + if index.begin_index is not None: + if not isinstance(index.begin_index, IntExpr): + return None + begin = index.begin_index.value + if index.end_index is not None: + if not isinstance(index.end_index, IntExpr): + return None + end = index.end_index.value + return (begin, end) + return None + + +def is_sys_attr(expr: Expression, name: str) -> bool: + # TODO: This currently doesn't work with code like this: + # - import sys as _sys + # - from sys import version_info + if isinstance(expr, MemberExpr) and expr.name == name: + if isinstance(expr.expr, NameExpr) and expr.expr.name == "sys": + # TODO: Guard against a local named sys, etc. + # (Though later passes will still do most checking.) + return True + return False + + +def mark_block_unreachable(block: Block) -> None: + block.is_unreachable = True + block.accept(MarkImportsUnreachableVisitor()) + + +class MarkImportsUnreachableVisitor(TraverserVisitor): + """Visitor that flags all imports nested within a node as unreachable.""" + + def visit_import(self, node: Import) -> None: + node.is_unreachable = True + + def visit_import_from(self, node: ImportFrom) -> None: + node.is_unreachable = True + + def visit_import_all(self, node: ImportAll) -> None: + node.is_unreachable = True + + +def mark_block_mypy_only(block: Block) -> None: + block.accept(MarkImportsMypyOnlyVisitor()) + + +class MarkImportsMypyOnlyVisitor(TraverserVisitor): + """Visitor that sets is_mypy_only (which affects priority).""" + + def visit_import(self, node: Import) -> None: + node.is_mypy_only = True + + def visit_import_from(self, node: ImportFrom) -> None: + node.is_mypy_only = True + + def visit_import_all(self, node: ImportAll) -> None: + node.is_mypy_only = True + + def visit_func_def(self, node: FuncDef) -> None: + node.is_mypy_only = True diff --git a/micromamba_root/Lib/site-packages/mypy/refinfo.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/refinfo.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..5d8dba5cb94758f2da162ea9358c8b400a699622 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/refinfo.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/refinfo.py b/micromamba_root/Lib/site-packages/mypy/refinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b92832bb7ee7e08bc4d4a9c9a1a01419323810 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/refinfo.py @@ -0,0 +1,92 @@ +"""Find line-level reference information from a mypy AST (undocumented feature)""" + +from __future__ import annotations + +from mypy.nodes import ( + LDEF, + Expression, + FuncDef, + MemberExpr, + MypyFile, + NameExpr, + RefExpr, + SymbolNode, + TypeInfo, +) +from mypy.traverser import TraverserVisitor +from mypy.typeops import tuple_fallback +from mypy.types import ( + FunctionLike, + Instance, + TupleType, + Type, + TypeType, + TypeVarLikeType, + get_proper_type, +) + + +class RefInfoVisitor(TraverserVisitor): + def __init__(self, type_map: dict[Expression, Type]) -> None: + super().__init__() + self.type_map = type_map + self.data: list[dict[str, object]] = [] + + def visit_name_expr(self, expr: NameExpr) -> None: + super().visit_name_expr(expr) + self.record_ref_expr(expr) + + def visit_member_expr(self, expr: MemberExpr) -> None: + super().visit_member_expr(expr) + self.record_ref_expr(expr) + + def visit_func_def(self, func: FuncDef) -> None: + if func.expanded: + for item in func.expanded: + if isinstance(item, FuncDef): + super().visit_func_def(item) + else: + super().visit_func_def(func) + + def record_ref_expr(self, expr: RefExpr) -> None: + fullname = None + if expr.kind != LDEF and "." in expr.fullname: + fullname = expr.fullname + elif isinstance(expr, MemberExpr): + typ = self.type_map.get(expr.expr) + sym = None + if isinstance(expr.expr, RefExpr): + sym = expr.expr.node + if typ: + tfn = type_fullname(typ, sym) + if tfn: + fullname = f"{tfn}.{expr.name}" + if not fullname: + fullname = f"*.{expr.name}" + if fullname is not None: + self.data.append({"line": expr.line, "column": expr.column, "target": fullname}) + + +def type_fullname(typ: Type, node: SymbolNode | None = None) -> str | None: + typ = get_proper_type(typ) + if isinstance(typ, Instance): + return typ.type.fullname + elif isinstance(typ, TypeType): + return type_fullname(typ.item) + elif isinstance(typ, FunctionLike) and typ.is_type_obj(): + if isinstance(node, TypeInfo): + return node.fullname + return type_fullname(typ.fallback) + elif isinstance(typ, TupleType): + return type_fullname(tuple_fallback(typ)) + elif isinstance(typ, TypeVarLikeType): + return type_fullname(typ.upper_bound) + return None + + +def get_undocumented_ref_info_json( + tree: MypyFile, type_map: dict[Expression, Type] +) -> list[dict[str, object]]: + visitor = RefInfoVisitor(type_map) + tree.accept(visitor) + return visitor.data diff --git a/micromamba_root/Lib/site-packages/mypy/renaming.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/renaming.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..1be39aa804ef598706f016f939f8e5b1ce84b54b Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/renaming.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/renaming.py b/micromamba_root/Lib/site-packages/mypy/renaming.py new file mode 100644 index 0000000000000000000000000000000000000000..dff76b157acc079d22103eb11a69bd5a3ed0f0fd --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/renaming.py @@ -0,0 +1,583 @@ +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Final + +from mypy.nodes import ( + AssignmentStmt, + Block, + BreakStmt, + ClassDef, + ContinueStmt, + ForStmt, + FuncDef, + Import, + ImportAll, + ImportFrom, + IndexExpr, + ListExpr, + Lvalue, + MatchStmt, + MemberExpr, + MypyFile, + NameExpr, + StarExpr, + TryStmt, + TupleExpr, + WhileStmt, + WithStmt, +) +from mypy.patterns import AsPattern +from mypy.traverser import TraverserVisitor + +# Scope kinds +FILE: Final = 0 +FUNCTION: Final = 1 +CLASS: Final = 2 + + +class VariableRenameVisitor(TraverserVisitor): + """Rename variables to allow redefinition of variables. + + For example, consider this code: + + x = 0 + f(x) + + x = "a" + g(x) + + It will be transformed like this: + + x' = 0 + f(x') + + x = "a" + g(x) + + There will be two independent variables (x' and x) that will have separate + inferred types. The publicly exposed variant will get the non-suffixed name. + This is the last definition at module top level and the first definition + (argument) within a function. + + Renaming only happens for assignments within the same block. Renaming is + performed before semantic analysis, immediately after parsing. + + The implementation performs a rudimentary static analysis. The analysis is + overly conservative to keep things simple. + """ + + def __init__(self) -> None: + # Counter for labeling new blocks + self.block_id = 0 + # Number of surrounding try statements that disallow variable redefinition + self.disallow_redef_depth = 0 + # Number of surrounding loop statements + self.loop_depth = 0 + # Map block id to loop depth. + self.block_loop_depth: dict[int, int] = {} + # Stack of block ids being processed. + self.blocks: list[int] = [] + # List of scopes; each scope maps short (unqualified) name to block id. + self.var_blocks: list[dict[str, int]] = [] + + # References to variables that we may need to rename. List of + # scopes; each scope is a mapping from name to list of collections + # of names that refer to the same logical variable. + self.refs: list[dict[str, list[list[NameExpr]]]] = [] + # Number of reads of the most recent definition of a variable (per scope) + self.num_reads: list[dict[str, int]] = [] + # Kinds of nested scopes (FILE, FUNCTION or CLASS) + self.scope_kinds: list[int] = [] + + def visit_mypy_file(self, file_node: MypyFile) -> None: + """Rename variables within a file. + + This is the main entry point to this class. + """ + self.clear() + with self.enter_scope(FILE), self.enter_block(): + for d in file_node.defs: + d.accept(self) + + def visit_func_def(self, fdef: FuncDef) -> None: + # Conservatively do not allow variable defined before a function to + # be redefined later, since function could refer to either definition. + self.reject_redefinition_of_vars_in_scope() + + with self.enter_scope(FUNCTION), self.enter_block(): + for arg in fdef.arguments: + name = arg.variable.name + # 'self' can't be redefined since it's special as it allows definition of + # attributes. 'cls' can't be used to define attributes so we can ignore it. + can_be_redefined = name != "self" # TODO: Proper check + self.record_assignment(arg.variable.name, can_be_redefined) + self.handle_arg(name) + + for stmt in fdef.body.body: + stmt.accept(self) + + def visit_class_def(self, cdef: ClassDef) -> None: + self.reject_redefinition_of_vars_in_scope() + with self.enter_scope(CLASS): + super().visit_class_def(cdef) + + def visit_block(self, block: Block) -> None: + with self.enter_block(): + super().visit_block(block) + + def visit_while_stmt(self, stmt: WhileStmt) -> None: + with self.enter_loop(): + super().visit_while_stmt(stmt) + + def visit_for_stmt(self, stmt: ForStmt) -> None: + stmt.expr.accept(self) + self.analyze_lvalue(stmt.index, True) + # Also analyze as non-lvalue so that every for loop index variable is assumed to be read. + stmt.index.accept(self) + with self.enter_loop(): + stmt.body.accept(self) + if stmt.else_body: + stmt.else_body.accept(self) + + def visit_break_stmt(self, stmt: BreakStmt) -> None: + self.reject_redefinition_of_vars_in_loop() + + def visit_continue_stmt(self, stmt: ContinueStmt) -> None: + self.reject_redefinition_of_vars_in_loop() + + def visit_try_stmt(self, stmt: TryStmt) -> None: + # Variables defined by a try statement get special treatment in the + # type checker which allows them to be always redefined, so no need to + # do renaming here. + with self.enter_try(): + stmt.body.accept(self) + + for var, tp, handler in zip(stmt.vars, stmt.types, stmt.handlers): + with self.enter_block(): + # Handle except variable together with its body + if tp is not None: + tp.accept(self) + if var is not None: + self.handle_def(var) + for s in handler.body: + s.accept(self) + if stmt.else_body is not None: + stmt.else_body.accept(self) + if stmt.finally_body is not None: + stmt.finally_body.accept(self) + + def visit_with_stmt(self, stmt: WithStmt) -> None: + for expr in stmt.expr: + expr.accept(self) + for target in stmt.target: + if target is not None: + self.analyze_lvalue(target) + # We allow redefinitions in the body of a with statement for + # convenience. This is unsafe since with statements can affect control + # flow by catching exceptions, but this is rare except for + # assertRaises() and other similar functions, where the exception is + # raised by the last statement in the body, which usually isn't a + # problem. + stmt.body.accept(self) + + def visit_import(self, imp: Import) -> None: + for id, as_id in imp.ids: + self.record_assignment(as_id or id, False) + + def visit_import_from(self, imp: ImportFrom) -> None: + for id, as_id in imp.names: + self.record_assignment(as_id or id, False) + + def visit_assignment_stmt(self, s: AssignmentStmt) -> None: + s.rvalue.accept(self) + for lvalue in s.lvalues: + self.analyze_lvalue(lvalue) + + def visit_match_stmt(self, s: MatchStmt) -> None: + s.subject.accept(self) + for i in range(len(s.patterns)): + with self.enter_block(): + s.patterns[i].accept(self) + guard = s.guards[i] + if guard is not None: + guard.accept(self) + # We already entered a block, so visit this block's statements directly + for stmt in s.bodies[i].body: + stmt.accept(self) + + def visit_capture_pattern(self, p: AsPattern) -> None: + if p.name is not None: + self.analyze_lvalue(p.name) + + def analyze_lvalue(self, lvalue: Lvalue, is_nested: bool = False) -> None: + """Process assignment; in particular, keep track of (re)defined names. + + Args: + is_nested: True for non-outermost Lvalue in a multiple assignment such as + "x, y = ..." + """ + if isinstance(lvalue, NameExpr): + name = lvalue.name + is_new = self.record_assignment(name, True) + if is_new: + self.handle_def(lvalue) + else: + self.handle_refine(lvalue) + if is_nested: + # This allows these to be redefined freely even if never read. Multiple + # assignment like "x, _ _ = y" defines dummy variables that are never read. + self.handle_ref(lvalue) + elif isinstance(lvalue, (ListExpr, TupleExpr)): + for item in lvalue.items: + self.analyze_lvalue(item, is_nested=True) + elif isinstance(lvalue, MemberExpr): + lvalue.expr.accept(self) + elif isinstance(lvalue, IndexExpr): + lvalue.base.accept(self) + lvalue.index.accept(self) + elif isinstance(lvalue, StarExpr): + # Propagate is_nested since in a typical use case like "x, *rest = ..." 'rest' may + # be freely reused. + self.analyze_lvalue(lvalue.expr, is_nested=is_nested) + + def visit_name_expr(self, expr: NameExpr) -> None: + self.handle_ref(expr) + + # Helpers for renaming references + + def handle_arg(self, name: str) -> None: + """Store function argument.""" + self.refs[-1][name] = [[]] + self.num_reads[-1][name] = 0 + + def handle_def(self, expr: NameExpr) -> None: + """Store new name definition.""" + name = expr.name + names = self.refs[-1].setdefault(name, []) + names.append([expr]) + self.num_reads[-1][name] = 0 + + def handle_refine(self, expr: NameExpr) -> None: + """Store assignment to an existing name (that replaces previous value, if any).""" + name = expr.name + if name in self.refs[-1]: + names = self.refs[-1][name] + if not names: + names.append([]) + names[-1].append(expr) + + def handle_ref(self, expr: NameExpr) -> None: + """Store reference to defined name.""" + name = expr.name + if name in self.refs[-1]: + names = self.refs[-1][name] + if not names: + names.append([]) + names[-1].append(expr) + num_reads = self.num_reads[-1] + num_reads[name] = num_reads.get(name, 0) + 1 + + def flush_refs(self) -> None: + """Rename all references within the current scope. + + This will be called at the end of a scope. + """ + is_func = self.scope_kinds[-1] == FUNCTION + for refs in self.refs[-1].values(): + if len(refs) == 1: + # Only one definition -- no renaming needed. + continue + if is_func: + # In a function, don't rename the first definition, as it + # may be an argument that must preserve the name. + to_rename = refs[1:] + else: + # At module top level, don't rename the final definition, + # as it will be publicly visible outside the module. + to_rename = refs[:-1] + for i, item in enumerate(to_rename): + rename_refs(item, i) + self.refs.pop() + + # Helpers for determining which assignments define new variables + + def clear(self) -> None: + self.blocks = [] + self.var_blocks = [] + + @contextmanager + def enter_block(self) -> Iterator[None]: + self.block_id += 1 + self.blocks.append(self.block_id) + self.block_loop_depth[self.block_id] = self.loop_depth + try: + yield + finally: + self.blocks.pop() + + @contextmanager + def enter_try(self) -> Iterator[None]: + self.disallow_redef_depth += 1 + try: + yield + finally: + self.disallow_redef_depth -= 1 + + @contextmanager + def enter_loop(self) -> Iterator[None]: + self.loop_depth += 1 + try: + yield + finally: + self.loop_depth -= 1 + + def current_block(self) -> int: + return self.blocks[-1] + + @contextmanager + def enter_scope(self, kind: int) -> Iterator[None]: + self.var_blocks.append({}) + self.refs.append({}) + self.num_reads.append({}) + self.scope_kinds.append(kind) + try: + yield + finally: + self.flush_refs() + self.var_blocks.pop() + self.num_reads.pop() + self.scope_kinds.pop() + + def is_nested(self) -> int: + return len(self.var_blocks) > 1 + + def reject_redefinition_of_vars_in_scope(self) -> None: + """Make it impossible to redefine defined variables in the current scope. + + This is used if we encounter a function definition that + can make it ambiguous which definition is live. Example: + + x = 0 + + def f() -> int: + return x + + x = '' # Error -- cannot redefine x across function definition + """ + var_blocks = self.var_blocks[-1] + for key in var_blocks: + var_blocks[key] = -1 + + def reject_redefinition_of_vars_in_loop(self) -> None: + """Reject redefinition of variables in the innermost loop. + + If there is an early exit from a loop, there may be ambiguity about which + value may escape the loop. Example where this matters: + + while f(): + x = 0 + if g(): + break + x = '' # Error -- not a redefinition + reveal_type(x) # int + + This method ensures that the second assignment to 'x' doesn't introduce a new + variable. + """ + var_blocks = self.var_blocks[-1] + for key, block in var_blocks.items(): + if self.block_loop_depth.get(block) == self.loop_depth: + var_blocks[key] = -1 + + def record_assignment(self, name: str, can_be_redefined: bool) -> bool: + """Record assignment to given name and return True if it defines a new variable. + + Args: + can_be_redefined: If True, allows assignment in the same block to redefine + this name (if this is a new definition) + """ + if self.num_reads[-1].get(name, -1) == 0: + # Only set, not read, so no reason to redefine + return False + if self.disallow_redef_depth > 0: + # Can't redefine within try/with a block. + can_be_redefined = False + block = self.current_block() + var_blocks = self.var_blocks[-1] + if name not in var_blocks: + # New definition in this scope. + if can_be_redefined: + # Store the block where this was defined to allow redefinition in + # the same block only. + var_blocks[name] = block + else: + # This doesn't support arbitrary redefinition. + var_blocks[name] = -1 + return True + elif var_blocks[name] == block: + # Redefinition -- defines a new variable with the same name. + return True + else: + # Assigns to an existing variable. + return False + + +class LimitedVariableRenameVisitor(TraverserVisitor): + """Perform some limited variable renaming in with statements. + + This allows reusing a variable in multiple with statements with + different types. For example, the two instances of 'x' can have + incompatible types: + + with C() as x: + f(x) + with D() as x: + g(x) + + The above code gets renamed conceptually into this (not valid Python!): + + with C() as x': + f(x') + with D() as x: + g(x) + + If there's a reference to a variable defined in 'with' outside the + statement, or if there's any trickiness around variable visibility + (e.g. function definitions), we give up and won't perform renaming. + + The main use case is to allow binding both readable and writable + binary files into the same variable. These have different types: + + with open(fnam, 'rb') as f: ... + with open(fnam, 'wb') as f: ... + """ + + def __init__(self) -> None: + # Short names of variables bound in with statements using "as" + # in a surrounding scope + self.bound_vars: list[str] = [] + # Stack of names that can't be safely renamed, per scope ('*' means that + # no names can be renamed) + self.skipped: list[set[str]] = [] + # References to variables that we may need to rename. Stack of + # scopes; each scope is a mapping from name to list of collections + # of names that refer to the same logical variable. + self.refs: list[dict[str, list[list[NameExpr]]]] = [] + + def visit_mypy_file(self, file_node: MypyFile) -> None: + """Rename variables within a file. + + This is the main entry point to this class. + """ + with self.enter_scope(): + for d in file_node.defs: + d.accept(self) + + def visit_func_def(self, fdef: FuncDef) -> None: + self.reject_redefinition_of_vars_in_scope() + with self.enter_scope(): + for arg in fdef.arguments: + self.record_skipped(arg.variable.name) + super().visit_func_def(fdef) + + def visit_class_def(self, cdef: ClassDef) -> None: + self.reject_redefinition_of_vars_in_scope() + with self.enter_scope(): + super().visit_class_def(cdef) + + def visit_with_stmt(self, stmt: WithStmt) -> None: + for expr in stmt.expr: + expr.accept(self) + old_len = len(self.bound_vars) + for target in stmt.target: + if target is not None: + self.analyze_lvalue(target) + for target in stmt.target: + if target: + target.accept(self) + stmt.body.accept(self) + + while len(self.bound_vars) > old_len: + self.bound_vars.pop() + + def analyze_lvalue(self, lvalue: Lvalue) -> None: + if isinstance(lvalue, NameExpr): + name = lvalue.name + if name in self.bound_vars: + # Name bound in a surrounding with statement, so it can be renamed + self.visit_name_expr(lvalue) + else: + var_info = self.refs[-1] + if name not in var_info: + var_info[name] = [] + var_info[name].append([]) + self.bound_vars.append(name) + elif isinstance(lvalue, (ListExpr, TupleExpr)): + for item in lvalue.items: + self.analyze_lvalue(item) + elif isinstance(lvalue, MemberExpr): + lvalue.expr.accept(self) + elif isinstance(lvalue, IndexExpr): + lvalue.base.accept(self) + lvalue.index.accept(self) + elif isinstance(lvalue, StarExpr): + self.analyze_lvalue(lvalue.expr) + + def visit_import(self, imp: Import) -> None: + # We don't support renaming imports + for id, as_id in imp.ids: + self.record_skipped(as_id or id) + + def visit_import_from(self, imp: ImportFrom) -> None: + # We don't support renaming imports + for id, as_id in imp.names: + self.record_skipped(as_id or id) + + def visit_import_all(self, imp: ImportAll) -> None: + # Give up, since we don't know all imported names yet + self.reject_redefinition_of_vars_in_scope() + + def visit_name_expr(self, expr: NameExpr) -> None: + name = expr.name + if name in self.bound_vars: + # Record reference so that it can be renamed later + for scope in reversed(self.refs): + if name in scope: + scope[name][-1].append(expr) + else: + self.record_skipped(name) + + @contextmanager + def enter_scope(self) -> Iterator[None]: + self.skipped.append(set()) + self.refs.append({}) + yield None + self.flush_refs() + + def reject_redefinition_of_vars_in_scope(self) -> None: + self.record_skipped("*") + + def record_skipped(self, name: str) -> None: + self.skipped[-1].add(name) + + def flush_refs(self) -> None: + ref_dict = self.refs.pop() + skipped = self.skipped.pop() + if "*" not in skipped: + for name, refs in ref_dict.items(): + if len(refs) <= 1 or name in skipped: + continue + # At module top level we must not rename the final definition, + # as it may be publicly visible + to_rename = refs[:-1] + for i, item in enumerate(to_rename): + rename_refs(item, i) + + +def rename_refs(names: list[NameExpr], index: int) -> None: + name = names[0].name + new_name = name + "'" * (index + 1) + for expr in names: + expr.name = new_name diff --git a/micromamba_root/Lib/site-packages/mypy/report.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/report.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..be8bf5f2a885d05d9bb0be66c07432b50498a025 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/report.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/report.py b/micromamba_root/Lib/site-packages/mypy/report.py new file mode 100644 index 0000000000000000000000000000000000000000..885d077d259e54ef6bc3edaba193df7e03bc51a5 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/report.py @@ -0,0 +1,930 @@ +"""Classes for producing HTML reports about imprecision.""" + +from __future__ import annotations + +import collections +import itertools +import json +import os +import shutil +import sys +import sysconfig +import time +import tokenize +from abc import ABCMeta, abstractmethod +from collections.abc import Callable, Iterator +from operator import attrgetter +from typing import Any, Final, TypeAlias as _TypeAlias +from urllib.request import pathname2url + +from mypy import stats +from mypy.defaults import REPORTER_NAMES +from mypy.nodes import Expression, FuncDef, MypyFile +from mypy.options import Options +from mypy.traverser import TraverserVisitor +from mypy.types import Type, TypeOfAny +from mypy.version import __version__ + +try: + if sys.version_info >= (3, 14) and bool(sysconfig.get_config_var("Py_GIL_DISABLED")): + # lxml doesn't support free-threading yet + LXML_INSTALLED = False + else: + from lxml import etree # type: ignore[import-untyped] + + LXML_INSTALLED = True +except ImportError: + LXML_INSTALLED = False + +type_of_any_name_map: Final[collections.OrderedDict[int, str]] = collections.OrderedDict( + [ + (TypeOfAny.unannotated, "Unannotated"), + (TypeOfAny.explicit, "Explicit"), + (TypeOfAny.from_unimported_type, "Unimported"), + (TypeOfAny.from_omitted_generics, "Omitted Generics"), + (TypeOfAny.from_error, "Error"), + (TypeOfAny.special_form, "Special Form"), + (TypeOfAny.implementation_artifact, "Implementation Artifact"), + ] +) + +ReporterClasses: _TypeAlias = dict[ + str, tuple[Callable[["Reports", str], "AbstractReporter"], bool] +] + +reporter_classes: Final[ReporterClasses] = {} + + +class Reports: + def __init__(self, data_dir: str, report_dirs: dict[str, str]) -> None: + self.data_dir = data_dir + self.reporters: list[AbstractReporter] = [] + self.named_reporters: dict[str, AbstractReporter] = {} + + for report_type, report_dir in sorted(report_dirs.items()): + self.add_report(report_type, report_dir) + + def add_report(self, report_type: str, report_dir: str) -> AbstractReporter: + try: + return self.named_reporters[report_type] + except KeyError: + pass + reporter_cls, needs_lxml = reporter_classes[report_type] + if needs_lxml and not LXML_INSTALLED: + print( + ( + "You must install the lxml package before you can run mypy" + " with `--{}-report`.\n" + "You can do this with `python3 -m pip install lxml`." + ).format(report_type), + file=sys.stderr, + ) + raise ImportError + reporter = reporter_cls(self, report_dir) + self.reporters.append(reporter) + self.named_reporters[report_type] = reporter + return reporter + + def file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + for reporter in self.reporters: + reporter.on_file(tree, modules, type_map, options) + + def finish(self) -> None: + for reporter in self.reporters: + reporter.on_finish() + + +class AbstractReporter(metaclass=ABCMeta): + def __init__(self, reports: Reports, output_dir: str) -> None: + self.output_dir = output_dir + if output_dir != "": + os.makedirs(output_dir, exist_ok=True) + + @abstractmethod + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + pass + + @abstractmethod + def on_finish(self) -> None: + pass + + +def register_reporter( + report_name: str, + reporter: Callable[[Reports, str], AbstractReporter], + needs_lxml: bool = False, +) -> None: + reporter_classes[report_name] = (reporter, needs_lxml) + + +def alias_reporter(source_reporter: str, target_reporter: str) -> None: + reporter_classes[target_reporter] = reporter_classes[source_reporter] + + +def should_skip_path(path: str) -> bool: + if stats.is_special_module(path): + return True + if path.startswith(".."): + return True + if "stubs" in path.split("/") or "stubs" in path.split(os.sep): + return True + return False + + +def iterate_python_lines(path: str) -> Iterator[tuple[int, str]]: + """Return an iterator over (line number, line text) from a Python file.""" + if not os.path.isdir(path): # can happen with namespace packages + with tokenize.open(path) as input_file: + yield from enumerate(input_file, 1) + + +class FuncCounterVisitor(TraverserVisitor): + def __init__(self) -> None: + super().__init__() + self.counts = [0, 0] + + def visit_func_def(self, defn: FuncDef) -> None: + self.counts[defn.type is not None] += 1 + + +class LineCountReporter(AbstractReporter): + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + self.counts: dict[str, tuple[int, int, int, int]] = {} + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + # Count physical lines. This assumes the file's encoding is a + # superset of ASCII (or at least uses \n in its line endings). + if not os.path.isdir(tree.path): # can happen with namespace packages + with open(tree.path, "rb") as f: + physical_lines = len(f.readlines()) + else: + physical_lines = 0 + + func_counter = FuncCounterVisitor() + tree.accept(func_counter) + unannotated_funcs, annotated_funcs = func_counter.counts + total_funcs = annotated_funcs + unannotated_funcs + + # Don't count lines or functions as annotated if they have their errors ignored. + if options.ignore_errors: + annotated_funcs = 0 + + imputed_annotated_lines = ( + physical_lines * annotated_funcs // total_funcs if total_funcs else physical_lines + ) + + self.counts[tree._fullname] = ( + imputed_annotated_lines, + physical_lines, + annotated_funcs, + total_funcs, + ) + + def on_finish(self) -> None: + counts: list[tuple[tuple[int, int, int, int], str]] = sorted( + ((c, p) for p, c in self.counts.items()), reverse=True + ) + total_counts = tuple(sum(c[i] for c, p in counts) for i in range(4)) + with open(os.path.join(self.output_dir, "linecount.txt"), "w") as f: + f.write("{:7} {:7} {:6} {:6} total\n".format(*total_counts)) + for c, p in counts: + f.write(f"{c[0]:7} {c[1]:7} {c[2]:6} {c[3]:6} {p}\n") + + +register_reporter("linecount", LineCountReporter) + + +class AnyExpressionsReporter(AbstractReporter): + """Report frequencies of different kinds of Any types.""" + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + self.counts: dict[str, tuple[int, int]] = {} + self.any_types_counter: dict[str, collections.Counter[int]] = {} + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + visitor = stats.StatisticsVisitor( + inferred=True, + filename=tree.fullname, + modules=modules, + typemap=type_map, + all_nodes=True, + visit_untyped_defs=False, + ) + tree.accept(visitor) + self.any_types_counter[tree.fullname] = visitor.type_of_any_counter + num_unanalyzed_lines = list(visitor.line_map.values()).count(stats.TYPE_UNANALYZED) + # count each line of dead code as one expression of type "Any" + num_any = visitor.num_any_exprs + num_unanalyzed_lines + num_total = visitor.num_imprecise_exprs + visitor.num_precise_exprs + num_any + if num_total > 0: + self.counts[tree.fullname] = (num_any, num_total) + + def on_finish(self) -> None: + self._report_any_exprs() + self._report_types_of_anys() + + def _write_out_report( + self, filename: str, header: list[str], rows: list[list[str]], footer: list[str] + ) -> None: + row_len = len(header) + assert all(len(row) == row_len for row in rows + [header, footer]) + min_column_distance = 3 # minimum distance between numbers in two columns + widths = [-1] * row_len + for row in rows + [header, footer]: + for i, value in enumerate(row): + widths[i] = max(widths[i], len(value)) + for i, w in enumerate(widths): + # Do not add min_column_distance to the first column. + if i > 0: + widths[i] = w + min_column_distance + with open(os.path.join(self.output_dir, filename), "w") as f: + header_str = ("{:>{}}" * len(widths)).format(*itertools.chain(*zip(header, widths))) + separator = "-" * len(header_str) + f.write(header_str + "\n") + f.write(separator + "\n") + for row_values in rows: + r = ("{:>{}}" * len(widths)).format(*itertools.chain(*zip(row_values, widths))) + f.write(r + "\n") + f.write(separator + "\n") + footer_str = ("{:>{}}" * len(widths)).format(*itertools.chain(*zip(footer, widths))) + f.write(footer_str + "\n") + + def _report_any_exprs(self) -> None: + total_any = sum(num_any for num_any, _ in self.counts.values()) + total_expr = sum(total for _, total in self.counts.values()) + total_coverage = 100.0 + if total_expr > 0: + total_coverage = (float(total_expr - total_any) / float(total_expr)) * 100 + + column_names = ["Name", "Anys", "Exprs", "Coverage"] + rows: list[list[str]] = [] + for filename in sorted(self.counts): + num_any, num_total = self.counts[filename] + coverage = (float(num_total - num_any) / float(num_total)) * 100 + coverage_str = f"{coverage:.2f}%" + rows.append([filename, str(num_any), str(num_total), coverage_str]) + rows.sort(key=lambda x: x[0]) + total_row = ["Total", str(total_any), str(total_expr), f"{total_coverage:.2f}%"] + self._write_out_report("any-exprs.txt", column_names, rows, total_row) + + def _report_types_of_anys(self) -> None: + total_counter: collections.Counter[int] = collections.Counter() + for counter in self.any_types_counter.values(): + for any_type, value in counter.items(): + total_counter[any_type] += value + file_column_name = "Name" + total_row_name = "Total" + column_names = [file_column_name] + list(type_of_any_name_map.values()) + rows: list[list[str]] = [] + for filename, counter in self.any_types_counter.items(): + rows.append([filename] + [str(counter[typ]) for typ in type_of_any_name_map]) + rows.sort(key=lambda x: x[0]) + total_row = [total_row_name] + [str(total_counter[typ]) for typ in type_of_any_name_map] + self._write_out_report("types-of-anys.txt", column_names, rows, total_row) + + +register_reporter("any-exprs", AnyExpressionsReporter) + + +class LineCoverageVisitor(TraverserVisitor): + def __init__(self, source: list[str]) -> None: + self.source = source + + # For each line of source, we maintain a pair of + # * the indentation level of the surrounding function + # (-1 if not inside a function), and + # * whether the surrounding function is typed. + # Initially, everything is covered at indentation level -1. + self.lines_covered = [(-1, True) for l in source] + + # The Python AST has position information for the starts of + # elements, but not for their ends. Fortunately the + # indentation-based syntax makes it pretty easy to find where a + # block ends without doing any real parsing. + + # TODO: Handle line continuations (explicit and implicit) and + # multi-line string literals. (But at least line continuations + # are normally more indented than their surrounding block anyways, + # by PEP 8.) + + def indentation_level(self, line_number: int) -> int | None: + """Return the indentation of a line of the source (specified by + zero-indexed line number). Returns None for blank lines or comments.""" + line = self.source[line_number] + indent = 0 + for char in list(line): + if char == " ": + indent += 1 + elif char == "\t": + indent = 8 * ((indent + 8) // 8) + elif char == "#": + # Line is a comment; ignore it + return None + elif char == "\n": + # Line is entirely whitespace; ignore it + return None + # TODO line continuation (\) + else: + # Found a non-whitespace character + return indent + # Line is entirely whitespace, and at end of file + # with no trailing newline; ignore it + return None + + def visit_func_def(self, defn: FuncDef) -> None: + start_line = defn.line - 1 + start_indent = None + # When a function is decorated, sometimes the start line will point to + # whitespace or comments between the decorator and the function, so + # we have to look for the start. + while start_line < len(self.source): + start_indent = self.indentation_level(start_line) + if start_indent is not None: + break + start_line += 1 + # If we can't find the function give up and don't annotate anything. + # Our line numbers are not reliable enough to be asserting on. + if start_indent is None: + return + + cur_line = start_line + 1 + end_line = cur_line + # After this loop, function body will be lines [start_line, end_line) + while cur_line < len(self.source): + cur_indent = self.indentation_level(cur_line) + if cur_indent is None: + # Consume the line, but don't mark it as belonging to the function yet. + cur_line += 1 + elif cur_indent > start_indent: + # A non-blank line that belongs to the function. + cur_line += 1 + end_line = cur_line + else: + # We reached a line outside the function definition. + break + + is_typed = defn.type is not None + for line in range(start_line, end_line): + old_indent, _ = self.lines_covered[line] + # If there was an old indent level for this line, and the new + # level isn't increasing the indentation, ignore it. + # This is to be defensive against funniness in our line numbers, + # which are not always reliable. + if old_indent <= start_indent: + self.lines_covered[line] = (start_indent, is_typed) + + # Visit the body, in case there are nested functions + super().visit_func_def(defn) + + +class LineCoverageReporter(AbstractReporter): + """Exact line coverage reporter. + + This reporter writes a JSON dictionary with one field 'lines' to + the file 'coverage.json' in the specified report directory. The + value of that field is a dictionary which associates to each + source file's absolute pathname the list of line numbers that + belong to typed functions in that file. + """ + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + self.lines_covered: dict[str, list[int]] = {} + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + if os.path.isdir(tree.path): # can happen with namespace packages + return + + with open(tree.path) as f: + tree_source = f.readlines() + + coverage_visitor = LineCoverageVisitor(tree_source) + tree.accept(coverage_visitor) + + covered_lines = [] + for line_number, (_, typed) in enumerate(coverage_visitor.lines_covered): + if typed: + covered_lines.append(line_number + 1) + + self.lines_covered[os.path.abspath(tree.path)] = covered_lines + + def on_finish(self) -> None: + with open(os.path.join(self.output_dir, "coverage.json"), "w") as f: + json.dump({"lines": self.lines_covered}, f) + + +register_reporter("linecoverage", LineCoverageReporter) + + +class FileInfo: + def __init__(self, name: str, module: str) -> None: + self.name = name + self.module = module + self.counts = [0] * len(stats.precision_names) + + def total(self) -> int: + return sum(self.counts) + + def attrib(self) -> dict[str, str]: + return {name: str(val) for name, val in sorted(zip(stats.precision_names, self.counts))} + + +class MemoryXmlReporter(AbstractReporter): + """Internal reporter that generates XML in memory. + + This is used by all other XML-based reporters to avoid duplication. + """ + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + + self.xslt_html_path = os.path.join(reports.data_dir, "xml", "mypy-html.xslt") + self.xslt_txt_path = os.path.join(reports.data_dir, "xml", "mypy-txt.xslt") + self.css_html_path = os.path.join(reports.data_dir, "xml", "mypy-html.css") + xsd_path = os.path.join(reports.data_dir, "xml", "mypy.xsd") + self.schema = etree.XMLSchema(etree.parse(xsd_path)) + self.last_xml: Any | None = None + self.files: list[FileInfo] = [] + + # XML doesn't like control characters, but they are sometimes + # legal in source code (e.g. comments, string literals). + # Tabs (#x09) are allowed in XML content. + control_fixer: Final = str.maketrans("".join(chr(i) for i in range(32) if i != 9), "?" * 31) + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + self.last_xml = None + + try: + path = os.path.relpath(tree.path) + except ValueError: + return + + if should_skip_path(path) or os.path.isdir(path): + return # `path` can sometimes be a directory, see #11334 + + visitor = stats.StatisticsVisitor( + inferred=True, + filename=tree.fullname, + modules=modules, + typemap=type_map, + all_nodes=True, + ) + tree.accept(visitor) + + root = etree.Element("mypy-report-file", name=path, module=tree._fullname) + doc = etree.ElementTree(root) + file_info = FileInfo(path, tree._fullname) + + for lineno, line_text in iterate_python_lines(path): + status = visitor.line_map.get(lineno, stats.TYPE_EMPTY) + file_info.counts[status] += 1 + etree.SubElement( + root, + "line", + any_info=self._get_any_info_for_line(visitor, lineno), + content=line_text.rstrip("\n").translate(self.control_fixer), + number=str(lineno), + precision=stats.precision_names[status], + ) + # Assumes a layout similar to what XmlReporter uses. + xslt_path = os.path.relpath("mypy-html.xslt", path) + transform_pi = etree.ProcessingInstruction( + "xml-stylesheet", f'type="text/xsl" href="{pathname2url(xslt_path)}"' + ) + root.addprevious(transform_pi) + self.schema.assertValid(doc) + + self.last_xml = doc + self.files.append(file_info) + + @staticmethod + def _get_any_info_for_line(visitor: stats.StatisticsVisitor, lineno: int) -> str: + if lineno in visitor.any_line_map: + result = "Any Types on this line: " + counter: collections.Counter[int] = collections.Counter() + for typ in visitor.any_line_map[lineno]: + counter[typ.type_of_any] += 1 + for any_type, occurrences in counter.items(): + result += f"\n{type_of_any_name_map[any_type]} (x{occurrences})" + return result + else: + return "No Anys on this line!" + + def on_finish(self) -> None: + self.last_xml = None + # index_path = os.path.join(self.output_dir, 'index.xml') + output_files = sorted(self.files, key=lambda x: x.module) + + root = etree.Element("mypy-report-index", name="index") + doc = etree.ElementTree(root) + + for file_info in output_files: + etree.SubElement( + root, + "file", + file_info.attrib(), + module=file_info.module, + name=pathname2url(file_info.name), + total=str(file_info.total()), + ) + xslt_path = os.path.relpath("mypy-html.xslt", ".") + transform_pi = etree.ProcessingInstruction( + "xml-stylesheet", f'type="text/xsl" href="{pathname2url(xslt_path)}"' + ) + root.addprevious(transform_pi) + self.schema.assertValid(doc) + + self.last_xml = doc + + +register_reporter("memory-xml", MemoryXmlReporter, needs_lxml=True) + + +def get_line_rate(covered_lines: int, total_lines: int) -> str: + if total_lines == 0: + return str(1.0) + else: + return f"{covered_lines / total_lines:.4f}" + + +class CoberturaPackage: + """Container for XML and statistics mapping python modules to Cobertura package.""" + + def __init__(self, name: str) -> None: + self.name = name + self.classes: dict[str, Any] = {} + self.packages: dict[str, CoberturaPackage] = {} + self.total_lines = 0 + self.covered_lines = 0 + + def as_xml(self) -> Any: + package_element = etree.Element("package", complexity="1.0", name=self.name) + package_element.attrib["branch-rate"] = "0" + package_element.attrib["line-rate"] = get_line_rate(self.covered_lines, self.total_lines) + classes_element = etree.SubElement(package_element, "classes") + for class_name in sorted(self.classes): + classes_element.append(self.classes[class_name]) + self.add_packages(package_element) + return package_element + + def add_packages(self, parent_element: Any) -> None: + if self.packages: + packages_element = etree.SubElement(parent_element, "packages") + for package in sorted(self.packages.values(), key=attrgetter("name")): + packages_element.append(package.as_xml()) + + +class CoberturaXmlReporter(AbstractReporter): + """Reporter for generating Cobertura compliant XML.""" + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + + self.root = etree.Element("coverage", timestamp=str(int(time.time())), version=__version__) + self.doc = etree.ElementTree(self.root) + self.root_package = CoberturaPackage(".") + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + path = os.path.relpath(tree.path) + visitor = stats.StatisticsVisitor( + inferred=True, + filename=tree.fullname, + modules=modules, + typemap=type_map, + all_nodes=True, + ) + tree.accept(visitor) + + class_name = os.path.basename(path) + file_info = FileInfo(path, tree._fullname) + class_element = etree.Element("class", complexity="1.0", filename=path, name=class_name) + etree.SubElement(class_element, "methods") + lines_element = etree.SubElement(class_element, "lines") + + class_lines_covered = 0 + class_total_lines = 0 + for lineno, _ in iterate_python_lines(path): + status = visitor.line_map.get(lineno, stats.TYPE_EMPTY) + hits = 0 + branch = False + if status == stats.TYPE_EMPTY: + continue + class_total_lines += 1 + if status != stats.TYPE_ANY: + class_lines_covered += 1 + hits = 1 + if status == stats.TYPE_IMPRECISE: + branch = True + file_info.counts[status] += 1 + line_element = etree.SubElement( + lines_element, + "line", + branch=str(branch).lower(), + hits=str(hits), + number=str(lineno), + precision=stats.precision_names[status], + ) + if branch: + line_element.attrib["condition-coverage"] = "50% (1/2)" + class_element.attrib["branch-rate"] = "0" + class_element.attrib["line-rate"] = get_line_rate(class_lines_covered, class_total_lines) + # parent_module is set to whichever module contains this file. For most files, we want + # to simply strip the last element off of the module. But for __init__.py files, + # the module == the parent module. + parent_module = file_info.module.rsplit(".", 1)[0] + if file_info.name.endswith("__init__.py"): + parent_module = file_info.module + + if parent_module not in self.root_package.packages: + self.root_package.packages[parent_module] = CoberturaPackage(parent_module) + current_package = self.root_package.packages[parent_module] + packages_to_update = [self.root_package, current_package] + for package in packages_to_update: + package.total_lines += class_total_lines + package.covered_lines += class_lines_covered + current_package.classes[class_name] = class_element + + def on_finish(self) -> None: + self.root.attrib["line-rate"] = get_line_rate( + self.root_package.covered_lines, self.root_package.total_lines + ) + self.root.attrib["branch-rate"] = "0" + self.root.attrib["lines-covered"] = str(self.root_package.covered_lines) + self.root.attrib["lines-valid"] = str(self.root_package.total_lines) + sources = etree.SubElement(self.root, "sources") + source_element = etree.SubElement(sources, "source") + source_element.text = os.getcwd() + self.root_package.add_packages(self.root) + out_path = os.path.join(self.output_dir, "cobertura.xml") + self.doc.write(out_path, encoding="utf-8", pretty_print=True) + print("Generated Cobertura report:", os.path.abspath(out_path)) + + +register_reporter("cobertura-xml", CoberturaXmlReporter, needs_lxml=True) + + +class AbstractXmlReporter(AbstractReporter): + """Internal abstract class for reporters that work via XML.""" + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + + memory_reporter = reports.add_report("memory-xml", "") + assert isinstance(memory_reporter, MemoryXmlReporter) + # The dependency will be called first. + self.memory_xml = memory_reporter + + +class XmlReporter(AbstractXmlReporter): + """Public reporter that exports XML. + + The produced XML files contain a reference to the absolute path + of the html transform, so they will be locally viewable in a browser. + + However, there is a bug in Chrome and all other WebKit-based browsers + that makes it fail from file:// URLs but work on http:// URLs. + """ + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + last_xml = self.memory_xml.last_xml + if last_xml is None: + return + path = os.path.relpath(tree.path) + if path.startswith(".."): + return + out_path = os.path.join(self.output_dir, "xml", path + ".xml") + os.makedirs(os.path.dirname(out_path), exist_ok=True) + last_xml.write(out_path, encoding="utf-8") + + def on_finish(self) -> None: + last_xml = self.memory_xml.last_xml + assert last_xml is not None + out_path = os.path.join(self.output_dir, "index.xml") + out_xslt = os.path.join(self.output_dir, "mypy-html.xslt") + out_css = os.path.join(self.output_dir, "mypy-html.css") + last_xml.write(out_path, encoding="utf-8") + shutil.copyfile(self.memory_xml.xslt_html_path, out_xslt) + shutil.copyfile(self.memory_xml.css_html_path, out_css) + print("Generated XML report:", os.path.abspath(out_path)) + + +register_reporter("xml", XmlReporter, needs_lxml=True) + + +class XsltHtmlReporter(AbstractXmlReporter): + """Public reporter that exports HTML via XSLT. + + This is slightly different than running `xsltproc` on the .xml files, + because it passes a parameter to rewrite the links. + """ + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + + self.xslt_html = etree.XSLT(etree.parse(self.memory_xml.xslt_html_path)) + self.param_html = etree.XSLT.strparam("html") + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + last_xml = self.memory_xml.last_xml + if last_xml is None: + return + path = os.path.relpath(tree.path) + if path.startswith(".."): + return + out_path = os.path.join(self.output_dir, "html", path + ".html") + os.makedirs(os.path.dirname(out_path), exist_ok=True) + transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html)) + with open(out_path, "wb") as out_file: + out_file.write(transformed_html) + + def on_finish(self) -> None: + last_xml = self.memory_xml.last_xml + assert last_xml is not None + out_path = os.path.join(self.output_dir, "index.html") + out_css = os.path.join(self.output_dir, "mypy-html.css") + transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html)) + with open(out_path, "wb") as out_file: + out_file.write(transformed_html) + shutil.copyfile(self.memory_xml.css_html_path, out_css) + print("Generated HTML report (via XSLT):", os.path.abspath(out_path)) + + +register_reporter("xslt-html", XsltHtmlReporter, needs_lxml=True) + + +class XsltTxtReporter(AbstractXmlReporter): + """Public reporter that exports TXT via XSLT. + + Currently this only does the summary, not the individual reports. + """ + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + + self.xslt_txt = etree.XSLT(etree.parse(self.memory_xml.xslt_txt_path)) + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + pass + + def on_finish(self) -> None: + last_xml = self.memory_xml.last_xml + assert last_xml is not None + out_path = os.path.join(self.output_dir, "index.txt") + transformed_txt = bytes(self.xslt_txt(last_xml)) + with open(out_path, "wb") as out_file: + out_file.write(transformed_txt) + print("Generated TXT report (via XSLT):", os.path.abspath(out_path)) + + +register_reporter("xslt-txt", XsltTxtReporter, needs_lxml=True) + +alias_reporter("xslt-html", "html") +alias_reporter("xslt-txt", "txt") + + +class LinePrecisionReporter(AbstractReporter): + """Report per-module line counts for typing precision. + + Each line is classified into one of these categories: + + * precise (fully type checked) + * imprecise (Any types in a type component, such as List[Any]) + * any (something with an Any type, implicit or explicit) + * empty (empty line, comment or docstring) + * unanalyzed (mypy considers line unreachable) + + The meaning of these categories varies slightly depending on + context. + """ + + def __init__(self, reports: Reports, output_dir: str) -> None: + super().__init__(reports, output_dir) + self.files: list[FileInfo] = [] + + def on_file( + self, + tree: MypyFile, + modules: dict[str, MypyFile], + type_map: dict[Expression, Type], + options: Options, + ) -> None: + try: + path = os.path.relpath(tree.path) + except ValueError: + return + + if should_skip_path(path): + return + + visitor = stats.StatisticsVisitor( + inferred=True, + filename=tree.fullname, + modules=modules, + typemap=type_map, + all_nodes=True, + ) + tree.accept(visitor) + + file_info = FileInfo(path, tree._fullname) + for lineno, _ in iterate_python_lines(path): + status = visitor.line_map.get(lineno, stats.TYPE_EMPTY) + file_info.counts[status] += 1 + + self.files.append(file_info) + + def on_finish(self) -> None: + if not self.files: + # Nothing to do. + return + output_files = sorted(self.files, key=lambda x: x.module) + report_file = os.path.join(self.output_dir, "lineprecision.txt") + width = max(4, max(len(info.module) for info in output_files)) + titles = ("Lines", "Precise", "Imprecise", "Any", "Empty", "Unanalyzed") + widths = (width,) + tuple(len(t) for t in titles) + fmt = "{:%d} {:%d} {:%d} {:%d} {:%d} {:%d} {:%d}\n" % widths + with open(report_file, "w") as f: + f.write(fmt.format("Name", *titles)) + f.write("-" * (width + 51) + "\n") + for file_info in output_files: + counts = file_info.counts + f.write( + fmt.format( + file_info.module.ljust(width), + file_info.total(), + counts[stats.TYPE_PRECISE], + counts[stats.TYPE_IMPRECISE], + counts[stats.TYPE_ANY], + counts[stats.TYPE_EMPTY], + counts[stats.TYPE_UNANALYZED], + ) + ) + + +register_reporter("lineprecision", LinePrecisionReporter) + + +# Reporter class names are defined twice to speed up mypy startup, as this +# module is slow to import. Ensure that the two definitions match. +assert set(reporter_classes) == set(REPORTER_NAMES) diff --git a/micromamba_root/Lib/site-packages/mypy/scope.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/scope.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e4cc93418abb0955dc9b92192e0eb739d701007a Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/scope.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/scope.py b/micromamba_root/Lib/site-packages/mypy/scope.py new file mode 100644 index 0000000000000000000000000000000000000000..7c234a3c7bc5640b22e5b07774b487e96edcf815 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/scope.py @@ -0,0 +1,125 @@ +"""Track current scope to easily calculate the corresponding fine-grained target. + +TODO: Use everywhere where we track targets, including in mypy.errors. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager, nullcontext +from typing import TypeAlias as _TypeAlias + +from mypy.nodes import FuncBase, TypeInfo + +SavedScope: _TypeAlias = tuple[str, TypeInfo | None, FuncBase | None] + + +class Scope: + """Track which target we are processing at any given time.""" + + def __init__(self) -> None: + self.module: str | None = None + self.classes: list[TypeInfo] = [] + self.function: FuncBase | None = None + self.functions: list[FuncBase] = [] + # Number of nested scopes ignored (that don't get their own separate targets) + self.ignored = 0 + + def current_module_id(self) -> str: + assert self.module + return self.module + + def current_target(self) -> str: + """Return the current target (non-class; for a class return enclosing module).""" + assert self.module + if self.function: + fullname = self.function.fullname + return fullname or "" + return self.module + + def current_full_target(self) -> str: + """Return the current target (may be a class).""" + assert self.module + if self.function: + return self.function.fullname + if self.classes: + return self.classes[-1].fullname + return self.module + + def current_type_name(self) -> str | None: + """Return the current type's short name if it exists""" + return self.classes[-1].name if self.classes else None + + def current_function_name(self) -> str | None: + """Return the current function's short name if it exists""" + return self.function.name if self.function else None + + @contextmanager + def module_scope(self, prefix: str) -> Iterator[None]: + self.module = prefix + self.classes = [] + self.function = None + self.ignored = 0 + yield + assert self.module + self.module = None + + @contextmanager + def function_scope(self, fdef: FuncBase) -> Iterator[None]: + self.functions.append(fdef) + if not self.function: + self.function = fdef + else: + # Nested functions are part of the topmost function target. + self.ignored += 1 + yield + self.functions.pop() + if self.ignored: + # Leave a scope that's included in the enclosing target. + self.ignored -= 1 + else: + assert self.function + self.function = None + + def outer_functions(self) -> list[FuncBase]: + return self.functions[:-1] + + def enter_class(self, info: TypeInfo) -> None: + """Enter a class target scope.""" + if not self.function: + self.classes.append(info) + else: + # Classes within functions are part of the enclosing function target. + self.ignored += 1 + + def leave_class(self) -> None: + """Leave a class target scope.""" + if self.ignored: + # Leave a scope that's included in the enclosing target. + self.ignored -= 1 + else: + assert self.classes + # Leave the innermost class. + self.classes.pop() + + @contextmanager + def class_scope(self, info: TypeInfo) -> Iterator[None]: + self.enter_class(info) + yield + self.leave_class() + + def save(self) -> SavedScope: + """Produce a saved scope that can be entered with saved_scope()""" + assert self.module + # We only save the innermost class, which is sufficient since + # the rest are only needed for when classes are left. + cls = self.classes[-1] if self.classes else None + return self.module, cls, self.function + + @contextmanager + def saved_scope(self, saved: SavedScope) -> Iterator[None]: + module, info, function = saved + with self.module_scope(module): + with self.class_scope(info) if info else nullcontext(): + with self.function_scope(function) if function else nullcontext(): + yield diff --git a/micromamba_root/Lib/site-packages/mypy/semanal.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/semanal.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..c146e1e72aa794e80e04a649c406f8b715943153 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/semanal.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/semanal.py b/micromamba_root/Lib/site-packages/mypy/semanal.py new file mode 100644 index 0000000000000000000000000000000000000000..d944c60cd16e4aa68d9c9d5011d32e516144d319 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/semanal.py @@ -0,0 +1,8390 @@ +"""The semantic analyzer. + +Bind names to definitions and do various other simple consistency +checks. Populate symbol tables. The semantic analyzer also detects +special forms which reuse generic syntax such as NamedTuple and +cast(). Multiple analysis iterations may be needed to analyze forward +references and import cycles. Each iteration "fills in" additional +bindings and references until everything has been bound. + +For example, consider this program: + + x = 1 + y = x + +Here semantic analysis would detect that the assignment 'x = 1' +defines a new variable, the type of which is to be inferred (in a +later pass; type inference or type checking is not part of semantic +analysis). Also, it would bind both references to 'x' to the same +module-level variable (Var) node. The second assignment would also +be analyzed, and the type of 'y' marked as being inferred. + +Semantic analysis of types is implemented in typeanal.py. + +See semanal_main.py for the top-level logic. + +Some important properties: + +* After semantic analysis is complete, no PlaceholderNode and + PlaceholderType instances should remain. During semantic analysis, + if we encounter one of these, the current target should be deferred. + +* A TypeInfo is only created once we know certain basic information about + a type, such as the MRO, existence of a Tuple base class (e.g., for named + tuples), and whether we have a TypedDict. We use a temporary + PlaceholderNode node in the symbol table if some such information is + missing. + +* For assignments, we only add a non-placeholder symbol table entry once + we know the sort of thing being defined (variable, NamedTuple, type alias, + etc.). + +* Every part of the analysis step must support multiple iterations over + the same AST nodes, and each iteration must be able to fill in arbitrary + things that were missing or incomplete in previous iterations. + +* Changes performed by the analysis need to be reversible, since mypy + daemon strips and reuses existing ASTs (to improve performance and/or + reduce memory use). +""" + +from __future__ import annotations + +import re +from collections.abc import Callable, Collection, Iterable, Iterator +from contextlib import contextmanager +from typing import Any, Final, TypeAlias as _TypeAlias, TypeGuard, TypeVar, cast +from typing_extensions import assert_never + +from mypy import errorcodes as codes, message_registry +from mypy.constant_fold import constant_fold_expr +from mypy.errorcodes import PROPERTY_DECORATOR, ErrorCode +from mypy.errors import Errors, report_internal_error +from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type +from mypy.message_registry import ErrorMessage +from mypy.messages import ( + SUGGESTED_TEST_FIXTURES, + TYPES_FOR_UNIMPORTED_HINTS, + MessageBuilder, + best_matches, + pretty_seq, +) +from mypy.mro import MroError, calculate_mro +from mypy.nodes import ( + ARG_NAMED, + ARG_POS, + ARG_STAR2, + CONTRAVARIANT, + COVARIANT, + GDEF, + IMPLICITLY_ABSTRACT, + INVARIANT, + IS_ABSTRACT, + LDEF, + MDEF, + NOT_ABSTRACT, + PARAM_SPEC_KIND, + REVEAL_LOCALS, + REVEAL_TYPE, + RUNTIME_PROTOCOL_DECOS, + SYMBOL_FUNCBASE_TYPES, + TYPE_VAR_KIND, + TYPE_VAR_TUPLE_KIND, + VARIANCE_NOT_READY, + ArgKind, + AssertStmt, + AssertTypeExpr, + AssignmentExpr, + AssignmentStmt, + AwaitExpr, + Block, + BreakStmt, + BytesExpr, + CallExpr, + CastExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + Context, + ContinueStmt, + DataclassTransformSpec, + Decorator, + DelStmt, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + EnumCallExpr, + Expression, + ExpressionStmt, + FakeExpression, + FloatExpr, + ForStmt, + FuncBase, + FuncDef, + FuncItem, + GeneratorExpr, + GlobalDecl, + IfStmt, + Import, + ImportAll, + ImportBase, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + Lvalue, + MatchStmt, + MaybeTypeExpression, + MemberExpr, + MypyFile, + NamedTupleExpr, + NameExpr, + Node, + NonlocalDecl, + OperatorAssignmentStmt, + OpExpr, + OverloadedFuncDef, + OverloadPart, + ParamSpecExpr, + PassStmt, + PlaceholderNode, + PromoteExpr, + RaiseStmt, + RefExpr, + ReturnStmt, + RevealExpr, + SetComprehension, + SetExpr, + SliceExpr, + SplittingVisitor, + StarExpr, + Statement, + StrExpr, + SuperExpr, + SymbolNode, + SymbolTable, + SymbolTableNode, + TemplateStrExpr, + TempNode, + TryStmt, + TupleExpr, + TypeAlias, + TypeAliasExpr, + TypeAliasStmt, + TypeApplication, + TypedDictExpr, + TypeFormExpr, + TypeInfo, + TypeParam, + TypeVarExpr, + TypeVarLikeExpr, + TypeVarTupleExpr, + UnaryExpr, + Var, + WhileStmt, + WithStmt, + YieldExpr, + YieldFromExpr, + get_member_expr_fullname, + implicit_module_attrs, + is_final_node, + type_aliases, + type_aliases_source_versions, + typing_extensions_aliases, +) +from mypy.options import TYPE_FORM, Options +from mypy.patterns import ( + AsPattern, + ClassPattern, + MappingPattern, + OrPattern, + SequencePattern, + SingletonPattern, + StarredPattern, + ValuePattern, +) +from mypy.plugin import ( + ClassDefContext, + DynamicClassDefContext, + Plugin, + SemanticAnalyzerPluginInterface, +) +from mypy.plugins import dataclasses as dataclasses_plugin +from mypy.reachability import ( + ALWAYS_FALSE, + ALWAYS_TRUE, + MYPY_FALSE, + MYPY_TRUE, + infer_condition_value, + infer_reachability_of_if_statement, + infer_reachability_of_match_statement, +) +from mypy.scope import Scope +from mypy.semanal_enum import EnumCallAnalyzer +from mypy.semanal_namedtuple import NamedTupleAnalyzer +from mypy.semanal_newtype import NewTypeAnalyzer +from mypy.semanal_shared import ( + ALLOW_INCOMPATIBLE_OVERRIDE, + PRIORITY_FALLBACKS, + SemanticAnalyzerInterface, + calculate_tuple_fallback, + find_dataclass_transform_spec, + has_placeholder, + parse_bool, + require_bool_literal_argument, + set_callable_name as set_callable_name, +) +from mypy.semanal_typeddict import TypedDictAnalyzer +from mypy.tvar_scope import TypeVarLikeScope +from mypy.typeanal import ( + SELF_TYPE_NAMES, + FindTypeVarVisitor, + TypeAnalyser, + TypeVarDefaultTranslator, + TypeVarLikeList, + analyze_type_alias, + check_for_explicit_any, + check_vec_type_args, + detect_diverging_alias, + find_self_type, + fix_instance, + has_any_from_unimported_type, + type_constructors, + validate_instance, +) +from mypy.typeops import function_type, get_type_vars, try_getting_str_literals_from_type +from mypy.types import ( + ASSERT_TYPE_NAMES, + DATACLASS_TRANSFORM_NAMES, + DEPRECATED_TYPE_NAMES, + DISJOINT_BASE_DECORATOR_NAMES, + FINAL_DECORATOR_NAMES, + FINAL_TYPE_NAMES, + IMPORTED_REVEAL_TYPE_NAMES, + NEVER_NAMES, + OVERLOAD_NAMES, + OVERRIDE_DECORATOR_NAMES, + PROTOCOL_NAMES, + REVEAL_TYPE_NAMES, + TPDICT_NAMES, + TYPE_ALIAS_NAMES, + TYPE_CHECK_ONLY_NAMES, + TYPE_NAMES, + TYPE_VAR_LIKE_NAMES, + TYPED_NAMEDTUPLE_NAMES, + UNPACK_TYPE_NAMES, + AnyType, + CallableType, + FunctionLike, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PlaceholderType, + ProperType, + TrivialSyntheticTypeTranslator, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeStrVisitor, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UnionType, + UnpackType, + flatten_nested_tuples, + get_proper_type, + get_proper_types, + has_type_vars, + is_named_instance, + remove_dups, + type_vars_as_args, +) +from mypy.types_utils import is_invalid_recursive_alias, store_argument_type +from mypy.typevars import fill_typevars +from mypy.util import correct_relative_import, is_dunder, module_prefix, unmangle, unnamed_function +from mypy.visitor import NodeVisitor + +T = TypeVar("T") + + +# Whether to print diagnostic information for failed full parses +# in SemanticAnalyzer.try_parse_as_type_expression(). +# +# See also: misc/analyze_typeform_stats.py +DEBUG_TYPE_EXPRESSION_FULL_PARSE_FAILURES: Final = False + + +FUTURE_IMPORTS: Final = { + "__future__.nested_scopes": "nested_scopes", + "__future__.generators": "generators", + "__future__.division": "division", + "__future__.absolute_import": "absolute_import", + "__future__.with_statement": "with_statement", + "__future__.print_function": "print_function", + "__future__.unicode_literals": "unicode_literals", + "__future__.barry_as_FLUFL": "barry_as_FLUFL", + "__future__.generator_stop": "generator_stop", + "__future__.annotations": "annotations", +} + + +# Special cased built-in classes that are needed for basic functionality and need to be +# available very early on. +CORE_BUILTIN_CLASSES: Final = ["object", "bool", "function"] + + +# Python has several different scope/namespace kinds with subtly different semantics. +SCOPE_GLOBAL: Final = 0 # Module top level +SCOPE_CLASS: Final = 1 # Class body +SCOPE_FUNC: Final = 2 # Function or lambda +SCOPE_COMPREHENSION: Final = 3 # Comprehension or generator expression +SCOPE_ANNOTATION: Final = 4 # Annotation scopes for type parameters and aliases (PEP 695) + + +# Used for tracking incomplete references +Tag: _TypeAlias = int + + +# Matches two words separated by whitespace, where each word lacks +# any symbols which have special meaning in a type expression. +# +# Any string literal matching this common pattern cannot be a valid +# type expression and can be ignored quickly when attempting to parse a +# string literal as a type expression. +_MULTIPLE_WORDS_NONTYPE_RE = re.compile(r'\s*[^\s.\'"|\[]+\s+[^\s.\'"|\[]') + +# Matches any valid Python identifier, including identifiers with Unicode characters. +# +# [^\d\W] = word character that is not a digit +# \w = word character +# \Z = match end of string; does not allow a trailing \n, unlike $ +_IDENTIFIER_RE = re.compile(r"^[^\d\W]\w*\Z", re.UNICODE) + + +class SemanticAnalyzer( + NodeVisitor[None], SemanticAnalyzerInterface, SemanticAnalyzerPluginInterface, SplittingVisitor +): + """Semantically analyze parsed mypy files. + + The analyzer binds names and does various consistency checks for an + AST. Note that type checking is performed as a separate pass. + """ + + __deletable__ = ["patches", "options", "cur_mod_node"] + + # Module name space + modules: dict[str, MypyFile] + # Global name space for current module + globals: SymbolTable + # Names declared using "global" (separate set for each scope) + global_decls: list[set[str]] + # Names declared using "nonlocal" (separate set for each scope) + nonlocal_decls: list[set[str]] + # Local names of function scopes; None for non-function scopes. + locals: list[SymbolTable | None] + # Type of each scope (SCOPE_*, indexes match locals) + scope_stack: list[int] + # Nested block depths of scopes + block_depth: list[int] + # TypeInfo of directly enclosing class (or None) + _type: TypeInfo | None = None + # Stack of outer classes (the second tuple item contains tvars). + type_stack: list[TypeInfo | None] + # Type variables bound by the current scope, be it class or function + tvar_scope: TypeVarLikeScope + # Per-module options + options: Options + + # Stack of functions being analyzed + function_stack: list[FuncItem] + + # Set to True if semantic analysis defines a name, or replaces a + # placeholder definition. If some iteration makes no progress, + # there can be at most one additional final iteration (see below). + progress = False + deferred = False # Set to true if another analysis pass is needed + incomplete = False # Set to true if current module namespace is missing things + # Is this the final iteration of semantic analysis (where we report + # unbound names due to cyclic definitions and should not defer)? + _final_iteration = False + # These names couldn't be added to the symbol table due to incomplete deps. + # Note that missing names are per module, _not_ per namespace. This means that e.g. + # a missing name at global scope will block adding same name at a class scope. + # This should not affect correctness and is purely a performance issue, + # since it can cause unnecessary deferrals. These are represented as + # PlaceholderNodes in the symbol table. We use this to ensure that the first + # definition takes precedence even if it's incomplete. + # + # Note that a star import adds a special name '*' to the set, this blocks + # adding _any_ names in the current file. + missing_names: list[set[str]] + # Callbacks that will be called after semantic analysis to tweak things. + patches: list[tuple[int, Callable[[], None]]] + loop_depth: list[int] # Depth of breakable loops + cur_mod_id = "" # Current module id (or None) (phase 2) + _is_stub_file = False # Are we analyzing a stub file? + _is_typeshed_stub_file = False # Are we analyzing a typeshed stub file? + imports: set[str] # Imported modules (during phase 2 analysis) + # Note: some imports (and therefore dependencies) might + # not be found in phase 1, for example due to * imports. + errors: Errors # Keeps track of generated errors + plugin: Plugin # Mypy plugin for special casing of library features + statement: Statement | None = None # Statement/definition being analyzed + + # Mapping from 'async def' function definitions to their return type wrapped as a + # 'Coroutine[Any, Any, T]'. Used to keep track of whether a function definition's + # return type has already been wrapped, by checking if the function definition's + # type is stored in this mapping and that it still matches. + wrapped_coro_return_types: dict[FuncDef, Type] = {} + + def __init__( + self, + modules: dict[str, MypyFile], + missing_modules: dict[str, int], + incomplete_namespaces: set[str], + errors: Errors, + plugin: Plugin, + import_map: dict[str, set[str]], + ) -> None: + """Construct semantic analyzer. + + We reuse the same semantic analyzer instance across multiple modules. + + Args: + modules: Global modules dictionary + missing_modules: Modules that could not be imported encountered so far + incomplete_namespaces: Namespaces that are being populated during semantic analysis + (can contain modules and classes within the current SCC; mutated by the caller) + errors: Report analysis errors using this instance + """ + self.locals = [None] + self.scope_stack = [SCOPE_GLOBAL] + # Saved namespaces from previous iteration. Every top-level function/method body is + # analyzed in several iterations until all names are resolved. We need to save + # the local namespaces for the top level function and all nested functions between + # these iterations. See also semanal_main.process_top_level_function(). + self.saved_locals: dict[ + FuncItem | GeneratorExpr | DictionaryComprehension, SymbolTable + ] = {} + self.imports = set() + self._type = None + self.type_stack = [] + # Are the namespaces of classes being processed complete? + self.incomplete_type_stack: list[bool] = [] + self.tvar_scope = TypeVarLikeScope() + self.function_stack = [] + self.block_depth = [0] + self.loop_depth = [0] + self.errors = errors + self.modules = modules + self.import_map = import_map + self.msg = MessageBuilder(errors, modules) + self.missing_modules = missing_modules + self.missing_names = [set()] + # These namespaces are still in process of being populated. If we encounter a + # missing name in these namespaces, we need to defer the current analysis target, + # since it's possible that the name will be there once the namespace is complete. + self.incomplete_namespaces = incomplete_namespaces + self.all_exports: list[str] = [] + self.plugin = plugin + self.recurse_into_functions = True + self.scope = Scope() + + # Trace line numbers for every file where deferral happened during analysis of + # current SCC or top-level function. + self.deferral_debug_context: list[tuple[str, int]] = [] + + # This is needed to properly support recursive type aliases. The problem is that + # Foo[Bar] could mean three things depending on context: a target for type alias, + # a normal index expression (including enum index), or a type application. + # The latter is particularly problematic as it can falsely create incomplete + # refs while analysing rvalues of type aliases. To avoid this we first analyse + # rvalues while temporarily setting this to True. + self.basic_type_applications = False + + # Used to temporarily enable unbound type variables in some contexts. Namely, + # in base class expressions, and in right hand sides of type aliases. Do not add + # new uses of this, as this may cause leaking `UnboundType`s to type checking. + self.allow_unbound_tvars = False + + # Used to pass information about current overload index to visit_func_def(). + self.current_overload_item: int | None = None + + # Used to track whether currently inside an except* block. This helps + # to invoke errors when continue/break/return is used inside except* block. + self.inside_except_star_block: bool = False + # Used to track edge case when return is still inside except* if it enters a loop + self.return_stmt_inside_except_star_block: bool = False + + self._str_type: Instance | None = None + self._function_type: Instance | None = None + self._object_type: Instance | None = None + + # TypeForm profiling counters + self.type_expression_parse_count: int = 0 # Total try_parse_as_type_expression calls + self.type_expression_full_parse_success_count: int = 0 # Successful full parses + self.type_expression_full_parse_failure_count: int = 0 # Failed full parses + + # Imports of submodules transitively visible from given module. + # This is needed to support patterns like this + # [a.py] + # import b + # import foo + # foo.bar # <- this should work even if bar is not re-exported in foo + # [b.py] + # import foo.bar + self.transitive_submodule_imports: dict[str, set[str]] = {} + + # mypyc doesn't properly handle implementing an abstractproperty + # with a regular attribute so we make them properties + @property + def type(self) -> TypeInfo | None: + return self._type + + @property + def is_stub_file(self) -> bool: + return self._is_stub_file + + @property + def is_typeshed_stub_file(self) -> bool: + return self._is_typeshed_stub_file + + @property + def final_iteration(self) -> bool: + return self._final_iteration + + @contextmanager + def allow_unbound_tvars_set(self) -> Iterator[None]: + old = self.allow_unbound_tvars + self.allow_unbound_tvars = True + try: + yield + finally: + self.allow_unbound_tvars = old + + @contextmanager + def inside_except_star_block_set( + self, value: bool, entering_loop: bool = False + ) -> Iterator[None]: + old = self.inside_except_star_block + self.inside_except_star_block = value + + # Return statement would still be in except* scope if entering loops + if not entering_loop: + old_return_stmt_flag = self.return_stmt_inside_except_star_block + self.return_stmt_inside_except_star_block = value + + try: + yield + finally: + self.inside_except_star_block = old + if not entering_loop: + self.return_stmt_inside_except_star_block = old_return_stmt_flag + + # + # Preparing module (performed before semantic analysis) + # + + def prepare_file(self, file_node: MypyFile) -> None: + """Prepare a freshly parsed file for semantic analysis.""" + if "builtins" in self.modules: + file_node.names["__builtins__"] = SymbolTableNode(GDEF, self.modules["builtins"]) + if file_node.fullname == "builtins": + self.prepare_builtins_namespace(file_node) + if file_node.fullname == "typing": + self.prepare_typing_namespace(file_node, type_aliases) + if file_node.fullname == "typing_extensions": + self.prepare_typing_namespace(file_node, typing_extensions_aliases) + + def prepare_typing_namespace(self, file_node: MypyFile, aliases: dict[str, str]) -> None: + """Remove dummy alias definitions such as List = TypeAlias(object) from typing. + + They will be replaced with real aliases when corresponding targets are ready. + """ + + # This is all pretty unfortunate. typeshed now has a + # sys.version_info check for OrderedDict, and we shouldn't + # take it out, because it is correct and a typechecker should + # use that as a source of truth. But instead we rummage + # through IfStmts to remove the info first. (I tried to + # remove this whole machinery and ran into issues with the + # builtins/typing import cycle.) + def helper(defs: list[Statement]) -> None: + for stmt in defs.copy(): + if isinstance(stmt, IfStmt): + for body in stmt.body: + helper(body.body) + if stmt.else_body: + helper(stmt.else_body.body) + if ( + isinstance(stmt, AssignmentStmt) + and len(stmt.lvalues) == 1 + and isinstance(stmt.lvalues[0], NameExpr) + ): + # Assignment to a simple name, remove it if it is a dummy alias. + if f"{file_node.fullname}.{stmt.lvalues[0].name}" in aliases: + defs.remove(stmt) + + helper(file_node.defs) + + def prepare_builtins_namespace(self, file_node: MypyFile) -> None: + """Add certain special-cased definitions to the builtins module. + + Some definitions are too special or fundamental to be processed + normally from the AST. + """ + names = file_node.names + + # Add empty definition for core built-in classes, since they are required for basic + # operation. These will be completed later on. + for name in CORE_BUILTIN_CLASSES: + cdef = ClassDef(name, Block([])) # Dummy ClassDef, will be replaced later + info = TypeInfo(SymbolTable(), cdef, "builtins") + info._fullname = f"builtins.{name}" + names[name] = SymbolTableNode(GDEF, info) + + bool_info = names["bool"].node + assert isinstance(bool_info, TypeInfo) + bool_type = Instance(bool_info, []) + + special_var_types: list[tuple[str, Type]] = [ + ("None", NoneType()), + # reveal_type is a mypy-only function that gives an error with + # the type of its arg. + ("reveal_type", AnyType(TypeOfAny.special_form)), + # reveal_locals is a mypy-only function that gives an error with the types of + # locals + ("reveal_locals", AnyType(TypeOfAny.special_form)), + ("True", bool_type), + ("False", bool_type), + ("__debug__", bool_type), + ] + + for name, typ in special_var_types: + v = Var(name, typ) + v._fullname = f"builtins.{name}" + file_node.names[name] = SymbolTableNode(GDEF, v) + + # + # Analyzing a target + # + + def refresh_partial( + self, + node: MypyFile | FuncDef | OverloadedFuncDef, + patches: list[tuple[int, Callable[[], None]]], + final_iteration: bool, + file_node: MypyFile, + options: Options, + active_type: TypeInfo | None = None, + ) -> None: + """Refresh a stale target in fine-grained incremental mode.""" + self.patches = patches + self.deferred = False + self.incomplete = False + self._final_iteration = final_iteration + self.missing_names[-1] = set() + + with self.file_context(file_node, options, active_type): + if isinstance(node, MypyFile): + self.refresh_top_level(node) + else: + self.recurse_into_functions = True + self.accept(node) + del self.patches + + def refresh_top_level(self, file_node: MypyFile) -> None: + """Reanalyze a stale module top-level in fine-grained incremental mode.""" + if self.options.allow_redefinition_new and not self.options.local_partial_types: + n = TempNode(AnyType(TypeOfAny.special_form)) + n.line = 1 + n.column = 0 + n.end_line = 1 + n.end_column = 0 + self.fail("--local-partial-types must be enabled if using --allow-redefinition-new", n) + if self.options.allow_redefinition_new and self.options.allow_redefinition_old: + n = TempNode(AnyType(TypeOfAny.special_form)) + n.line = 1 + n.column = 0 + n.end_line = 1 + n.end_column = 0 + self.fail( + "--allow-redefinition-old and --allow-redefinition-new" + " should not be used together", + n, + ) + self.recurse_into_functions = False + self.add_implicit_module_attrs(file_node) + for d in file_node.defs: + self.accept(d) + if file_node.fullname == "typing": + self.add_builtin_aliases(file_node) + if file_node.fullname == "typing_extensions": + self.add_typing_extension_aliases(file_node) + self.adjust_public_exports() + self.all_exports = [] + + def add_implicit_module_attrs(self, file_node: MypyFile) -> None: + """Manually add implicit definitions of module '__name__' etc.""" + str_type: Type | None = self.named_type_or_none("builtins.str") + if str_type is None: + str_type = UnboundType("builtins.str") + inst: Type | None + for name, t in implicit_module_attrs.items(): + if name == "__doc__": + typ: Type = str_type + elif name == "__path__": + if not file_node.is_package_init_file(): + continue + # Need to construct the type ourselves, to avoid issues with __builtins__.list + # not being subscriptable or typing.List not getting bound + inst = self.named_type_or_none("builtins.list", [str_type]) + if inst is None: + assert not self.final_iteration, "Cannot find builtins.list to add __path__" + self.defer() + return + typ = inst + elif name == "__annotations__": + inst = self.named_type_or_none( + "builtins.dict", [str_type, AnyType(TypeOfAny.special_form)] + ) + if inst is None: + assert ( + not self.final_iteration + ), "Cannot find builtins.dict to add __annotations__" + self.defer() + return + typ = inst + elif name == "__spec__": + if self.options.use_builtins_fixtures: + inst = self.named_type_or_none("builtins.object") + else: + inst = self.named_type_or_none("importlib.machinery.ModuleSpec") + if inst is None: + if ( + self.final_iteration + or self.options.clone_for_module("importlib.machinery").follow_imports + == "skip" + ): + # If we are not allowed to resolve imports from `importlib.machinery`, + # ModuleSpec will not be available at any iteration. + # Use the fallback earlier. + # (see https://github.com/python/mypy/issues/18237) + inst = self.named_type_or_none("builtins.object") + assert inst is not None, "Cannot find builtins.object" + else: + self.defer() + return + if file_node.name == "__main__": + # https://docs.python.org/3/reference/import.html#main-spec + inst = UnionType.make_union([inst, NoneType()]) + typ = inst + else: + assert t is not None, f"type should be specified for {name}" + typ = UnboundType(t) + + existing = file_node.names.get(name) + if existing is not None and not isinstance(existing.node, PlaceholderNode): + # Already exists. + continue + + an_type = self.anal_type(typ) + if an_type: + var = Var(name, an_type) + var._fullname = self.qualified_name(name) + var.is_ready = True + self.add_symbol(name, var, dummy_context()) + else: + self.add_symbol( + name, + PlaceholderNode(self.qualified_name(name), file_node, -1), + dummy_context(), + ) + + def add_builtin_aliases(self, tree: MypyFile) -> None: + """Add builtin type aliases to typing module. + + For historical reasons, the aliases like `List = list` are not defined + in typeshed stubs for typing module. Instead we need to manually add the + corresponding nodes on the fly. We explicitly mark these aliases as normalized, + so that a user can write `typing.List[int]`. + """ + assert tree.fullname == "typing" + for alias, target_name in type_aliases.items(): + if ( + alias in type_aliases_source_versions + and type_aliases_source_versions[alias] > self.options.python_version + ): + # This alias is not available on this Python version. + continue + name = alias.split(".")[-1] + if name in tree.names and not isinstance(tree.names[name].node, PlaceholderNode): + continue + self.create_alias(tree, target_name, alias, name) + + def add_typing_extension_aliases(self, tree: MypyFile) -> None: + """Typing extensions module does contain some type aliases. + + We need to analyze them as such, because in typeshed + they are just defined as `_Alias()` call. + Which is not supported natively. + """ + assert tree.fullname == "typing_extensions" + + for alias, target_name in typing_extensions_aliases.items(): + name = alias.split(".")[-1] + if name in tree.names and isinstance(tree.names[name].node, TypeAlias): + continue # Do not reset TypeAliases on the second pass. + + # We need to remove any node that is there at the moment. It is invalid. + tree.names.pop(name, None) + + # Now, create a new alias. + self.create_alias(tree, target_name, alias, name) + + def create_alias(self, tree: MypyFile, target_name: str, alias: str, name: str) -> None: + tag = self.track_incomplete_refs() + n = self.lookup_fully_qualified_or_none(target_name) + if n: + if isinstance(n.node, PlaceholderNode): + self.mark_incomplete(name, tree) + else: + # Found built-in class target. Create alias. + target = self.named_type_or_none(target_name, []) + assert target is not None + # Transform List to List[Any], etc. + fix_instance( + target, self.fail, self.note, disallow_any=False, options=self.options + ) + alias_node = TypeAlias( + target, + alias, + tree.fullname, + line=-1, + column=-1, # there is no context + no_args=True, + normalized=True, + ) + self.add_symbol(name, alias_node, tree) + elif self.found_incomplete_ref(tag): + # Built-in class target may not ready yet -- defer. + self.mark_incomplete(name, tree) + else: + # Test fixtures may be missing some builtin classes, which is okay. + # Kill the placeholder if there is one. + if name in tree.names: + assert isinstance(tree.names[name].node, PlaceholderNode) + del tree.names[name] + + def adjust_public_exports(self) -> None: + """Adjust the module visibility of globals due to __all__.""" + if "__all__" in self.globals: + for name, g in self.globals.items(): + # Being included in __all__ explicitly exports and makes public. + if name in self.all_exports: + g.module_public = True + g.module_hidden = False + # But when __all__ is defined, and a symbol is not included in it, + # it cannot be public. + else: + g.module_public = False + + @contextmanager + def file_context( + self, file_node: MypyFile, options: Options, active_type: TypeInfo | None = None + ) -> Iterator[None]: + """Configure analyzer for analyzing targets within a file/class. + + Args: + file_node: target file + options: options specific to the file + active_type: must be the surrounding class to analyze method targets + """ + scope = self.scope + self.options = options + self.errors.set_file(file_node.path, file_node.fullname, scope=scope, options=options) + self.cur_mod_node = file_node + self.cur_mod_id = file_node.fullname + with scope.module_scope(self.cur_mod_id): + self._is_stub_file = file_node.path.lower().endswith(".pyi") + self._is_typeshed_stub_file = file_node.is_typeshed_file(options) + self.globals = file_node.names + self.tvar_scope = TypeVarLikeScope() + + self.named_tuple_analyzer = NamedTupleAnalyzer(options, self, self.msg) + self.typed_dict_analyzer = TypedDictAnalyzer(options, self, self.msg) + self.enum_call_analyzer = EnumCallAnalyzer(options, self) + self.newtype_analyzer = NewTypeAnalyzer(options, self, self.msg) + + # Counter that keeps track of references to undefined things potentially caused by + # incomplete namespaces. + self.num_incomplete_refs = 0 + + if active_type: + enclosing_fullname = active_type.fullname.rsplit(".", 1)[0] + if "." in enclosing_fullname: + enclosing_node = self.lookup_fully_qualified_or_none(enclosing_fullname) + if enclosing_node and isinstance(enclosing_node.node, TypeInfo): + self._type = enclosing_node.node + self.push_type_args(active_type.defn.type_args, active_type.defn) + self.incomplete_type_stack.append(False) + scope.enter_class(active_type) + self.enter_class(active_type.defn.info) + for tvar in active_type.defn.type_vars: + self.tvar_scope.bind_existing(tvar) + + yield + + if active_type: + scope.leave_class() + self.leave_class() + self._type = None + self.incomplete_type_stack.pop() + self.pop_type_args(active_type.defn.type_args) + del self.options + + # + # Functions + # + + def visit_func_def(self, defn: FuncDef) -> None: + self.statement = defn + + # Visit default values because they may contain assignment expressions. + for arg in defn.arguments: + if arg.initializer: + arg.initializer.accept(self) + + defn.is_conditional = self.block_depth[-1] > 0 + + # Set full names even for those definitions that aren't added + # to a symbol table. For example, for overload items. + defn._fullname = self.qualified_name(defn.name) + + # We don't add module top-level functions to symbol tables + # when we analyze their bodies in the second phase on analysis, + # since they were added in the first phase. Nested functions + # get always added, since they aren't separate targets. + if not self.recurse_into_functions or len(self.function_stack) > 0: + if not defn.is_decorated and not defn.is_overload: + self.add_function_to_symbol_table(defn) + + if not self.recurse_into_functions and not defn.def_or_infer_vars: + return + + with self.scope.function_scope(defn), self.set_recurse_into_functions(): + with self.inside_except_star_block_set(value=False): + self.analyze_func_def(defn) + + def function_fullname(self, fullname: str) -> str: + if self.current_overload_item is None: + return fullname + return f"{fullname}#{self.current_overload_item}" + + def analyze_func_def(self, defn: FuncDef) -> None: + if self.push_type_args(defn.type_args, defn) is None: + self.defer(defn) + return + + self.function_stack.append(defn) + + if defn.type: + assert isinstance(defn.type, CallableType) + has_self_type = self.update_function_type_variables(defn.type, defn) + else: + has_self_type = False + + self.function_stack.pop() + + if self.is_class_scope(): + # Method definition + assert self.type is not None + defn.info = self.type + if defn.type is not None and defn.name in ("__init__", "__init_subclass__"): + assert isinstance(defn.type, CallableType) + if isinstance(get_proper_type(defn.type.ret_type), AnyType): + defn.type = defn.type.copy_modified(ret_type=NoneType()) + self.prepare_method_signature(defn, self.type, has_self_type) + + # Analyze function signature + fullname = self.function_fullname(defn.fullname) + with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)): + if defn.type: + self.check_classvar_in_signature(defn.type) + assert isinstance(defn.type, CallableType) + # Signature must be analyzed in the surrounding scope so that + # class-level imported names and type variables are in scope. + analyzer = self.type_analyzer() + tag = self.track_incomplete_refs() + result = analyzer.visit_callable_type(defn.type, nested=False, namespace=fullname) + # Don't store not ready types (including placeholders). + if self.found_incomplete_ref(tag) or has_placeholder(result): + self.defer(defn) + self.pop_type_args(defn.type_args) + return + assert isinstance(result, ProperType) + if isinstance(result, CallableType): + # type guards need to have a positional argument, to spec + skip_self = self.is_class_scope() and not defn.is_static + if result.type_guard and ARG_POS not in result.arg_kinds[skip_self:]: + self.fail( + "TypeGuard functions must have a positional argument", + result, + code=codes.VALID_TYPE, + ) + # in this case, we just kind of just ... remove the type guard. + result = result.copy_modified(type_guard=None) + if result.type_is and ARG_POS not in result.arg_kinds[skip_self:]: + self.fail( + '"TypeIs" functions must have a positional argument', + result, + code=codes.VALID_TYPE, + ) + result = result.copy_modified(type_is=None) + + result = self.remove_unpack_kwargs(defn, result) + if has_self_type and self.type is not None: + info = self.type + if info.self_type is not None: + result.variables = (info.self_type,) + result.variables + defn.type = result + self.add_type_alias_deps(analyzer.aliases_used) + self.check_function_signature(defn) + if isinstance(defn, FuncDef): + assert isinstance(defn.type, CallableType) + defn.type = set_callable_name(defn.type, defn) + + self.analyze_arg_initializers(defn) + self.analyze_function_body(defn) + + if self.is_class_scope(): + assert self.type is not None + # Mark protocol methods with empty bodies as implicitly abstract. + # This makes explicit protocol subclassing type-safe. + if ( + self.type.is_protocol + and not self.is_stub_file # Bodies in stub files are always empty. + and (not isinstance(self.scope.function, OverloadedFuncDef) or defn.is_property) + and defn.abstract_status != IS_ABSTRACT + and is_trivial_body(defn.body) + ): + defn.abstract_status = IMPLICITLY_ABSTRACT + if ( + is_trivial_body(defn.body) + and not self.is_stub_file + and defn.abstract_status != NOT_ABSTRACT + ): + defn.is_trivial_body = True + + if ( + defn.is_coroutine + and isinstance(defn.type, CallableType) + and self.wrapped_coro_return_types.get(defn) != defn.type + ): + if defn.is_async_generator: + # Async generator types are handled elsewhere + pass + else: + # A coroutine defined as `async def foo(...) -> T: ...` + # has external return type `Coroutine[Any, Any, T]`. + any_type = AnyType(TypeOfAny.special_form) + ret_type = self.named_type_or_none( + "typing.Coroutine", [any_type, any_type, defn.type.ret_type] + ) + assert ret_type is not None, "Internal error: typing.Coroutine not found" + defn.type = defn.type.copy_modified(ret_type=ret_type) + self.wrapped_coro_return_types[defn] = defn.type + + self.pop_type_args(defn.type_args) + + def remove_unpack_kwargs(self, defn: FuncDef, typ: CallableType) -> CallableType: + if not typ.arg_kinds or typ.arg_kinds[-1] is not ArgKind.ARG_STAR2: + return typ + last_type = typ.arg_types[-1] + if not isinstance(last_type, UnpackType): + return typ + p_last_type = get_proper_type(last_type.type) + if not isinstance(p_last_type, TypedDictType): + self.fail("Unpack item in ** parameter must be a TypedDict", last_type) + new_arg_types = typ.arg_types[:-1] + [AnyType(TypeOfAny.from_error)] + return typ.copy_modified(arg_types=new_arg_types) + overlap = set(typ.arg_names) & set(p_last_type.items) + # It is OK for TypedDict to have a key named 'kwargs'. + overlap.discard(typ.arg_names[-1]) + if overlap: + overlapped = ", ".join([f'"{name}"' for name in sorted(filter(None, overlap))]) + self.fail( + f"Overlap between parameter names and ** TypedDict items: {overlapped}", defn + ) + new_arg_types = typ.arg_types[:-1] + [AnyType(TypeOfAny.from_error)] + return typ.copy_modified(arg_types=new_arg_types) + # OK, everything looks right now, mark the callable type as using unpack. + new_arg_types = typ.arg_types[:-1] + [p_last_type] + return typ.copy_modified(arg_types=new_arg_types, unpack_kwargs=True) + + def prepare_method_signature(self, func: FuncDef, info: TypeInfo, has_self_type: bool) -> None: + """Check basic signature validity and tweak annotation of self/cls argument.""" + # Only non-static methods are special, as well as __new__. + functype = func.type + if func.name == "__new__": + func.is_static = True + if func.has_self_or_cls_argument: + if func.name in ["__init_subclass__", "__class_getitem__"]: + func.is_class = True + if func.arguments and isinstance(functype, CallableType): + self_type = get_proper_type(functype.arg_types[0]) + if isinstance(self_type, AnyType): + if has_self_type: + assert self.type is not None and self.type.self_type is not None + leading_type: Type = self.type.self_type + else: + func.is_trivial_self = True + leading_type = fill_typevars(info) + if func.is_class or func.name == "__new__": + leading_type = self.class_type(leading_type) + func.type = replace_implicit_first_type(functype, leading_type) + elif has_self_type and isinstance(func.unanalyzed_type, CallableType): + if not isinstance(get_proper_type(func.unanalyzed_type.arg_types[0]), AnyType): + if self.is_expected_self_type( + self_type, func.is_class or func.name == "__new__" + ): + # This error is off by default, since it is explicitly allowed + # by the PEP 673. + self.fail( + 'Redundant "Self" annotation for the first method argument', + func, + code=codes.REDUNDANT_SELF_TYPE, + ) + else: + self.fail( + "Method cannot have explicit self annotation and Self type", func + ) + elif has_self_type: + self.fail("Static methods cannot use Self type", func) + + def is_expected_self_type(self, typ: Type, is_classmethod: bool) -> bool: + """Does this (analyzed or not) type represent the expected Self type for a method?""" + assert self.type is not None + typ = get_proper_type(typ) + if is_classmethod: + if isinstance(typ, TypeType): + return self.is_expected_self_type(typ.item, is_classmethod=False) + if isinstance(typ, UnboundType): + sym = self.lookup_qualified(typ.name, typ, suppress_errors=True) + if sym is not None and sym.fullname in TYPE_NAMES and typ.args: + return self.is_expected_self_type(typ.args[0], is_classmethod=False) + return False + if isinstance(typ, TypeVarType): + return typ == self.type.self_type + if isinstance(typ, UnboundType): + sym = self.lookup_qualified(typ.name, typ, suppress_errors=True) + return sym is not None and sym.fullname in SELF_TYPE_NAMES + return False + + def set_original_def(self, previous: Node | None, new: FuncDef | Decorator) -> bool: + """If 'new' conditionally redefine 'previous', set 'previous' as original + + We reject straight redefinitions of functions, as they are usually + a programming error. For example: + + def f(): ... + def f(): ... # Error: 'f' redefined + """ + if isinstance(new, Decorator): + new = new.func + if ( + isinstance(previous, (FuncDef, Decorator)) + and unnamed_function(new.name) + and unnamed_function(previous.name) + ): + return True + if isinstance(previous, (FuncDef, Var, Decorator)) and new.is_conditional: + new.original_def = previous + return True + else: + return False + + def update_function_type_variables(self, fun_type: CallableType, defn: FuncItem) -> bool: + """Make any type variables in the signature of defn explicit. + + Update the signature of defn to contain type variable definitions + if defn is generic. Return True, if the signature contains typing.Self + type, or False otherwise. + """ + fullname = self.function_fullname(defn.fullname) + with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)): + a = self.type_analyzer() + fun_type.variables, has_self_type = a.bind_function_type_variables(fun_type, defn) + if has_self_type and self.type is not None: + self.setup_self_type() + if defn.type_args: + bound_fullnames = {v.fullname for v in fun_type.variables} + declared_fullnames = {self.qualified_name(p.name) for p in defn.type_args} + extra = sorted(bound_fullnames - declared_fullnames) + if extra: + self.msg.type_parameters_should_be_declared( + [n.split(".")[-1] for n in extra], defn + ) + return has_self_type + + def setup_self_type(self) -> None: + """Setup a (shared) Self type variable for current class. + + We intentionally don't add it to the class symbol table, + so it can be accessed only by mypy and will not cause + clashes with user defined names. + """ + assert self.type is not None + info = self.type + if info.self_type is not None: + if has_placeholder(info.self_type.upper_bound): + # Similar to regular (user defined) type variables. + self.process_placeholder( + None, + "Self upper bound", + info, + force_progress=info.self_type.upper_bound != fill_typevars(info), + ) + else: + return + info.self_type = TypeVarType( + "Self", + f"{info.fullname}.Self", + id=TypeVarId(0), # 0 is a special value for self-types. + values=[], + upper_bound=fill_typevars(info), + default=AnyType(TypeOfAny.from_omitted_generics), + ) + + def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None: + self.statement = defn + self.add_function_to_symbol_table(defn) + + if not self.recurse_into_functions and not defn.def_or_infer_vars: + return + + # NB: Since _visit_overloaded_func_def will call accept on the + # underlying FuncDefs, the function might get entered twice. + # This is fine, though, because only the outermost function is + # used to compute targets. + with self.scope.function_scope(defn), self.set_recurse_into_functions(): + self.analyze_overloaded_func_def(defn) + + @contextmanager + def overload_item_set(self, item: int | None) -> Iterator[None]: + self.current_overload_item = item + try: + yield + finally: + self.current_overload_item = None + + def analyze_overloaded_func_def(self, defn: OverloadedFuncDef) -> None: + # OverloadedFuncDef refers to any legitimate situation where you have + # more than one declaration for the same function in a row. This occurs + # with a @property with a setter or a deleter, and for a classic + # @overload. + + defn._fullname = self.qualified_name(defn.name) + # TODO: avoid modifying items. + defn.items = defn.unanalyzed_items.copy() + + first_item = defn.items[0] + first_item.is_overload = True + with self.overload_item_set(0): + first_item.accept(self) + + bare_setter_type = None + is_property = False + if isinstance(first_item, Decorator) and first_item.func.is_property: + is_property = True + # This is a property. + first_item.func.is_overload = True + bare_setter_type = self.analyze_property_with_multi_part_definition(defn) + typ = function_type(first_item.func, self.function_type()) + assert isinstance(typ, CallableType) + typ.definition = first_item + types = [typ] + else: + # This is a normal overload. Find the item signatures, the + # implementation (if outside a stub), and any missing @overload + # decorators. + types, impl, non_overload_indexes = self.analyze_overload_sigs_and_impl(defn) + defn.impl = impl + if non_overload_indexes: + self.handle_missing_overload_decorators( + defn, non_overload_indexes, some_overload_decorators=len(types) > 0 + ) + # If we found an implementation, remove it from the overload item list, + # as it's special. + if impl is not None: + assert impl is defn.items[-1] + defn.items = defn.items[:-1] + elif not non_overload_indexes: + self.handle_missing_overload_implementation(defn) + + if types and not any( + # If some overload items are decorated with other decorators, then + # the overload type will be determined during type checking. + # Note: bare @property is removed in visit_decorator(). + isinstance(it, Decorator) + and len(it.decorators) > (1 if i > 0 or not is_property else 0) + for i, it in enumerate(defn.items) + ): + # TODO: should we enforce decorated overloads consistency somehow? + # Some existing code uses both styles: + # * Put decorator only on implementation, use "effective" types in overloads + # * Put decorator everywhere, use "bare" types in overloads. + defn.type = Overloaded(types) + defn.type.line = defn.line + # In addition, we can set the getter/setter type for valid properties as some + # code paths may either use the above type, or var.type etc. of the first item. + if isinstance(first_item, Decorator) and bare_setter_type: + first_item.var.type = types[0] + first_item.var.setter_type = bare_setter_type + + if not defn.items: + # It was not a real overload after all, but function redefinition. We've + # visited the redefinition(s) already. + if not defn.impl: + # For really broken overloads with no items and no implementation we need to keep + # at least one item to hold basic information like function name. + defn.impl = defn.unanalyzed_items[-1] + return + + # We know this is an overload def. Infer properties and perform some checks. + self.process_deprecated_overload(defn) + self.process_final_in_overload(defn) + self.process_static_or_class_method_in_overload(defn) + self.process_overload_impl(defn) + + def process_deprecated_overload(self, defn: OverloadedFuncDef) -> None: + if defn.is_property: + return + + if isinstance(impl := defn.impl, Decorator) and ( + (deprecated := impl.func.deprecated) is not None + ): + defn.deprecated = deprecated + for item in defn.items: + if isinstance(item, Decorator): + item.func.deprecated = deprecated + + for item in defn.items: + deprecation = False + if isinstance(item, Decorator): + for d in item.decorators: + if deprecation and refers_to_fullname(d, OVERLOAD_NAMES): + self.msg.note("@overload should be placed before @deprecated", d) + elif (deprecated := self.get_deprecated(d)) is not None: + deprecation = True + if isinstance(typ := item.func.type, CallableType): + typestr = f" {typ.accept(TypeStrVisitor(options=self.options))} " + else: + typestr = " " + item.func.deprecated = ( + f"overload{typestr}of function {defn.fullname} is deprecated: " + f"{deprecated}" + ) + + @staticmethod + def get_deprecated(expression: Expression) -> str | None: + if ( + isinstance(expression, CallExpr) + and refers_to_fullname(expression.callee, DEPRECATED_TYPE_NAMES) + and (len(args := expression.args) >= 1) + and isinstance(deprecated := args[0], StrExpr) + ): + return deprecated.value + return None + + def process_overload_impl(self, defn: OverloadedFuncDef) -> None: + """Set flags for an overload implementation. + + Currently, this checks for a trivial body in protocols classes, + where it makes the method implicitly abstract. + """ + if defn.impl is None: + return + impl = defn.impl if isinstance(defn.impl, FuncDef) else defn.impl.func + if is_trivial_body(impl.body) and self.is_class_scope() and not self.is_stub_file: + assert self.type is not None + if self.type.is_protocol: + impl.abstract_status = IMPLICITLY_ABSTRACT + if impl.abstract_status != NOT_ABSTRACT: + impl.is_trivial_body = True + + def analyze_overload_sigs_and_impl( + self, defn: OverloadedFuncDef + ) -> tuple[list[CallableType], OverloadPart | None, list[int]]: + """Find overload signatures, the implementation, and items with missing @overload. + + Assume that the first was already analyzed. As a side effect: + analyzes remaining items and updates 'is_overload' flags. + """ + types = [] + non_overload_indexes = [] + impl: OverloadPart | None = None + for i, item in enumerate(defn.items): + if i != 0: + # Assume that the first item was already visited + item.is_overload = True + with self.overload_item_set(i if i < len(defn.items) - 1 else None): + item.accept(self) + # TODO: support decorated overloaded functions properly + if isinstance(item, Decorator): + callable = function_type(item.func, self.function_type()) + assert isinstance(callable, CallableType) + callable.definition = item + if not any(refers_to_fullname(dec, OVERLOAD_NAMES) for dec in item.decorators): + if i == len(defn.items) - 1 and not self.is_stub_file: + # Last item outside a stub is impl + impl = item + else: + # Oops it wasn't an overload after all. A clear error + # will vary based on where in the list it is, record + # that. + non_overload_indexes.append(i) + else: + item.func.is_overload = True + types.append(callable) + if item.var.is_property: + self.fail("An overload can not be a property", item) + # If any item was decorated with `@override`, the whole overload + # becomes an explicit override. + defn.is_explicit_override |= item.func.is_explicit_override + elif isinstance(item, FuncDef): + if i == len(defn.items) - 1 and not self.is_stub_file: + impl = item + else: + non_overload_indexes.append(i) + return types, impl, non_overload_indexes + + def handle_missing_overload_decorators( + self, + defn: OverloadedFuncDef, + non_overload_indexes: list[int], + some_overload_decorators: bool, + ) -> None: + """Generate errors for overload items without @overload. + + Side effect: remote non-overload items. + """ + if some_overload_decorators: + # Some of them were overloads, but not all. + for idx in non_overload_indexes: + if self.is_stub_file: + self.fail( + "An implementation for an overloaded function " + "is not allowed in a stub file", + defn.items[idx], + ) + else: + self.fail( + "The implementation for an overloaded function must come last", + defn.items[idx], + ) + else: + for idx in non_overload_indexes[1:]: + self.name_already_defined(defn.name, defn.items[idx], defn.items[0]) + if defn.impl: + self.name_already_defined(defn.name, defn.impl, defn.items[0]) + # Remove the non-overloads + for idx in reversed(non_overload_indexes): + del defn.items[idx] + + def handle_missing_overload_implementation(self, defn: OverloadedFuncDef) -> None: + """Generate error about missing overload implementation (only if needed).""" + if not self.is_stub_file: + if self.type and self.type.is_protocol and not self.is_func_scope(): + # An overloaded protocol method doesn't need an implementation, + # but if it doesn't have one, then it is considered abstract. + for item in defn.items: + if isinstance(item, Decorator): + item.func.abstract_status = IS_ABSTRACT + else: + item.abstract_status = IS_ABSTRACT + elif all( + isinstance(item, Decorator) and item.func.abstract_status == IS_ABSTRACT + for item in defn.items + ): + # Since there is no implementation, it can't be called via super(). + if defn.items: + assert isinstance(defn.items[0], Decorator) + defn.items[0].func.is_trivial_body = True + else: + self.fail( + "An overloaded function outside a stub file must have an implementation", + defn, + code=codes.NO_OVERLOAD_IMPL, + ) + + def process_final_in_overload(self, defn: OverloadedFuncDef) -> None: + """Detect the @final status of an overloaded function (and perform checks).""" + # If the implementation is marked as @final (or the first overload in + # stubs), then the whole overloaded definition if @final. + if any(item.is_final for item in defn.items): + # We anyway mark it as final because it was probably the intention. + defn.is_final = True + # Only show the error once per overload + bad_final = next(ov for ov in defn.items if ov.is_final) + if not self.is_stub_file: + self.fail("@final should be applied only to overload implementation", bad_final) + elif any(item.is_final for item in defn.items[1:]): + bad_final = next(ov for ov in defn.items[1:] if ov.is_final) + self.fail( + "In a stub file @final must be applied only to the first overload", bad_final + ) + if defn.impl is not None and defn.impl.is_final: + defn.is_final = True + + def process_static_or_class_method_in_overload(self, defn: OverloadedFuncDef) -> None: + class_status = [] + static_status = [] + for item in defn.items: + if isinstance(item, Decorator): + inner = item.func + elif isinstance(item, FuncDef): + inner = item + else: + assert False, f"The 'item' variable is an unexpected type: {type(item)}" + class_status.append(inner.is_class) + static_status.append(inner.is_static) + + if defn.impl is not None: + if isinstance(defn.impl, Decorator): + inner = defn.impl.func + elif isinstance(defn.impl, FuncDef): + inner = defn.impl + else: + assert False, f"Unexpected impl type: {type(defn.impl)}" + class_status.append(inner.is_class) + static_status.append(inner.is_static) + + if len(set(class_status)) != 1: + self.msg.overload_inconsistently_applies_decorator("classmethod", defn) + elif len(set(static_status)) != 1: + self.msg.overload_inconsistently_applies_decorator("staticmethod", defn) + else: + defn.is_class = class_status[0] + defn.is_static = static_status[0] + + def analyze_property_with_multi_part_definition( + self, defn: OverloadedFuncDef + ) -> CallableType | None: + """Analyze a property defined using multiple methods (e.g., using @x.setter). + + Assume that the first method (@property) has already been analyzed. + Return bare setter type (without any other decorators applied), this may be used + by the caller for performance optimizations. + """ + defn.is_property = True + items = defn.items + first_item = defn.items[0] + assert isinstance(first_item, Decorator) + deleted_items = [] + bare_setter_type = None + func_name = first_item.func.name + for i, item in enumerate(items[1:]): + if isinstance(item, Decorator): + item.func.accept(self) + if item.decorators: + first_node = item.decorators[0] + if self._is_valid_property_decorator(first_node, func_name): + # Get abstractness from the original definition. + item.func.abstract_status = first_item.func.abstract_status + if first_node.name == "setter": + # The first item represents the entire property. + first_item.var.is_settable_property = True + setter_func_type = function_type(item.func, self.function_type()) + assert isinstance(setter_func_type, CallableType) + bare_setter_type = setter_func_type + defn.setter_index = i + 1 + for other_node in item.decorators[1:]: + other_node.accept(self) + else: + self.fail( + f'Only supported top decorators are "@{func_name}.setter" and "@{func_name}.deleter"', + first_node, + ) + else: + self.fail(f'Unexpected definition for property "{func_name}"', item) + deleted_items.append(i + 1) + for i in reversed(deleted_items): + del items[i] + + for item in items[1:]: + if isinstance(item, Decorator): + for d in item.decorators: + if (deprecated := self.get_deprecated(d)) is not None: + item.func.deprecated = ( + f"function {item.fullname} is deprecated: {deprecated}" + ) + return bare_setter_type + + def _is_valid_property_decorator( + self, deco: Expression, property_name: str + ) -> TypeGuard[MemberExpr]: + if not isinstance(deco, MemberExpr): + return False + if not isinstance(deco.expr, NameExpr) or deco.expr.name != property_name: + return False + if deco.name not in {"setter", "deleter"}: + # This intentionally excludes getter. While `@prop.getter` is valid at + # runtime, that would mean replacing the already processed getter type. + # Such usage is almost definitely a mistake (except for overrides in + # subclasses but we don't support them anyway) and might be a typo + # (only one letter away from `setter`), it's likely almost never used, + # so supporting it properly won't pay off. + return False + return True + + def add_function_to_symbol_table(self, func: FuncDef | OverloadedFuncDef) -> None: + if self.is_class_scope(): + assert self.type is not None + func.info = self.type + func._fullname = self.qualified_name(func.name) + self.add_symbol(func.name, func, func) + + def analyze_arg_initializers(self, defn: FuncItem) -> None: + fullname = self.function_fullname(defn.fullname) + with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)): + # Analyze default arguments + for arg in defn.arguments: + if arg.initializer: + arg.initializer.accept(self) + + def analyze_function_body(self, defn: FuncItem) -> None: + is_method = self.is_class_scope() + fullname = self.function_fullname(defn.fullname) + with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)): + # Bind the type variables again to visit the body. + if defn.type: + a = self.type_analyzer() + typ = defn.type + assert isinstance(typ, CallableType) + a.bind_function_type_variables(typ, defn) + for i in range(len(typ.arg_types)): + store_argument_type(defn, i, typ, self.named_type) + self.function_stack.append(defn) + with self.enter(defn): + for arg in defn.arguments: + self.add_local(arg.variable, defn) + + # The first argument of a non-static, non-class method is like 'self' + # (though the name could be different), having the enclosing class's + # instance type. + if is_method and defn.has_self_or_cls_argument and defn.arguments: + if not defn.is_class: + defn.arguments[0].variable.is_self = True + else: + defn.arguments[0].variable.is_cls = True + + defn.body.accept(self) + self.function_stack.pop() + + def check_classvar_in_signature(self, typ: ProperType) -> None: + t: ProperType + if isinstance(typ, Overloaded): + for t in typ.items: + self.check_classvar_in_signature(t) + return + if not isinstance(typ, CallableType): + return + for t in get_proper_types(typ.arg_types) + [get_proper_type(typ.ret_type)]: + if self.is_classvar(t): + self.fail_invalid_classvar(t) + # Show only one error per signature + break + + def check_function_signature(self, fdef: FuncItem) -> None: + sig = fdef.type + assert isinstance(sig, CallableType) + if len(sig.arg_types) < len(fdef.arguments): + self.fail("Type signature has too few arguments", fdef) + # Add dummy Any arguments to prevent crashes later. + num_extra_anys = len(fdef.arguments) - len(sig.arg_types) + extra_anys = [AnyType(TypeOfAny.from_error)] * num_extra_anys + sig.arg_types.extend(extra_anys) + elif len(sig.arg_types) > len(fdef.arguments): + self.fail("Type signature has too many arguments", fdef, blocker=True) + + def visit_decorator(self, dec: Decorator) -> None: + self.statement = dec + # TODO: better don't modify them at all. + dec.decorators = dec.original_decorators.copy() + dec.func.is_conditional = self.block_depth[-1] > 0 + if not dec.is_overload: + self.add_symbol(dec.name, dec, dec) + dec.func._fullname = self.qualified_name(dec.name) + dec.var._fullname = self.qualified_name(dec.name) + for d in dec.decorators: + d.accept(self) + removed: list[int] = [] + no_type_check = False + could_be_decorated_property = False + for i, d in enumerate(dec.decorators): + # A bunch of decorators are special cased here. + if refers_to_fullname(d, "abc.abstractmethod"): + removed.append(i) + dec.func.abstract_status = IS_ABSTRACT + self.check_decorated_function_is_method("abstractmethod", dec) + elif refers_to_fullname(d, ("asyncio.coroutines.coroutine", "types.coroutine")): + removed.append(i) + dec.func.is_awaitable_coroutine = True + elif refers_to_fullname(d, "builtins.staticmethod"): + removed.append(i) + dec.func.is_static = True + dec.var.is_staticmethod = True + self.check_decorated_function_is_method("staticmethod", dec) + elif refers_to_fullname(d, "builtins.classmethod"): + removed.append(i) + dec.func.is_class = True + dec.var.is_classmethod = True + self.check_decorated_function_is_method("classmethod", dec) + elif refers_to_fullname(d, OVERRIDE_DECORATOR_NAMES): + removed.append(i) + dec.func.is_explicit_override = True + self.check_decorated_function_is_method("override", dec) + elif refers_to_fullname( + d, + ( + "builtins.property", + "abc.abstractproperty", + "functools.cached_property", + "enum.property", + "types.DynamicClassAttribute", + ), + ): + removed.append(i) + dec.func.is_property = True + dec.var.is_property = True + if refers_to_fullname(d, "abc.abstractproperty"): + dec.func.abstract_status = IS_ABSTRACT + elif refers_to_fullname(d, "functools.cached_property"): + dec.var.is_settable_property = True + self.check_decorated_function_is_method("property", dec) + elif refers_to_fullname(d, "typing.no_type_check"): + dec.var.type = AnyType(TypeOfAny.special_form) + no_type_check = True + elif refers_to_fullname(d, FINAL_DECORATOR_NAMES): + if self.is_class_scope(): + assert self.type is not None, "No type set at class scope" + if self.type.is_protocol: + self.msg.protocol_members_cant_be_final(d) + else: + dec.func.is_final = True + dec.var.is_final = True + removed.append(i) + else: + self.fail("@final cannot be used with non-method functions", d) + elif refers_to_fullname(d, TYPE_CHECK_ONLY_NAMES): + # TODO: support `@overload` funcs. + dec.func.is_type_check_only = True + elif isinstance(d, CallExpr) and refers_to_fullname( + d.callee, DATACLASS_TRANSFORM_NAMES + ): + dec.func.dataclass_transform_spec = self.parse_dataclass_transform_spec(d) + elif (deprecated := self.get_deprecated(d)) is not None: + dec.func.deprecated = f"function {dec.fullname} is deprecated: {deprecated}" + elif not dec.var.is_property: + # We have seen a "non-trivial" decorator before seeing @property, if + # we will see a @property later, give an error, as we don't support this. + could_be_decorated_property = True + for i in reversed(removed): + del dec.decorators[i] + if (not dec.is_overload or dec.var.is_property) and self.type: + dec.var.info = self.type + dec.var.is_initialized_in_class = True + if no_type_check: + erase_func_annotations(dec.func) + if not no_type_check and (self.recurse_into_functions or dec.func.def_or_infer_vars): + with self.set_recurse_into_functions(): + dec.func.accept(self) + if could_be_decorated_property and dec.decorators and dec.var.is_property: + self.fail( + "Decorators on top of @property are not supported", dec, code=PROPERTY_DECORATOR + ) + if (dec.func.is_static or dec.func.is_class) and dec.var.is_property: + self.fail("Only instance methods can be decorated with @property", dec) + if dec.func.abstract_status == IS_ABSTRACT and dec.func.is_final: + self.fail(f"Method {dec.func.name} is both abstract and final", dec) + if dec.func.is_static and dec.func.is_class: + self.fail(message_registry.CLASS_PATTERN_CLASS_OR_STATIC_METHOD, dec) + + def check_decorated_function_is_method(self, decorator: str, context: Context) -> None: + if not self.type or self.is_func_scope(): + self.fail(f'"{decorator}" used with a non-method', context) + + # + # Classes + # + + def visit_class_def(self, defn: ClassDef) -> None: + self.statement = defn + self.incomplete_type_stack.append(not defn.info) + namespace = self.qualified_name(defn.name) + with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)): + if self.push_type_args(defn.type_args, defn) is None: + self.mark_incomplete(defn.name, defn) + return + + self.analyze_class(defn) + self.pop_type_args(defn.type_args) + self.incomplete_type_stack.pop() + + def push_type_args( + self, type_args: list[TypeParam] | None, context: Context + ) -> list[tuple[str, TypeVarLikeExpr]] | None: + if not type_args: + return [] + self.locals.append(SymbolTable()) + self.scope_stack.append(SCOPE_ANNOTATION) + tvs: list[tuple[str, TypeVarLikeExpr]] = [] + for p in type_args: + tv = self.analyze_type_param(p, context) + if tv is None: + return None + tvs.append((p.name, tv)) + + if self.is_defined_type_param(p.name): + self.fail(f'"{p.name}" already defined as a type parameter', context) + else: + assert self.add_symbol( + p.name, tv, context, no_progress=True, type_param=True + ), "Type parameter should not be discarded" + + return tvs + + def is_defined_type_param(self, name: str) -> bool: + for names in self.locals: + if names is None: + continue + if name in names: + node = names[name].node + if isinstance(node, TypeVarLikeExpr): + return True + return False + + def analyze_type_param( + self, type_param: TypeParam, context: Context + ) -> TypeVarLikeExpr | None: + fullname = self.qualified_name(type_param.name) + if type_param.upper_bound: + upper_bound = self.anal_type(type_param.upper_bound, allow_placeholder=True) + # TODO: we should validate the upper bound is valid for a given kind. + if upper_bound is None: + # This and below copies special-casing for old-style type variables, that + # is equally necessary for new-style classes to break a vicious circle. + upper_bound = PlaceholderType(None, [], context.line) + else: + if type_param.kind == TYPE_VAR_TUPLE_KIND: + upper_bound = self.named_type("builtins.tuple", [self.object_type()]) + else: + upper_bound = self.object_type() + if type_param.default: + default = self.anal_type( + type_param.default, + allow_placeholder=True, + allow_unbound_tvars=True, + report_invalid_types=False, + allow_param_spec_literals=type_param.kind == PARAM_SPEC_KIND, + allow_tuple_literal=type_param.kind == PARAM_SPEC_KIND, + allow_unpack=type_param.kind == TYPE_VAR_TUPLE_KIND, + ) + if default is None: + default = PlaceholderType(None, [], context.line) + elif type_param.kind == TYPE_VAR_KIND: + default = self.check_typevar_default(default, type_param.default) + elif type_param.kind == PARAM_SPEC_KIND: + default = self.check_paramspec_default(default, type_param.default) + elif type_param.kind == TYPE_VAR_TUPLE_KIND: + default = self.check_typevartuple_default(default, type_param.default) + else: + default = AnyType(TypeOfAny.from_omitted_generics) + if type_param.kind == TYPE_VAR_KIND: + values: list[Type] = [] + if type_param.values: + for value in type_param.values: + analyzed = self.anal_type(value, allow_placeholder=True) + if analyzed is None: + analyzed = PlaceholderType(None, [], context.line) + if has_type_vars(analyzed): + self.fail(message_registry.TYPE_VAR_GENERIC_CONSTRAINT_TYPE, context) + values.append(AnyType(TypeOfAny.from_error)) + else: + values.append(analyzed) + return TypeVarExpr( + name=type_param.name, + fullname=fullname, + values=values, + upper_bound=upper_bound, + default=default, + variance=VARIANCE_NOT_READY, + is_new_style=True, + line=context.line, + ) + elif type_param.kind == PARAM_SPEC_KIND: + return ParamSpecExpr( + name=type_param.name, + fullname=fullname, + upper_bound=upper_bound, + default=default, + is_new_style=True, + line=context.line, + ) + else: + assert type_param.kind == TYPE_VAR_TUPLE_KIND + tuple_fallback = self.named_type("builtins.tuple", [self.object_type()]) + return TypeVarTupleExpr( + name=type_param.name, + fullname=fullname, + upper_bound=upper_bound, + tuple_fallback=tuple_fallback, + default=default, + is_new_style=True, + line=context.line, + ) + + def pop_type_args(self, type_args: list[TypeParam] | None) -> None: + if not type_args: + return + self.locals.pop() + self.scope_stack.pop() + + def analyze_class(self, defn: ClassDef) -> None: + fullname = self.qualified_name(defn.name) + if not defn.info and not self.is_core_builtin_class(defn): + # Add placeholder so that self-references in base classes can be + # resolved. We don't want this to cause a deferral, since if there + # are no incomplete references, we'll replace this with a TypeInfo + # before returning. + placeholder = PlaceholderNode(fullname, defn, defn.line, becomes_typeinfo=True) + self.add_symbol(defn.name, placeholder, defn, can_defer=False) + + tag = self.track_incomplete_refs() + + # Restore base classes after previous iteration (things like Generic[T] might be removed). + defn.base_type_exprs.extend(defn.removed_base_type_exprs) + defn.removed_base_type_exprs.clear() + + self.infer_metaclass_and_bases_from_compat_helpers(defn) + + bases = defn.base_type_exprs + bases, tvar_defs, is_protocol = self.clean_up_bases_and_infer_type_variables( + defn, bases, context=defn + ) + + self.check_type_alias_bases(bases) + + for tvd in tvar_defs: + if isinstance(tvd, TypeVarType) and any( + has_placeholder(t) for t in [tvd.upper_bound] + tvd.values + ): + # Some type variable bounds or values are not ready, we need + # to re-analyze this class. + self.defer() + if has_placeholder(tvd.default): + # Placeholder values in TypeVarLikeTypes may get substituted in. + # Defer current target until they are ready. + self.mark_incomplete(defn.name, defn) + return + + self.analyze_class_keywords(defn) + bases_result = self.analyze_base_classes(bases) + if bases_result is None or self.found_incomplete_ref(tag): + # Something was incomplete. Defer current target. + self.mark_incomplete(defn.name, defn) + return + + base_types, base_error = bases_result + if any(isinstance(base, PlaceholderType) for base, _ in base_types): + # We need to know the TypeInfo of each base to construct the MRO. Placeholder types + # are okay in nested positions, since they can't affect the MRO. + self.mark_incomplete(defn.name, defn) + return + + declared_metaclass, should_defer, any_meta = self.get_declared_metaclass( + defn.name, defn.metaclass + ) + if should_defer or self.found_incomplete_ref(tag): + # Metaclass was not ready. Defer current target. + self.mark_incomplete(defn.name, defn) + return + + if self.analyze_typeddict_classdef(defn): + if defn.info: + self.setup_type_vars(defn, tvar_defs) + self.setup_alias_type_vars(defn) + return + + if self.analyze_namedtuple_classdef(defn, tvar_defs): + return + + # Create TypeInfo for class now that base classes and the MRO can be calculated. + self.prepare_class_def(defn) + self.setup_type_vars(defn, tvar_defs) + if base_error: + defn.info.fallback_to_any = True + if any_meta: + defn.info.meta_fallback_to_any = True + + with self.scope.class_scope(defn.info): + self.configure_base_classes(defn, base_types) + defn.info.is_protocol = is_protocol + self.recalculate_metaclass(defn, declared_metaclass) + defn.info.runtime_protocol = False + + if defn.type_args: + # PEP 695 type parameters are not in scope in class decorators, so + # temporarily disable type parameter namespace. + type_params_names = self.locals.pop() + self.scope_stack.pop() + for decorator in defn.decorators: + self.analyze_class_decorator(defn, decorator) + if defn.type_args: + self.locals.append(type_params_names) + self.scope_stack.append(SCOPE_ANNOTATION) + + self.analyze_class_body_common(defn) + + def check_type_alias_bases(self, bases: list[Expression]) -> None: + for base in bases: + if isinstance(base, IndexExpr): + base = base.base + if ( + isinstance(base, RefExpr) + and isinstance(base.node, TypeAlias) + and base.node.python_3_12_type_alias + ): + self.fail( + 'Type alias defined using "type" statement not valid as base class', base + ) + + def setup_type_vars(self, defn: ClassDef, tvar_defs: list[TypeVarLikeType]) -> None: + defn.type_vars = tvar_defs + defn.info.type_vars = [] + # we want to make sure any additional logic in add_type_vars gets run + defn.info.add_type_vars() + + def setup_alias_type_vars(self, defn: ClassDef) -> None: + assert defn.info.special_alias is not None + defn.info.special_alias.alias_tvars = list(defn.type_vars) + # It is a bit unfortunate that we need to inline some logic from TypeAlias constructor, + # but it is required, since type variables may change during semantic analyzer passes. + for i, t in enumerate(defn.type_vars): + if isinstance(t, TypeVarTupleType): + defn.info.special_alias.tvar_tuple_index = i + target = defn.info.special_alias.target + assert isinstance(target, ProperType) + if isinstance(target, TypedDictType): + target.fallback.args = type_vars_as_args(defn.type_vars) + elif isinstance(target, TupleType): + target.partial_fallback.args = type_vars_as_args(defn.type_vars) + else: + assert False, f"Unexpected special alias type: {type(target)}" + + def is_core_builtin_class(self, defn: ClassDef) -> bool: + return self.cur_mod_id == "builtins" and defn.name in CORE_BUILTIN_CLASSES + + def analyze_class_body_common(self, defn: ClassDef) -> None: + """Parts of class body analysis that are common to all kinds of class defs.""" + self.enter_class(defn.info) + if any(b.self_type is not None for b in defn.info.mro): + self.setup_self_type() + defn.defs.accept(self) + self.apply_class_plugin_hooks(defn) + self.leave_class() + + def analyze_typeddict_classdef(self, defn: ClassDef) -> bool: + if ( + defn.info + and defn.info.typeddict_type + and not has_placeholder(defn.info.typeddict_type) + ): + # This is a valid TypedDict, and it is fully analyzed. + return True + is_typeddict, info = self.typed_dict_analyzer.analyze_typeddict_classdef(defn) + if is_typeddict: + for decorator in defn.decorators: + decorator.accept(self) + if info is not None: + self.analyze_class_decorator_common(defn, info, decorator) + if info is None: + self.mark_incomplete(defn.name, defn) + else: + self.prepare_class_def(defn, info, custom_names=True) + return True + return False + + def analyze_namedtuple_classdef( + self, defn: ClassDef, tvar_defs: list[TypeVarLikeType] + ) -> bool: + """Check if this class can define a named tuple.""" + if ( + defn.info + and defn.info.is_named_tuple + and defn.info.tuple_type + and not has_placeholder(defn.info.tuple_type) + ): + # Don't reprocess everything. We just need to process methods defined + # in the named tuple class body. + is_named_tuple = True + info: TypeInfo | None = defn.info + else: + is_named_tuple, info = self.named_tuple_analyzer.analyze_namedtuple_classdef( + defn, self.is_stub_file, self.is_func_scope() + ) + if is_named_tuple: + if info is None: + self.mark_incomplete(defn.name, defn) + else: + self.prepare_class_def(defn, info, custom_names=True) + self.setup_type_vars(defn, tvar_defs) + self.setup_alias_type_vars(defn) + with self.scope.class_scope(defn.info): + for deco in defn.decorators: + deco.accept(self) + self.analyze_class_decorator_common(defn, defn.info, deco) + with self.named_tuple_analyzer.save_namedtuple_body(info): + self.analyze_class_body_common(defn) + return True + return False + + def apply_class_plugin_hooks(self, defn: ClassDef) -> None: + """Apply a plugin hook that may infer a more precise definition for a class.""" + + for decorator in defn.decorators: + decorator_name = self.get_fullname_for_hook(decorator) + if decorator_name: + hook = self.plugin.get_class_decorator_hook(decorator_name) + # Special case: if the decorator is itself decorated with + # typing.dataclass_transform, apply the hook for the dataclasses plugin + # TODO: remove special casing here + if hook is None and find_dataclass_transform_spec(decorator): + hook = dataclasses_plugin.dataclass_tag_callback + if hook: + hook(ClassDefContext(defn, decorator, self)) + + if defn.metaclass: + metaclass_name = self.get_fullname_for_hook(defn.metaclass) + if metaclass_name: + hook = self.plugin.get_metaclass_hook(metaclass_name) + if hook: + hook(ClassDefContext(defn, defn.metaclass, self)) + + for base_expr in defn.base_type_exprs: + base_name = self.get_fullname_for_hook(base_expr) + if base_name: + hook = self.plugin.get_base_class_hook(base_name) + if hook: + hook(ClassDefContext(defn, base_expr, self)) + + # Check if the class definition itself triggers a dataclass transform (via a parent class/ + # metaclass) + spec = find_dataclass_transform_spec(defn) + if spec is not None: + dataclasses_plugin.add_dataclass_tag(defn.info) + + def get_fullname_for_hook(self, expr: Expression) -> str | None: + if isinstance(expr, CallExpr): + return self.get_fullname_for_hook(expr.callee) + elif isinstance(expr, IndexExpr): + return self.get_fullname_for_hook(expr.base) + elif isinstance(expr, RefExpr): + if expr.fullname: + return expr.fullname + # If we don't have a fullname look it up. This happens because base classes are + # analyzed in a different manner (see exprtotype.py) and therefore those AST + # nodes will not have full names. + sym = self.lookup_type_node(expr) + if sym: + return sym.fullname + return None + + def analyze_class_keywords(self, defn: ClassDef) -> None: + for value in defn.keywords.values(): + value.accept(self) + + def enter_class(self, info: TypeInfo) -> None: + # Remember previous active class + self.type_stack.append(self.type) + self.locals.append(None) # Add class scope + self.scope_stack.append(SCOPE_CLASS) + self.block_depth.append(-1) # The class body increments this to 0 + self.loop_depth.append(0) + self._type = info + self.missing_names.append(set()) + + def leave_class(self) -> None: + """Restore analyzer state.""" + self.block_depth.pop() + self.loop_depth.pop() + self.locals.pop() + self.scope_stack.pop() + self._type = self.type_stack.pop() + self.missing_names.pop() + + def analyze_class_decorator(self, defn: ClassDef, decorator: Expression) -> None: + decorator.accept(self) + self.analyze_class_decorator_common(defn, defn.info, decorator) + if isinstance(decorator, RefExpr): + if decorator.fullname in RUNTIME_PROTOCOL_DECOS: + if defn.info.is_protocol: + defn.info.runtime_protocol = True + else: + self.fail("@runtime_checkable can only be used with protocol classes", defn) + elif isinstance(decorator, CallExpr) and refers_to_fullname( + decorator.callee, DATACLASS_TRANSFORM_NAMES + ): + defn.info.dataclass_transform_spec = self.parse_dataclass_transform_spec(decorator) + + def analyze_class_decorator_common( + self, defn: ClassDef, info: TypeInfo, decorator: Expression + ) -> None: + """Common method for applying class decorators. + + Called on regular classes, typeddicts, and namedtuples. + """ + if refers_to_fullname(decorator, FINAL_DECORATOR_NAMES): + info.is_final = True + elif refers_to_fullname(decorator, DISJOINT_BASE_DECORATOR_NAMES): + if info.is_protocol: + self.fail("@disjoint_base cannot be used with protocol class", decorator) + elif info.typeddict_type is not None: + self.fail("@disjoint_base cannot be used with TypedDict", decorator) + else: + info.is_disjoint_base = True + elif refers_to_fullname(decorator, TYPE_CHECK_ONLY_NAMES): + info.is_type_check_only = True + elif (deprecated := self.get_deprecated(decorator)) is not None: + info.deprecated = f"class {defn.fullname} is deprecated: {deprecated}" + + def clean_up_bases_and_infer_type_variables( + self, defn: ClassDef, base_type_exprs: list[Expression], context: Context + ) -> tuple[list[Expression], list[TypeVarLikeType], bool]: + """Remove extra base classes such as Generic and infer type vars. + + For example, consider this class: + + class Foo(Bar, Generic[T]): ... + + Now we will remove Generic[T] from bases of Foo and infer that the + type variable 'T' is a type argument of Foo. + + Note that this is performed *before* semantic analysis. + + Returns (remaining base expressions, inferred type variables, is protocol). + """ + removed: list[int] = [] + declared_tvars: TypeVarLikeList = [] + is_protocol = False + has_type_var_tuple = False + if defn.type_args is not None: + for p in defn.type_args: + node = self.lookup(p.name, context) + assert node is not None + assert isinstance(node.node, TypeVarLikeExpr) + if isinstance(node.node, TypeVarTupleExpr): + if has_type_var_tuple: + self.fail("Can only use one type var tuple in a class def", context) + continue + has_type_var_tuple = True + declared_tvars.append((p.name, node.node)) + + for i, base_expr in enumerate(base_type_exprs): + if isinstance(base_expr, StarExpr): + base_expr.valid = True + self.analyze_type_expr(base_expr) + + try: + base = self.expr_to_unanalyzed_type(base_expr) + except TypeTranslationError: + # This error will be caught later. + continue + result = self.analyze_class_typevar_declaration(base, has_type_var_tuple) + if result is not None: + tvars = result[0] + is_protocol |= result[1] + if declared_tvars: + if defn.type_args: + if is_protocol: + self.fail('No arguments expected for "Protocol" base class', context) + else: + self.fail("Generic[...] base class is redundant", context) + else: + self.fail( + "Only single Generic[...] or Protocol[...] can be in bases", context + ) + removed.append(i) + declared_tvars.extend(tvars) + if isinstance(base, UnboundType): + sym = self.lookup_qualified(base.name, base) + if sym is not None and sym.node is not None: + if sym.node.fullname in PROTOCOL_NAMES and i not in removed: + # also remove bare 'Protocol' bases + removed.append(i) + is_protocol = True + + all_tvars = self.get_all_bases_tvars(base_type_exprs, removed) + if declared_tvars: + if len(remove_dups(declared_tvars)) < len(declared_tvars) and not defn.type_args: + self.fail("Duplicate type variables in Generic[...] or Protocol[...]", context) + declared_tvars = remove_dups(declared_tvars) + if not set(all_tvars).issubset(set(declared_tvars)): + if defn.type_args: + undeclared = sorted(set(all_tvars) - set(declared_tvars)) + self.msg.type_parameters_should_be_declared( + [tv[0] for tv in undeclared], context + ) + else: + self.fail( + "If Generic[...] or Protocol[...] is present" + " it should list all type variables", + context, + ) + # In case of error, Generic tvars will go first + declared_tvars = remove_dups(declared_tvars + all_tvars) + else: + declared_tvars = all_tvars + for i in reversed(removed): + # We need to actually remove the base class expressions like Generic[T], + # mostly because otherwise they will create spurious dependencies in fine + # grained incremental mode. + defn.removed_base_type_exprs.append(defn.base_type_exprs[i]) + del base_type_exprs[i] + tvar_defs = self.tvar_defs_from_tvars(declared_tvars, context) + return base_type_exprs, tvar_defs, is_protocol + + def analyze_class_typevar_declaration( + self, base: Type, has_type_var_tuple: bool + ) -> tuple[TypeVarLikeList, bool] | None: + """Analyze type variables declared using Generic[...] or Protocol[...]. + + Args: + base: Non-analyzed base class + + Return None if the base class does not declare type variables. Otherwise, + return the type variables. + """ + if not isinstance(base, UnboundType): + return None + unbound = base + sym = self.lookup_qualified(unbound.name, unbound) + if sym is None or sym.node is None: + return None + if ( + sym.node.fullname == "typing.Generic" + or sym.node.fullname in PROTOCOL_NAMES + and base.args + ): + is_proto = sym.node.fullname != "typing.Generic" + tvars: TypeVarLikeList = [] + for arg in unbound.args: + tag = self.track_incomplete_refs() + tvar = self.analyze_unbound_tvar(arg) + if tvar: + if isinstance(tvar[1], TypeVarTupleExpr): + if has_type_var_tuple: + self.fail("Can only use one type var tuple in a class def", base) + continue + has_type_var_tuple = True + tvars.append(tvar) + elif not self.found_incomplete_ref(tag): + self.fail("Free type variable expected in %s[...]" % sym.node.name, base) + return tvars, is_proto + return None + + def analyze_unbound_tvar(self, t: Type) -> tuple[str, TypeVarLikeExpr] | None: + if isinstance(t, UnpackType) and isinstance(t.type, UnboundType): + return self.analyze_unbound_tvar_impl(t.type, is_unpacked=True) + if isinstance(t, UnboundType): + sym = self.lookup_qualified(t.name, t) + if sym and sym.fullname in UNPACK_TYPE_NAMES: + inner_t = t.args[0] + if isinstance(inner_t, UnboundType): + return self.analyze_unbound_tvar_impl(inner_t, is_unpacked=True) + return None + return self.analyze_unbound_tvar_impl(t) + return None + + def analyze_unbound_tvar_impl( + self, t: UnboundType, is_unpacked: bool = False, is_typealias_param: bool = False + ) -> tuple[str, TypeVarLikeExpr] | None: + assert not is_unpacked or not is_typealias_param, "Mutually exclusive conditions" + sym = self.lookup_qualified(t.name, t) + if sym and isinstance(sym.node, PlaceholderNode): + self.record_incomplete_ref() + if not is_unpacked and sym and isinstance(sym.node, ParamSpecExpr): + if sym.fullname and not self.tvar_scope.allow_binding(sym.fullname): + # It's bound by our type variable scope + return None + return t.name, sym.node + if (is_unpacked or is_typealias_param) and sym and isinstance(sym.node, TypeVarTupleExpr): + if sym.fullname and not self.tvar_scope.allow_binding(sym.fullname): + # It's bound by our type variable scope + return None + return t.name, sym.node + if sym is None or not isinstance(sym.node, TypeVarExpr) or is_unpacked: + return None + elif sym.fullname and not self.tvar_scope.allow_binding(sym.fullname): + # It's bound by our type variable scope + return None + else: + assert isinstance(sym.node, TypeVarExpr) + return t.name, sym.node + + def find_type_var_likes(self, t: Type) -> TypeVarLikeList: + visitor = FindTypeVarVisitor(self, self.tvar_scope) + t.accept(visitor) + return visitor.type_var_likes + + def get_all_bases_tvars( + self, base_type_exprs: list[Expression], removed: list[int] + ) -> TypeVarLikeList: + """Return all type variable references in bases.""" + tvars: TypeVarLikeList = [] + for i, base_expr in enumerate(base_type_exprs): + if i not in removed: + try: + base = self.expr_to_unanalyzed_type(base_expr) + except TypeTranslationError: + # This error will be caught later. + continue + base_tvars = self.find_type_var_likes(base) + tvars.extend(base_tvars) + return remove_dups(tvars) + + def tvar_defs_from_tvars( + self, tvars: TypeVarLikeList, context: Context + ) -> list[TypeVarLikeType]: + tvar_defs: list[TypeVarLikeType] = [] + last_tvar_name_with_default: str | None = None + for name, tvar_expr in tvars: + tvar_expr.default = tvar_expr.default.accept( + TypeVarDefaultTranslator(self, tvar_expr.name, context) + ) + # PEP-695 type variables that are redeclared in an inner scope are warned + # about elsewhere. + if not tvar_expr.is_new_style and not self.tvar_scope.allow_binding( + tvar_expr.fullname + ): + self.fail( + message_registry.TYPE_VAR_REDECLARED_IN_NESTED_CLASS.format(name), context + ) + tvar_def = self.tvar_scope.bind_new(name, tvar_expr, self.fail, context) + if last_tvar_name_with_default is not None and not tvar_def.has_default(): + self.msg.tvar_without_default_type( + tvar_def.name, last_tvar_name_with_default, context + ) + tvar_def.default = AnyType(TypeOfAny.from_error) + elif tvar_def.has_default(): + last_tvar_name_with_default = tvar_def.name + tvar_defs.append(tvar_def) + return tvar_defs + + def get_and_bind_all_tvars(self, type_exprs: list[Expression]) -> list[TypeVarLikeType]: + """Return all type variable references in item type expressions. + + This is a helper for generic TypedDicts and NamedTuples. Essentially it is + a simplified version of the logic we use for ClassDef bases. We duplicate + some amount of code, because it is hard to refactor common pieces. + """ + tvars: dict[str, tuple[TypeVarLikeExpr, Expression]] = {} + for base_expr in type_exprs: + try: + base = self.expr_to_unanalyzed_type(base_expr) + except TypeTranslationError: + # This error will be caught later. + continue + for name, expr in self.find_type_var_likes(base): + tvars.setdefault(name, (expr, base_expr)) + tvar_defs = [] + for name, (tvar_expr, context) in tvars.items(): + tvar_def = self.tvar_scope.bind_new(name, tvar_expr, self.fail, context) + tvar_defs.append(tvar_def) + return tvar_defs + + def prepare_class_def( + self, defn: ClassDef, info: TypeInfo | None = None, custom_names: bool = False + ) -> None: + """Prepare for the analysis of a class definition. + + Create an empty TypeInfo and store it in a symbol table, or if the 'info' + argument is provided, store it instead (used for magic type definitions). + """ + if not defn.info: + defn.fullname = self.qualified_name(defn.name) + # TODO: Nested classes + info = info or self.make_empty_type_info(defn) + defn.info = info + info.defn = defn + if not custom_names: + # Some special classes (in particular NamedTuples) use custom fullname logic. + # Don't override it here (also see comment below, this needs cleanup). + if not self.is_func_scope(): + info._fullname = self.qualified_name(defn.name) + else: + info._fullname = info.name + local_name = defn.name + if "@" in local_name: + local_name = local_name.split("@")[0] + self.add_symbol(local_name, defn.info, defn) + if self.is_nested_within_func_scope(): + # We need to preserve local classes, let's store them + # in globals under mangled unique names + # + # TODO: Putting local classes into globals breaks assumptions in fine-grained + # incremental mode and we should avoid it. In general, this logic is too + # ad-hoc and needs to be removed/refactored. + if "@" not in defn.info._fullname: + global_name = defn.info.name + "@" + str(defn.line) + defn.info._fullname = self.cur_mod_id + "." + global_name + else: + # Preserve name from previous fine-grained incremental run. + global_name = defn.info.name + defn.fullname = defn.info._fullname + if defn.info.is_named_tuple or defn.info.typeddict_type: + # Named tuples and Typed dicts nested within a class are stored + # in the class symbol table. + self.add_symbol_skip_local(global_name, defn.info) + else: + self.globals[global_name] = SymbolTableNode(GDEF, defn.info) + + def make_empty_type_info(self, defn: ClassDef) -> TypeInfo: + if ( + self.is_module_scope() + and self.cur_mod_id == "builtins" + and defn.name in CORE_BUILTIN_CLASSES + ): + # Special case core built-in classes. A TypeInfo was already + # created for it before semantic analysis, but with a dummy + # ClassDef. Patch the real ClassDef object. + info = self.globals[defn.name].node + assert isinstance(info, TypeInfo) + else: + info = TypeInfo(SymbolTable(), defn, self.cur_mod_id) + info.set_line(defn) + return info + + def get_name_repr_of_expr(self, expr: Expression) -> str | None: + """Try finding a short simplified textual representation of a base class expression.""" + if isinstance(expr, NameExpr): + return expr.name + if isinstance(expr, MemberExpr): + return get_member_expr_fullname(expr) + if isinstance(expr, IndexExpr): + return self.get_name_repr_of_expr(expr.base) + if isinstance(expr, CallExpr): + return self.get_name_repr_of_expr(expr.callee) + return None + + def analyze_base_classes( + self, base_type_exprs: list[Expression] + ) -> tuple[list[tuple[ProperType, Expression]], bool] | None: + """Analyze base class types. + + Return None if some definition was incomplete. Otherwise, return a tuple + with these items: + + * List of (analyzed type, original expression) tuples + * Boolean indicating whether one of the bases had a semantic analysis error + """ + is_error = False + bases = [] + for base_expr in base_type_exprs: + if ( + isinstance(base_expr, RefExpr) + and base_expr.fullname in TYPED_NAMEDTUPLE_NAMES + TPDICT_NAMES + ) or ( + isinstance(base_expr, CallExpr) + and isinstance(base_expr.callee, RefExpr) + and base_expr.callee.fullname in TPDICT_NAMES + ): + # Ignore magic bases for now. + # For example: + # class Foo(TypedDict): ... # RefExpr + # class Foo(NamedTuple): ... # RefExpr + # class Foo(TypedDict("Foo", {"a": int})): ... # CallExpr + continue + + try: + base = self.expr_to_analyzed_type( + base_expr, allow_placeholder=True, allow_type_any=True + ) + except TypeTranslationError: + name = self.get_name_repr_of_expr(base_expr) + if isinstance(base_expr, CallExpr): + msg = "Unsupported dynamic base class" + else: + msg = "Invalid base class" + if name: + msg += f' "{name}"' + self.fail(msg, base_expr) + is_error = True + continue + if base is None: + return None + base = get_proper_type(base) + bases.append((base, base_expr)) + return bases, is_error + + def configure_base_classes( + self, defn: ClassDef, bases: list[tuple[ProperType, Expression]] + ) -> None: + """Set up base classes. + + This computes several attributes on the corresponding TypeInfo defn.info + related to the base classes: defn.info.bases, defn.info.mro, and + miscellaneous others (at least tuple_type, fallback_to_any, and is_enum.) + """ + base_types: list[Instance] = [] + info = defn.info + + for base, base_expr in bases: + if isinstance(base, TupleType): + actual_base = self.configure_tuple_base_class(defn, base) + base_types.append(actual_base) + elif isinstance(base, Instance): + if base.type.is_newtype: + self.fail('Cannot subclass "NewType"', defn) + base_types.append(base) + elif isinstance(base, AnyType): + if self.options.disallow_subclassing_any: + if isinstance(base_expr, (NameExpr, MemberExpr)): + msg = f'Class cannot subclass "{base_expr.name}" (has type "Any")' + else: + msg = 'Class cannot subclass value of type "Any"' + self.fail(msg, base_expr) + info.fallback_to_any = True + elif isinstance(base, TypedDictType): + base_types.append(base.fallback) + else: + msg = "Invalid base class" + name = self.get_name_repr_of_expr(base_expr) + if name: + msg += f' "{name}"' + self.fail(msg, base_expr) + info.fallback_to_any = True + if self.options.disallow_any_unimported and has_any_from_unimported_type(base): + if isinstance(base_expr, (NameExpr, MemberExpr)): + prefix = f"Base type {base_expr.name}" + else: + prefix = "Base type" + self.msg.unimported_type_becomes_any(prefix, base, base_expr) + check_for_explicit_any( + base, self.options, self.is_typeshed_stub_file, self.msg, context=base_expr + ) + + # Add 'object' as implicit base if there is no other base class. + if not base_types and defn.fullname != "builtins.object": + base_types.append(self.object_type()) + + info.bases = base_types + + # Calculate the MRO. + if not self.verify_base_classes(defn): + self.set_dummy_mro(defn.info) + return + if not self.verify_duplicate_base_classes(defn): + # We don't want to block the typechecking process, + # so, we just insert `Any` as the base class and show an error. + self.set_any_mro(defn.info) + self.calculate_class_mro(defn, self.object_type) + + def configure_tuple_base_class(self, defn: ClassDef, base: TupleType) -> Instance: + info = defn.info + + # There may be an existing valid tuple type from previous semanal iterations. + # Use equality to check if it is the case. + if info.tuple_type and info.tuple_type != base and not has_placeholder(info.tuple_type): + self.fail("Class has two incompatible bases derived from tuple", defn) + defn.has_incompatible_baseclass = True + if has_placeholder(base): + self.process_placeholder( + None, "tuple base", defn, force_progress=base != info.tuple_type + ) + info.update_tuple_type(base) + self.setup_alias_type_vars(defn) + + if base.partial_fallback.type.fullname == "builtins.tuple" and not has_placeholder(base): + # Fallback can only be safely calculated after semantic analysis, since base + # classes may be incomplete. Postpone the calculation. + self.schedule_patch(PRIORITY_FALLBACKS, lambda: calculate_tuple_fallback(base)) + + return base.partial_fallback + + def set_dummy_mro(self, info: TypeInfo) -> None: + # Give it an MRO consisting of just the class itself and object. + info.mro = [info, self.object_type().type] + info.bad_mro = True + + def set_any_mro(self, info: TypeInfo) -> None: + # Give it an MRO consisting direct `Any` subclass. + info.fallback_to_any = True + info.mro = [info, self.object_type().type] + + def calculate_class_mro( + self, defn: ClassDef, obj_type: Callable[[], Instance] | None = None + ) -> None: + """Calculate method resolution order for a class. + + `obj_type` exists just to fill in empty base class list in case of an error. + """ + try: + calculate_mro(defn.info, obj_type) + except MroError: + self.fail( + f'Cannot determine consistent method resolution order (MRO) for "{defn.name}"', + defn, + ) + self.set_dummy_mro(defn.info) + # Allow plugins to alter the MRO to handle the fact that `def mro()` + # on metaclasses permits MRO rewriting. + if defn.fullname: + hook = self.plugin.get_customize_class_mro_hook(defn.fullname) + if hook: + hook(ClassDefContext(defn, FakeExpression(), self)) + + def infer_metaclass_and_bases_from_compat_helpers(self, defn: ClassDef) -> None: + """Lookup for special metaclass declarations, and update defn fields accordingly. + + * six.with_metaclass(M, B1, B2, ...) + * @six.add_metaclass(M) + * future.utils.with_metaclass(M, B1, B2, ...) + * past.utils.with_metaclass(M, B1, B2, ...) + """ + + # Look for six.with_metaclass(M, B1, B2, ...) + with_meta_expr: Expression | None = None + if len(defn.base_type_exprs) == 1: + base_expr = defn.base_type_exprs[0] + if isinstance(base_expr, CallExpr) and isinstance(base_expr.callee, RefExpr): + self.analyze_type_expr(base_expr) + if ( + base_expr.callee.fullname + in { + "six.with_metaclass", + "future.utils.with_metaclass", + "past.utils.with_metaclass", + } + and len(base_expr.args) >= 1 + and all(kind == ARG_POS for kind in base_expr.arg_kinds) + ): + with_meta_expr = base_expr.args[0] + defn.base_type_exprs = base_expr.args[1:] + + # Look for @six.add_metaclass(M) + add_meta_expr: Expression | None = None + for dec_expr in defn.decorators: + if isinstance(dec_expr, CallExpr) and isinstance(dec_expr.callee, RefExpr): + dec_expr.callee.accept(self) + if ( + dec_expr.callee.fullname == "six.add_metaclass" + and len(dec_expr.args) == 1 + and dec_expr.arg_kinds[0] == ARG_POS + ): + add_meta_expr = dec_expr.args[0] + break + + metas = {defn.metaclass, with_meta_expr, add_meta_expr} - {None} + if len(metas) == 0: + return + if len(metas) > 1: + self.fail("Multiple metaclass definitions", defn, code=codes.METACLASS) + return + defn.metaclass = metas.pop() + + def verify_base_classes(self, defn: ClassDef) -> bool: + info = defn.info + cycle = False + for base in info.bases: + baseinfo = base.type + if self.is_base_class(info, baseinfo): + self.fail("Cycle in inheritance hierarchy", defn) + cycle = True + return not cycle + + def verify_duplicate_base_classes(self, defn: ClassDef) -> bool: + dup = find_duplicate(defn.info.direct_base_classes()) + if dup: + self.fail(f'Duplicate base class "{dup.name}"', defn) + return not dup + + def is_base_class(self, t: TypeInfo, s: TypeInfo) -> bool: + """Determine if t is a base class of s (but do not use mro).""" + # Search the base class graph for t, starting from s. + worklist = [s] + visited = {s} + while worklist: + nxt = worklist.pop() + if nxt == t: + return True + for base in nxt.bases: + if base.type not in visited: + worklist.append(base.type) + visited.add(base.type) + return False + + def get_declared_metaclass( + self, name: str, metaclass_expr: Expression | None + ) -> tuple[Instance | None, bool, bool]: + """Get declared metaclass from metaclass expression. + + Returns a tuple of three values: + * A metaclass instance or None + * A boolean indicating whether we should defer + * A boolean indicating whether we should set metaclass Any fallback + (either for Any metaclass or invalid/dynamic metaclass). + + The two boolean flags can only be True if instance is None. + """ + declared_metaclass = None + if metaclass_expr: + metaclass_name = None + if isinstance(metaclass_expr, NameExpr): + metaclass_name = metaclass_expr.name + elif isinstance(metaclass_expr, MemberExpr): + metaclass_name = get_member_expr_fullname(metaclass_expr) + if metaclass_name is None: + self.fail( + f'Dynamic metaclass not supported for "{name}"', + metaclass_expr, + code=codes.METACLASS, + ) + return None, False, True + sym = self.lookup_qualified(metaclass_name, metaclass_expr) + if sym is None: + # Probably a name error - it is already handled elsewhere + return None, False, True + if isinstance(sym.node, Var) and isinstance(get_proper_type(sym.node.type), AnyType): + if self.options.disallow_subclassing_any: + self.fail( + f'Class cannot use "{sym.node.name}" as a metaclass (has type "Any")', + metaclass_expr, + code=codes.METACLASS, + ) + return None, False, True + if isinstance(sym.node, PlaceholderNode): + return None, True, False # defer later in the caller + + # Support type aliases, like `_Meta: TypeAlias = type` + metaclass_info: Node | None = sym.node + if ( + isinstance(sym.node, TypeAlias) + and not sym.node.python_3_12_type_alias + and not sym.node.alias_tvars + ): + target = get_proper_type(sym.node.target) + if isinstance(target, Instance): + metaclass_info = target.type + + if not isinstance(metaclass_info, TypeInfo) or metaclass_info.tuple_type is not None: + self.fail( + f'Invalid metaclass "{metaclass_name}"', metaclass_expr, code=codes.METACLASS + ) + return None, False, False + if not metaclass_info.is_metaclass(): + self.fail( + 'Metaclasses not inheriting from "type" are not supported', + metaclass_expr, + code=codes.METACLASS, + ) + return None, False, False + inst = fill_typevars(metaclass_info) + assert isinstance(inst, Instance) + declared_metaclass = inst + return declared_metaclass, False, False + + def recalculate_metaclass(self, defn: ClassDef, declared_metaclass: Instance | None) -> None: + defn.info.declared_metaclass = declared_metaclass + defn.info.metaclass_type = defn.info.calculate_metaclass_type() + if any(info.is_protocol for info in defn.info.mro): + if ( + not defn.info.metaclass_type + or defn.info.metaclass_type.type.fullname == "builtins.type" + ): + # All protocols and their subclasses have ABCMeta metaclass by default. + # TODO: add a metaclass conflict check if there is another metaclass. + abc_meta = self.named_type_or_none("abc.ABCMeta", []) + if abc_meta is not None: # May be None in tests with incomplete lib-stub. + defn.info.metaclass_type = abc_meta + if defn.info.metaclass_type and defn.info.metaclass_type.type.has_base("enum.EnumMeta"): + defn.info.is_enum = True + if defn.type_vars: + self.fail("Enum class cannot be generic", defn) + + # + # Imports + # + + def visit_import(self, i: Import) -> None: + self.statement = i + for id, as_id in i.ids: + # Modules imported in a stub file without using 'import X as X' won't get exported + # When implicit re-exporting is disabled, we have the same behavior as stubs. + use_implicit_reexport = not self.is_stub_file and self.options.implicit_reexport + if as_id is not None: + base_id = id + imported_id = as_id + module_public = use_implicit_reexport or id == as_id + else: + base_id = id.split(".")[0] + imported_id = base_id + module_public = use_implicit_reexport + + if base_id in self.modules: + node = self.modules[base_id] + if self.is_func_scope(): + kind = LDEF + elif self.type is not None: + kind = MDEF + else: + kind = GDEF + symbol = SymbolTableNode( + kind, node, module_public=module_public, module_hidden=not module_public + ) + self.add_imported_symbol( + imported_id, + symbol, + context=i, + module_public=module_public, + module_hidden=not module_public, + ) + else: + self.add_unknown_imported_symbol( + imported_id, + context=i, + target_name=base_id, + module_public=module_public, + module_hidden=not module_public, + ) + + def visit_import_from(self, imp: ImportFrom) -> None: + self.statement = imp + module_id = self.correct_relative_import(imp) + module = self.modules.get(module_id) + for id, as_id in imp.names: + fullname = module_id + "." + id + self.set_future_import_flags(fullname) + if module is None: + node = None + elif module_id == self.cur_mod_id and fullname in self.modules: + # Submodule takes precedence over definition in surround package, for + # compatibility with runtime semantics in typical use cases. This + # could more precisely model runtime semantics by taking into account + # the line number beyond which the local definition should take + # precedence, but doesn't seem to be important in most use cases. + node = SymbolTableNode(GDEF, self.modules[fullname]) + else: + if id == as_id == "__all__": + # For modules with __all__ public status of symbols is determined uniquely + # by contents of __all__, so we can recover the latter here, and avoid + # serializing this (redundant) information in MypyFile. + self.all_exports[:] = [ + name for name, sym in module.names.items() if sym.module_public + ] + node = module.names.get(id) + + missing_submodule = False + imported_id = as_id or id + + # Modules imported in a stub file without using 'from Y import X as X' will + # not get exported. + # When implicit re-exporting is disabled, we have the same behavior as stubs. + use_implicit_reexport = not self.is_stub_file and self.options.implicit_reexport + module_public = use_implicit_reexport or (as_id is not None and id == as_id) + + # If the module does not contain a symbol with the name 'id', + # try checking if it's a module instead. + if not node: + mod = self.modules.get(fullname) + if mod is not None: + kind = self.current_symbol_kind() + node = SymbolTableNode(kind, mod) + elif fullname in self.missing_modules: + missing_submodule = True + # If it is still not resolved, check for a module level __getattr__ + if module and not node and "__getattr__" in module.names: + # We store the fullname of the original definition so that we can + # detect whether two imported names refer to the same thing. + fullname = module_id + "." + id + gvar = self.create_getattr_var(module.names["__getattr__"], imported_id, fullname) + if gvar: + self.add_symbol( + imported_id, + gvar, + imp, + module_public=module_public, + module_hidden=not module_public, + ) + continue + + if node: + self.process_imported_symbol( + node, module_id, id, imported_id, fullname, module_public, context=imp + ) + if node.module_hidden: + self.report_missing_module_attribute( + module_id, + id, + imported_id, + module_public=module_public, + module_hidden=not module_public, + context=imp, + add_unknown_imported_symbol=False, + ) + elif module and not missing_submodule: + # Target module exists but the imported name is missing or hidden. + self.report_missing_module_attribute( + module_id, + id, + imported_id, + module_public=module_public, + module_hidden=not module_public, + context=imp, + ) + else: + # Import of a missing (sub)module. + self.add_unknown_imported_symbol( + imported_id, + imp, + target_name=fullname, + module_public=module_public, + module_hidden=not module_public, + ) + + def process_imported_symbol( + self, + node: SymbolTableNode, + module_id: str, + id: str, + imported_id: str, + fullname: str, + module_public: bool, + context: ImportBase, + ) -> None: + module_hidden = not module_public and ( + # `from package import submodule` should work regardless of whether package + # re-exports submodule, so we shouldn't hide it + not isinstance(node.node, MypyFile) + or fullname not in self.modules + # but given `from somewhere import random_unrelated_module` we should hide + # random_unrelated_module + or not fullname.startswith(self.cur_mod_id + ".") + ) + + if isinstance(node.node, PlaceholderNode): + if self.final_iteration: + self.report_missing_module_attribute( + module_id, + id, + imported_id, + module_public=module_public, + module_hidden=module_hidden, + context=context, + ) + return + else: + # This might become a type. + self.mark_incomplete( + imported_id, + node.node, + module_public=module_public, + module_hidden=module_hidden, + becomes_typeinfo=True, + ) + # NOTE: we take the original node even for final `Var`s. This is to support + # a common pattern when constants are re-exported (same applies to import *). + self.add_imported_symbol( + imported_id, node, context, module_public=module_public, module_hidden=module_hidden + ) + + def report_missing_module_attribute( + self, + import_id: str, + source_id: str, + imported_id: str, + module_public: bool, + module_hidden: bool, + context: Node, + add_unknown_imported_symbol: bool = True, + ) -> None: + # Missing attribute. + if self.is_incomplete_namespace(import_id): + # We don't know whether the name will be there, since the namespace + # is incomplete. Defer the current target. + self.mark_incomplete( + imported_id, context, module_public=module_public, module_hidden=module_hidden + ) + return + message = f'Module "{import_id}" has no attribute "{source_id}"' + # Suggest alternatives, if any match is found. + module = self.modules.get(import_id) + if module: + if source_id in module.names.keys() and not module.names[source_id].module_public: + message = ( + f'Module "{import_id}" does not explicitly export attribute "{source_id}"' + ) + elif not ( + self.options.ignore_errors or self.cur_mod_node.path in self.errors.ignored_files + ): + alternatives = set(module.names.keys()).difference({source_id}) + matches = best_matches(source_id, alternatives, n=3) + if matches: + suggestion = f"; maybe {pretty_seq(matches, 'or')}?" + message += f"{suggestion}" + self.fail(message, context, code=codes.ATTR_DEFINED) + if add_unknown_imported_symbol: + self.add_unknown_imported_symbol( + imported_id, + context, + target_name=None, + module_public=module_public, + module_hidden=not module_public, + ) + + if import_id == "typing": + # The user probably has a missing definition in a test fixture. Let's verify. + fullname = f"builtins.{source_id.lower()}" + if ( + self.lookup_fully_qualified_or_none(fullname) is None + and fullname in SUGGESTED_TEST_FIXTURES + ): + # Yes. Generate a helpful note. + self.msg.add_fixture_note(fullname, context) + else: + typing_extensions = self.modules.get("typing_extensions") + if typing_extensions and source_id in typing_extensions.names: + self.msg.note( + f"Use `from typing_extensions import {source_id}` instead", + context, + code=codes.ATTR_DEFINED, + ) + self.msg.note( + "See https://mypy.readthedocs.io/en/stable/runtime_troubles.html#using-new-additions-to-the-typing-module", + context, + code=codes.ATTR_DEFINED, + ) + + def process_import_over_existing_name( + self, + imported_id: str, + existing_symbol: SymbolTableNode, + module_symbol: SymbolTableNode, + import_node: ImportBase, + ) -> bool: + if existing_symbol.node is module_symbol.node: + # We added this symbol on previous iteration. + return False + if existing_symbol.kind in (LDEF, GDEF, MDEF) and isinstance( + existing_symbol.node, (Var, FuncDef, TypeInfo, Decorator, TypeAlias) + ): + # This is a valid import over an existing definition in the file. Construct a dummy + # assignment that we'll use to type check the import. + lvalue = NameExpr(imported_id) + lvalue.kind = existing_symbol.kind + lvalue.node = existing_symbol.node + rvalue = NameExpr(imported_id) + rvalue.kind = module_symbol.kind + rvalue.node = module_symbol.node + if isinstance(rvalue.node, TypeAlias): + # Suppress bogus errors from the dummy assignment if rvalue is an alias. + # Otherwise mypy may complain that alias is invalid in runtime context. + rvalue.is_alias_rvalue = True + assignment = AssignmentStmt([lvalue], rvalue) + for node in assignment, lvalue, rvalue: + node.set_line(import_node) + import_node.assignments.append(assignment) + return True + return False + + def correct_relative_import(self, node: ImportFrom | ImportAll) -> str: + import_id, ok = correct_relative_import( + self.cur_mod_id, node.relative, node.id, self.cur_mod_node.is_package_init_file() + ) + if not ok: + self.fail("Relative import climbs too many namespaces", node) + return import_id + + def visit_import_all(self, i: ImportAll) -> None: + i_id = self.correct_relative_import(i) + if i_id in self.modules: + m = self.modules[i_id] + if self.is_incomplete_namespace(i_id): + # Any names could be missing from the current namespace if the target module + # namespace is incomplete. + self.mark_incomplete("*", i) + for name, node in m.names.items(): + if node.no_serialize: + # This is either internal or generated symbol, skip it to avoid problems + # like accidental name conflicts or invalid cross-references. + continue + fullname = i_id + "." + name + self.set_future_import_flags(fullname) + # if '__all__' exists, all nodes not included have had module_public set to + # False, and we can skip checking '_' because it's been explicitly included. + if node.module_public and (not name.startswith("_") or "__all__" in m.names): + if isinstance(node.node, MypyFile): + # Star import of submodule from a package, add it as a dependency. + self.imports.add(node.node.fullname) + # `from x import *` always reexports symbols + self.add_imported_symbol( + name, node, context=i, module_public=True, module_hidden=False + ) + # This is a (minimalist) copy of the logic in visit_import_from(), we need + # to clean-up any remaining placeholders by replacing them with Var(Any). + if isinstance(node.node, PlaceholderNode) and self.final_iteration: + self.add_unknown_imported_symbol( + name, i, target_name=None, module_public=True, module_hidden=False + ) + + else: + # Don't add any dummy symbols for 'from x import *' if 'x' is unknown. + pass + + # + # Assignment + # + + def visit_assignment_expr(self, s: AssignmentExpr) -> None: + s.value.accept(self) + if self.is_func_scope(): + if not self.check_valid_comprehension(s): + return + self.analyze_lvalue(s.target, escape_comprehensions=True, has_explicit_value=True) + + def check_valid_comprehension(self, s: AssignmentExpr) -> bool: + """Check that assignment expression is not nested within comprehension at class scope. + + class C: + [(j := i) for i in [1, 2, 3]] + is a syntax error that is not enforced by Python parser, but at later steps. + """ + for i, scope_type in enumerate(reversed(self.scope_stack)): + if scope_type != SCOPE_COMPREHENSION and i < len(self.locals) - 1: + if self.locals[-1 - i] is None: + self.fail( + "Assignment expression within a comprehension" + " cannot be used in a class body", + s, + code=codes.SYNTAX, + serious=True, + blocker=True, + ) + return False + break + return True + + def visit_assignment_stmt(self, s: AssignmentStmt) -> None: + self.statement = s + + # Special case assignment like X = X. + if self.analyze_identity_global_assignment(s): + return + + tag = self.track_incomplete_refs() + + # Here we have a chicken and egg problem: at this stage we can't call + # can_be_type_alias(), because we have not enough information about rvalue. + # But we can't use a full visit because it may emit extra incomplete refs (namely + # when analysing any type applications there) thus preventing the further analysis. + # To break the tie, we first analyse rvalue partially, if it can be a type alias. + if self.can_possibly_be_type_form(s): + old_basic_type_applications = self.basic_type_applications + self.basic_type_applications = True + with self.allow_unbound_tvars_set(): + s.rvalue.accept(self) + self.basic_type_applications = old_basic_type_applications + elif self.can_possibly_be_typevarlike_declaration(s): + # Allow unbound tvars inside TypeVarLike defaults to be evaluated later + with self.allow_unbound_tvars_set(): + s.rvalue.accept(self) + else: + s.rvalue.accept(self) + + if self.found_incomplete_ref(tag) or self.should_wait_rhs(s.rvalue): + # Initializer couldn't be fully analyzed. Defer the current node and give up. + # Make sure that if we skip the definition of some local names, they can't be + # added later in this scope, since an earlier definition should take precedence. + for expr in names_modified_by_assignment(s): + self.mark_incomplete(expr.name, expr) + return + if self.can_possibly_be_type_form(s): + # Now re-visit those rvalues that were we skipped type applications above. + # This should be safe as generally semantic analyzer is idempotent. + with self.allow_unbound_tvars_set(): + s.rvalue.accept(self) + + # The r.h.s. is now ready to be classified, first check if it is a special form: + special_form = False + # * type alias + if self.check_and_set_up_type_alias(s): + s.is_alias_def = True + special_form = True + elif isinstance(s.rvalue, CallExpr): + # * type variable definition + if self.process_typevar_declaration(s): + special_form = True + elif self.process_paramspec_declaration(s): + special_form = True + elif self.process_typevartuple_declaration(s): + special_form = True + # * type constructors + elif self.analyze_namedtuple_assign(s): + special_form = True + elif self.analyze_typeddict_assign(s): + special_form = True + elif self.newtype_analyzer.process_newtype_declaration(s): + special_form = True + elif self.analyze_enum_assign(s): + special_form = True + + if special_form: + self.record_special_form_lvalue(s) + return + # Clear the alias flag if assignment turns out not a special form after all. It + # may be set to True while there were still placeholders due to forward refs. + s.is_alias_def = False + + # OK, this is a regular assignment, perform the necessary analysis steps. + s.is_final_def = self.unwrap_final(s) + self.analyze_lvalues(s) + self.check_final_implicit_def(s) + self.store_final_status(s) + self.check_classvar(s) + self.process_type_annotation(s) + self.analyze_rvalue_as_type_form(s) + self.apply_dynamic_class_hook(s) + if not s.type: + self.process_module_assignment(s.lvalues, s.rvalue, s) + self.process__all__(s) + self.process__deletable__(s) + self.process__slots__(s) + + def analyze_identity_global_assignment(self, s: AssignmentStmt) -> bool: + """Special case 'X = X' in global scope. + + This allows supporting some important use cases. + + Return true if special casing was applied. + """ + if not isinstance(s.rvalue, NameExpr) or len(s.lvalues) != 1: + # Not of form 'X = X' + return False + lvalue = s.lvalues[0] + if not isinstance(lvalue, NameExpr) or s.rvalue.name != lvalue.name: + # Not of form 'X = X' + return False + if self.type is not None or self.is_func_scope(): + # Not in global scope + return False + # It's an assignment like 'X = X' in the global scope. + name = lvalue.name + sym = self.lookup(name, s) + if sym is None: + if self.final_iteration: + # Fall back to normal assignment analysis. + return False + else: + self.defer() + return True + else: + if sym.node is None: + # Something special -- fall back to normal assignment analysis. + return False + if name not in self.globals: + # The name is from builtins. Add an alias to the current module. + self.add_symbol(name, sym.node, s) + if not isinstance(sym.node, PlaceholderNode): + for node in s.rvalue, lvalue: + node.node = sym.node + node.kind = GDEF + node.fullname = sym.node.fullname + return True + + def should_wait_rhs(self, rv: Expression) -> bool: + """Can we already classify this r.h.s. of an assignment or should we wait? + + This returns True if we don't have enough information to decide whether + an assignment is just a normal variable definition or a special form. + Always return False if this is a final iteration. This will typically cause + the lvalue to be classified as a variable plus emit an error. + """ + if self.final_iteration: + # No chance, nothing has changed. + return False + if isinstance(rv, NameExpr): + n = self.lookup(rv.name, rv) + if n and isinstance(n.node, PlaceholderNode) and not n.node.becomes_typeinfo: + return True + elif isinstance(rv, MemberExpr): + fname = get_member_expr_fullname(rv) + if fname: + n = self.lookup_qualified(fname, rv, suppress_errors=True) + if n and isinstance(n.node, PlaceholderNode) and not n.node.becomes_typeinfo: + return True + elif isinstance(rv, IndexExpr) and isinstance(rv.base, RefExpr): + return self.should_wait_rhs(rv.base) + elif isinstance(rv, CallExpr) and isinstance(rv.callee, RefExpr): + # This is only relevant for builtin SCC where things like 'TypeVar' + # may be not ready. + return self.should_wait_rhs(rv.callee) + return False + + def can_be_type_alias(self, rv: Expression, allow_none: bool = False) -> bool: + """Is this a valid r.h.s. for an alias definition? + + Note: this function should be only called for expressions where self.should_wait_rhs() + returns False. + """ + if isinstance(rv, RefExpr) and self.is_type_ref(rv, bare=True): + return True + if isinstance(rv, IndexExpr) and self.is_type_ref(rv.base, bare=False): + return True + if self.is_none_alias(rv): + return True + if allow_none and isinstance(rv, NameExpr) and rv.fullname == "builtins.None": + return True + if isinstance(rv, OpExpr) and rv.op == "|": + if self.is_stub_file: + return True + if self.can_be_type_alias(rv.left, allow_none=True) and self.can_be_type_alias( + rv.right, allow_none=True + ): + return True + return False + + def can_possibly_be_type_form(self, s: AssignmentStmt) -> bool: + """Like can_be_type_alias(), but simpler and doesn't require fully analyzed rvalue. + + Instead, use lvalues/annotations structure to figure out whether this can potentially be + a type alias definition, NamedTuple, or TypedDict. Another difference from above function + is that we are only interested IndexExpr, CallExpr and OpExpr rvalues, since only those + can be potentially recursive (things like `A = A` are never valid). + """ + if len(s.lvalues) > 1: + return False + if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.callee, RefExpr): + ref = s.rvalue.callee.fullname + return ref in TPDICT_NAMES or ref in TYPED_NAMEDTUPLE_NAMES + if not isinstance(s.lvalues[0], NameExpr): + return False + if s.unanalyzed_type is not None and not self.is_pep_613(s): + return False + if not isinstance(s.rvalue, (IndexExpr, OpExpr)): + return False + # Something that looks like Foo = Bar[Baz, ...] + return True + + def can_possibly_be_typevarlike_declaration(self, s: AssignmentStmt) -> bool: + """Check if r.h.s. can be a TypeVarLike declaration.""" + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr): + return False + if not isinstance(s.rvalue, CallExpr) or not isinstance(s.rvalue.callee, NameExpr): + return False + ref = s.rvalue.callee + ref.accept(self) + return ref.fullname in TYPE_VAR_LIKE_NAMES + + def is_type_ref(self, rv: Expression, bare: bool = False) -> bool: + """Does this expression refer to a type? + + This includes: + * Special forms, like Any or Union + * Classes (except subscripted enums) + * Other type aliases + * PlaceholderNodes with becomes_typeinfo=True (these can be not ready class + definitions, and not ready aliases). + + If bare is True, this is not a base of an index expression, so some special + forms are not valid (like a bare Union). + + Note: This method should be only used in context of a type alias definition. + This method can only return True for RefExprs, to check if C[int] is a valid + target for type alias call this method on expr.base (i.e. on C in C[int]). + See also can_be_type_alias(). + """ + if not isinstance(rv, RefExpr): + return False + if isinstance(rv.node, TypeVarLikeExpr): + self.fail(f'Type variable "{rv.fullname}" is invalid as target for type alias', rv) + return False + + if bare: + # These three are valid even if bare, for example + # A = Tuple is just equivalent to A = Tuple[Any, ...]. + valid_refs = {"typing.Any", "typing.Tuple", "typing.Callable"} + else: + valid_refs = type_constructors + + if isinstance(rv.node, TypeAlias) or rv.fullname in valid_refs: + return True + if isinstance(rv.node, TypeInfo): + if bare: + return True + # Assignment color = Color['RED'] defines a variable, not an alias. + return not rv.node.is_enum + if isinstance(rv.node, Var): + return rv.node.fullname in NEVER_NAMES + + if isinstance(rv, NameExpr): + n = self.lookup(rv.name, rv) + if n and isinstance(n.node, PlaceholderNode) and n.node.becomes_typeinfo: + return True + elif isinstance(rv, MemberExpr): + fname = get_member_expr_fullname(rv) + if fname: + # The r.h.s. for variable definitions may not be a type reference but just + # an instance attribute, so suppress the errors. + n = self.lookup_qualified(fname, rv, suppress_errors=True) + if n and isinstance(n.node, PlaceholderNode) and n.node.becomes_typeinfo: + return True + return False + + def is_none_alias(self, node: Expression) -> bool: + """Is this a r.h.s. for a None alias? + + We special case the assignments like Void = type(None), to allow using + Void in type annotations. + """ + if isinstance(node, CallExpr): + if ( + isinstance(node.callee, NameExpr) + and len(node.args) == 1 + and isinstance(node.args[0], NameExpr) + ): + call = self.lookup_qualified(node.callee.name, node.callee) + arg = self.lookup_qualified(node.args[0].name, node.args[0]) + if ( + call is not None + and call.node + and call.node.fullname == "builtins.type" + and arg is not None + and arg.node + and arg.node.fullname == "builtins.None" + ): + return True + return False + + def record_special_form_lvalue(self, s: AssignmentStmt) -> None: + """Record minimal necessary information about l.h.s. of a special form. + + This exists mostly for compatibility with the old semantic analyzer. + """ + lvalue = s.lvalues[0] + assert isinstance(lvalue, NameExpr) + lvalue.is_special_form = True + if self.current_symbol_kind() == GDEF: + lvalue.fullname = self.qualified_name(lvalue.name) + lvalue.kind = self.current_symbol_kind() + + def analyze_enum_assign(self, s: AssignmentStmt) -> bool: + """Check if s defines an Enum.""" + if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, EnumCallExpr): + # This is an analyzed enum definition. + # It is valid iff it can be stored correctly, failures were already reported. + return self._is_single_name_assignment(s) + return self.enum_call_analyzer.process_enum_call(s, self.is_func_scope()) + + def analyze_namedtuple_assign(self, s: AssignmentStmt) -> bool: + """Check if s defines a namedtuple.""" + if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, NamedTupleExpr): + if s.rvalue.analyzed.info.tuple_type and not has_placeholder( + s.rvalue.analyzed.info.tuple_type + ): + # This is an analyzed named tuple definition. + # It is valid iff it can be stored correctly, failures were already reported. + return self._is_single_name_assignment(s) + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], (NameExpr, MemberExpr)): + return False + lvalue = s.lvalues[0] + if isinstance(lvalue, MemberExpr): + if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.callee, RefExpr): + fullname = s.rvalue.callee.fullname + if fullname == "collections.namedtuple" or fullname in TYPED_NAMEDTUPLE_NAMES: + self.fail("NamedTuple type as an attribute is not supported", lvalue) + return False + name = lvalue.name + namespace = self.qualified_name(name) + with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)): + internal_name, info, tvar_defs = self.named_tuple_analyzer.check_namedtuple( + s.rvalue, name, self.is_func_scope() + ) + if internal_name is None: + return False + if internal_name != name: + self.fail( + 'First argument to namedtuple() should be "{}", not "{}"'.format( + name, internal_name + ), + s.rvalue, + code=codes.NAME_MATCH, + ) + return True + # Yes, it's a valid namedtuple, but defer if it is not ready. + if not info: + self.mark_incomplete(name, lvalue, becomes_typeinfo=True) + else: + self.setup_type_vars(info.defn, tvar_defs) + self.setup_alias_type_vars(info.defn) + return True + + def analyze_typeddict_assign(self, s: AssignmentStmt) -> bool: + """Check if s defines a typed dict.""" + if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, TypedDictExpr): + if s.rvalue.analyzed.info.typeddict_type and not has_placeholder( + s.rvalue.analyzed.info.typeddict_type + ): + # This is an analyzed typed dict definition. + # It is valid iff it can be stored correctly, failures were already reported. + return self._is_single_name_assignment(s) + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], (NameExpr, MemberExpr)): + return False + lvalue = s.lvalues[0] + name = lvalue.name + namespace = self.qualified_name(name) + with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)): + is_typed_dict, info, tvar_defs = self.typed_dict_analyzer.check_typeddict( + s.rvalue, name, self.is_func_scope() + ) + if not is_typed_dict: + return False + if isinstance(lvalue, MemberExpr): + self.fail("TypedDict type as attribute is not supported", lvalue) + return False + # Yes, it's a valid typed dict, but defer if it is not ready. + if not info: + self.mark_incomplete(name, lvalue, becomes_typeinfo=True) + else: + defn = info.defn + self.setup_type_vars(defn, tvar_defs) + self.setup_alias_type_vars(defn) + return True + + def _is_single_name_assignment(self, s: AssignmentStmt) -> bool: + return len(s.lvalues) == 1 and isinstance(s.lvalues[0], NameExpr) + + def analyze_lvalues(self, s: AssignmentStmt) -> None: + # We cannot use s.type, because analyze_simple_literal_type() will set it. + explicit = s.unanalyzed_type is not None + if self.is_final_type(s.unanalyzed_type): + # We need to exclude bare Final. + assert isinstance(s.unanalyzed_type, UnboundType) + if not s.unanalyzed_type.args: + explicit = False + + if s.rvalue: + if isinstance(s.rvalue, TempNode): + has_explicit_value = not s.rvalue.no_rhs + else: + has_explicit_value = True + else: + has_explicit_value = False + + for lval in s.lvalues: + self.analyze_lvalue( + lval, + explicit_type=explicit, + is_final=s.is_final_def, + has_explicit_value=has_explicit_value, + ) + + def analyze_rvalue_as_type_form(self, s: AssignmentStmt) -> None: + if TYPE_FORM in self.options.enable_incomplete_feature: + self.try_parse_as_type_expression(s.rvalue) + + def apply_dynamic_class_hook(self, s: AssignmentStmt) -> None: + if not isinstance(s.rvalue, CallExpr): + return + fname = "" + call = s.rvalue + while True: + if isinstance(call.callee, RefExpr): + fname = call.callee.fullname + # check if method call + if not fname and isinstance(call.callee, MemberExpr): + callee_expr = call.callee.expr + if isinstance(callee_expr, RefExpr) and callee_expr.fullname: + method_name = call.callee.name + fname = callee_expr.fullname + "." + method_name + elif ( + isinstance(callee_expr, IndexExpr) + and isinstance(callee_expr.base, RefExpr) + and isinstance(callee_expr.analyzed, TypeApplication) + ): + method_name = call.callee.name + fname = callee_expr.base.fullname + "." + method_name + elif isinstance(callee_expr, CallExpr): + # check if chain call + call = callee_expr + continue + break + if not fname: + return + hook = self.plugin.get_dynamic_class_hook(fname) + if not hook: + return + for lval in s.lvalues: + if not isinstance(lval, NameExpr): + continue + hook(DynamicClassDefContext(call, lval.name, self)) + + def unwrap_final(self, s: AssignmentStmt) -> bool: + """Strip Final[...] if present in an assignment. + + This is done to invoke type inference during type checking phase for this + assignment. Also, Final[...] doesn't affect type in any way -- it is rather an + access qualifier for given `Var`. + + Also perform various consistency checks. + + Returns True if Final[...] was present. + """ + if not s.unanalyzed_type or not self.is_final_type(s.unanalyzed_type): + return False + assert isinstance(s.unanalyzed_type, UnboundType) + if len(s.unanalyzed_type.args) > 1: + self.fail("Final[...] takes at most one type argument", s.unanalyzed_type) + invalid_bare_final = False + if not s.unanalyzed_type.args: + s.type = None + if ( + isinstance(s.rvalue, TempNode) + and s.rvalue.no_rhs + # Filter duplicate errors, we already reported this: + and not (self.type and self.type.is_named_tuple) + ): + invalid_bare_final = True + self.fail("Type in Final[...] can only be omitted if there is an initializer", s) + else: + s.type = s.unanalyzed_type.args[0] + + if ( + s.type is not None + and self.options.python_version < (3, 13) + and self.is_classvar(s.type) + ): + self.fail("Variable should not be annotated with both ClassVar and Final", s) + return False + + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], RefExpr): + self.fail("Invalid final declaration", s) + return False + lval = s.lvalues[0] + assert isinstance(lval, RefExpr) + + # Reset inferred status if it was set due to simple literal rvalue on previous iteration. + # TODO: this is a best-effort quick fix, we should avoid the need to manually sync this, + # see https://github.com/python/mypy/issues/6458. + if lval.is_new_def: + lval.is_inferred_def = s.type is None + + if self.loop_depth[-1] > 0: + self.fail("Cannot use Final inside a loop", s) + if self.type and self.type.is_protocol: + if self.is_class_scope(): + self.msg.protocol_members_cant_be_final(s) + if ( + isinstance(s.rvalue, TempNode) + and s.rvalue.no_rhs + and not self.is_stub_file + and not self.is_class_scope() + ): + if not invalid_bare_final: # Skip extra error messages. + self.msg.final_without_value(s) + return True + + def check_final_implicit_def(self, s: AssignmentStmt) -> None: + """Do basic checks for final declaration on self in __init__. + + Additional re-definition checks are performed by `analyze_lvalue`. + """ + if not s.is_final_def: + return + lval = s.lvalues[0] + assert isinstance(lval, RefExpr) + if isinstance(lval, MemberExpr): + if not self.is_self_member_ref(lval): + self.fail("Final can be only applied to a name or an attribute on self", s) + s.is_final_def = False + return + else: + assert self.function_stack + if self.function_stack[-1].name != "__init__": + self.fail("Can only declare a final attribute in class body or __init__", s) + s.is_final_def = False + return + + def store_final_status(self, s: AssignmentStmt) -> None: + """If this is a locally valid final declaration, set the corresponding flag on `Var`.""" + if s.is_final_def: + if len(s.lvalues) == 1 and isinstance(s.lvalues[0], RefExpr): + node = s.lvalues[0].node + if isinstance(node, Var): + node.is_final = True + if s.type: + node.final_value = constant_fold_expr(s.rvalue, self.cur_mod_id) + if self.is_class_scope() and ( + isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs + ): + node.final_unset_in_class = True + else: + for lval in self.flatten_lvalues(s.lvalues): + # Special case: we are working with an `Enum`: + # + # class MyEnum(Enum): + # key = 'some value' + # + # Here `key` is implicitly final. In runtime, code like + # + # MyEnum.key = 'modified' + # + # will fail with `AttributeError: Cannot reassign members.` + # That's why we need to replicate this. + if ( + isinstance(lval, NameExpr) + and isinstance(self.type, TypeInfo) + and self.type.is_enum + ): + cur_node = self.type.names.get(lval.name, None) + if ( + cur_node + and isinstance(cur_node.node, Var) + and not (isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs) + ): + # Double underscored members are writable on an `Enum`. + # (Except read-only `__members__` but that is handled in type checker) + cur_node.node.is_final = s.is_final_def = not is_dunder(cur_node.node.name) + + # Special case: deferred initialization of a final attribute in __init__. + # In this case we just pretend this is a valid final definition to suppress + # errors about assigning to final attribute. + if isinstance(lval, MemberExpr) and self.is_self_member_ref(lval): + assert self.type, "Self member outside a class" + cur_node = self.type.names.get(lval.name, None) + if cur_node and isinstance(cur_node.node, Var) and cur_node.node.is_final: + assert self.function_stack + current_function = self.function_stack[-1] + if ( + current_function.name == "__init__" + and cur_node.node.final_unset_in_class + and not cur_node.node.final_set_in_init + and not (isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs) + ): + cur_node.node.final_set_in_init = True + s.is_final_def = True + + def flatten_lvalues(self, lvalues: list[Expression]) -> list[Expression]: + res: list[Expression] = [] + for lv in lvalues: + if isinstance(lv, (TupleExpr, ListExpr)): + res.extend(self.flatten_lvalues(lv.items)) + else: + res.append(lv) + return res + + def process_type_annotation(self, s: AssignmentStmt) -> None: + """Analyze type annotation or infer simple literal type.""" + if s.type: + lvalue = s.lvalues[-1] + allow_tuple_literal = isinstance(lvalue, TupleExpr) + analyzed = self.anal_type(s.type, allow_tuple_literal=allow_tuple_literal) + # Don't store not ready types (including placeholders). + if analyzed is None or has_placeholder(analyzed): + self.defer(s) + return + s.type = analyzed + if ( + self.type + and self.type.is_protocol + and isinstance(lvalue, NameExpr) + and isinstance(s.rvalue, TempNode) + and s.rvalue.no_rhs + ): + if isinstance(lvalue.node, Var): + lvalue.node.is_abstract_var = True + else: + if ( + self.type + and self.type.is_protocol + and self.is_annotated_protocol_member(s) + and not self.is_func_scope() + ): + self.fail("All protocol members must have explicitly declared types", s) + # Set the type if the rvalue is a simple literal (even if the above error occurred). + if len(s.lvalues) == 1 and isinstance(s.lvalues[0], RefExpr): + ref_expr = s.lvalues[0] + safe_literal_inference = True + if self.type and isinstance(ref_expr, NameExpr) and len(self.type.mro) > 1: + # Check if there is a definition in supertype. If yes, we can't safely + # decide here what to infer: int or Literal[42]. + safe_literal_inference = self.type.mro[1].get(ref_expr.name) is None + if safe_literal_inference and ref_expr.is_inferred_def: + s.type = self.analyze_simple_literal_type(s.rvalue, s.is_final_def) + if s.type: + # Store type into nodes. + for lvalue in s.lvalues: + self.store_declared_types(lvalue, s.type) + + def is_annotated_protocol_member(self, s: AssignmentStmt) -> bool: + """Check whether a protocol member is annotated. + + There are some exceptions that can be left unannotated, like ``__slots__``.""" + return any( + (isinstance(lv, NameExpr) and lv.name != "__slots__" and lv.is_inferred_def) + for lv in s.lvalues + ) + + def analyze_simple_literal_type(self, rvalue: Expression, is_final: bool) -> Type | None: + """Return builtins.int if rvalue is an int literal, etc. + + If this is a 'Final' context, we return "Literal[...]" instead. + """ + if self.function_stack: + # Skip inside a function; this is to avoid confusing + # the code that handles dead code due to isinstance() + # inside type variables with value restrictions (like + # AnyStr). + return None + + value = constant_fold_expr(rvalue, self.cur_mod_id) + if value is None or isinstance(value, complex): + return None + + if isinstance(value, bool): + type_name = "builtins.bool" + elif isinstance(value, int): + type_name = "builtins.int" + elif isinstance(value, str): + type_name = "builtins.str" + elif isinstance(value, float): + type_name = "builtins.float" + + typ = self.named_type_or_none(type_name) + if typ and is_final: + return typ.copy_modified(last_known_value=LiteralType(value=value, fallback=typ)) + return typ + + def analyze_alias( + self, + name: str, + rvalue: Expression, + allow_placeholder: bool = False, + declared_type_vars: TypeVarLikeList | None = None, + all_declared_type_params_names: list[str] | None = None, + python_3_12_type_alias: bool = False, + ) -> tuple[Type | None, list[TypeVarLikeType], set[str], bool]: + """Check if 'rvalue' is a valid type allowed for aliasing (e.g. not a type variable). + + If yes, return the corresponding type, a list of type variables for generic aliases, + a set of names the alias depends on, and True if the original type has empty tuple index. + An example for the dependencies: + A = int + B = str + analyze_alias(dict[A, B])[2] == {'__main__.A', '__main__.B'} + """ + dynamic = bool(self.function_stack and self.function_stack[-1].is_dynamic()) + global_scope = not self.type and not self.function_stack + try: + typ = expr_to_unanalyzed_type( + rvalue, self.options, self.is_stub_file, lookup_qualified=self.lookup_qualified + ) + except TypeTranslationError: + self.fail( + "Invalid type alias: expression is not a valid type", rvalue, code=codes.VALID_TYPE + ) + return None, [], set(), False + + found_type_vars = self.find_type_var_likes(typ) + namespace = self.qualified_name(name) + alias_type_vars = found_type_vars if declared_type_vars is None else declared_type_vars + with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)): + tvar_defs = self.tvar_defs_from_tvars(alias_type_vars, typ) + + if python_3_12_type_alias: + with self.allow_unbound_tvars_set(): + rvalue.accept(self) + + analyzed, depends_on = analyze_type_alias( + typ, + self, + self.tvar_scope, + self.plugin, + self.options, + self.cur_mod_node, + self.is_typeshed_stub_file, + allow_placeholder=allow_placeholder, + in_dynamic_func=dynamic, + global_scope=global_scope, + allowed_alias_tvars=tvar_defs, + alias_type_params_names=all_declared_type_params_names, + python_3_12_type_alias=python_3_12_type_alias, + ) + + # There can be only one variadic variable at most, the error is reported elsewhere. + new_tvar_defs = [] + variadic = False + for td in tvar_defs: + if isinstance(td, TypeVarTupleType): + if variadic: + continue + variadic = True + new_tvar_defs.append(td) + + indexed = bool(isinstance(typ, UnboundType) and (typ.args or typ.empty_tuple_index)) + return analyzed, new_tvar_defs, depends_on, indexed + + def is_pep_613(self, s: AssignmentStmt) -> bool: + if s.unanalyzed_type is not None and isinstance(s.unanalyzed_type, UnboundType): + lookup = self.lookup_qualified(s.unanalyzed_type.name, s, suppress_errors=True) + if lookup and lookup.fullname in TYPE_ALIAS_NAMES: + return True + return False + + def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool: + """Check if assignment creates a type alias and set it up as needed. + + Return True if it is a type alias (even if the target is not ready), + or False otherwise. + + Note: the resulting types for subscripted (including generic) aliases + are also stored in rvalue.analyzed. + """ + if s.invalid_recursive_alias: + return True + lvalue = s.lvalues[0] + if len(s.lvalues) > 1 or not isinstance(lvalue, NameExpr): + # First rule: Only simple assignments like Alias = ... create aliases. + return False + + pep_613 = self.is_pep_613(s) + if not pep_613 and s.unanalyzed_type is not None: + # Second rule: Explicit type (cls: Type[A] = A) always creates variable, not alias. + # unless using PEP 613 `cls: TypeAlias = A` + return False + + # It can be `A = TypeAliasType('A', ...)` call, in this case, + # we just take the second argument and analyze it: + type_params: TypeVarLikeList | None + all_type_params_names: list[str] | None + if self.check_type_alias_type_call(s.rvalue, name=lvalue.name): + rvalue = ( + s.rvalue.args[1] + if s.rvalue.arg_kinds[1] == ARG_POS + else s.rvalue.args[s.rvalue.arg_names.index("value")] + ) + pep_695 = True + type_params, all_type_params_names = self.analyze_type_alias_type_params(s.rvalue) + else: + rvalue = s.rvalue + pep_695 = False + type_params = None + all_type_params_names = None + + if isinstance(rvalue, CallExpr) and rvalue.analyzed: + return False + + existing = self.current_symbol_table().get(lvalue.name) + # Third rule: type aliases can't be re-defined. For example: + # A: Type[float] = int + # A = float # OK, but this doesn't define an alias + # B = int + # B = float # Error! + # Don't create an alias in these cases: + if existing and ( + isinstance(existing.node, Var) # existing variable + or (isinstance(existing.node, TypeAlias) and not s.is_alias_def) # existing alias + or (isinstance(existing.node, PlaceholderNode) and existing.node.node.line < s.line) + ): # previous incomplete definition + # TODO: find a more robust way to track the order of definitions. + # Note: if is_alias_def=True, this is just a node from previous iteration. + if isinstance(existing.node, TypeAlias) and not s.is_alias_def: + self.fail( + 'Cannot assign multiple types to name "{}"' + ' without an explicit "type[...]" annotation'.format(lvalue.name), + lvalue, + ) + return False + + non_global_scope = self.type or self.is_func_scope() + if not pep_613 and not pep_695 and isinstance(rvalue, RefExpr) and non_global_scope: + # Fourth rule (special case): Non-subscripted right hand side creates a variable + # at class and function scopes. For example: + # + # class Model: + # ... + # class C: + # model = Model # this is automatically a variable with type 'Type[Model]' + # + # without this rule, this typical use case will require a lot of explicit + # annotations (see the second rule). + return False + if not pep_613 and not pep_695 and not self.can_be_type_alias(rvalue): + return False + + if existing and not isinstance(existing.node, (PlaceholderNode, TypeAlias)): + # Cannot redefine existing node as type alias. + return False + + res: Type | None = None + if self.is_none_alias(rvalue): + res = NoneType() + alias_tvars: list[TypeVarLikeType] = [] + depends_on: set[str] = set() + indexed = False + else: + tag = self.track_incomplete_refs() + res, alias_tvars, depends_on, indexed = self.analyze_alias( + lvalue.name, + rvalue, + allow_placeholder=True, + declared_type_vars=type_params, + all_declared_type_params_names=all_type_params_names, + ) + if not res: + return False + if not self.is_func_scope(): + # Only marking incomplete for top-level placeholders makes recursive aliases like + # `A = Sequence[str | A]` valid here, similar to how we treat base classes in class + # definitions, allowing `class str(Sequence[str]): ...` + incomplete_target = isinstance(res, ProperType) and isinstance( + res, PlaceholderType + ) + else: + incomplete_target = has_placeholder(res) + if self.found_incomplete_ref(tag) or incomplete_target: + # Since we have got here, we know this must be a type alias (incomplete refs + # may appear in nested positions), therefore use becomes_typeinfo=True. + self.mark_incomplete(lvalue.name, rvalue, becomes_typeinfo=True) + return True + self.add_type_alias_deps(depends_on) + check_for_explicit_any(res, self.options, self.is_typeshed_stub_file, self.msg, context=s) + # When this type alias gets "inlined", the Any is not explicit anymore, + # so we need to replace it with non-explicit Anys. + res = make_any_non_explicit(res) + if self.options.disallow_any_unimported and has_any_from_unimported_type(res): + # Only show error message once, when the type is fully analyzed. + if not has_placeholder(res): + self.msg.unimported_type_becomes_any("Type alias target", res, s) + res = make_any_non_unimported(res) + # Note: with the new (lazy) type alias representation we only need to set no_args to True + # if the expected number of arguments is non-zero, so that aliases like `A = List` work + # but not aliases like `A = TypeAliasType("A", List)` as these need explicit type params. + # However, eagerly expanding aliases like Text = str is a nice performance optimization. + no_args = ( + isinstance(res, ProperType) + and isinstance(res, Instance) + and not pep_695 + and not indexed + ) + if isinstance(res, ProperType) and isinstance(res, Instance): + if not validate_instance(res, self.fail, indexed): + fix_instance(res, self.fail, self.note, disallow_any=False, options=self.options) + # Aliases defined within functions can't be accessed outside + # the function, since the symbol table will no longer + # exist. Work around by expanding them eagerly when used. + eager = self.is_func_scope() + alias_node = TypeAlias( + res, + self.qualified_name(lvalue.name), + self.cur_mod_id, + s.line, + s.column, + alias_tvars=alias_tvars, + no_args=no_args, + eager=eager, + python_3_12_type_alias=pep_695, + ) + if isinstance(s.rvalue, (IndexExpr, CallExpr, OpExpr)) and ( + not isinstance(rvalue, OpExpr) + or (self.options.python_version >= (3, 10) or self.is_stub_file) + ): + # Note: CallExpr is for "void = type(None)" and OpExpr is for "X | Y" union syntax. + if not isinstance(s.rvalue.analyzed, TypeAliasExpr): + # Any existing node will be updated in-place below. + s.rvalue.analyzed = TypeAliasExpr(alias_node) + s.rvalue.analyzed.line = s.line + # we use the column from resulting target, to get better location for errors + s.rvalue.analyzed.column = res.column + elif isinstance(s.rvalue, RefExpr): + s.rvalue.is_alias_rvalue = True + + if existing: + # An alias gets updated. + updated = False + if isinstance(existing.node, TypeAlias): + if existing.node.target != res: + # Copy expansion to the existing alias, this matches how we update base classes + # for a TypeInfo _in place_ if there are nested placeholders. + existing.node.target = res + existing.node.alias_tvars = alias_tvars + existing.node.no_args = no_args + updated = True + # Invalidate recursive status cache in case it was previously set. + existing.node._is_recursive = None + else: + # Otherwise just replace existing placeholder with type alias. + existing.node = alias_node + updated = True + if updated: + if self.final_iteration: + self.cannot_resolve_name(lvalue.name, "name", s) + return True + else: + # We need to defer so that this change can get propagated to base classes. + self.defer(s, force_progress=True) + else: + self.add_symbol(lvalue.name, alias_node, s) + if isinstance(rvalue, RefExpr) and isinstance(rvalue.node, TypeAlias): + alias_node.normalized = rvalue.node.normalized + current_node = existing.node if existing else alias_node + assert isinstance(current_node, TypeAlias) + self.disable_invalid_recursive_aliases(s, current_node, s.rvalue) + if self.is_class_scope(): + assert self.type is not None + if self.type.is_protocol: + self.fail("Type aliases are prohibited in protocol bodies", s) + if not lvalue.name[0].isupper(): + self.note("Use variable annotation syntax to define protocol members", s) + return True + + def check_type_alias_type_call(self, rvalue: Expression, *, name: str) -> TypeGuard[CallExpr]: + if not isinstance(rvalue, CallExpr): + return False + + names = ["typing_extensions.TypeAliasType"] + if self.options.python_version >= (3, 12): + names.append("typing.TypeAliasType") + if not refers_to_fullname(rvalue.callee, tuple(names)): + return False + if not self.check_typevarlike_name(rvalue, name, rvalue): + return False + if rvalue.arg_kinds.count(ARG_POS) != ( + 2 - ("value" in rvalue.arg_names) - ("name" in rvalue.arg_names) + ): + return False + + return True + + def analyze_type_alias_type_params( + self, rvalue: CallExpr + ) -> tuple[TypeVarLikeList, list[str]]: + """Analyze type_params of TypeAliasType. + + Returns declared unbound type variable expressions and a list of all declared type + variable names for error reporting. + """ + if "type_params" in rvalue.arg_names: + type_params_arg = rvalue.args[rvalue.arg_names.index("type_params")] + if not isinstance(type_params_arg, TupleExpr): + self.fail( + "Tuple literal expected as the type_params argument to TypeAliasType", + type_params_arg, + ) + return [], [] + type_params = type_params_arg.items + else: + return [], [] + + declared_tvars: TypeVarLikeList = [] + all_declared_tvar_names: list[str] = [] # includes bound type variables + have_type_var_tuple = False + for tp_expr in type_params: + if isinstance(tp_expr, StarExpr): + tp_expr.valid = False + self.analyze_type_expr(tp_expr) + try: + base = self.expr_to_unanalyzed_type(tp_expr) + except TypeTranslationError: + continue + if not isinstance(base, UnboundType): + continue + + tag = self.track_incomplete_refs() + tvar = self.analyze_unbound_tvar_impl(base, is_typealias_param=True) + if tvar: + if isinstance(tvar[1], TypeVarTupleExpr): + if have_type_var_tuple: + self.fail( + "Can only use one TypeVarTuple in type_params argument to TypeAliasType", + base, + code=codes.TYPE_VAR, + ) + have_type_var_tuple = True + continue + have_type_var_tuple = True + elif not self.found_incomplete_ref(tag): + sym = self.lookup_qualified(base.name, base) + if sym and isinstance(sym.node, TypeVarLikeExpr): + all_declared_tvar_names.append(sym.node.name) # Error will be reported later + else: + self.fail( + "Free type variable expected in type_params argument to TypeAliasType", + base, + code=codes.TYPE_VAR, + ) + if sym and sym.fullname in UNPACK_TYPE_NAMES: + self.note( + "Don't Unpack type variables in type_params", base, code=codes.TYPE_VAR + ) + continue + if tvar in declared_tvars: + self.fail( + f'Duplicate type variable "{tvar[0]}" in type_params argument to TypeAliasType', + base, + code=codes.TYPE_VAR, + ) + continue + if tvar: + all_declared_tvar_names.append(tvar[0]) + declared_tvars.append(tvar) + return declared_tvars, all_declared_tvar_names + + def disable_invalid_recursive_aliases( + self, s: AssignmentStmt | TypeAliasStmt, current_node: TypeAlias, ctx: Context + ) -> None: + """Prohibit and fix recursive type aliases that are invalid/unsupported.""" + messages = [] + if ( + isinstance(current_node.target, TypeAliasType) + and current_node.target.alias is current_node + ): + # We want to have consistent error messages, but not calling name_not_defined(), + # since it will do a bunch of unrelated things we don't want here. + messages.append( + f'Cannot resolve name "{current_node.name}" (possible cyclic definition)' + ) + elif is_invalid_recursive_alias({current_node}, current_node.target): + target = ( + "tuple" if isinstance(get_proper_type(current_node.target), TupleType) else "union" + ) + messages.append(f"Invalid recursive alias: a {target} item of itself") + if detect_diverging_alias( + current_node, current_node.target, self.lookup_qualified, self.tvar_scope + ): + messages.append("Invalid recursive alias: type variable nesting on right hand side") + if messages: + current_node.target = AnyType(TypeOfAny.from_error) + s.invalid_recursive_alias = True + for msg in messages: + self.fail(msg, ctx) + + def analyze_lvalue( + self, + lval: Lvalue, + nested: bool = False, + explicit_type: bool = False, + is_final: bool = False, + escape_comprehensions: bool = False, + has_explicit_value: bool = False, + is_index_var: bool = False, + ) -> None: + """Analyze an lvalue or assignment target. + + Args: + lval: The target lvalue + nested: If true, the lvalue is within a tuple or list lvalue expression + explicit_type: Assignment has type annotation + escape_comprehensions: If we are inside a comprehension, set the variable + in the enclosing scope instead. This implements + https://www.python.org/dev/peps/pep-0572/#scope-of-the-target + is_index_var: If lval is the index variable in a for loop + """ + if escape_comprehensions: + assert isinstance(lval, NameExpr), "assignment expression target must be NameExpr" + if isinstance(lval, NameExpr): + self.analyze_name_lvalue( + lval, + explicit_type, + is_final, + escape_comprehensions, + has_explicit_value=has_explicit_value, + is_index_var=is_index_var, + ) + elif isinstance(lval, MemberExpr): + self.analyze_member_lvalue(lval, explicit_type, is_final, has_explicit_value) + if explicit_type and not self.is_self_member_ref(lval): + self.fail("Type cannot be declared in assignment to non-self attribute", lval) + elif isinstance(lval, IndexExpr): + if explicit_type: + self.fail("Unexpected type declaration", lval) + lval.accept(self) + elif isinstance(lval, TupleExpr): + self.analyze_tuple_or_list_lvalue(lval, explicit_type) + elif isinstance(lval, StarExpr): + if nested: + self.analyze_lvalue(lval.expr, nested, explicit_type) + else: + self.fail("Starred assignment target must be in a list or tuple", lval) + else: + self.fail("Invalid assignment target", lval) + + def analyze_name_lvalue( + self, + lvalue: NameExpr, + explicit_type: bool, + is_final: bool, + escape_comprehensions: bool, + has_explicit_value: bool, + is_index_var: bool, + ) -> None: + """Analyze an lvalue that targets a name expression. + + Arguments are similar to "analyze_lvalue". + """ + if lvalue.node: + # This has been bound already in a previous iteration. + return + + name = lvalue.name + if self.is_alias_for_final_name(name): + if is_final: + self.fail("Cannot redefine an existing name as final", lvalue) + else: + self.msg.cant_assign_to_final(name, self.type is not None, lvalue) + + kind = self.current_symbol_kind() + names = self.current_symbol_table(escape_comprehensions=escape_comprehensions) + existing = names.get(name) + + outer = self.is_global_or_nonlocal(name) + if ( + kind == MDEF + and isinstance(self.type, TypeInfo) + and self.type.is_enum + and not name.startswith("__") + ): + # Special case: we need to be sure that `Enum` keys are unique. + if existing is not None and not isinstance(existing.node, PlaceholderNode): + self.fail( + 'Attempted to reuse member name "{}" in Enum definition "{}"'.format( + name, self.type.name + ), + lvalue, + ) + + if explicit_type and has_explicit_value: + self.fail("Enum members must be left unannotated", lvalue) + self.note( + "See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members", + lvalue, + ) + + if (not existing or isinstance(existing.node, PlaceholderNode)) and not outer: + # Define new variable. + var = self.make_name_lvalue_var( + lvalue, kind, not explicit_type, has_explicit_value, is_index_var + ) + added = self.add_symbol(name, var, lvalue, escape_comprehensions=escape_comprehensions) + # Only bind expression if we successfully added name to symbol table. + if added: + lvalue.is_new_def = True + lvalue.is_inferred_def = True + lvalue.kind = kind + lvalue.node = var + if kind == GDEF: + lvalue.fullname = var._fullname + else: + lvalue.fullname = lvalue.name + if self.is_func_scope(): + if unmangle(name) == "_" and not self.options.allow_redefinition_new: + # Special case for assignment to local named '_': always infer 'Any'. + # This isn't needed with --allow-redefinition-new, since arbitrary + # types can be assigned to '_' anyway. + typ = AnyType(TypeOfAny.special_form) + self.store_declared_types(lvalue, typ) + if is_final and self.is_final_redefinition(kind, name): + self.fail("Cannot redefine an existing name as final", lvalue) + else: + self.make_name_lvalue_point_to_existing_def(lvalue, explicit_type, is_final) + + def is_final_redefinition(self, kind: int, name: str) -> bool: + if kind == GDEF: + return self.is_mangled_global(name) and not self.is_initial_mangled_global(name) + elif kind == MDEF and self.type: + return unmangle(name) + "'" in self.type.names + return False + + def is_alias_for_final_name(self, name: str) -> bool: + if self.is_func_scope(): + if not name.endswith("'"): + # Not a mangled name -- can't be an alias + return False + name = unmangle(name) + assert self.locals[-1] is not None, "No locals at function scope" + existing = self.locals[-1].get(name) + return existing is not None and is_final_node(existing.node) + elif self.type is not None: + orig_name = unmangle(name) + "'" + if name == orig_name: + return False + existing = self.type.names.get(orig_name) + return existing is not None and is_final_node(existing.node) + else: + orig_name = unmangle(name) + "'" + if name == orig_name: + return False + existing = self.globals.get(orig_name) + return existing is not None and is_final_node(existing.node) + + def make_name_lvalue_var( + self, + lvalue: NameExpr, + kind: int, + inferred: bool, + has_explicit_value: bool, + is_index_var: bool, + ) -> Var: + """Return a Var node for an lvalue that is a name expression.""" + name = lvalue.name + v = Var(name) + v.set_line(lvalue) + v.is_inferred = inferred + if kind == MDEF: + assert self.type is not None + v.info = self.type + v.is_initialized_in_class = True + v.allow_incompatible_override = name in ALLOW_INCOMPATIBLE_OVERRIDE + if kind != LDEF: + v._fullname = self.qualified_name(name) + else: + # fullname should never stay None + v._fullname = name + v.is_ready = False # Type not inferred yet + v.has_explicit_value = has_explicit_value + v.is_index_var = is_index_var + return v + + def make_name_lvalue_point_to_existing_def( + self, lval: NameExpr, explicit_type: bool, is_final: bool + ) -> None: + """Update an lvalue to point to existing definition in the same scope. + + Arguments are similar to "analyze_lvalue". + + Assume that an existing name exists. + """ + if is_final: + # Redefining an existing name with final is always an error. + self.fail("Cannot redefine an existing name as final", lval) + original_def = self.lookup(lval.name, lval, suppress_errors=True) + if original_def is None and self.type and not self.is_func_scope(): + # Workaround to allow "x, x = ..." in class body. + original_def = self.type.get(lval.name) + if explicit_type: + # Don't re-bind if there is a type annotation. + self.name_already_defined(lval.name, lval, original_def) + else: + # Bind to an existing name. + if original_def: + self.bind_name_expr(lval, original_def) + else: + self.name_not_defined(lval.name, lval) + self.check_lvalue_validity(lval.node, lval) + + if self.scope.functions and lval.name in self.global_decls[-1]: + # Technically, we only need to set this if original r.h.s. would be inferred + # as None, but it is tricky to detect reliably during semantic analysis. + if ( + original_def + and isinstance(original_def.node, Var) + and original_def.node.is_inferred + ): + for func in self.scope.functions: + func.def_or_infer_vars = True + + def analyze_tuple_or_list_lvalue(self, lval: TupleExpr, explicit_type: bool = False) -> None: + """Analyze an lvalue or assignment target that is a list or tuple.""" + items = lval.items + star_exprs = [item for item in items if isinstance(item, StarExpr)] + + if len(star_exprs) > 1: + self.fail("Two starred expressions in assignment", lval) + else: + if len(star_exprs) == 1: + star_exprs[0].valid = True + for i in items: + self.analyze_lvalue( + lval=i, + nested=True, + explicit_type=explicit_type, + # Lists and tuples always have explicit values defined: + # `a, b, c = value` + has_explicit_value=True, + ) + + def analyze_member_lvalue( + self, lval: MemberExpr, explicit_type: bool, is_final: bool, has_explicit_value: bool + ) -> None: + """Analyze lvalue that is a member expression. + + Arguments: + lval: The target lvalue + explicit_type: Assignment has type annotation + is_final: Is the target final + """ + if lval.node: + # This has been bound already in a previous iteration. + return + lval.accept(self) + if self.is_self_member_ref(lval): + assert self.type, "Self member outside a class" + cur_node = self.type.names.get(lval.name) + node = self.type.get(lval.name) + if cur_node and is_final: + # Overrides will be checked in type checker. + self.fail("Cannot redefine an existing name as final", lval) + # On first encounter with this definition, if this attribute was defined before + # with an inferred type and it's marked with an explicit type now, give an error. + if ( + not lval.node + and cur_node + and isinstance(cur_node.node, Var) + and cur_node.node.is_inferred + and explicit_type + ): + self.attribute_already_defined(lval.name, lval, cur_node) + if self.type.is_protocol and has_explicit_value and cur_node is not None: + # Make this variable non-abstract, it would be safer to do this only if we + # are inside __init__, but we do this always to preserve historical behaviour. + if isinstance(cur_node.node, Var): + cur_node.node.is_abstract_var = False + if ( + # If the attribute of self is not defined, create a new Var, ... + node is None + # ... or if it is defined as abstract in a *superclass*. + or (cur_node is None and isinstance(node.node, Var) and node.node.is_abstract_var) + # ... also an explicit declaration on self also creates a new Var. + # Note that `explicit_type` might have been erased for bare `Final`, + # so we also check if `is_final` is passed. + or (cur_node is None and (explicit_type or is_final)) + ): + if self.type.is_protocol and node is None: + self.fail("Protocol members cannot be defined via assignment to self", lval) + else: + # Implicit attribute definition in __init__. + lval.is_new_def = True + lval.is_inferred_def = True + v = Var(lval.name) + v.set_line(lval) + v._fullname = self.qualified_name(lval.name) + v.info = self.type + v.is_ready = False + v.explicit_self_type = explicit_type or is_final + lval.def_var = v + lval.node = v + # TODO: should we also set lval.kind = MDEF? + self.type.names[lval.name] = SymbolTableNode(MDEF, v, implicit=True) + for func in self.scope.functions: + func.def_or_infer_vars = True + if ( + cur_node + and isinstance(cur_node.node, Var) + and cur_node.node.is_inferred + and cur_node.node.is_initialized_in_class + ): + for func in self.scope.functions: + func.def_or_infer_vars = True + self.check_lvalue_validity(lval.node, lval) + + def is_self_member_ref(self, memberexpr: MemberExpr) -> bool: + """Does memberexpr to refer to an attribute of self?""" + if not isinstance(memberexpr.expr, NameExpr): + return False + node = memberexpr.expr.node + return isinstance(node, Var) and node.is_self + + def check_lvalue_validity(self, node: Expression | SymbolNode | None, ctx: Context) -> None: + if isinstance(node, TypeVarExpr): + self.fail("Invalid assignment target", ctx) + elif isinstance(node, TypeInfo): + self.fail(message_registry.CANNOT_ASSIGN_TO_TYPE, ctx) + + def store_declared_types(self, lvalue: Lvalue, typ: Type) -> None: + if isinstance(lvalue, RefExpr): + lvalue.is_inferred_def = False + if isinstance(lvalue.node, Var): + var = lvalue.node + var.type = typ + var.is_ready = True + typ = get_proper_type(typ) + if ( + var.is_final + and isinstance(typ, Instance) + and typ.last_known_value + and (not self.type or not self.type.is_enum) + ): + var.final_value = typ.last_known_value.value + # If node is not a variable, we'll catch it elsewhere. + elif isinstance(lvalue, TupleExpr): + typ = get_proper_type(typ) + if isinstance(typ, TupleType): + if len(lvalue.items) != len(typ.items): + self.fail("Incompatible number of tuple items", lvalue) + return + for item, itemtype in zip(lvalue.items, typ.items): + self.store_declared_types(item, itemtype) + else: + self.fail("Tuple type expected for multiple variables", lvalue) + elif isinstance(lvalue, StarExpr): + # Historical behavior for the old parser + self.store_declared_types(lvalue.expr, typ) + else: + # This has been flagged elsewhere as an error, so just ignore here. + pass + + def process_typevar_declaration(self, s: AssignmentStmt) -> bool: + """Check if s declares a TypeVar; it yes, store it in symbol table. + + Return True if this looks like a type variable declaration (but maybe + with errors), otherwise return False. + """ + call = self.get_typevarlike_declaration(s, ("typing.TypeVar", "typing_extensions.TypeVar")) + if not call: + return False + + name = self.extract_typevarlike_name(s, call) + if name is None: + return False + + # Constraining types + n_values = call.arg_kinds[1:].count(ARG_POS) + values = self.analyze_value_types(call.args[1 : 1 + n_values]) + + res = self.process_typevar_parameters( + call.args[1 + n_values :], + call.arg_names[1 + n_values :], + call.arg_kinds[1 + n_values :], + n_values, + s, + ) + if res is None: + return False + variance, upper_bound, default = res + + existing = self.current_symbol_table().get(name) + if existing and not ( + isinstance(existing.node, PlaceholderNode) + or + # Also give error for another type variable with the same name. + (isinstance(existing.node, TypeVarExpr) and existing.node is call.analyzed) + ): + self.fail(f'Cannot redefine "{name}" as a type variable', s) + return False + + if self.options.disallow_any_unimported: + for idx, constraint in enumerate(values, start=1): + if has_any_from_unimported_type(constraint): + prefix = f"Constraint {idx}" + self.msg.unimported_type_becomes_any(prefix, constraint, s) + + if has_any_from_unimported_type(upper_bound): + prefix = "Upper bound of type variable" + self.msg.unimported_type_becomes_any(prefix, upper_bound, s) + + for t in values + [upper_bound, default]: + check_for_explicit_any( + t, self.options, self.is_typeshed_stub_file, self.msg, context=s + ) + + # mypyc suppresses making copies of a function to check each + # possible type, so set the upper bound to Any to prevent that + # from causing errors. + if values and self.options.mypyc: + upper_bound = AnyType(TypeOfAny.implementation_artifact) + + # Yes, it's a valid type variable definition! Add it to the symbol table. + if not call.analyzed: + type_var = TypeVarExpr( + name, self.qualified_name(name), values, upper_bound, default, variance + ) + type_var.line = call.line + call.analyzed = type_var + updated = True + else: + assert isinstance(call.analyzed, TypeVarExpr) + updated = ( + values != call.analyzed.values + or upper_bound != call.analyzed.upper_bound + or default != call.analyzed.default + ) + call.analyzed.upper_bound = upper_bound + call.analyzed.values = values + call.analyzed.default = default + if any(has_placeholder(v) for v in values): + self.process_placeholder(None, "TypeVar values", s, force_progress=updated) + elif has_placeholder(upper_bound): + self.process_placeholder(None, "TypeVar upper bound", s, force_progress=updated) + elif has_placeholder(default): + self.process_placeholder(None, "TypeVar default", s, force_progress=updated) + + self.add_symbol(name, call.analyzed, s) + return True + + def check_typevar_default(self, default: Type, context: Context) -> Type: + typ = get_proper_type(default) + if isinstance(typ, AnyType) and typ.is_from_error: + self.fail( + message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format("TypeVar", "default"), context + ) + return default + + def check_paramspec_default(self, default: Type, context: Context) -> Type: + typ = get_proper_type(default) + if isinstance(typ, Parameters): + for i, arg_type in enumerate(typ.arg_types): + arg_ptype = get_proper_type(arg_type) + if isinstance(arg_ptype, AnyType) and arg_ptype.is_from_error: + self.fail(f"Argument {i} of ParamSpec default must be a type", context) + elif ( + isinstance(typ, AnyType) + and typ.is_from_error + or not isinstance(typ, (AnyType, UnboundType)) + ): + self.fail( + "The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec", + context, + ) + default = AnyType(TypeOfAny.from_error) + return default + + def check_typevartuple_default(self, default: Type, context: Context) -> Type: + typ = get_proper_type(default) + if not isinstance(typ, UnpackType): + self.fail("The default argument to TypeVarTuple must be an Unpacked tuple", context) + default = AnyType(TypeOfAny.from_error) + return default + + def check_typevarlike_name(self, call: CallExpr, name: str, context: Context) -> bool: + """Checks that the name of a TypeVar or ParamSpec matches its variable.""" + name = unmangle(name) + assert isinstance(call.callee, RefExpr) + typevarlike_type = ( + call.callee.name if isinstance(call.callee, NameExpr) else call.callee.fullname + ) + if len(call.args) < 1: + self.fail(f"Too few arguments for {typevarlike_type}()", context) + return False + if not isinstance(call.args[0], StrExpr) or call.arg_kinds[0] != ARG_POS: + self.fail(f"{typevarlike_type}() expects a string literal as first argument", context) + return False + elif call.args[0].value != name: + msg = 'String argument 1 "{}" to {}(...) does not match variable name "{}"' + self.fail(msg.format(call.args[0].value, typevarlike_type, name), context) + return False + return True + + def get_typevarlike_declaration( + self, s: AssignmentStmt, typevarlike_types: tuple[str, ...] + ) -> CallExpr | None: + """Returns the call expression if `s` is a declaration of `typevarlike_type` + (TypeVar or ParamSpec), or None otherwise. + """ + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr): + return None + if not isinstance(s.rvalue, CallExpr): + return None + call = s.rvalue + callee = call.callee + if not isinstance(callee, RefExpr): + return None + if callee.fullname not in typevarlike_types: + return None + return call + + def process_typevar_parameters( + self, + args: list[Expression], + names: list[str | None], + kinds: list[ArgKind], + num_values: int, + context: Context, + ) -> tuple[int, Type, Type] | None: + has_values = num_values > 0 + covariant = False + contravariant = False + upper_bound: Type = self.object_type() + default: Type = AnyType(TypeOfAny.from_omitted_generics) + for param_value, param_name, param_kind in zip(args, names, kinds): + if not param_kind.is_named(): + self.fail(message_registry.TYPEVAR_UNEXPECTED_ARGUMENT, context) + return None + if param_name == "covariant": + if isinstance(param_value, NameExpr) and param_value.name in ("True", "False"): + covariant = param_value.name == "True" + else: + self.fail(message_registry.TYPEVAR_VARIANCE_DEF.format("covariant"), context) + return None + elif param_name == "contravariant": + if isinstance(param_value, NameExpr) and param_value.name in ("True", "False"): + contravariant = param_value.name == "True" + else: + self.fail( + message_registry.TYPEVAR_VARIANCE_DEF.format("contravariant"), context + ) + return None + elif param_name == "bound": + if has_values: + self.fail("TypeVar cannot have both values and an upper bound", context) + return None + tv_arg = self.get_typevarlike_argument("TypeVar", param_name, param_value, context) + if tv_arg is None: + return None + upper_bound = tv_arg + elif param_name == "default": + tv_arg = self.get_typevarlike_argument( + "TypeVar", param_name, param_value, context, allow_unbound_tvars=True + ) + default = tv_arg or AnyType(TypeOfAny.from_error) + elif param_name == "values": + # Probably using obsolete syntax with values=(...). Explain the current syntax. + self.fail('TypeVar "values" argument not supported', context) + self.fail( + "Use TypeVar('T', t, ...) instead of TypeVar('T', values=(t, ...))", context + ) + return None + else: + self.fail( + f'{message_registry.TYPEVAR_UNEXPECTED_ARGUMENT}: "{param_name}"', context + ) + return None + + if covariant and contravariant: + self.fail("TypeVar cannot be both covariant and contravariant", context) + return None + elif num_values == 1: + self.fail(message_registry.TYPE_VAR_TOO_FEW_CONSTRAINED_TYPES, context) + return None + elif covariant: + variance = COVARIANT + elif contravariant: + variance = CONTRAVARIANT + else: + variance = INVARIANT + return variance, upper_bound, default + + def get_typevarlike_argument( + self, + typevarlike_name: str, + param_name: str, + param_value: Expression, + context: Context, + *, + allow_unbound_tvars: bool = False, + allow_param_spec_literals: bool = False, + allow_unpack: bool = False, + report_invalid_typevar_arg: bool = True, + ) -> ProperType | None: + try: + # We want to use our custom error message below, so we suppress + # the default error message for invalid types here. + analyzed = self.expr_to_analyzed_type( + param_value, + allow_placeholder=True, + report_invalid_types=False, + allow_unbound_tvars=allow_unbound_tvars, + allow_param_spec_literals=allow_param_spec_literals, + allow_unpack=allow_unpack, + ) + if analyzed is None: + # Type variables are special: we need to place them in the symbol table + # soon, even if upper bound is not ready yet. Otherwise, avoiding + # a "deadlock" in this common pattern would be tricky: + # T = TypeVar('T', bound=Custom[Any]) + # class Custom(Generic[T]): + # ... + analyzed = PlaceholderType(None, [], context.line) + typ = get_proper_type(analyzed) + if report_invalid_typevar_arg and isinstance(typ, AnyType) and typ.is_from_error: + self.fail( + message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format(typevarlike_name, param_name), + param_value, + ) + # Note: we do not return 'None' here -- we want to continue + # using the AnyType. + return typ + except TypeTranslationError: + if report_invalid_typevar_arg: + self.fail( + message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format(typevarlike_name, param_name), + param_value, + ) + return None + + def extract_typevarlike_name(self, s: AssignmentStmt, call: CallExpr) -> str | None: + if not call: + return None + + lvalue = s.lvalues[0] + assert isinstance(lvalue, NameExpr) + if s.type: + self.fail("Cannot declare the type of a TypeVar or similar construct", s) + return None + + if not self.check_typevarlike_name(call, lvalue.name, s): + return None + return lvalue.name + + def process_paramspec_declaration(self, s: AssignmentStmt) -> bool: + """Checks if s declares a ParamSpec; if yes, store it in symbol table. + + Return True if this looks like a ParamSpec (maybe with errors), otherwise return False. + + In the future, ParamSpec may accept bounds and variance arguments, in which + case more aggressive sharing of code with process_typevar_declaration should be pursued. + """ + call = self.get_typevarlike_declaration( + s, ("typing_extensions.ParamSpec", "typing.ParamSpec") + ) + if not call: + return False + + name = self.extract_typevarlike_name(s, call) + if name is None: + return False + + n_values = call.arg_kinds[1:].count(ARG_POS) + if n_values != 0: + self.fail('Too many positional arguments for "ParamSpec"', s) + + default: Type = AnyType(TypeOfAny.from_omitted_generics) + for param_value, param_name in zip( + call.args[1 + n_values :], call.arg_names[1 + n_values :] + ): + if param_name == "default": + tv_arg = self.get_typevarlike_argument( + "ParamSpec", + param_name, + param_value, + s, + allow_unbound_tvars=True, + allow_param_spec_literals=True, + report_invalid_typevar_arg=False, + ) + default = tv_arg or AnyType(TypeOfAny.from_error) + default = self.check_paramspec_default(default, param_value) + else: + # ParamSpec is different from a regular TypeVar: + # arguments are not semantically valid. But, allowed in runtime. + # So, we need to warn users about possible invalid usage. + self.fail( + "The variance and bound arguments to ParamSpec do not have defined semantics yet", + s, + ) + + # PEP 612 reserves the right to define bound, covariant and contravariant arguments to + # ParamSpec in a later PEP. If and when that happens, we should do something + # on the lines of process_typevar_parameters + + if not call.analyzed: + paramspec_var = ParamSpecExpr( + name, self.qualified_name(name), self.object_type(), default, INVARIANT + ) + paramspec_var.line = call.line + call.analyzed = paramspec_var + updated = True + else: + assert isinstance(call.analyzed, ParamSpecExpr) + updated = default != call.analyzed.default + call.analyzed.default = default + if has_placeholder(default): + self.process_placeholder(None, "ParamSpec default", s, force_progress=updated) + + self.add_symbol(name, call.analyzed, s) + return True + + def process_typevartuple_declaration(self, s: AssignmentStmt) -> bool: + """Checks if s declares a TypeVarTuple; if yes, store it in symbol table. + + Return True if this looks like a TypeVarTuple (maybe with errors), otherwise return False. + """ + call = self.get_typevarlike_declaration( + s, ("typing_extensions.TypeVarTuple", "typing.TypeVarTuple") + ) + if not call: + return False + + n_values = call.arg_kinds[1:].count(ARG_POS) + if n_values != 0: + self.fail('Too many positional arguments for "TypeVarTuple"', s) + + default: Type = AnyType(TypeOfAny.from_omitted_generics) + for param_value, param_name in zip( + call.args[1 + n_values :], call.arg_names[1 + n_values :] + ): + if param_name == "default": + tv_arg = self.get_typevarlike_argument( + "TypeVarTuple", + param_name, + param_value, + s, + allow_unbound_tvars=True, + report_invalid_typevar_arg=False, + allow_unpack=True, + ) + default = tv_arg or AnyType(TypeOfAny.from_error) + default = self.check_typevartuple_default(default, param_value) + else: + self.fail(f'Unexpected keyword argument "{param_name}" for "TypeVarTuple"', s) + + name = self.extract_typevarlike_name(s, call) + if name is None: + return False + + # PEP 646 does not specify the behavior of variance, constraints, or bounds. + if not call.analyzed: + tuple_fallback = self.named_type("builtins.tuple", [self.object_type()]) + typevartuple_var = TypeVarTupleExpr( + name, + self.qualified_name(name), + # Upper bound for *Ts is *tuple[object, ...], it can never be object. + tuple_fallback.copy_modified(), + tuple_fallback, + default, + INVARIANT, + ) + typevartuple_var.line = call.line + call.analyzed = typevartuple_var + updated = True + else: + assert isinstance(call.analyzed, TypeVarTupleExpr) + updated = default != call.analyzed.default + call.analyzed.default = default + if has_placeholder(default): + self.process_placeholder(None, "TypeVarTuple default", s, force_progress=updated) + + self.add_symbol(name, call.analyzed, s) + return True + + def basic_new_typeinfo(self, name: str, basetype_or_fallback: Instance, line: int) -> TypeInfo: + if self.is_func_scope() and not self.type and "@" not in name: + name += "@" + str(line) + class_def = ClassDef(name, Block([])) + if self.is_func_scope() and not self.type: + # Full names of generated classes should always be prefixed with the module names + # even if they are nested in a function, since these classes will be (de-)serialized. + # (Note that the caller should append @line to the name to avoid collisions.) + # TODO: clean this up, see #6422. + class_def.fullname = self.cur_mod_id + "." + self.qualified_name(name) + else: + class_def.fullname = self.qualified_name(name) + + info = TypeInfo(SymbolTable(), class_def, self.cur_mod_id) + class_def.info = info + mro = basetype_or_fallback.type.mro + if not mro: + # Probably an error, we should not crash so generate something meaningful. + mro = [basetype_or_fallback.type, self.object_type().type] + info.mro = [info] + mro + info.bases = [basetype_or_fallback] + return info + + def analyze_value_types(self, items: list[Expression]) -> list[Type]: + """Analyze types from values expressions in type variable definition.""" + result: list[Type] = [] + for node in items: + try: + analyzed = self.anal_type( + self.expr_to_unanalyzed_type(node), allow_placeholder=True + ) + if analyzed is None: + # Type variables are special: we need to place them in the symbol table + # soon, even if some value is not ready yet, see process_typevar_parameters() + # for an example. + analyzed = PlaceholderType(None, [], node.line) + if has_type_vars(analyzed): + self.fail(message_registry.TYPE_VAR_GENERIC_CONSTRAINT_TYPE, node) + result.append(AnyType(TypeOfAny.from_error)) + else: + result.append(analyzed) + except TypeTranslationError: + self.fail("Type expected", node) + result.append(AnyType(TypeOfAny.from_error)) + return result + + def check_classvar(self, s: AssignmentStmt) -> None: + """Check if assignment defines a class variable.""" + lvalue = s.lvalues[0] + if len(s.lvalues) != 1 or not isinstance(lvalue, RefExpr): + return + if not s.type or not self.is_classvar(s.type): + return + assert isinstance(s.type, UnboundType) + if self.is_class_scope() and isinstance(lvalue, NameExpr): + node = lvalue.node + if isinstance(node, Var): + node.is_classvar = True + analyzed = self.anal_type(s.type) + assert self.type is not None + if ( + analyzed is not None + and self.type.self_type in get_type_vars(analyzed) + and self.type.defn.type_vars + ): + self.fail(message_registry.CLASS_VAR_WITH_GENERIC_SELF, s) + elif not isinstance(lvalue, MemberExpr) or self.is_self_member_ref(lvalue): + # In case of member access, report error only when assigning to self + # Other kinds of member assignments should be already reported + self.fail_invalid_classvar(lvalue) + if not s.type.args: + if isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs: + if self.options.disallow_any_generics: + self.fail("ClassVar without type argument becomes Any", s, code=codes.TYPE_ARG) + return + s.type = None + + def is_classvar(self, typ: Type) -> bool: + if not isinstance(typ, UnboundType): + return False + sym = self.lookup_qualified(typ.name, typ) + if not sym or not sym.node: + return False + return sym.node.fullname == "typing.ClassVar" + + def is_final_type(self, typ: Type | None) -> bool: + if not isinstance(typ, UnboundType): + return False + sym = self.lookup_qualified(typ.name, typ) + if not sym or not sym.node: + return False + return sym.node.fullname in FINAL_TYPE_NAMES + + def fail_invalid_classvar(self, context: Context) -> None: + self.fail(message_registry.CLASS_VAR_OUTSIDE_OF_CLASS, context) + + def process_module_assignment( + self, lvals: list[Lvalue], rval: Expression, ctx: AssignmentStmt + ) -> None: + """Propagate module references across assignments. + + Recursively handles the simple form of iterable unpacking; doesn't + handle advanced unpacking with *rest, dictionary unpacking, etc. + + In an expression like x = y = z, z is the rval and lvals will be [x, + y]. + + """ + if isinstance(rval, (TupleExpr, ListExpr)) and all( + isinstance(v, TupleExpr) for v in lvals + ): + # rval and all lvals are either list or tuple, so we are dealing + # with unpacking assignment like `x, y = a, b`. Mypy didn't + # understand our all(isinstance(...)), so cast them as TupleExpr + # so mypy knows it is safe to access their .items attribute. + seq_lvals = cast(list[TupleExpr], lvals) + # given an assignment like: + # (x, y) = (m, n) = (a, b) + # we now have: + # seq_lvals = [(x, y), (m, n)] + # seq_rval = (a, b) + # We now zip this into: + # elementwise_assignments = [(a, x, m), (b, y, n)] + # where each elementwise assignment includes one element of rval and the + # corresponding element of each lval. Basically we unpack + # (x, y) = (m, n) = (a, b) + # into elementwise assignments + # x = m = a + # y = n = b + # and then we recursively call this method for each of those assignments. + # If the rval and all lvals are not all of the same length, zip will just ignore + # extra elements, so no error will be raised here; mypy will later complain + # about the length mismatch in type-checking. + elementwise_assignments = zip(rval.items, *[v.items for v in seq_lvals]) + for rv, *lvs in elementwise_assignments: + self.process_module_assignment(lvs, rv, ctx) + elif isinstance(rval, RefExpr): + rnode = self.lookup_type_node(rval) + if rnode and isinstance(rnode.node, MypyFile): + for lval in lvals: + if not isinstance(lval, RefExpr): + continue + # respect explicitly annotated type + if isinstance(lval.node, Var) and lval.node.type is not None: + continue + + # We can handle these assignments to locals and to self + if isinstance(lval, NameExpr): + lnode = self.current_symbol_table().get(lval.name) + elif isinstance(lval, MemberExpr) and self.is_self_member_ref(lval): + assert self.type is not None + lnode = self.type.names.get(lval.name) + else: + continue + + if lnode: + if isinstance(lnode.node, MypyFile) and lnode.node is not rnode.node: + assert isinstance(lval, (NameExpr, MemberExpr)) + self.fail( + 'Cannot assign multiple modules to name "{}" ' + 'without explicit "types.ModuleType" annotation'.format(lval.name), + ctx, + ) + # never create module alias except on initial var definition + elif lval.is_inferred_def: + assert rnode.node is not None + lnode.node = rnode.node + + def process__all__(self, s: AssignmentStmt) -> None: + """Export names if argument is a __all__ assignment.""" + if ( + len(s.lvalues) == 1 + and isinstance(s.lvalues[0], NameExpr) + and s.lvalues[0].name == "__all__" + and s.lvalues[0].kind == GDEF + and isinstance(s.rvalue, (ListExpr, TupleExpr)) + ): + self.add_exports(s.rvalue.items) + + def process__deletable__(self, s: AssignmentStmt) -> None: + if not self.options.mypyc: + return + if ( + len(s.lvalues) == 1 + and isinstance(s.lvalues[0], NameExpr) + and s.lvalues[0].name == "__deletable__" + and s.lvalues[0].kind == MDEF + ): + rvalue = s.rvalue + if not isinstance(rvalue, (ListExpr, TupleExpr)): + self.fail('"__deletable__" must be initialized with a list or tuple expression', s) + return + items = rvalue.items + attrs = [] + for item in items: + if not isinstance(item, StrExpr): + self.fail('Invalid "__deletable__" item; string literal expected', item) + else: + attrs.append(item.value) + assert self.type + self.type.deletable_attributes = attrs + + def process__slots__(self, s: AssignmentStmt) -> None: + """ + Processing ``__slots__`` if defined in type. + + See: https://docs.python.org/3/reference/datamodel.html#slots + """ + # Later we can support `__slots__` defined as `__slots__ = other = ('a', 'b')` + if ( + isinstance(self.type, TypeInfo) + and len(s.lvalues) == 1 + and isinstance(s.lvalues[0], NameExpr) + and s.lvalues[0].name == "__slots__" + and s.lvalues[0].kind == MDEF + ): + # We understand `__slots__` defined as string, tuple, list, set, and dict: + if not isinstance(s.rvalue, (StrExpr, ListExpr, TupleExpr, SetExpr, DictExpr)): + # For example, `__slots__` can be defined as a variable, + # we don't support it for now. + return + + if any(p.slots is None for p in self.type.mro[1:-1]): + # At least one type in mro (excluding `self` and `object`) + # does not have concrete `__slots__` defined. Ignoring. + return + + concrete_slots = True + rvalue: list[Expression] = [] + if isinstance(s.rvalue, StrExpr): + rvalue.append(s.rvalue) + elif isinstance(s.rvalue, (ListExpr, TupleExpr, SetExpr)): + rvalue.extend(s.rvalue.items) + else: + # We have a special treatment of `dict` with possible `{**kwargs}` usage. + # In this case we consider all `__slots__` to be non-concrete. + for key, _ in s.rvalue.items: + if concrete_slots and key is not None: + rvalue.append(key) + else: + concrete_slots = False + + slots = [] + for item in rvalue: + # Special case for `'__dict__'` value: + # when specified it will still allow any attribute assignment. + if isinstance(item, StrExpr) and item.value != "__dict__": + slots.append(item.value) + else: + concrete_slots = False + if not concrete_slots: + # Some slot items are dynamic, we don't want any false positives, + # so, we just pretend that this type does not have any slots at all. + return + + # We need to copy all slots from super types: + for super_type in self.type.mro[1:-1]: + assert super_type.slots is not None + slots.extend(super_type.slots) + self.type.slots = set(slots) + + # + # Misc statements + # + + def visit_block(self, b: Block) -> None: + if b.is_unreachable: + return + self.block_depth[-1] += 1 + for s in b.body: + self.accept(s) + self.block_depth[-1] -= 1 + + def visit_block_maybe(self, b: Block | None) -> None: + if b: + self.visit_block(b) + + def visit_expression_stmt(self, s: ExpressionStmt) -> None: + self.statement = s + s.expr.accept(self) + + def visit_return_stmt(self, s: ReturnStmt) -> None: + old = self.statement + self.statement = s + if not self.is_func_scope(): + self.fail('"return" outside function', s) + if self.return_stmt_inside_except_star_block: + self.fail('"return" not allowed in except* block', s, serious=True) + if s.expr: + s.expr.accept(self) + if TYPE_FORM in self.options.enable_incomplete_feature: + self.try_parse_as_type_expression(s.expr) + self.statement = old + + def visit_raise_stmt(self, s: RaiseStmt) -> None: + self.statement = s + if s.expr: + s.expr.accept(self) + if s.from_expr: + s.from_expr.accept(self) + + def visit_assert_stmt(self, s: AssertStmt) -> None: + self.statement = s + if s.expr: + s.expr.accept(self) + if s.msg: + s.msg.accept(self) + + def visit_operator_assignment_stmt(self, s: OperatorAssignmentStmt) -> None: + self.statement = s + s.lvalue.accept(self) + s.rvalue.accept(self) + if ( + isinstance(s.lvalue, NameExpr) + and s.lvalue.name == "__all__" + and s.lvalue.kind == GDEF + and isinstance(s.rvalue, (ListExpr, TupleExpr)) + ): + self.add_exports(s.rvalue.items) + + def visit_while_stmt(self, s: WhileStmt) -> None: + self.statement = s + s.expr.accept(self) + self.loop_depth[-1] += 1 + with self.inside_except_star_block_set(value=False, entering_loop=True): + s.body.accept(self) + self.loop_depth[-1] -= 1 + self.visit_block_maybe(s.else_body) + + def visit_for_stmt(self, s: ForStmt) -> None: + if s.is_async: + if not self.is_func_scope() or not self.function_stack[-1].is_coroutine: + self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, s, code=codes.SYNTAX) + + self.statement = s + s.expr.accept(self) + + # Bind index variables and check if they define new names. + self.analyze_lvalue(s.index, explicit_type=s.index_type is not None, is_index_var=True) + if s.index_type: + if self.is_classvar(s.index_type): + self.fail_invalid_classvar(s.index) + allow_tuple_literal = isinstance(s.index, TupleExpr) + analyzed = self.anal_type(s.index_type, allow_tuple_literal=allow_tuple_literal) + if analyzed is not None: + self.store_declared_types(s.index, analyzed) + s.index_type = analyzed + + self.loop_depth[-1] += 1 + with self.inside_except_star_block_set(value=False, entering_loop=True): + self.visit_block(s.body) + self.loop_depth[-1] -= 1 + self.visit_block_maybe(s.else_body) + + def visit_break_stmt(self, s: BreakStmt) -> None: + self.statement = s + if self.loop_depth[-1] == 0: + self.fail('"break" outside loop', s, serious=True, blocker=True) + if self.inside_except_star_block: + self.fail('"break" not allowed in except* block', s, serious=True) + + def visit_continue_stmt(self, s: ContinueStmt) -> None: + self.statement = s + if self.loop_depth[-1] == 0: + self.fail('"continue" outside loop', s, serious=True, blocker=True) + if self.inside_except_star_block: + self.fail('"continue" not allowed in except* block', s, serious=True) + + def visit_if_stmt(self, s: IfStmt) -> None: + self.statement = s + infer_reachability_of_if_statement(s, self.options) + for i in range(len(s.expr)): + s.expr[i].accept(self) + self.visit_block(s.body[i]) + self.visit_block_maybe(s.else_body) + + def visit_try_stmt(self, s: TryStmt) -> None: + self.statement = s + self.analyze_try_stmt(s, self) + + def analyze_try_stmt(self, s: TryStmt, visitor: NodeVisitor[None]) -> None: + s.body.accept(visitor) + for type, var, handler in zip(s.types, s.vars, s.handlers): + if type: + type.accept(visitor) + if var: + self.analyze_lvalue(var) + with self.inside_except_star_block_set(self.inside_except_star_block or s.is_star): + handler.accept(visitor) + if s.else_body: + s.else_body.accept(visitor) + if s.finally_body: + s.finally_body.accept(visitor) + + def visit_with_stmt(self, s: WithStmt) -> None: + self.statement = s + types: list[Type] = [] + + if s.is_async: + if not self.is_func_scope() or not self.function_stack[-1].is_coroutine: + self.fail(message_registry.ASYNC_WITH_OUTSIDE_COROUTINE, s, code=codes.SYNTAX) + + if s.unanalyzed_type: + assert isinstance(s.unanalyzed_type, ProperType) + actual_targets = [t for t in s.target if t is not None] + if len(actual_targets) == 0: + # We have a type for no targets + self.fail('Invalid type comment: "with" statement has no targets', s) + elif len(actual_targets) == 1: + # We have one target and one type + types = [s.unanalyzed_type] + elif isinstance(s.unanalyzed_type, TupleType): + # We have multiple targets and multiple types + if len(actual_targets) == len(s.unanalyzed_type.items): + types = s.unanalyzed_type.items.copy() + else: + # But it's the wrong number of items + self.fail('Incompatible number of types for "with" targets', s) + else: + # We have multiple targets and one type + self.fail('Multiple types expected for multiple "with" targets', s) + + new_types: list[Type] = [] + for e, n in zip(s.expr, s.target): + e.accept(self) + if n: + self.analyze_lvalue(n, explicit_type=s.unanalyzed_type is not None) + + # Since we have a target, pop the next type from types + if types: + t = types.pop(0) + if self.is_classvar(t): + self.fail_invalid_classvar(n) + allow_tuple_literal = isinstance(n, TupleExpr) + analyzed = self.anal_type(t, allow_tuple_literal=allow_tuple_literal) + if analyzed is not None: + # TODO: Deal with this better + new_types.append(analyzed) + self.store_declared_types(n, analyzed) + + s.analyzed_types = new_types + + self.visit_block(s.body) + + def visit_del_stmt(self, s: DelStmt) -> None: + self.statement = s + s.expr.accept(self) + if not self.is_valid_del_target(s.expr): + self.fail("Invalid delete target", s) + + def is_valid_del_target(self, s: Expression) -> bool: + if isinstance(s, (IndexExpr, NameExpr, MemberExpr)): + return True + elif isinstance(s, (TupleExpr, ListExpr)): + return all(self.is_valid_del_target(item) for item in s.items) + else: + return False + + def visit_global_decl(self, g: GlobalDecl) -> None: + self.statement = g + for name in g.names: + if name in self.nonlocal_decls[-1]: + self.fail(f'Name "{name}" is nonlocal and global', g) + self.global_decls[-1].add(name) + + def visit_nonlocal_decl(self, d: NonlocalDecl) -> None: + self.statement = d + if self.is_module_scope(): + self.fail("nonlocal declaration not allowed at module level", d) + else: + for name in d.names: + for table, scope_type in zip( + reversed(self.locals[:-1]), reversed(self.scope_stack[:-1]) + ): + if table is not None and name in table: + if scope_type == SCOPE_ANNOTATION: + self.fail( + f'nonlocal binding not allowed for type parameter "{name}"', d + ) + break + else: + self.fail(f'No binding for nonlocal "{name}" found', d) + + if self.locals[-1] is not None and name in self.locals[-1]: + self.fail( + 'Name "{}" is already defined in local ' + "scope before nonlocal declaration".format(name), + d, + ) + + if name in self.global_decls[-1]: + self.fail(f'Name "{name}" is nonlocal and global', d) + self.nonlocal_decls[-1].add(name) + + def visit_match_stmt(self, s: MatchStmt) -> None: + self.statement = s + infer_reachability_of_match_statement(s, self.options) + s.subject.accept(self) + for i in range(len(s.patterns)): + s.patterns[i].accept(self) + guard = s.guards[i] + if guard is not None: + guard.accept(self) + self.visit_block(s.bodies[i]) + + def visit_type_alias_stmt(self, s: TypeAliasStmt) -> None: + if s.invalid_recursive_alias: + return + self.statement = s + type_params = self.push_type_args(s.type_args, s) + if type_params is None: + self.defer(s) + return + all_type_params_names = [p.name for p in s.type_args] + + try: + existing = self.current_symbol_table().get(s.name.name) + if existing and not ( + isinstance(existing.node, TypeAlias) + or (isinstance(existing.node, PlaceholderNode) and existing.node.line == s.line) + ): + self.already_defined(s.name.name, s, existing, "Name") + return + + tag = self.track_incomplete_refs() + res, alias_tvars, depends_on, indexed = self.analyze_alias( + s.name.name, + s.value.expr(), + allow_placeholder=True, + declared_type_vars=type_params, + all_declared_type_params_names=all_type_params_names, + python_3_12_type_alias=True, + ) + if not res: + res = AnyType(TypeOfAny.from_error) + + if not self.is_func_scope(): + # Only marking incomplete for top-level placeholders makes recursive aliases like + # `A = Sequence[str | A]` valid here, similar to how we treat base classes in class + # definitions, allowing `class str(Sequence[str]): ...` + incomplete_target = isinstance(res, ProperType) and isinstance( + res, PlaceholderType + ) + else: + incomplete_target = has_placeholder(res) + + if self.found_incomplete_ref(tag) or incomplete_target: + # Since we have got here, we know this must be a type alias (incomplete refs + # may appear in nested positions), therefore use becomes_typeinfo=True. + self.mark_incomplete(s.name.name, s.value, becomes_typeinfo=True) + return + + # Now go through all new variables and temporary replace all tvars that still + # refer to some placeholders. We defer the whole alias and will revisit it again, + # as well as all its dependents. + for i, tv in enumerate(alias_tvars): + if has_placeholder(tv): + self.mark_incomplete(s.name.name, s.value, becomes_typeinfo=True) + alias_tvars[i] = self._trivial_typevarlike_like(tv) + + self.add_type_alias_deps(depends_on) + check_for_explicit_any( + res, self.options, self.is_typeshed_stub_file, self.msg, context=s + ) + # When this type alias gets "inlined", the Any is not explicit anymore, + # so we need to replace it with non-explicit Anys. + res = make_any_non_explicit(res) + if self.options.disallow_any_unimported and has_any_from_unimported_type(res): + self.msg.unimported_type_becomes_any("Type alias target", res, s) + res = make_any_non_unimported(res) + eager = self.is_func_scope() + if isinstance(res, ProperType) and isinstance(res, Instance): + fix_instance(res, self.fail, self.note, disallow_any=False, options=self.options) + alias_node = TypeAlias( + res, + self.qualified_name(s.name.name), + self.cur_mod_id, + s.line, + s.column, + alias_tvars=alias_tvars, + no_args=False, + eager=eager, + python_3_12_type_alias=True, + ) + s.alias_node = alias_node + + if ( + existing + and isinstance(existing.node, (PlaceholderNode, TypeAlias)) + and existing.node.line == s.line + ): + updated = False + if isinstance(existing.node, TypeAlias): + if ( + existing.node.target != res + or existing.node.alias_tvars != alias_node.alias_tvars + ): + # Copy expansion to the existing alias, this matches how we update base classes + # for a TypeInfo _in place_ if there are nested placeholders. + existing.node.target = res + existing.node.alias_tvars = alias_tvars + updated = True + # Invalidate recursive status cache in case it was previously set. + existing.node._is_recursive = None + else: + # Otherwise just replace existing placeholder with type alias. + existing.node = alias_node + updated = True + + if updated: + if self.final_iteration: + self.cannot_resolve_name(s.name.name, "name", s) + return + else: + # We need to defer so that this change can get propagated to base classes. + self.defer(s, force_progress=True) + else: + self.add_symbol(s.name.name, alias_node, s) + + current_node = existing.node if existing else alias_node + assert isinstance(current_node, TypeAlias) + self.disable_invalid_recursive_aliases(s, current_node, s.value) + s.name.accept(self) + finally: + self.pop_type_args(s.type_args) + + def _trivial_typevarlike_like(self, tv: TypeVarLikeType) -> TypeVarLikeType: + object_type = self.named_type("builtins.object") + if isinstance(tv, TypeVarType): + return TypeVarType( + tv.name, + tv.fullname, + tv.id, + values=[], + upper_bound=object_type, + default=AnyType(TypeOfAny.from_omitted_generics), + variance=tv.variance, + line=tv.line, + column=tv.column, + ) + elif isinstance(tv, TypeVarTupleType): + tuple_type = self.named_type("builtins.tuple", [object_type]) + return TypeVarTupleType( + tv.name, + tv.fullname, + tv.id, + upper_bound=tuple_type, + tuple_fallback=tuple_type, + default=AnyType(TypeOfAny.from_omitted_generics), + line=tv.line, + column=tv.column, + ) + elif isinstance(tv, ParamSpecType): + return ParamSpecType( + tv.name, + tv.fullname, + tv.id, + flavor=tv.flavor, + upper_bound=object_type, + default=AnyType(TypeOfAny.from_omitted_generics), + line=tv.line, + column=tv.column, + ) + else: + assert False, f"Unknown TypeVarLike: {tv!r}" + + # + # Expressions + # + + def visit_name_expr(self, expr: NameExpr) -> None: + n = self.lookup(expr.name, expr) + if n: + self.bind_name_expr(expr, n) + + def bind_name_expr(self, expr: NameExpr, sym: SymbolTableNode) -> None: + """Bind name expression to a symbol table node.""" + if ( + isinstance(sym.node, TypeVarExpr) + and self.tvar_scope.get_binding(sym) + and not self.allow_unbound_tvars + ): + self.fail(f'"{expr.name}" is a type variable and only valid in type context', expr) + elif isinstance(sym.node, PlaceholderNode): + self.process_placeholder(expr.name, "name", expr) + else: + expr.kind = sym.kind + expr.node = sym.node + expr.fullname = sym.fullname or "" + + def visit_super_expr(self, expr: SuperExpr) -> None: + if not self.type and not expr.call.args: + self.fail('"super" used outside class', expr) + return + expr.info = self.type + for arg in expr.call.args: + arg.accept(self) + + def visit_tuple_expr(self, expr: TupleExpr) -> None: + for item in expr.items: + if isinstance(item, StarExpr): + item.valid = True + item.accept(self) + + def visit_list_expr(self, expr: ListExpr) -> None: + for item in expr.items: + if isinstance(item, StarExpr): + item.valid = True + item.accept(self) + + def visit_set_expr(self, expr: SetExpr) -> None: + for item in expr.items: + if isinstance(item, StarExpr): + item.valid = True + item.accept(self) + + def visit_dict_expr(self, expr: DictExpr) -> None: + for key, value in expr.items: + if key is not None: + key.accept(self) + value.accept(self) + + def visit_template_str_expr(self, expr: TemplateStrExpr) -> None: + for item in expr.items: + if isinstance(item, tuple): + item[0].accept(self) + if item[3] is not None: + item[3].accept(self) + else: + item.accept(self) + + def visit_star_expr(self, expr: StarExpr) -> None: + if not expr.valid: + self.fail("can't use starred expression here", expr, blocker=True) + else: + expr.expr.accept(self) + + def visit_yield_from_expr(self, e: YieldFromExpr) -> None: + if not self.is_func_scope(): + self.fail('"yield from" outside function', e, serious=True, blocker=True) + elif self.scope_stack[-1] == SCOPE_COMPREHENSION: + self.fail( + '"yield from" inside comprehension or generator expression', + e, + serious=True, + blocker=True, + ) + elif self.function_stack[-1].is_coroutine: + self.fail('"yield from" in async function', e, serious=True, blocker=True) + else: + self.function_stack[-1].is_generator = True + if e.expr: + e.expr.accept(self) + + def visit_call_expr(self, expr: CallExpr) -> None: + """Analyze a call expression. + + Some call expressions are recognized as special forms, including + cast(...). + """ + expr.callee.accept(self) + if refers_to_fullname(expr.callee, "typing.cast"): + # Special form cast(...). + if not self.check_fixed_args(expr, 2, "cast"): + return + # Translate first argument to an unanalyzed type. + try: + target = self.expr_to_unanalyzed_type(expr.args[0]) + except TypeTranslationError: + self.fail("Cast target is not a type", expr) + return + # Piggyback CastExpr object to the CallExpr object; it takes + # precedence over the CallExpr semantics. + expr.analyzed = CastExpr(expr.args[1], target) + expr.analyzed.line = expr.line + expr.analyzed.column = expr.column + expr.analyzed.accept(self) + elif refers_to_fullname(expr.callee, ASSERT_TYPE_NAMES): + if not self.check_fixed_args(expr, 2, "assert_type"): + return + # Translate second argument to an unanalyzed type. + try: + target = self.expr_to_unanalyzed_type(expr.args[1]) + except TypeTranslationError: + self.fail("assert_type() type is not a type", expr) + return + expr.analyzed = AssertTypeExpr(expr.args[0], target) + expr.analyzed.line = expr.line + expr.analyzed.column = expr.column + expr.analyzed.accept(self) + elif refers_to_fullname(expr.callee, REVEAL_TYPE_NAMES): + if not self.check_fixed_args(expr, 1, "reveal_type"): + return + reveal_imported = False + reveal_type_node = self.lookup("reveal_type", expr, suppress_errors=True) + if ( + reveal_type_node + and isinstance(reveal_type_node.node, SYMBOL_FUNCBASE_TYPES) + and reveal_type_node.fullname in IMPORTED_REVEAL_TYPE_NAMES + ): + reveal_imported = True + expr.analyzed = RevealExpr( + kind=REVEAL_TYPE, expr=expr.args[0], is_imported=reveal_imported + ) + expr.analyzed.line = expr.line + expr.analyzed.column = expr.column + expr.analyzed.accept(self) + elif refers_to_fullname(expr.callee, "builtins.reveal_locals"): + # Store the local variable names into the RevealExpr for use in the + # type checking pass + local_nodes: list[Var] = [] + if self.is_module_scope(): + # try to determine just the variable declarations in module scope + # self.globals.values() contains SymbolTableNode's + # Each SymbolTableNode has an attribute node that is nodes.Var + # look for variable nodes that marked as is_inferred + # Each symboltable node has a Var node as .node + local_nodes = [ + n.node + for name, n in self.globals.items() + if getattr(n.node, "is_inferred", False) and isinstance(n.node, Var) + ] + elif self.is_class_scope(): + # type = None # type: Optional[TypeInfo] + if self.type is not None: + local_nodes = [ + st.node for st in self.type.names.values() if isinstance(st.node, Var) + ] + elif self.is_func_scope(): + # locals = None # type: List[Optional[SymbolTable]] + if self.locals is not None: + symbol_table = self.locals[-1] + if symbol_table is not None: + local_nodes = [ + st.node for st in symbol_table.values() if isinstance(st.node, Var) + ] + expr.analyzed = RevealExpr(kind=REVEAL_LOCALS, local_nodes=local_nodes) + expr.analyzed.line = expr.line + expr.analyzed.column = expr.column + expr.analyzed.accept(self) + elif refers_to_fullname(expr.callee, "typing.Any"): + # Special form Any(...) no longer supported. + self.fail("Any(...) is no longer supported. Use cast(Any, ...) instead", expr) + elif refers_to_fullname(expr.callee, "typing._promote"): + # Special form _promote(...). + if not self.check_fixed_args(expr, 1, "_promote"): + return + # Translate first argument to an unanalyzed type. + try: + target = self.expr_to_unanalyzed_type(expr.args[0]) + except TypeTranslationError: + self.fail("Argument 1 to _promote is not a type", expr) + return + expr.analyzed = PromoteExpr(target) + expr.analyzed.line = expr.line + expr.analyzed.accept(self) + elif refers_to_fullname(expr.callee, "builtins.dict") and not ( + isinstance(expr.callee, RefExpr) + and isinstance(expr.callee.node, TypeAlias) + and not expr.callee.node.no_args + ): + expr.analyzed = self.translate_dict_call(expr) + elif refers_to_fullname(expr.callee, "builtins.divmod"): + if not self.check_fixed_args(expr, 2, "divmod"): + return + expr.analyzed = OpExpr("divmod", expr.args[0], expr.args[1]) + expr.analyzed.line = expr.line + expr.analyzed.accept(self) + elif refers_to_fullname( + expr.callee, ("typing.TypeAliasType", "typing_extensions.TypeAliasType") + ): + with self.allow_unbound_tvars_set(): + for a in expr.args: + a.accept(self) + elif refers_to_fullname(expr.callee, ("typing.TypeForm", "typing_extensions.TypeForm")): + # Special form TypeForm(...). + if not self.check_fixed_args(expr, 1, "TypeForm"): + return + # Translate first argument to an unanalyzed type. + try: + typ = self.expr_to_unanalyzed_type(expr.args[0]) + except TypeTranslationError: + self.fail("TypeForm argument is not a type", expr) + # Suppress future error: "" not callable + expr.analyzed = CastExpr(expr.args[0], AnyType(TypeOfAny.from_error)) + return + # Piggyback TypeFormExpr object to the CallExpr object; it takes + # precedence over the CallExpr semantics. + expr.analyzed = TypeFormExpr(typ) + expr.analyzed.line = expr.line + expr.analyzed.column = expr.column + expr.analyzed.accept(self) + else: + # Normal call expression. + calculate_type_forms = TYPE_FORM in self.options.enable_incomplete_feature + for a in expr.args: + a.accept(self) + if calculate_type_forms: + self.try_parse_as_type_expression(a) + + if ( + isinstance(expr.callee, MemberExpr) + and isinstance(expr.callee.expr, NameExpr) + and expr.callee.expr.name == "__all__" + and expr.callee.expr.kind == GDEF + and expr.callee.name in ("append", "extend", "remove") + ): + if expr.callee.name == "append" and expr.args: + self.add_exports(expr.args[0]) + elif ( + expr.callee.name == "extend" + and expr.args + and isinstance(expr.args[0], (ListExpr, TupleExpr)) + ): + self.add_exports(expr.args[0].items) + elif ( + expr.callee.name == "remove" + and expr.args + and isinstance(expr.args[0], StrExpr) + ): + self.all_exports = [n for n in self.all_exports if n != expr.args[0].value] + + def translate_dict_call(self, call: CallExpr) -> DictExpr | None: + """Translate 'dict(x=y, ...)' to {'x': y, ...} and 'dict()' to {}. + + For other variants of dict(...), return None. + """ + if not all(kind in (ARG_NAMED, ARG_STAR2) for kind in call.arg_kinds): + # Must still accept those args. + for a in call.args: + a.accept(self) + return None + expr = DictExpr( + [ + (StrExpr(key) if key is not None else None, value) + for key, value in zip(call.arg_names, call.args) + ] + ) + expr.set_line(call) + expr.accept(self) + return expr + + def check_fixed_args(self, expr: CallExpr, numargs: int, name: str) -> bool: + """Verify that expr has specified number of positional args. + + Return True if the arguments are valid. + """ + s = "s" + if numargs == 1: + s = "" + if len(expr.args) != numargs: + self.fail('"%s" expects %d argument%s' % (name, numargs, s), expr) + return False + if expr.arg_kinds != [ARG_POS] * numargs: + self.fail(f'"{name}" must be called with {numargs} positional argument{s}', expr) + return False + return True + + def visit_member_expr(self, expr: MemberExpr) -> None: + base = expr.expr + base.accept(self) + if isinstance(base, RefExpr) and isinstance(base.node, MypyFile): + # Handle module attribute. + sym = self.get_module_symbol(base.node, expr.name) + if sym: + if isinstance(sym.node, PlaceholderNode): + self.process_placeholder(expr.name, "attribute", expr) + return + self.record_imported_symbol(sym) + expr.kind = sym.kind + expr.fullname = sym.fullname or "" + expr.node = sym.node + elif isinstance(base, RefExpr): + # This branch handles the case C.bar (or cls.bar or self.bar inside + # a classmethod/method), where C is a class and bar is a type + # definition or a module resulting from `import bar` (or a module + # assignment) inside class C. We look up bar in the class' TypeInfo + # namespace. This is done only when bar is a module or a type; + # other things (e.g. methods) are handled by other code in + # checkmember. + type_info = None + if isinstance(base.node, TypeInfo): + # C.bar where C is a class + type_info = base.node + elif isinstance(base.node, Var) and self.type and self.function_stack: + # check for self.bar or cls.bar in method/classmethod + func_def = self.function_stack[-1] + if ( + func_def.has_self_or_cls_argument + and func_def.info is self.type + and isinstance(func_def.type, CallableType) + and func_def.arguments + and base.node is func_def.arguments[0].variable + ): + type_info = self.type + elif isinstance(base.node, TypeAlias) and base.node.no_args: + assert isinstance(base.node.target, ProperType) + if isinstance(base.node.target, Instance): + type_info = base.node.target.type + + if type_info: + n = type_info.names.get(expr.name) + if n is not None and isinstance(n.node, (MypyFile, TypeInfo, TypeAlias)): + self.record_imported_symbol(n) + expr.kind = n.kind + expr.fullname = n.fullname or "" + expr.node = n.node + + def visit_op_expr(self, expr: OpExpr) -> None: + expr.left.accept(self) + + if expr.op in ("and", "or"): + inferred = infer_condition_value(expr.left, self.options) + if (inferred in (ALWAYS_FALSE, MYPY_FALSE) and expr.op == "and") or ( + inferred in (ALWAYS_TRUE, MYPY_TRUE) and expr.op == "or" + ): + expr.right_unreachable = True + return + elif (inferred in (ALWAYS_TRUE, MYPY_TRUE) and expr.op == "and") or ( + inferred in (ALWAYS_FALSE, MYPY_FALSE) and expr.op == "or" + ): + expr.right_always = True + + expr.right.accept(self) + + def visit_comparison_expr(self, expr: ComparisonExpr) -> None: + for operand in expr.operands: + operand.accept(self) + + def visit_unary_expr(self, expr: UnaryExpr) -> None: + expr.expr.accept(self) + + def visit_index_expr(self, expr: IndexExpr) -> None: + base = expr.base + base.accept(self) + if ( + isinstance(base, RefExpr) + and isinstance(base.node, TypeInfo) + and not base.node.is_generic() + ): + expr.index.accept(self) + elif ( + isinstance(base, RefExpr) and isinstance(base.node, TypeAlias) + ) or refers_to_class_or_function(base): + # We need to do full processing on every iteration, since some type + # arguments may contain placeholder types. + self.analyze_type_application(expr) + else: + expr.index.accept(self) + + def analyze_type_application(self, expr: IndexExpr) -> None: + """Analyze special form -- type application (either direct or via type aliasing).""" + types = self.analyze_type_application_args(expr) + if types is None: + return + base = expr.base + expr.analyzed = TypeApplication(base, types) + expr.analyzed.line = expr.line + expr.analyzed.column = expr.column + + if isinstance(base, RefExpr) and base.fullname == "librt.vecs.vec": + # Apply restrictions specific to vec + check_vec_type_args(types, expr, self) + + def analyze_type_application_args(self, expr: IndexExpr) -> list[Type] | None: + """Analyze type arguments (index) in a type application. + + Return None if anything was incomplete. + """ + index = expr.index + tag = self.track_incomplete_refs() + self.analyze_type_expr(index) + if self.found_incomplete_ref(tag): + return None + if self.basic_type_applications: + # Postpone the rest until we have more information (for r.h.s. of an assignment) + return None + types: list[Type] = [] + if isinstance(index, TupleExpr): + items = index.items + is_tuple = isinstance(expr.base, RefExpr) and expr.base.fullname == "builtins.tuple" + if is_tuple and len(items) == 2 and isinstance(items[-1], EllipsisExpr): + items = items[:-1] + else: + items = [index] + + # TODO: this needs a clean-up. + # Probably always allow Parameters literals, and validate in semanal_typeargs.py + base = expr.base + if isinstance(base, RefExpr) and isinstance(base.node, TypeAlias): + allow_unpack = base.node.tvar_tuple_index is not None + alias = base.node + if any(isinstance(t, ParamSpecType) for t in alias.alias_tvars): + has_param_spec = True + num_args = len(alias.alias_tvars) + else: + has_param_spec = False + num_args = -1 + elif isinstance(base, RefExpr) and isinstance(base.node, TypeInfo): + allow_unpack = ( + base.node.has_type_var_tuple_type or base.node.fullname == "builtins.tuple" + ) + has_param_spec = base.node.has_param_spec_type + num_args = len(base.node.type_vars) + else: + allow_unpack = False + has_param_spec = False + num_args = -1 + + for item in items: + try: + typearg = self.expr_to_unanalyzed_type(item, allow_unpack=True) + except TypeTranslationError: + self.fail("Type expected within [...]", expr) + return None + analyzed = self.anal_type( + typearg, + # The type application may appear in base class expression, + # where type variables are not bound yet. Or when accepting + # r.h.s. of type alias before we figured out it is a type alias. + allow_unbound_tvars=self.allow_unbound_tvars, + allow_placeholder=True, + allow_param_spec_literals=has_param_spec, + allow_unpack=allow_unpack, + ) + if analyzed is None: + return None + types.append(analyzed) + + if allow_unpack: + # need to flatten away harmless unpacks like Unpack[tuple[int]] + flattened_items = flatten_nested_tuples(types) + types = self.type_analyzer().check_unpacks_in_list(flattened_items) + if has_param_spec and num_args == 1 and types: + first_arg = get_proper_type(types[0]) + single_any = len(types) == 1 and isinstance(first_arg, AnyType) + if not (single_any or any(isinstance(t, (Parameters, ParamSpecType)) for t in types)): + types = [Parameters(types, [ARG_POS] * len(types), [None] * len(types))] + + return types + + def visit_slice_expr(self, expr: SliceExpr) -> None: + if expr.begin_index: + expr.begin_index.accept(self) + if expr.end_index: + expr.end_index.accept(self) + if expr.stride: + expr.stride.accept(self) + + def visit_cast_expr(self, expr: CastExpr) -> None: + expr.expr.accept(self) + analyzed = self.anal_type(expr.type) + if analyzed is not None: + expr.type = analyzed + + def visit_type_form_expr(self, expr: TypeFormExpr) -> None: + analyzed = self.anal_type(expr.type) + if analyzed is not None: + expr.type = analyzed + + def visit_assert_type_expr(self, expr: AssertTypeExpr) -> None: + expr.expr.accept(self) + analyzed = self.anal_type(expr.type) + if analyzed is not None: + expr.type = analyzed + + def visit_reveal_expr(self, expr: RevealExpr) -> None: + if expr.kind == REVEAL_TYPE: + if expr.expr is not None: + expr.expr.accept(self) + else: + # Reveal locals doesn't have an inner expression, there's no + # need to traverse inside it + pass + + def visit_type_application(self, expr: TypeApplication) -> None: + expr.expr.accept(self) + for i in range(len(expr.types)): + analyzed = self.anal_type(expr.types[i]) + if analyzed is not None: + expr.types[i] = analyzed + + def visit_list_comprehension(self, expr: ListComprehension) -> None: + if any(expr.generator.is_async): + if ( + not self.is_func_scope() + or not self.function_stack + or not self.function_stack[-1].is_coroutine + ): + self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, expr, code=codes.SYNTAX) + + expr.generator.accept(self) + + def visit_set_comprehension(self, expr: SetComprehension) -> None: + if any(expr.generator.is_async): + if ( + not self.is_func_scope() + or not self.function_stack + or not self.function_stack[-1].is_coroutine + ): + self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, expr, code=codes.SYNTAX) + + expr.generator.accept(self) + + def visit_dictionary_comprehension(self, expr: DictionaryComprehension) -> None: + if any(expr.is_async): + if ( + not self.is_func_scope() + or not self.function_stack + or not self.function_stack[-1].is_coroutine + ): + self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, expr, code=codes.SYNTAX) + + with self.enter(expr): + self.analyze_comp_for(expr) + expr.key.accept(self) + expr.value.accept(self) + self.analyze_comp_for_2(expr) + + def visit_generator_expr(self, expr: GeneratorExpr) -> None: + with self.enter(expr): + self.analyze_comp_for(expr) + expr.left_expr.accept(self) + self.analyze_comp_for_2(expr) + + def analyze_comp_for(self, expr: GeneratorExpr | DictionaryComprehension) -> None: + """Analyses the 'comp_for' part of comprehensions (part 1). + + That is the part after 'for' in (x for x in l if p). This analyzes + variables and conditions which are analyzed in a local scope. + """ + for i, (index, sequence, conditions) in enumerate( + zip(expr.indices, expr.sequences, expr.condlists) + ): + if i > 0: + sequence.accept(self) + # Bind index variables. + self.analyze_lvalue(index) + for cond in conditions: + cond.accept(self) + + def analyze_comp_for_2(self, expr: GeneratorExpr | DictionaryComprehension) -> None: + """Analyses the 'comp_for' part of comprehensions (part 2). + + That is the part after 'for' in (x for x in l if p). This analyzes + the 'l' part which is analyzed in the surrounding scope. + """ + expr.sequences[0].accept(self) + + def visit_lambda_expr(self, expr: LambdaExpr) -> None: + self.analyze_arg_initializers(expr) + with self.inside_except_star_block_set(False, entering_loop=False): + self.analyze_function_body(expr) + + def visit_conditional_expr(self, expr: ConditionalExpr) -> None: + expr.if_expr.accept(self) + expr.cond.accept(self) + expr.else_expr.accept(self) + + def visit__promote_expr(self, expr: PromoteExpr) -> None: + analyzed = self.anal_type(expr.type) + if analyzed is not None: + assert isinstance(analyzed, ProperType), "Cannot use type aliases for promotions" + expr.type = analyzed + + def visit_yield_expr(self, e: YieldExpr) -> None: + if not self.is_func_scope(): + self.fail('"yield" outside function', e, serious=True, blocker=True) + elif self.scope_stack[-1] == SCOPE_COMPREHENSION: + self.fail( + '"yield" inside comprehension or generator expression', + e, + serious=True, + blocker=True, + ) + elif self.function_stack[-1].is_coroutine: + self.function_stack[-1].is_generator = True + self.function_stack[-1].is_async_generator = True + else: + self.function_stack[-1].is_generator = True + if e.expr: + e.expr.accept(self) + + def visit_await_expr(self, expr: AwaitExpr) -> None: + if not self.is_func_scope() or not self.function_stack: + # We check both because is_function_scope() returns True inside comprehensions. + # This is not a blocker, because some environments (like ipython) + # support top level awaits. + self.fail('"await" outside function', expr, serious=True, code=codes.TOP_LEVEL_AWAIT) + elif not self.function_stack[-1].is_coroutine: + self.fail( + '"await" outside coroutine ("async def")', + expr, + serious=True, + code=codes.AWAIT_NOT_ASYNC, + ) + expr.expr.accept(self) + + # + # Patterns + # + + def visit_as_pattern(self, p: AsPattern) -> None: + if p.pattern is not None: + p.pattern.accept(self) + if p.name is not None: + self.analyze_lvalue(p.name) + + def visit_or_pattern(self, p: OrPattern) -> None: + for pattern in p.patterns: + pattern.accept(self) + + def visit_value_pattern(self, p: ValuePattern) -> None: + p.expr.accept(self) + + def visit_sequence_pattern(self, p: SequencePattern) -> None: + for pattern in p.patterns: + pattern.accept(self) + + def visit_starred_pattern(self, p: StarredPattern) -> None: + if p.capture is not None: + self.analyze_lvalue(p.capture) + + def visit_mapping_pattern(self, p: MappingPattern) -> None: + for key in p.keys: + key.accept(self) + for value in p.values: + value.accept(self) + if p.rest is not None: + self.analyze_lvalue(p.rest) + + def visit_class_pattern(self, p: ClassPattern) -> None: + p.class_ref.accept(self) + for pos in p.positionals: + pos.accept(self) + for v in p.keyword_values: + v.accept(self) + + # + # Lookup functions + # + + def lookup( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + node = self._lookup(name, ctx, suppress_errors) + if node is not None: + # This call is unfortunate from performance point of view, but + # needed for rare cases like e.g. testIncrementalChangingAlias. + self.record_imported_symbol(node) + return node + + def record_imported_symbol(self, sym: SymbolTableNode) -> None: + """If the symbol was not defined in current module, add its module to module_refs.""" + if sym.kind == LDEF or sym.node is None: + return + node = sym.node + if isinstance(node, PlaceholderNode) or not node.fullname: + # This node is not ready yet. + return + if node.fullname.startswith(("builtins.", "typing.")): + # Skip dependencies on builtins/typing. + return + # Modules, classes, and type aliases store defining module directly. + if isinstance(node, MypyFile): + fullname = node.fullname + elif isinstance(node, TypeInfo): + fullname = node.module_name + elif isinstance(node, TypeAlias): + fullname = node.module + elif isinstance(node, (Var, FuncDef, OverloadedFuncDef, Decorator)): + # For functions/variables infer defining module from enclosing class. + info = node.var.info if isinstance(node, Decorator) else node.info + if info: + fullname = info.module_name + else: + # global function/variable + fullname = node.fullname.rsplit(".", maxsplit=1)[0] + else: + # Some nodes (currently only TypeVarLikeExpr subclasses) don't store + # module fullname explicitly, infer it from the node fullname iteratively. + # TODO: this is not 100% robust for type variables nested within a class + # with a name that matches name of a submodule. + fullname = node.fullname.rsplit(".", maxsplit=1)[0] + if fullname == self.cur_mod_id: + return + while "." in fullname and fullname not in self.modules: + fullname = fullname.rsplit(".", maxsplit=1)[0] + if fullname != self.cur_mod_id: + self.cur_mod_node.module_refs.add(fullname) + + def _lookup( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + """Look up an unqualified (no dots) name in all active namespaces. + + Note that the result may contain a PlaceholderNode. The caller may + want to defer in that case. + + Generate an error if the name is not defined unless suppress_errors + is true or the current namespace is incomplete. In the latter case + defer. + """ + implicit_name = False + # 1a. Name declared using 'global x' takes precedence + if name in self.global_decls[-1]: + if name in self.globals: + return self.globals[name] + if not suppress_errors: + self.name_not_defined(name, ctx) + return None + # 1b. Name declared using 'nonlocal x' takes precedence + if name in self.nonlocal_decls[-1]: + for table in reversed(self.locals[:-1]): + if table is not None and name in table: + return table[name] + if not suppress_errors: + self.name_not_defined(name, ctx) + return None + # 2a. Class attributes (if within class definition) + if self.type and not self.is_func_scope() and name in self.type.names: + node = self.type.names[name] + if not node.implicit: + if self.is_active_symbol_in_class_body(node.node): + return node + else: + # Defined through self.x assignment + implicit_name = True + implicit_node = node + # 2b. Class attributes __qualname__ and __module__ + if self.type and not self.is_func_scope() and name in {"__qualname__", "__module__"}: + v = Var(name, self.str_type()) + v._fullname = self.qualified_name(name) + return SymbolTableNode(MDEF, v) + # 3. Local (function) scopes + for table in reversed(self.locals): + if table is not None and name in table: + return table[name] + + # 4. Current file global scope + if name in self.globals: + return self.globals[name] + # 5. Builtins + b = self.globals.get("__builtins__", None) + if b: + assert isinstance(b.node, MypyFile) + table = b.node.names + if name in table: + if len(name) > 1 and name[0] == "_" and name[1] != "_": + if not suppress_errors: + self.name_not_defined(name, ctx) + return None + node = table[name] + return node + # Give up. + if not implicit_name and not suppress_errors: + self.name_not_defined(name, ctx) + else: + if implicit_name: + return implicit_node + return None + + def is_active_symbol_in_class_body(self, node: SymbolNode | None) -> bool: + """Can a symbol defined in class body accessed at current statement? + + Only allow access to class attributes textually after + the definition, so that it's possible to fall back to the + outer scope. Example: + + class X: ... + + class C: + X = X # Initializer refers to outer scope + + Nested classes are an exception, since we want to support + arbitrary forward references in type annotations. Also, we + allow forward references to type aliases to support recursive + types. + """ + # TODO: Forward reference to name imported in class body is not + # caught. + if self.statement is None: + # Assume it's fine -- don't have enough context to check + return True + if ( + node is None + or self.is_textually_before_statement(node) + or not self.is_defined_in_current_module(node.fullname) + ): + return True + if self.is_type_like(node): + # Allow forward references to classes/type aliases (see docstring), but + # a forward reference should never shadow an existing regular reference. + if node.name not in self.globals: + return True + global_node = self.globals[node.name] + if not self.is_textually_before_class(global_node.node): + return True + return not self.is_type_like(global_node.node) + return False + + def is_type_like(self, node: SymbolNode | None) -> bool: + return isinstance(node, (TypeInfo, TypeAlias)) or ( + isinstance(node, PlaceholderNode) and node.becomes_typeinfo + ) + + def is_textually_before_statement(self, node: SymbolNode) -> bool: + """Check if a node is defined textually before the current statement + + Note that decorated functions' line number are the same as + the top decorator. + """ + assert self.statement + line_diff = self.statement.line - node.line + + # The first branch handles reference an overloaded function variant inside itself, + # this is a corner case where mypy technically deviates from runtime name resolution, + # but it is fine because we want an overloaded function to be treated as a single unit. + if self.is_overloaded_item(node, self.statement): + return False + elif isinstance(node, Decorator) and not node.is_overload: + return line_diff > len(node.original_decorators) + else: + return line_diff > 0 + + def is_textually_before_class(self, node: SymbolNode | None) -> bool: + """Similar to above, but check if a node is defined before current class.""" + assert self.type is not None + if node is None: + return False + return node.line < self.type.defn.line + + def is_overloaded_item(self, node: SymbolNode, statement: Statement) -> bool: + """Check whether the function belongs to the overloaded variants""" + if isinstance(node, OverloadedFuncDef) and isinstance(statement, FuncDef): + in_items = statement in { + item.func if isinstance(item, Decorator) else item for item in node.items + } + in_impl = node.impl is not None and ( + (isinstance(node.impl, Decorator) and statement is node.impl.func) + or statement is node.impl + ) + return in_items or in_impl + return False + + def is_defined_in_current_module(self, fullname: str | None) -> bool: + if not fullname: + return False + return module_prefix(self.modules, fullname) == self.cur_mod_id + + def lookup_qualified( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + """Lookup a qualified name in all activate namespaces. + + Note that the result may contain a PlaceholderNode. The caller may + want to defer in that case. + + Generate an error if the name is not defined unless suppress_errors + is true or the current namespace is incomplete. In the latter case + defer. + """ + if "." not in name: + # Simple case: look up a short name. + return self.lookup(name, ctx, suppress_errors=suppress_errors) + parts = name.split(".") + namespace = self.cur_mod_id + sym = self.lookup(parts[0], ctx, suppress_errors=suppress_errors) + if sym: + for i in range(1, len(parts)): + node = sym.node + part = parts[i] + if isinstance(node, TypeInfo): + nextsym = node.get(part) + elif isinstance(node, MypyFile): + nextsym = self.get_module_symbol(node, part) + namespace = node.fullname + elif isinstance(node, PlaceholderNode): + return sym + elif isinstance(node, TypeAlias) and node.no_args: + assert isinstance(node.target, ProperType) + if isinstance(node.target, Instance): + nextsym = node.target.type.get(part) + else: + nextsym = None + else: + if isinstance(node, Var): + typ = get_proper_type(node.type) + if isinstance(typ, AnyType): + # Allow access through Var with Any type without error. + return self.implicit_symbol(sym, name, parts[i:], typ) + # This might be something like valid `P.args` or invalid `P.__bound__` access. + # Important note that `ParamSpecExpr` is also ignored in other places. + # See https://github.com/python/mypy/pull/13468 + if isinstance(node, ParamSpecExpr) and part in ("args", "kwargs"): + return None + # Lookup through invalid node, such as variable or function + nextsym = None + if not nextsym or nextsym.module_hidden: + if not suppress_errors: + self.name_not_defined(name, ctx, namespace=namespace) + return None + sym = nextsym + if sym is not None: + self.record_imported_symbol(sym) + return sym + + def lookup_type_node(self, expr: Expression) -> SymbolTableNode | None: + try: + t = self.expr_to_unanalyzed_type(expr) + except TypeTranslationError: + return None + if isinstance(t, UnboundType): + n = self.lookup_qualified(t.name, expr, suppress_errors=True) + return n + return None + + def get_module_symbol(self, node: MypyFile, name: str) -> SymbolTableNode | None: + """Look up a symbol from a module. + + Return None if no matching symbol could be bound. + """ + module = node.fullname + names = node.names + sym = names.get(name) + if not sym: + fullname = module + "." + name + if fullname in self.modules and self.is_visible_import(module, fullname): + sym = SymbolTableNode(GDEF, self.modules[fullname]) + elif self.is_incomplete_namespace(module): + self.record_incomplete_ref() + elif "__getattr__" in names: + gvar = self.create_getattr_var(names["__getattr__"], name, fullname) + if gvar: + sym = SymbolTableNode(GDEF, gvar) + elif self.is_missing_module(fullname): + # We use the fullname of the original definition so that we can + # detect whether two names refer to the same thing. + var_type = AnyType(TypeOfAny.from_unimported_type) + v = Var(name, type=var_type) + v._fullname = fullname + sym = SymbolTableNode(GDEF, v) + elif sym.module_hidden: + sym = None + return sym + + def is_visible_import(self, base_id: str, id: str) -> bool: + # TODO: can we reuse SCC-level tracking from build.py instead? + if id in self.import_map[self.cur_mod_id]: + # Fast path: module is imported locally. + return True + if base_id not in self.transitive_submodule_imports: + # This is a performance optimization for a common pattern. If one module + # in a codebase uses import numpy as np; np.foo.bar, then it is likely that + # other modules use similar pattern as well. So we pre-compute transitive + # dependencies for np, to avoid possible duplicate work in the future. + self.add_transitive_submodule_imports(base_id) + if self.cur_mod_id not in self.transitive_submodule_imports: + self.add_transitive_submodule_imports(self.cur_mod_id) + return id in self.transitive_submodule_imports[self.cur_mod_id] + + def add_transitive_submodule_imports(self, mod_id: str) -> None: + if mod_id not in self.import_map: + return + todo = self.import_map[mod_id] + seen = {mod_id} + result = {mod_id} + while todo: + dep = todo.pop() + if dep in seen: + continue + seen.add(dep) + if "." in dep: + result.add(dep) + if dep in self.transitive_submodule_imports: + result |= self.transitive_submodule_imports[dep] + continue + if dep in self.import_map: + todo |= self.import_map[dep] + self.transitive_submodule_imports[mod_id] = result + + def is_missing_module(self, module: str) -> bool: + return module in self.missing_modules + + def implicit_symbol( + self, sym: SymbolTableNode, name: str, parts: list[str], source_type: AnyType + ) -> SymbolTableNode: + """Create symbol for a qualified name reference through Any type.""" + if sym.node is None: + basename = None + else: + basename = sym.node.fullname + if basename is None: + fullname = name + else: + fullname = basename + "." + ".".join(parts) + var_type = AnyType(TypeOfAny.from_another_any, source_type) + var = Var(parts[-1], var_type) + var._fullname = fullname + return SymbolTableNode(GDEF, var) + + def create_getattr_var( + self, getattr_defn: SymbolTableNode, name: str, fullname: str + ) -> Var | None: + """Create a dummy variable using module-level __getattr__ return type. + + If not possible, return None. + + Note that multiple Var nodes can be created for a single name. We + can use the from_module_getattr and the fullname attributes to + check if two dummy Var nodes refer to the same thing. Reusing Var + nodes would require non-local mutable state, which we prefer to + avoid. + """ + if isinstance(getattr_defn.node, (FuncDef, Var)): + node_type = get_proper_type(getattr_defn.node.type) + if isinstance(node_type, CallableType): + typ = node_type.ret_type + else: + typ = AnyType(TypeOfAny.from_error) + v = Var(name, type=typ) + v._fullname = fullname + v.from_module_getattr = True + return v + return None + + def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode: + ret = self.lookup_fully_qualified_or_none(fullname) + assert ret is not None, fullname + return ret + + def lookup_fully_qualified_or_none(self, fullname: str) -> SymbolTableNode | None: + """Lookup a fully qualified name that refers to a module-level definition. + + Don't assume that the name is defined. This happens in the global namespace -- + the local module namespace is ignored. This does not dereference indirect + refs. + + Note that this can't be used for names nested in class namespaces. + """ + # TODO: unify/clean-up/simplify lookup methods, see #4157. + module, name = fullname.rsplit(".", maxsplit=1) + + if module in self.modules: + # If the module exists, look up the name in the module. + # This is the common case. + filenode = self.modules[module] + result = filenode.names.get(name) + if result is None and self.is_incomplete_namespace(module): + # TODO: More explicit handling of incomplete refs? + self.record_incomplete_ref() + return result + else: + # Else, try to find the longest prefix of the module name that is in the modules dictionary. + splitted_modules = fullname.split(".") + names = [] + + while splitted_modules and ".".join(splitted_modules) not in self.modules: + names.append(splitted_modules.pop()) + + if not splitted_modules or not names: + # If no module or name is found, return None. + return None + + # Reverse the names list to get the correct order of names. + names.reverse() + + module = ".".join(splitted_modules) + filenode = self.modules[module] + result = filenode.names.get(names[0]) + + if result is None and self.is_incomplete_namespace(module): + # TODO: More explicit handling of incomplete refs? + self.record_incomplete_ref() + + for part in names[1:]: + if result is not None and isinstance(result.node, TypeInfo): + result = result.node.names.get(part) + else: + return None + return result + + def object_type(self) -> Instance: + if self._object_type is None: + self._object_type = self.named_type("builtins.object") + return self._object_type + + def str_type(self) -> Instance: + if self._str_type is None: + self._str_type = self.named_type("builtins.str") + return self._str_type + + def function_type(self) -> Instance: + if self._function_type is None: + self._function_type = self.named_type("builtins.function") + return self._function_type + + def named_type(self, fullname: str, args: list[Type] | None = None) -> Instance: + sym = self.lookup_fully_qualified(fullname) + assert sym, "Internal error: attempted to construct unknown type" + node = sym.node + assert isinstance(node, TypeInfo), node + if args: + # TODO: assert len(args) == len(node.defn.type_vars) + return Instance(node, args) + return Instance(node, [AnyType(TypeOfAny.special_form)] * len(node.defn.type_vars)) + + def named_type_or_none(self, fullname: str, args: list[Type] | None = None) -> Instance | None: + sym = self.lookup_fully_qualified_or_none(fullname) + if not sym or isinstance(sym.node, PlaceholderNode): + return None + node = sym.node + if isinstance(node, TypeAlias): + assert isinstance(node.target, Instance) # type: ignore[misc] + node = node.target.type + assert isinstance(node, TypeInfo), node + if args is not None: + # TODO: assert len(args) == len(node.defn.type_vars) + return Instance(node, args) + return Instance(node, [AnyType(TypeOfAny.unannotated)] * len(node.defn.type_vars)) + + def builtin_type(self, fully_qualified_name: str) -> Instance: + """Legacy function -- use named_type() instead.""" + return self.named_type(fully_qualified_name) + + def lookup_current_scope(self, name: str) -> SymbolTableNode | None: + if self.locals[-1] is not None: + return self.locals[-1].get(name) + elif self.type is not None: + return self.type.names.get(name) + else: + return self.globals.get(name) + + # + # Adding symbols + # + + def add_symbol( + self, + name: str, + node: SymbolNode, + context: Context, + module_public: bool = True, + module_hidden: bool = False, + can_defer: bool = True, + escape_comprehensions: bool = False, + no_progress: bool = False, + type_param: bool = False, + ) -> bool: + """Add symbol to the currently active symbol table. + + Generally additions to symbol table should go through this method or + one of the methods below so that kinds, redefinitions, conditional + definitions, and skipped names are handled consistently. + + Return True if we actually added the symbol, or False if we refused to do so + (because something is not ready). + + If can_defer is True, defer current target if adding a placeholder. + """ + if self.is_func_scope(): + kind = LDEF + elif self.type is not None: + kind = MDEF + else: + kind = GDEF + symbol = SymbolTableNode( + kind, node, module_public=module_public, module_hidden=module_hidden + ) + return self.add_symbol_table_node( + name, symbol, context, can_defer, escape_comprehensions, no_progress, type_param + ) + + def add_symbol_skip_local(self, name: str, node: SymbolNode) -> None: + """Same as above, but skipping the local namespace. + + This doesn't check for previous definition and is only used + for serialization of method-level classes. + + Classes defined within methods can be exposed through an + attribute type, but method-level symbol tables aren't serialized. + This method can be used to add such classes to an enclosing, + serialized symbol table. + """ + # TODO: currently this is only used by named tuples and typed dicts. + # Use this method also by normal classes, see issue #6422. + if self.type is not None: + names = self.type.names + kind = MDEF + else: + names = self.globals + kind = GDEF + symbol = SymbolTableNode(kind, node) + names[name] = symbol + + def add_symbol_table_node( + self, + name: str, + symbol: SymbolTableNode, + context: Context | None = None, + can_defer: bool = True, + escape_comprehensions: bool = False, + no_progress: bool = False, + type_param: bool = False, + ) -> bool: + """Add symbol table node to the currently active symbol table. + + Return True if we actually added the symbol, or False if we refused + to do so (because something is not ready or it was a no-op). + + Generate an error if there is an invalid redefinition. + + If context is None, unconditionally add node, since we can't report + an error. Note that this is used by plugins to forcibly replace nodes! + + TODO: Prevent plugins from replacing nodes, as it could cause problems? + + Args: + name: short name of symbol + symbol: Node to add + can_defer: if True, defer current target if adding a placeholder + context: error context (see above about None value) + """ + names = self.current_symbol_table( + escape_comprehensions=escape_comprehensions, type_param=type_param + ) + existing = names.get(name) + if isinstance(symbol.node, PlaceholderNode) and can_defer: + if context is not None: + self.process_placeholder(name, "name", context) + else: + # see note in docstring describing None contexts + self.defer() + + if ( + existing is not None + and context is not None + and not is_valid_replacement(existing, symbol) + ): + # There is an existing node, so this may be a redefinition. + # If the new node points to the same node as the old one, + # or if both old and new nodes are placeholders, we don't + # need to do anything. + old = existing.node + new = symbol.node + if isinstance(new, PlaceholderNode): + # We don't know whether this is okay. Let's wait until the next iteration. + return False + if not is_same_symbol(old, new): + if isinstance(new, (FuncDef, Decorator, OverloadedFuncDef, TypeInfo)): + self.add_redefinition(names, name, symbol) + if isinstance(old, Var) and is_init_only(old): + if old.has_explicit_value: + self.fail("InitVar with default value cannot be redefined", context) + elif not ( + isinstance(new, (FuncDef, Decorator)) and self.set_original_def(old, new) + ): + self.name_already_defined(name, context, existing) + elif type_param or ( + name not in self.missing_names[-1] and "*" not in self.missing_names[-1] + ): + names[name] = symbol + if not no_progress: + self.progress = True + return True + return False + + def add_redefinition(self, names: SymbolTable, name: str, symbol: SymbolTableNode) -> None: + """Add a symbol table node that reflects a redefinition as a function or a class. + + Redefinitions need to be added to the symbol table so that they can be found + through AST traversal, but they have dummy names of form 'name-redefinition[N]', + where N ranges over 2, 3, ... (omitted for the first redefinition). + + Note: we always store redefinitions independently of whether they are valid or not + (so they will be semantically analyzed), the caller should give an error for invalid + redefinitions (such as e.g. variable redefined as a class). + """ + i = 1 + # Don't serialize redefined nodes. They are likely to have + # busted internal references which can cause problems with + # serialization and they can't have any external references to + # them. + symbol.no_serialize = True + while True: + if i == 1: + new_name = f"{name}-redefinition" + else: + new_name = f"{name}-redefinition{i}" + existing = names.get(new_name) + if existing is None: + names[new_name] = symbol + return + elif existing.node is symbol.node: + # Already there + return + i += 1 + + def add_local(self, node: Var | FuncDef | OverloadedFuncDef, context: Context) -> None: + """Add local variable or function.""" + assert self.is_func_scope() + name = node.name + node._fullname = name + self.add_symbol(name, node, context) + + def _get_node_for_class_scoped_import( + self, name: str, symbol_node: SymbolNode | None, context: Context + ) -> SymbolNode | None: + if symbol_node is None: + return None + # I promise this type checks; I'm just making mypyc issues go away. + # mypyc is absolutely convinced that `symbol_node` narrows to a Var in the following, + # when it can also be a FuncBase. Once fixed, `f` in the following can be removed. + # See also https://github.com/mypyc/mypyc/issues/892 + f: Callable[[object], Any] = lambda x: x + if isinstance(f(symbol_node), (Decorator, FuncBase, Var)): + # For imports in class scope, we construct a new node to represent the symbol and + # set its `info` attribute to `self.type`. + existing = self.current_symbol_table().get(name) + if ( + # The redefinition checks in `add_symbol_table_node` don't work for our + # constructed Var / FuncBase, so check for possible redefinitions here. + existing is not None + and isinstance(f(existing.node), (Decorator, FuncBase, Var)) + and ( + isinstance(f(existing.type), f(AnyType)) + or f(existing.type) == f(symbol_node).type + ) + ): + return existing.node + + # Construct the new node + if isinstance(f(symbol_node), (FuncBase, Decorator)): + # In theory we could construct a new node here as well, but in practice + # it doesn't work well, see #12197 + typ: Type | None = AnyType(TypeOfAny.from_error) + self.fail("Unsupported class scoped import", context) + else: + typ = f(symbol_node).type + symbol_node = Var(name, typ) + symbol_node._fullname = self.qualified_name(name) + assert self.type is not None # guaranteed by is_class_scope + symbol_node.info = self.type + symbol_node.line = context.line + symbol_node.column = context.column + return symbol_node + + def add_imported_symbol( + self, + name: str, + node: SymbolTableNode, + context: ImportBase, + module_public: bool, + module_hidden: bool, + ) -> None: + """Add an alias to an existing symbol through import.""" + assert not module_hidden or not module_public + + existing_symbol = self.lookup_current_scope(name) + if ( + existing_symbol + and not isinstance(existing_symbol.node, PlaceholderNode) + and not isinstance(node.node, PlaceholderNode) + ): + # Import can redefine a variable. They get special treatment. + if self.process_import_over_existing_name(name, existing_symbol, node, context): + return + + symbol_node: SymbolNode | None = node.node + + if self.is_class_scope(): + symbol_node = self._get_node_for_class_scoped_import(name, symbol_node, context) + + symbol = SymbolTableNode( + node.kind, symbol_node, module_public=module_public, module_hidden=module_hidden + ) + self.add_symbol_table_node(name, symbol, context) + + def add_unknown_imported_symbol( + self, + name: str, + context: Context, + target_name: str | None, + module_public: bool, + module_hidden: bool, + ) -> None: + """Add symbol that we don't know what it points to because resolving an import failed. + + This can happen if a module is missing, or it is present, but doesn't have + the imported attribute. The `target_name` is the name of symbol in the namespace + it is imported from. For example, for 'from mod import x as y' the target_name is + 'mod.x'. This is currently used only to track logical dependencies. + """ + existing = self.current_symbol_table().get(name) + if existing and isinstance(existing.node, Var) and existing.node.is_suppressed_import: + # This missing import was already added -- nothing to do here. + return + var = Var(name) + if self.options.logical_deps and target_name is not None: + # This makes it possible to add logical fine-grained dependencies + # from a missing module. We can't use this by default, since in a + # few places we assume that the full name points to a real + # definition, but this name may point to nothing. + var._fullname = target_name + elif self.type: + var._fullname = self.type.fullname + "." + name + var.info = self.type + else: + var._fullname = self.qualified_name(name) + var.is_ready = True + any_type = AnyType(TypeOfAny.from_unimported_type, missing_import_name=var._fullname) + var.type = any_type + var.is_suppressed_import = True + self.add_symbol( + name, var, context, module_public=module_public, module_hidden=module_hidden + ) + + # + # Other helpers + # + + @contextmanager + def tvar_scope_frame(self, frame: TypeVarLikeScope) -> Iterator[None]: + old_scope = self.tvar_scope + self.tvar_scope = frame + yield + self.tvar_scope = old_scope + + def defer(self, debug_context: Context | None = None, force_progress: bool = False) -> None: + """Defer current analysis target to be analyzed again. + + This must be called if something in the current target is + incomplete or has a placeholder node. However, this must *not* + be called during the final analysis iteration! Instead, an error + should be generated. Often 'process_placeholder' is a good + way to either defer or generate an error. + + NOTE: Some methods, such as 'anal_type', 'mark_incomplete' and + 'record_incomplete_ref', call this implicitly, or when needed. + They are usually preferable to a direct defer() call. + """ + assert not self.final_iteration, "Must not defer during final iteration" + if force_progress: + # Usually, we report progress if we have replaced a placeholder node + # with an actual valid node. However, sometimes we need to update an + # existing node *in-place*. For example, this is used by type aliases + # in context of forward references and/or recursive aliases, and in + # similar situations (recursive named tuples etc). + self.progress = True + self.deferred = True + # Store debug info for this deferral. + line = ( + debug_context.line if debug_context else self.statement.line if self.statement else -1 + ) + self.deferral_debug_context.append((self.cur_mod_id, line)) + + def track_incomplete_refs(self) -> Tag: + """Return tag that can be used for tracking references to incomplete names.""" + return self.num_incomplete_refs + + def found_incomplete_ref(self, tag: Tag) -> bool: + """Have we encountered an incomplete reference since starting tracking?""" + return self.num_incomplete_refs != tag + + def record_incomplete_ref(self) -> None: + """Record the encounter of an incomplete reference and defer current analysis target.""" + self.defer() + self.num_incomplete_refs += 1 + + def mark_incomplete( + self, + name: str, + node: Node, + becomes_typeinfo: bool = False, + module_public: bool = True, + module_hidden: bool = False, + ) -> None: + """Mark a definition as incomplete (and defer current analysis target). + + Also potentially mark the current namespace as incomplete. + + Args: + name: The name that we weren't able to define (or '*' if the name is unknown) + node: The node that refers to the name (definition or lvalue) + becomes_typeinfo: Pass this to PlaceholderNode (used by special forms like + named tuples that will create TypeInfos). + """ + self.defer(node) + if name == "*": + self.incomplete = True + elif not self.is_global_or_nonlocal(name): + fullname = self.qualified_name(name) + assert self.statement + placeholder = PlaceholderNode( + fullname, node, self.statement.line, becomes_typeinfo=becomes_typeinfo + ) + self.add_symbol( + name, + placeholder, + module_public=module_public, + module_hidden=module_hidden, + context=dummy_context(), + ) + self.missing_names[-1].add(name) + + def is_incomplete_namespace(self, fullname: str) -> bool: + """Is a module or class namespace potentially missing some definitions? + + If a name is missing from an incomplete namespace, we'll need to defer the + current analysis target. + """ + return fullname in self.incomplete_namespaces + + def process_placeholder( + self, name: str | None, kind: str, ctx: Context, force_progress: bool = False + ) -> None: + """Process a reference targeting placeholder node. + + If this is not a final iteration, defer current node, + otherwise report an error. + + The 'kind' argument indicates if this a name or attribute expression + (used for better error message). + """ + if self.final_iteration: + self.cannot_resolve_name(name, kind, ctx) + else: + self.defer(ctx, force_progress=force_progress) + + def cannot_resolve_name(self, name: str | None, kind: str, ctx: Context) -> None: + name_format = f' "{name}"' if name else "" + self.fail(f"Cannot resolve {kind}{name_format} (possible cyclic definition)", ctx) + if self.is_func_scope(): + self.note("Recursive types are not allowed at function scope", ctx) + + def qualified_name(self, name: str) -> str: + if self.type is not None: + return self.type._fullname + "." + name + elif self.is_func_scope(): + return name + else: + return self.cur_mod_id + "." + name + + @contextmanager + def enter( + self, function: FuncItem | GeneratorExpr | DictionaryComprehension + ) -> Iterator[None]: + """Enter a function, generator or comprehension scope.""" + names = self.saved_locals.setdefault(function, SymbolTable()) + self.locals.append(names) + is_comprehension = isinstance(function, (GeneratorExpr, DictionaryComprehension)) + self.scope_stack.append(SCOPE_FUNC if not is_comprehension else SCOPE_COMPREHENSION) + self.global_decls.append(set()) + self.nonlocal_decls.append(set()) + # -1 since entering block will increment this to 0. + self.block_depth.append(-1) + self.loop_depth.append(0) + self.missing_names.append(set()) + try: + yield + finally: + self.locals.pop() + self.scope_stack.pop() + self.global_decls.pop() + self.nonlocal_decls.pop() + self.block_depth.pop() + self.loop_depth.pop() + self.missing_names.pop() + + def is_func_scope(self) -> bool: + scope_type = self.scope_stack[-1] + if scope_type == SCOPE_ANNOTATION: + scope_type = self.scope_stack[-2] + return scope_type in (SCOPE_FUNC, SCOPE_COMPREHENSION) + + def is_nested_within_func_scope(self) -> bool: + """Are we underneath a function scope, even if we are in a nested class also?""" + return any(s in (SCOPE_FUNC, SCOPE_COMPREHENSION) for s in self.scope_stack) + + def is_class_scope(self) -> bool: + return self.type is not None and not self.is_func_scope() + + def is_module_scope(self) -> bool: + return not (self.is_class_scope() or self.is_func_scope()) + + def current_symbol_kind(self) -> int: + if self.is_class_scope(): + kind = MDEF + elif self.is_func_scope(): + kind = LDEF + else: + kind = GDEF + return kind + + def current_symbol_table( + self, escape_comprehensions: bool = False, type_param: bool = False + ) -> SymbolTable: + if type_param and self.scope_stack[-1] == SCOPE_ANNOTATION: + n = self.locals[-1] + assert n is not None + return n + elif self.is_func_scope(): + if self.scope_stack[-1] == SCOPE_ANNOTATION: + n = self.locals[-2] + else: + n = self.locals[-1] + assert n is not None + if escape_comprehensions: + assert len(self.locals) == len(self.scope_stack) + # Retrieve the symbol table from the enclosing non-comprehension scope. + for i, scope_type in enumerate(reversed(self.scope_stack)): + if scope_type != SCOPE_COMPREHENSION: + if i == len(self.locals) - 1: # The last iteration. + # The caller of the comprehension is in the global space. + names = self.globals + else: + names_candidate = self.locals[-1 - i] + assert ( + names_candidate is not None + ), "Escaping comprehension from invalid scope" + names = names_candidate + break + else: + assert False, "Should have at least one non-comprehension scope" + else: + names = n + assert names is not None + elif self.type is not None: + names = self.type.names + else: + names = self.globals + return names + + def is_global_or_nonlocal(self, name: str) -> bool: + return self.is_func_scope() and ( + name in self.global_decls[-1] or name in self.nonlocal_decls[-1] + ) + + def add_exports(self, exp_or_exps: Iterable[Expression] | Expression) -> None: + exps = [exp_or_exps] if isinstance(exp_or_exps, Expression) else exp_or_exps + for exp in exps: + if isinstance(exp, StrExpr): + self.all_exports.append(exp.value) + + def name_not_defined(self, name: str, ctx: Context, namespace: str | None = None) -> None: + incomplete = self.is_incomplete_namespace(namespace or self.cur_mod_id) + if ( + namespace is None + and self.type + and not self.is_func_scope() + and self.incomplete_type_stack + and self.incomplete_type_stack[-1] + and not self.final_iteration + ): + # We are processing a class body for the first time, so it is incomplete. + incomplete = True + if incomplete: + # Target namespace is incomplete, so it's possible that the name will be defined + # later on. Defer current target. + self.record_incomplete_ref() + return + message = f'Name "{name}" is not defined' + self.fail(message, ctx, code=codes.NAME_DEFINED) + + if f"builtins.{name}" in SUGGESTED_TEST_FIXTURES: + # The user probably has a missing definition in a test fixture. Let's verify. + fullname = f"builtins.{name}" + if self.lookup_fully_qualified_or_none(fullname) is None: + # Yes. Generate a helpful note. + self.msg.add_fixture_note(fullname, ctx) + + modules_with_unimported_hints = { + name.split(".", 1)[0] for name in TYPES_FOR_UNIMPORTED_HINTS + } + lowercased = {name.lower(): name for name in TYPES_FOR_UNIMPORTED_HINTS} + for module in modules_with_unimported_hints: + fullname = f"{module}.{name}".lower() + if fullname not in lowercased: + continue + # User probably forgot to import these types. + hint = ( + 'Did you forget to import it from "{module}"?' + ' (Suggestion: "from {module} import {name}")' + ).format(module=module, name=lowercased[fullname].rsplit(".", 1)[-1]) + self.note(hint, ctx, code=codes.NAME_DEFINED) + + def already_defined( + self, name: str, ctx: Context, original_ctx: SymbolTableNode | SymbolNode | None, noun: str + ) -> None: + if isinstance(original_ctx, SymbolTableNode): + node: SymbolNode | None = original_ctx.node + elif isinstance(original_ctx, SymbolNode): + node = original_ctx + else: + node = None + + if isinstance(original_ctx, SymbolTableNode) and isinstance(original_ctx.node, MypyFile): + # Since this is an import, original_ctx.node points to the module definition. + # Therefore, its line number is always 1, which is not useful for this + # error message. + extra_msg = " (by an import)" + elif node and node.line != -1 and self.is_local_name(node.fullname): + # TODO: Using previous symbol node may give wrong line. We should use + # the line number where the binding was established instead. + extra_msg = f" on line {node.line}" + else: + extra_msg = " (possibly by an import)" + self.fail( + f'{noun} "{unmangle(name)}" already defined{extra_msg}', ctx, code=codes.NO_REDEF + ) + + def name_already_defined( + self, name: str, ctx: Context, original_ctx: SymbolTableNode | SymbolNode | None = None + ) -> None: + self.already_defined(name, ctx, original_ctx, noun="Name") + + def attribute_already_defined( + self, name: str, ctx: Context, original_ctx: SymbolTableNode | SymbolNode | None = None + ) -> None: + self.already_defined(name, ctx, original_ctx, noun="Attribute") + + def is_local_name(self, name: str) -> bool: + """Does name look like reference to a definition in the current module?""" + return self.is_defined_in_current_module(name) or "." not in name + + def in_checked_function(self) -> bool: + """Should we type-check the current function? + + - Yes if --check-untyped-defs is set. + - Yes outside functions. + - Yes in annotated functions. + - No otherwise. + """ + if self.options.check_untyped_defs or not self.function_stack: + return True + + current_index = len(self.function_stack) - 1 + while current_index >= 0: + current_func = self.function_stack[current_index] + if not isinstance(current_func, LambdaExpr): + return not current_func.is_dynamic() + + # Special case, `lambda` inherits the "checked" state from its parent. + # Because `lambda` itself cannot be annotated. + # `lambdas` can be deeply nested, so we try to find at least one other parent. + current_index -= 1 + + # This means that we only have a stack of `lambda` functions, + # no regular functions. + return True + + def fail( + self, + msg: str | ErrorMessage, + ctx: Context, + serious: bool = False, + *, + code: ErrorCode | None = None, + blocker: bool = False, + ) -> None: + if not serious and not self.in_checked_function(): + return + # In case it's a bug and we don't really have context + assert ctx is not None, msg + if isinstance(msg, ErrorMessage): + if code is None: + code = msg.code + msg = msg.value + self.errors.report( + ctx.line, + ctx.column, + msg, + blocker=blocker, + code=code, + end_line=ctx.end_line, + end_column=ctx.end_column, + ) + + def note(self, msg: str, ctx: Context, code: ErrorCode | None = None) -> None: + if not self.in_checked_function(): + return + self.errors.report(ctx.line, ctx.column, msg, severity="note", code=code) + + def incomplete_feature_enabled(self, feature: str, ctx: Context) -> bool: + if feature not in self.options.enable_incomplete_feature: + self.fail( + f'"{feature}" support is experimental,' + f" use --enable-incomplete-feature={feature} to enable", + ctx, + ) + return False + return True + + def accept(self, node: Node) -> None: + try: + node.accept(self) + except Exception as err: + report_internal_error(err, self.errors.file, node.line, self.errors, self.options) + + def expr_to_analyzed_type( + self, + expr: Expression, + report_invalid_types: bool = True, + allow_placeholder: bool = False, + allow_type_any: bool = False, + allow_unbound_tvars: bool = False, + allow_param_spec_literals: bool = False, + allow_unpack: bool = False, + ) -> Type | None: + if isinstance(expr, CallExpr): + # This is a legacy syntax intended mostly for Python 2, we keep it for + # backwards compatibility, but new features like generic named tuples + # and recursive named tuples will be not supported. + expr.accept(self) + internal_name, info, tvar_defs = self.named_tuple_analyzer.check_namedtuple( + expr, None, self.is_func_scope() + ) + if tvar_defs: + self.fail("Generic named tuples are not supported for legacy class syntax", expr) + self.note("Use either Python 3 class syntax, or the assignment syntax", expr) + if internal_name is None: + # Some form of namedtuple is the only valid type that looks like a call + # expression. This isn't a valid type. + raise TypeTranslationError() + elif not info: + self.defer(expr) + return None + assert info.tuple_type, "NamedTuple without tuple type" + fallback = Instance(info, []) + return TupleType(info.tuple_type.items, fallback=fallback) + typ = self.expr_to_unanalyzed_type(expr) + return self.anal_type( + typ, + report_invalid_types=report_invalid_types, + allow_placeholder=allow_placeholder, + allow_type_any=allow_type_any, + allow_unbound_tvars=allow_unbound_tvars, + allow_param_spec_literals=allow_param_spec_literals, + allow_unpack=allow_unpack, + ) + + def analyze_type_expr(self, expr: Expression) -> None: + # There are certain expressions that mypy does not need to semantically analyze, + # since they analyzed solely as type. (For example, indexes in type alias definitions + # and base classes in class defs). External consumers of the mypy AST may need + # them semantically analyzed, however, if they need to treat it as an expression + # and not a type. (Which is to say, mypyc needs to do this.) Do the analysis + # in a fresh tvar scope in order to suppress any errors about using type variables. + with self.tvar_scope_frame(TypeVarLikeScope()), self.allow_unbound_tvars_set(): + expr.accept(self) + + def type_analyzer( + self, + *, + tvar_scope: TypeVarLikeScope | None = None, + allow_tuple_literal: bool = False, + allow_unbound_tvars: bool = False, + allow_placeholder: bool = False, + allow_typed_dict_special_forms: bool = False, + allow_final: bool = False, + allow_param_spec_literals: bool = False, + allow_unpack: bool = False, + report_invalid_types: bool = True, + prohibit_self_type: str | None = None, + prohibit_special_class_field_types: str | None = None, + allow_type_any: bool = False, + ) -> TypeAnalyser: + if tvar_scope is None: + tvar_scope = self.tvar_scope + tpan = TypeAnalyser( + self, + tvar_scope, + self.plugin, + self.options, + self.cur_mod_node, + self.is_typeshed_stub_file, + allow_unbound_tvars=allow_unbound_tvars, + allow_tuple_literal=allow_tuple_literal, + report_invalid_types=report_invalid_types, + allow_placeholder=allow_placeholder, + allow_typed_dict_special_forms=allow_typed_dict_special_forms, + allow_final=allow_final, + allow_param_spec_literals=allow_param_spec_literals, + allow_unpack=allow_unpack, + prohibit_self_type=prohibit_self_type, + prohibit_special_class_field_types=prohibit_special_class_field_types, + allow_type_any=allow_type_any, + ) + tpan.in_dynamic_func = bool(self.function_stack and self.function_stack[-1].is_dynamic()) + tpan.global_scope = not self.type and not self.function_stack + return tpan + + def expr_to_unanalyzed_type(self, node: Expression, allow_unpack: bool = False) -> ProperType: + return expr_to_unanalyzed_type( + node, self.options, self.is_stub_file, allow_unpack=allow_unpack + ) + + def anal_type( + self, + typ: Type, + *, + tvar_scope: TypeVarLikeScope | None = None, + allow_tuple_literal: bool = False, + allow_unbound_tvars: bool = False, + allow_placeholder: bool = False, + allow_typed_dict_special_forms: bool = False, + allow_final: bool = False, + allow_param_spec_literals: bool = False, + allow_unpack: bool = False, + report_invalid_types: bool = True, + prohibit_self_type: str | None = None, + prohibit_special_class_field_types: str | None = None, + allow_type_any: bool = False, + ) -> Type | None: + """Semantically analyze a type. + + Args: + typ: Type to analyze (if already analyzed, this is a no-op) + allow_placeholder: If True, may return PlaceholderType if + encountering an incomplete definition + + Return None only if some part of the type couldn't be bound *and* it + referred to an incomplete namespace or definition. In this case also + defer as needed. During a final iteration this won't return None; + instead report an error if the type can't be analyzed and return + AnyType. + + In case of other errors, report an error message and return AnyType. + + NOTE: The caller shouldn't defer even if this returns None or a + placeholder type. + """ + has_self_type = find_self_type( + typ, lambda name: self.lookup_qualified(name, typ, suppress_errors=True) + ) + if has_self_type and self.type and prohibit_self_type is None: + self.setup_self_type() + a = self.type_analyzer( + tvar_scope=tvar_scope, + allow_unbound_tvars=allow_unbound_tvars, + allow_tuple_literal=allow_tuple_literal, + allow_placeholder=allow_placeholder, + allow_typed_dict_special_forms=allow_typed_dict_special_forms, + allow_final=allow_final, + allow_param_spec_literals=allow_param_spec_literals, + allow_unpack=allow_unpack, + report_invalid_types=report_invalid_types, + prohibit_self_type=prohibit_self_type, + prohibit_special_class_field_types=prohibit_special_class_field_types, + allow_type_any=allow_type_any, + ) + tag = self.track_incomplete_refs() + typ = typ.accept(a) + if self.found_incomplete_ref(tag): + # Something could not be bound yet. + return None + self.add_type_alias_deps(a.aliases_used) + return typ + + def class_type(self, self_type: Type) -> Type: + return TypeType.make_normalized(self_type) + + def schedule_patch(self, priority: int, patch: Callable[[], None]) -> None: + self.patches.append((priority, patch)) + + def report_hang(self) -> None: + print("Deferral trace:") + for mod, line in self.deferral_debug_context: + print(f" {mod}:{line}") + self.errors.report( + -1, + -1, + "INTERNAL ERROR: maximum semantic analysis iteration count reached", + blocker=True, + ) + + def add_plugin_dependency(self, trigger: str, target: str | None = None) -> None: + """Add dependency from trigger to a target. + + If the target is not given explicitly, use the current target. + """ + if target is None: + target = self.scope.current_target() + self.cur_mod_node.plugin_deps.setdefault(trigger, set()).add(target) + + def add_type_alias_deps( + self, aliases_used: Collection[str], target: str | None = None + ) -> None: + """Add full names of type aliases on which the current node depends. + + This is used by fine-grained incremental mode to re-check the corresponding nodes. + If `target` is None, then the target node used will be the current scope. + """ + if not aliases_used: + return + if target is None: + target = self.scope.current_target() + self.cur_mod_node.alias_deps[target].update(aliases_used) + + def is_mangled_global(self, name: str) -> bool: + # A global is mangled if there exists at least one renamed variant. + return unmangle(name) + "'" in self.globals + + def is_initial_mangled_global(self, name: str) -> bool: + # If there are renamed definitions for a global, the first one has exactly one prime. + return name == unmangle(name) + "'" + + def parse_bool(self, expr: Expression) -> bool | None: + # This wrapper is preserved for plugins. + return parse_bool(expr) + + def parse_str_literal(self, expr: Expression) -> str | None: + """Attempt to find the string literal value of the given expression. Returns `None` if no + literal value can be found.""" + if isinstance(expr, StrExpr): + return expr.value + if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.type is not None: + values = try_getting_str_literals_from_type(expr.node.type) + if values is not None and len(values) == 1: + return values[0] + return None + + def set_future_import_flags(self, module_name: str) -> None: + if module_name in FUTURE_IMPORTS: + self.modules[self.cur_mod_id].future_import_flags.add(FUTURE_IMPORTS[module_name]) + + def is_future_flag_set(self, flag: str) -> bool: + return self.modules[self.cur_mod_id].is_future_flag_set(flag) + + def parse_dataclass_transform_spec(self, call: CallExpr) -> DataclassTransformSpec: + """Build a DataclassTransformSpec from the arguments passed to the given call to + typing.dataclass_transform.""" + parameters = DataclassTransformSpec() + for name, value in zip(call.arg_names, call.args): + # Skip any positional args. Note that any such args are invalid, but we can rely on + # typeshed to enforce this and don't need an additional error here. + if name is None: + continue + + # field_specifiers is currently the only non-boolean argument; check for it first so + # so the rest of the block can fail through to handling booleans + if name == "field_specifiers": + parameters.field_specifiers = self.parse_dataclass_transform_field_specifiers( + value + ) + continue + + boolean = require_bool_literal_argument(self, value, name) + if boolean is None: + continue + + if name == "eq_default": + parameters.eq_default = boolean + elif name == "order_default": + parameters.order_default = boolean + elif name == "kw_only_default": + parameters.kw_only_default = boolean + elif name == "frozen_default": + parameters.frozen_default = boolean + else: + self.fail(f'Unrecognized dataclass_transform parameter "{name}"', call) + + return parameters + + def parse_dataclass_transform_field_specifiers(self, arg: Expression) -> tuple[str, ...]: + if not isinstance(arg, TupleExpr): + self.fail('"field_specifiers" argument must be a tuple literal', arg) + return () + + names = [] + for specifier in arg.items: + if not isinstance(specifier, RefExpr): + self.fail('"field_specifiers" must only contain identifiers', specifier) + return () + names.append(specifier.fullname) + return tuple(names) + + # leafs + def visit_int_expr(self, o: IntExpr, /) -> None: + return None + + def visit_str_expr(self, o: StrExpr, /) -> None: + return None + + def visit_bytes_expr(self, o: BytesExpr, /) -> None: + return None + + def visit_float_expr(self, o: FloatExpr, /) -> None: + return None + + def visit_complex_expr(self, o: ComplexExpr, /) -> None: + return None + + def visit_ellipsis(self, o: EllipsisExpr, /) -> None: + return None + + def visit_temp_node(self, o: TempNode, /) -> None: + return None + + def visit_pass_stmt(self, o: PassStmt, /) -> None: + return None + + def visit_singleton_pattern(self, o: SingletonPattern, /) -> None: + return None + + def try_parse_as_type_expression(self, maybe_type_expr: Expression) -> None: + """Try to parse a value Expression as a type expression. + If success then annotate the Expression with the type that it spells. + If fails then emit no errors and take no further action. + + A value expression that is parsable as a type expression may be used + where a TypeForm is expected to represent the spelled type. + + Unlike ExpressionChecker.try_parse_as_type_expression() + (used in the later TypeChecker pass), this function can recognize + ALL kinds of type expressions, including type expressions containing + string annotations. + + If the provided Expression will be parsable later in + ExpressionChecker.try_parse_as_type_expression(), this function will + skip parsing the Expression to improve performance, because the later + function is called many fewer times (i.e. only lazily in a rare TypeForm + type context) than this function is called (i.e. eagerly for EVERY + expression in certain syntactic positions). + """ + # Count every call to this method for profiling + self.type_expression_parse_count += 1 + + # Bail ASAP if the Expression matches a common pattern that cannot possibly + # be a valid type expression, because this function is called very frequently + if not isinstance(maybe_type_expr, MaybeTypeExpression): + return + # Check types in order from most common to least common, for best performance + if isinstance(maybe_type_expr, (NameExpr, MemberExpr)): + # Defer parsing to the later TypeChecker pass, + # and only lazily in contexts where a TypeForm is expected + return + elif isinstance(maybe_type_expr, StrExpr): + str_value = maybe_type_expr.value # cache + # Filter out string literals with common patterns that could not + # possibly be in a type expression + if _MULTIPLE_WORDS_NONTYPE_RE.match(str_value): + # A common pattern in string literals containing a sentence. + # But cannot be a type expression. + maybe_type_expr.as_type = None + return + # Filter out string literals which look like an identifier but + # cannot be a type expression, for a few common reasons + if _IDENTIFIER_RE.fullmatch(str_value): + sym = self.lookup(str_value, UnboundType(str_value), suppress_errors=True) + if sym is None: + # Does not refer to anything in the local symbol table + maybe_type_expr.as_type = None + return + else: # sym is not None + node = sym.node # cache + if isinstance(node, PlaceholderNode) and not node.becomes_typeinfo: + # Either: + # 1. f'Cannot resolve name "{t.name}" (possible cyclic definition)' + # 2. Reference to an unknown placeholder node. + maybe_type_expr.as_type = None + return + unbound_tvar_or_paramspec = ( + isinstance(node, (TypeVarExpr, TypeVarTupleExpr, ParamSpecExpr)) + and self.tvar_scope.get_binding(sym) is None + ) + if unbound_tvar_or_paramspec: + # Either: + # 1. unbound_tvar: 'Type variable "{}" is unbound' [codes.VALID_TYPE] + # 2. unbound_paramspec: f'ParamSpec "{name}" is unbound' [codes.VALID_TYPE] + maybe_type_expr.as_type = None + return + else: # does not look like an identifier + if '"' in str_value or "'" in str_value: + # Only valid inside a Literal[...] type + if "[" not in str_value: + # Cannot be a Literal[...] type + maybe_type_expr.as_type = None + return + elif str_value == "": + # Empty string is not a valid type + maybe_type_expr.as_type = None + return + elif isinstance(maybe_type_expr, IndexExpr): + if isinstance(maybe_type_expr.base, NameExpr): + if isinstance( + maybe_type_expr.base.node, Var + ) and not self.var_is_typing_special_form(maybe_type_expr.base.node): + # Leftmost part of IndexExpr refers to a Var. Not a valid type. + maybe_type_expr.as_type = None + return + elif isinstance(maybe_type_expr.base, MemberExpr): + next_leftmost = maybe_type_expr.base + while True: + leftmost = next_leftmost.expr + if not isinstance(leftmost, MemberExpr): + break + next_leftmost = leftmost + if isinstance(leftmost, NameExpr): + if isinstance(leftmost.node, Var) and not self.var_is_typing_special_form( + leftmost.node + ): + # Leftmost part of IndexExpr refers to a Var. Not a valid type. + maybe_type_expr.as_type = None + return + else: + # Leftmost part of IndexExpr is not a NameExpr. Not a valid type. + maybe_type_expr.as_type = None + return + else: + # IndexExpr base is neither a NameExpr nor MemberExpr. Not a valid type. + maybe_type_expr.as_type = None + return + elif isinstance(maybe_type_expr, OpExpr): + if maybe_type_expr.op != "|": + # Binary operators other than '|' never spell a valid type + maybe_type_expr.as_type = None + return + else: + assert_never(maybe_type_expr) + + with self.isolated_error_analysis(): + try: + t = self.expr_to_analyzed_type(maybe_type_expr) + if self.errors.is_errors(): + t = None + except TypeTranslationError: + # Not a type expression + t = None + + if DEBUG_TYPE_EXPRESSION_FULL_PARSE_FAILURES and t is None: + original_flushed_files = set(self.errors.flushed_files) # save + try: + errors = self.errors.new_messages() # capture + finally: + self.errors.flushed_files = original_flushed_files # restore + + print( + f"SA.try_parse_as_type_expression: Full parse failure: {maybe_type_expr}, errors={errors!r}" + ) + + # Count full parse attempts for profiling + if t is not None: + self.type_expression_full_parse_success_count += 1 + else: + self.type_expression_full_parse_failure_count += 1 + + maybe_type_expr.as_type = t + + @staticmethod + def var_is_typing_special_form(var: Var) -> bool: + return var.fullname.startswith("typing") and var.fullname in [ + "typing.Annotated", + "typing_extensions.Annotated", + "typing.Callable", + "typing.Literal", + "typing_extensions.Literal", + "typing.Optional", + "typing.TypeGuard", + "typing_extensions.TypeGuard", + "typing.TypeIs", + "typing_extensions.TypeIs", + "typing.Union", + ] + + @contextmanager + def isolated_error_analysis(self) -> Iterator[None]: + """ + Context manager for performing error analysis that should not + affect the main SemanticAnalyzer state. + + Upon entering this context, `self.errors` will start empty. + Within this context, you can analyze expressions for errors. + Upon exiting this context, the original `self.errors` will be restored, + and any errors collected during the analysis will be discarded. + """ + # Save state + original_errors = self.errors + original_num_incomplete_refs = self.num_incomplete_refs + original_progress = self.progress + original_deferred = self.deferred + original_deferral_debug_context_len = len(self.deferral_debug_context) + + self.errors = Errors(Options()) + try: + yield + finally: + # Restore state + self.errors = original_errors + self.num_incomplete_refs = original_num_incomplete_refs + self.progress = original_progress + self.deferred = original_deferred + del self.deferral_debug_context[original_deferral_debug_context_len:] + + +def replace_implicit_first_type(sig: FunctionLike, new: Type) -> FunctionLike: + if isinstance(sig, CallableType): + if len(sig.arg_types) == 0: + return sig + return sig.copy_modified(arg_types=[new] + sig.arg_types[1:]) + elif isinstance(sig, Overloaded): + return Overloaded( + [cast(CallableType, replace_implicit_first_type(i, new)) for i in sig.items] + ) + else: + assert False + + +def refers_to_fullname(node: Expression, fullnames: str | tuple[str, ...]) -> bool: + """Is node a name or member expression with the given full name?""" + if not isinstance(fullnames, tuple): + fullnames = (fullnames,) + + if not isinstance(node, RefExpr): + return False + if node.fullname in fullnames: + return True + if isinstance(node.node, TypeAlias) and not node.node.python_3_12_type_alias: + return is_named_instance(node.node.target, fullnames) + return False + + +def refers_to_class_or_function(node: Expression) -> bool: + """Does semantically analyzed node refer to a class?""" + return isinstance(node, RefExpr) and isinstance( + node.node, (TypeInfo, FuncDef, OverloadedFuncDef) + ) + + +def find_duplicate(list: list[T]) -> T | None: + """If the list has duplicates, return one of the duplicates. + + Otherwise, return None. + """ + for i in range(1, len(list)): + if list[i] in list[:i]: + return list[i] + return None + + +def remove_imported_names_from_symtable(names: SymbolTable, module: str) -> None: + """Remove all imported names from the symbol table of a module.""" + removed: list[str] = [] + for name, node in names.items(): + if node.node is None: + continue + fullname = node.node.fullname + prefix = fullname[: fullname.rfind(".")] + if prefix != module: + removed.append(name) + for name in removed: + del names[name] + + +def make_any_non_explicit(t: Type) -> Type: + """Replace all Any types within in with Any that has attribute 'explicit' set to False""" + return t.accept(MakeAnyNonExplicit()) + + +class MakeAnyNonExplicit(TrivialSyntheticTypeTranslator): + def visit_any(self, t: AnyType) -> Type: + if t.type_of_any == TypeOfAny.explicit: + return t.copy_modified(TypeOfAny.special_form) + return t + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + return t.copy_modified(args=[a.accept(self) for a in t.args]) + + +def make_any_non_unimported(t: Type) -> Type: + """Replace all Any types that come from unimported types with special form Any.""" + return t.accept(MakeAnyNonUnimported()) + + +class MakeAnyNonUnimported(TrivialSyntheticTypeTranslator): + def visit_any(self, t: AnyType) -> Type: + if t.type_of_any == TypeOfAny.from_unimported_type: + return t.copy_modified(TypeOfAny.special_form, missing_import_name=None) + return t + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + return t.copy_modified(args=[a.accept(self) for a in t.args]) + + +def apply_semantic_analyzer_patches(patches: list[tuple[int, Callable[[], None]]]) -> None: + """Call patch callbacks in the right order. + + This should happen after semantic analyzer pass 3. + """ + patches_by_priority = sorted(patches, key=lambda x: x[0]) + for priority, patch_func in patches_by_priority: + patch_func() + + +def names_modified_by_assignment(s: AssignmentStmt) -> list[NameExpr]: + """Return all unqualified (short) names assigned to in an assignment statement.""" + result: list[NameExpr] = [] + for lvalue in s.lvalues: + result += names_modified_in_lvalue(lvalue) + return result + + +def names_modified_in_lvalue(lvalue: Lvalue) -> list[NameExpr]: + """Return all NameExpr assignment targets in an Lvalue.""" + if isinstance(lvalue, NameExpr): + return [lvalue] + elif isinstance(lvalue, StarExpr): + return names_modified_in_lvalue(lvalue.expr) + elif isinstance(lvalue, (ListExpr, TupleExpr)): + result: list[NameExpr] = [] + for item in lvalue.items: + result += names_modified_in_lvalue(item) + return result + return [] + + +def is_same_var_from_getattr(n1: SymbolNode | None, n2: SymbolNode | None) -> bool: + """Do n1 and n2 refer to the same Var derived from module-level __getattr__?""" + return ( + isinstance(n1, Var) + and n1.from_module_getattr + and isinstance(n2, Var) + and n2.from_module_getattr + and n1.fullname == n2.fullname + ) + + +def dummy_context() -> Context: + return TempNode(AnyType(TypeOfAny.special_form)) + + +def is_valid_replacement(old: SymbolTableNode, new: SymbolTableNode) -> bool: + """Can symbol table node replace an existing one? + + These are the only valid cases: + + 1. Placeholder gets replaced with a non-placeholder + 2. Placeholder that isn't known to become type replaced with a + placeholder that can become a type + """ + if isinstance(old.node, PlaceholderNode): + if isinstance(new.node, PlaceholderNode): + return not old.node.becomes_typeinfo and new.node.becomes_typeinfo + else: + return True + return False + + +def is_same_symbol(a: SymbolNode | None, b: SymbolNode | None) -> bool: + return ( + a == b + or (isinstance(a, PlaceholderNode) and isinstance(b, PlaceholderNode)) + or is_same_var_from_getattr(a, b) + ) + + +def is_trivial_body(block: Block) -> bool: + """Returns 'true' if the given body is "trivial" -- if it contains just a "pass", + "..." (ellipsis), or "raise NotImplementedError()". A trivial body may also + start with a statement containing just a string (e.g. a docstring). + + Note: Functions that raise other kinds of exceptions do not count as + "trivial". We use this function to help us determine when it's ok to + relax certain checks on body, but functions that raise arbitrary exceptions + are more likely to do non-trivial work. For example: + + def halt(self, reason: str = ...) -> NoReturn: + raise MyCustomError("Fatal error: " + reason, self.line, self.context) + + A function that raises just NotImplementedError is much less likely to be + this complex. + + Note: If you update this, you may also need to update + mypy.fastparse.is_possible_trivial_body! + """ + body = block.body + if not body: + # Functions have empty bodies only if the body is stripped or the function is + # generated or deserialized. In these cases the body is unknown. + return False + + # Skip a docstring + if isinstance(body[0], ExpressionStmt) and isinstance(body[0].expr, StrExpr): + body = block.body[1:] + + if len(body) == 0: + # There's only a docstring (or no body at all). + return True + elif len(body) > 1: + return False + + stmt = body[0] + + if isinstance(stmt, RaiseStmt): + expr = stmt.expr + if expr is None: + return False + if isinstance(expr, CallExpr): + expr = expr.callee + + return isinstance(expr, NameExpr) and expr.fullname == "builtins.NotImplementedError" + + return isinstance(stmt, PassStmt) or ( + isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr) + ) + + +def is_init_only(node: Var) -> bool: + return ( + isinstance(type := get_proper_type(node.type), Instance) + and type.type.fullname == "dataclasses.InitVar" + ) + + +def erase_func_annotations(func: FuncDef) -> None: + func.type_args = None + for arg in func.arguments: + arg.type_annotation = None + arg.variable.type = None + func.type = None + func.unanalyzed_type = None diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_classprop.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/semanal_classprop.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..5d8f2371df37c3f404f6926d7d90cd0395ea3215 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/semanal_classprop.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_classprop.py b/micromamba_root/Lib/site-packages/mypy/semanal_classprop.py new file mode 100644 index 0000000000000000000000000000000000000000..c5ad34122f6c84330b6c1c5b966c2c80d3686dfc --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/semanal_classprop.py @@ -0,0 +1,188 @@ +"""Calculate some properties of classes. + +These happen after semantic analysis and before type checking. +""" + +from __future__ import annotations + +from typing import Final + +from mypy.errors import Errors +from mypy.nodes import ( + IMPLICITLY_ABSTRACT, + IS_ABSTRACT, + CallExpr, + Decorator, + FuncDef, + Node, + OverloadedFuncDef, + PromoteExpr, + SymbolTable, + TypeInfo, + Var, +) +from mypy.options import Options +from mypy.types import MYPYC_NATIVE_INT_NAMES, Instance, ProperType + +# Hard coded type promotions (shared between all Python versions). +# These add extra ad-hoc edges to the subtyping relation. For example, +# int is considered a subtype of float, even though there is no +# subclass relationship. +# Note that the bytearray -> bytes promotion is a little unsafe +# as some functions only accept bytes objects. Here convenience +# trumps safety. +TYPE_PROMOTIONS: Final = { + "builtins.int": "float", + "builtins.float": "complex", + "builtins.bytearray": "bytes", + "builtins.memoryview": "bytes", +} + + +def calculate_class_abstract_status(typ: TypeInfo, is_stub_file: bool, errors: Errors) -> None: + """Calculate abstract status of a class. + + Set is_abstract of the type to True if the type has an unimplemented + abstract attribute. Also compute a list of abstract attributes. + Report error is required ABCMeta metaclass is missing. + """ + typ.is_abstract = False + typ.abstract_attributes = [] + if typ.typeddict_type: + return # TypedDict can't be abstract + concrete: set[str] = set() + # List of abstract attributes together with their abstract status + abstract: list[tuple[str, int]] = [] + abstract_in_this_class: list[str] = [] + if typ.is_newtype: + # Special case: NewTypes are considered as always non-abstract, so they can be used as: + # Config = NewType('Config', Mapping[str, str]) + # default = Config({'cannot': 'modify'}) # OK + return + for base in typ.mro: + for name, symnode in base.names.items(): + node = symnode.node + if isinstance(node, OverloadedFuncDef): + # Unwrap an overloaded function definition. We can just + # check arbitrarily the first overload item. If the + # different items have a different abstract status, there + # should be an error reported elsewhere. + if node.items: # can be empty for invalid overloads + func: Node | None = node.items[0] + else: + func = None + else: + func = node + if isinstance(func, Decorator): + func = func.func + if isinstance(func, FuncDef): + if ( + func.abstract_status in (IS_ABSTRACT, IMPLICITLY_ABSTRACT) + and name not in concrete + ): + typ.is_abstract = True + abstract.append((name, func.abstract_status)) + if base is typ: + abstract_in_this_class.append(name) + elif isinstance(node, Var): + if node.is_abstract_var and name not in concrete: + typ.is_abstract = True + abstract.append((name, IS_ABSTRACT)) + if base is typ: + abstract_in_this_class.append(name) + concrete.add(name) + # In stubs, abstract classes need to be explicitly marked because it is too + # easy to accidentally leave a concrete class abstract by forgetting to + # implement some methods. + typ.abstract_attributes = sorted(abstract) + if is_stub_file: + if typ.declared_metaclass and typ.declared_metaclass.type.has_base("abc.ABCMeta"): + return + if typ.is_protocol: + return + if abstract and not abstract_in_this_class: + + def report(message: str, severity: str) -> None: + errors.report(typ.line, typ.column, message, severity=severity) + + attrs = ", ".join(f'"{attr}"' for attr, _ in sorted(abstract)) + report(f"Class {typ.fullname} has abstract attributes {attrs}", "error") + report( + "If it is meant to be abstract, add 'abc.ABCMeta' as an explicit metaclass", "note" + ) + if typ.is_final and abstract: + attrs = ", ".join(f'"{attr}"' for attr, _ in sorted(abstract)) + errors.report( + typ.line, typ.column, f"Final class {typ.fullname} has abstract attributes {attrs}" + ) + + +def check_protocol_status(info: TypeInfo, errors: Errors) -> None: + """Check that all classes in MRO of a protocol are protocols""" + if info.is_protocol: + for type in info.bases: + if not type.type.is_protocol and type.type.fullname != "builtins.object": + errors.report( + info.line, + info.column, + "All bases of a protocol must be protocols", + severity="error", + ) + + +def calculate_class_vars(info: TypeInfo) -> None: + """Try to infer additional class variables. + + Subclass attribute assignments with no type annotation are assumed + to be classvar if overriding a declared classvar from the base + class. + + This must happen after the main semantic analysis pass, since + this depends on base class bodies having been fully analyzed. + """ + for name, sym in info.names.items(): + node = sym.node + if isinstance(node, Var) and node.info and node.is_inferred and not node.is_classvar: + for base in info.mro[1:]: + member = base.names.get(name) + if member is not None and isinstance(member.node, Var) and member.node.is_classvar: + node.is_classvar = True + + +def add_type_promotion( + info: TypeInfo, module_names: SymbolTable, options: Options, builtin_names: SymbolTable +) -> None: + """Setup extra, ad-hoc subtyping relationships between classes (promotion). + + This includes things like 'int' being compatible with 'float'. + """ + defn = info.defn + promote_targets: list[ProperType] = [] + for decorator in defn.decorators: + if isinstance(decorator, CallExpr): + analyzed = decorator.analyzed + if isinstance(analyzed, PromoteExpr): + # _promote class decorator (undocumented feature). + promote_targets.append(analyzed.type) + if not promote_targets: + if defn.fullname in TYPE_PROMOTIONS: + target_sym = module_names.get(TYPE_PROMOTIONS[defn.fullname]) + if defn.fullname == "builtins.bytearray" and options.disable_bytearray_promotion: + target_sym = None + elif defn.fullname == "builtins.memoryview" and options.disable_memoryview_promotion: + target_sym = None + # With test stubs, the target may not exist. + if target_sym: + target_info = target_sym.node + assert isinstance(target_info, TypeInfo) + promote_targets.append(Instance(target_info, [])) + # Special case the promotions between 'int' and native integer types. + # These have promotions going both ways, such as from 'int' to 'i64' + # and 'i64' to 'int', for convenience. + if defn.fullname in MYPYC_NATIVE_INT_NAMES: + int_sym = builtin_names["int"] + assert isinstance(int_sym.node, TypeInfo) + int_sym.node._promote.append(Instance(defn.info, [])) + defn.info.alt_promote = Instance(int_sym.node, []) + if promote_targets: + defn.info._promote.extend(promote_targets) diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_enum.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/semanal_enum.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ca0c9ece192a1a87841e0967b614cc42b7c624e7 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/semanal_enum.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_enum.py b/micromamba_root/Lib/site-packages/mypy/semanal_enum.py new file mode 100644 index 0000000000000000000000000000000000000000..b1e267b4c781f7ae4173b0f83b598e86045b8f64 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/semanal_enum.py @@ -0,0 +1,269 @@ +"""Semantic analysis of call-based Enum definitions. + +This is conceptually part of mypy.semanal (semantic analyzer pass 2). +""" + +from __future__ import annotations + +from typing import Final, cast + +from mypy.nodes import ( + ARG_NAMED, + ARG_POS, + EXCLUDED_ENUM_ATTRIBUTES, + MDEF, + AssignmentStmt, + CallExpr, + Context, + DictExpr, + EnumCallExpr, + Expression, + ListExpr, + MemberExpr, + NameExpr, + RefExpr, + StrExpr, + SymbolTableNode, + TupleExpr, + TypeInfo, + Var, + is_StrExpr_list, +) +from mypy.options import Options +from mypy.semanal_shared import SemanticAnalyzerInterface +from mypy.types import LiteralType, get_proper_type + +# Note: 'enum.EnumMeta' is deliberately excluded from this list. Classes that directly use +# enum.EnumMeta do not necessarily automatically have the 'name' and 'value' attributes. +ENUM_BASES: Final = frozenset( + ("enum.Enum", "enum.IntEnum", "enum.Flag", "enum.IntFlag", "enum.StrEnum") +) +ENUM_SPECIAL_PROPS: Final = frozenset( + ( + "name", + "value", + "_name_", + "_value_", + *EXCLUDED_ENUM_ATTRIBUTES, + # Also attributes from `object`: + "__module__", + "__annotations__", + "__doc__", + "__slots__", + "__dict__", + ) +) + + +class EnumCallAnalyzer: + def __init__(self, options: Options, api: SemanticAnalyzerInterface) -> None: + self.options = options + self.api = api + + def process_enum_call(self, s: AssignmentStmt, is_func_scope: bool) -> bool: + """Check if s defines an Enum; if yes, store the definition in symbol table. + + Return True if this looks like an Enum definition (but maybe with errors), + otherwise return False. + """ + if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], (NameExpr, MemberExpr)): + return False + lvalue = s.lvalues[0] + name = lvalue.name + enum_call = self.check_enum_call(s.rvalue, name, is_func_scope) + if enum_call is None: + return False + if isinstance(lvalue, MemberExpr): + self.fail("Enum type as attribute is not supported", lvalue) + return False + # Yes, it's a valid Enum definition. Add it to the symbol table. + self.api.add_symbol(name, enum_call, s) + return True + + def check_enum_call( + self, node: Expression, var_name: str, is_func_scope: bool + ) -> TypeInfo | None: + """Check if a call defines an Enum. + + Example: + + A = enum.Enum('A', 'foo bar') + + is equivalent to: + + class A(enum.Enum): + foo = 1 + bar = 2 + """ + if not isinstance(node, CallExpr): + return None + call = node + callee = call.callee + if not isinstance(callee, RefExpr): + return None + fullname = callee.fullname + if fullname not in ENUM_BASES: + return None + + new_class_name, items, values, ok = self.parse_enum_call_args( + call, fullname.split(".")[-1] + ) + if not ok: + # Error. Construct dummy return value. + name = var_name + if is_func_scope: + name += "@" + str(call.line) + info = self.build_enum_call_typeinfo(name, [], fullname, node.line) + else: + if new_class_name != var_name: + msg = f'String argument 1 "{new_class_name}" to {fullname}(...) does not match variable name "{var_name}"' + self.fail(msg, call) + + name = cast(StrExpr, call.args[0]).value + if name != var_name or is_func_scope: + # Give it a unique name derived from the line number. + name += "@" + str(call.line) + info = self.build_enum_call_typeinfo(name, items, fullname, call.line) + # Store generated TypeInfo under both names, see semanal_namedtuple for more details. + if name != var_name or is_func_scope: + self.api.add_symbol_skip_local(name, info) + call.analyzed = EnumCallExpr(info, items, values) + call.analyzed.set_line(call) + info.line = node.line + return info + + def build_enum_call_typeinfo( + self, name: str, items: list[str], fullname: str, line: int + ) -> TypeInfo: + base = self.api.named_type_or_none(fullname) + assert base is not None + info = self.api.basic_new_typeinfo(name, base, line) + info.metaclass_type = info.calculate_metaclass_type() + info.is_enum = True + for item in items: + var = Var(item) + var.info = info + var.is_property = True + # When an enum is created by its functional form `Enum(name, values)` + # - if it is a string it is first split by commas/whitespace + # - if it is an iterable of single items each item is assigned a value starting at `start` + # - if it is an iterable of (name, value) then the given values will be used + # either way, each item should be treated as if it has an explicit value. + var.has_explicit_value = True + var._fullname = f"{info.fullname}.{item}" + info.names[item] = SymbolTableNode(MDEF, var) + return info + + def parse_enum_call_args( + self, call: CallExpr, class_name: str + ) -> tuple[str, list[str], list[Expression | None], bool]: + """Parse arguments of an Enum call. + + Return a tuple of fields, values, was there an error. + """ + args = call.args + if not all(arg_kind in [ARG_POS, ARG_NAMED] for arg_kind in call.arg_kinds): + return self.fail_enum_call_arg(f"Unexpected arguments to {class_name}()", call) + if len(args) < 2: + return self.fail_enum_call_arg(f"Too few arguments for {class_name}()", call) + if len(args) > 6: + return self.fail_enum_call_arg(f"Too many arguments for {class_name}()", call) + valid_name = [None, "value", "names", "module", "qualname", "type", "start"] + for arg_name in call.arg_names: + if arg_name not in valid_name: + self.fail_enum_call_arg(f'Unexpected keyword argument "{arg_name}"', call) + value, names = None, None + for arg_name, arg in zip(call.arg_names, args): + if arg_name == "value": + value = arg + if arg_name == "names": + names = arg + if value is None: + value = args[0] + if names is None: + names = args[1] + if not isinstance(value, StrExpr): + return self.fail_enum_call_arg( + f"{class_name}() expects a string literal as the first argument", call + ) + new_class_name = value.value + + items = [] + values: list[Expression | None] = [] + if isinstance(names, StrExpr): + fields = names.value + for field in fields.replace(",", " ").split(): + items.append(field) + elif isinstance(names, (TupleExpr, ListExpr)): + seq_items = names.items + if is_StrExpr_list(seq_items): + items = [seq_item.value for seq_item in seq_items] + elif all( + isinstance(seq_item, (TupleExpr, ListExpr)) + and len(seq_item.items) == 2 + and isinstance(seq_item.items[0], StrExpr) + for seq_item in seq_items + ): + for seq_item in seq_items: + assert isinstance(seq_item, (TupleExpr, ListExpr)) + name, value = seq_item.items + assert isinstance(name, StrExpr) + items.append(name.value) + values.append(value) + else: + return self.fail_enum_call_arg( + "%s() with tuple or list expects strings or (name, value) pairs" % class_name, + call, + ) + elif isinstance(names, DictExpr): + for key, value in names.items: + if not isinstance(key, StrExpr): + return self.fail_enum_call_arg( + f"{class_name}() with dict literal requires string literals", call + ) + items.append(key.value) + values.append(value) + elif isinstance(args[1], RefExpr) and isinstance(args[1].node, Var): + proper_type = get_proper_type(args[1].node.type) + if ( + proper_type is not None + and isinstance(proper_type, LiteralType) + and isinstance(proper_type.value, str) + ): + fields = proper_type.value + for field in fields.replace(",", " ").split(): + items.append(field) + elif args[1].node.is_final and isinstance(args[1].node.final_value, str): + fields = args[1].node.final_value + for field in fields.replace(",", " ").split(): + items.append(field) + else: + return self.fail_enum_call_arg( + "Second argument of %s() must be string, tuple, list or dict literal for mypy to determine Enum members" + % class_name, + call, + ) + else: + # TODO: Allow dict(x=1, y=2) as a substitute for {'x': 1, 'y': 2}? + return self.fail_enum_call_arg( + "Second argument of %s() must be string, tuple, list or dict literal for mypy to determine Enum members" + % class_name, + call, + ) + if not items: + return self.fail_enum_call_arg(f"{class_name}() needs at least one item", call) + if not values: + values = [None] * len(items) + assert len(items) == len(values) + return new_class_name, items, values, True + + def fail_enum_call_arg( + self, message: str, context: Context + ) -> tuple[str, list[str], list[Expression | None], bool]: + self.fail(message, context) + return "", [], [], False + + # Helpers + + def fail(self, msg: str, ctx: Context) -> None: + self.api.fail(msg, ctx) diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_infer.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/semanal_infer.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..928c14fe2661cf07bb558c94a71f5816d7758875 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/semanal_infer.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_infer.py b/micromamba_root/Lib/site-packages/mypy/semanal_infer.py new file mode 100644 index 0000000000000000000000000000000000000000..89a073cdad473d89ebd3dff23321c91c2c3443d5 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/semanal_infer.py @@ -0,0 +1,131 @@ +"""Simple type inference for decorated functions during semantic analysis.""" + +from __future__ import annotations + +from mypy.nodes import ARG_POS, CallExpr, Decorator, Expression, FuncDef, RefExpr, Var +from mypy.semanal_shared import SemanticAnalyzerInterface +from mypy.typeops import function_type +from mypy.types import ( + AnyType, + CallableType, + ProperType, + Type, + TypeOfAny, + TypeVarType, + get_proper_type, +) +from mypy.typevars import has_no_typevars + + +def infer_decorator_signature_if_simple( + dec: Decorator, analyzer: SemanticAnalyzerInterface +) -> None: + """Try to infer the type of the decorated function. + + This lets us resolve additional references to decorated functions + during type checking. Otherwise the type might not be available + when we need it, since module top levels can't be deferred. + + This basically uses a simple special-purpose type inference + engine just for decorators. + """ + if dec.var.is_property: + # Decorators are expected to have a callable type (it's a little odd). + # TODO: this may result in wrong type if @property is applied to decorated method. + if dec.func.type is None: + dec.var.type = CallableType( + [AnyType(TypeOfAny.special_form)], + [ARG_POS], + [None], + AnyType(TypeOfAny.special_form), + analyzer.named_type("builtins.function"), + name=dec.var.name, + ) + elif isinstance(dec.func.type, CallableType): + dec.var.type = dec.func.type + return + decorator_preserves_type = True + for expr in dec.decorators: + preserve_type = False + if isinstance(expr, RefExpr) and isinstance(expr.node, FuncDef): + if expr.fullname == "typing.no_type_check": + return + if expr.node.type and is_identity_signature(expr.node.type): + preserve_type = True + if not preserve_type: + decorator_preserves_type = False + break + if decorator_preserves_type: + # No non-identity decorators left. We can trivially infer the type + # of the function here. + dec.var.type = function_type(dec.func, analyzer.named_type("builtins.function")) + if dec.decorators: + return_type = calculate_return_type(dec.decorators[0]) + if return_type and isinstance(return_type, AnyType): + # The outermost decorator will return Any so we know the type of the + # decorated function. + dec.var.type = AnyType(TypeOfAny.from_another_any, source_any=return_type) + sig = find_fixed_callable_return(dec.decorators[0]) + if sig: + # The outermost decorator always returns the same kind of function, + # so we know that this is the type of the decorated function. + orig_sig = function_type(dec.func, analyzer.named_type("builtins.function")) + sig.name = orig_sig.items[0].name + dec.var.type = sig + + +def is_identity_signature(sig: Type) -> bool: + """Is type a callable of form T -> T (where T is a type variable)?""" + sig = get_proper_type(sig) + if isinstance(sig, CallableType) and sig.arg_kinds == [ARG_POS]: + if isinstance(sig.arg_types[0], TypeVarType) and isinstance(sig.ret_type, TypeVarType): + return sig.arg_types[0].id == sig.ret_type.id + return False + + +def calculate_return_type(expr: Expression) -> ProperType | None: + """Return the return type if we can calculate it. + + This only uses information available during semantic analysis so this + will sometimes return None because of insufficient information (as + type inference hasn't run yet). + """ + if isinstance(expr, RefExpr): + if isinstance(expr.node, FuncDef): + typ = expr.node.type + if typ is None: + # No signature -> default to Any. + return AnyType(TypeOfAny.unannotated) + # Explicit Any return? + if isinstance(typ, CallableType): + return get_proper_type(typ.ret_type) + return None + elif isinstance(expr.node, Var): + return get_proper_type(expr.node.type) + elif isinstance(expr, CallExpr): + return calculate_return_type(expr.callee) + return None + + +def find_fixed_callable_return(expr: Expression) -> CallableType | None: + """Return the return type, if expression refers to a callable that returns a callable. + + But only do this if the return type has no type variables. Return None otherwise. + This approximates things a lot as this is supposed to be called before type checking + when full type information is not available yet. + """ + if isinstance(expr, RefExpr): + if isinstance(expr.node, FuncDef): + typ = expr.node.type + if typ: + if isinstance(typ, CallableType) and has_no_typevars(typ.ret_type): + ret_type = get_proper_type(typ.ret_type) + if isinstance(ret_type, CallableType): + return ret_type + elif isinstance(expr, CallExpr): + t = find_fixed_callable_return(expr.callee) + if t: + ret_type = get_proper_type(t.ret_type) + if isinstance(ret_type, CallableType): + return ret_type + return None diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_main.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/semanal_main.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..eef4334ecc8c91465bc1e84e81aa9641029d2495 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/semanal_main.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_main.py b/micromamba_root/Lib/site-packages/mypy/semanal_main.py new file mode 100644 index 0000000000000000000000000000000000000000..edc6ee4143f292e3fe2c09c357422effb0178421 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/semanal_main.py @@ -0,0 +1,538 @@ +"""Top-level logic for the semantic analyzer. + +The semantic analyzer binds names, resolves imports, detects various +special constructs that don't have dedicated AST nodes after parse +(such as 'cast' which looks like a call), populates symbol tables, and +performs various simple consistency checks. + +Semantic analysis of each SCC (strongly connected component; import +cycle) is performed in one unit. Each module is analyzed as multiple +separate *targets*; the module top level is one target and each function +is a target. Nested functions are not separate targets, however. This is +mostly identical to targets used by mypy daemon (but classes aren't +targets in semantic analysis). + +We first analyze each module top level in an SCC. If we encounter some +names that we can't bind because the target of the name may not have +been processed yet, we *defer* the current target for further +processing. Deferred targets will be analyzed additional times until +everything can be bound, or we reach a maximum number of iterations. + +We keep track of a set of incomplete namespaces, i.e. namespaces that we +haven't finished populating yet. References to these namespaces cause a +deferral if they can't be satisfied. Initially every module in the SCC +will be incomplete. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +from contextlib import nullcontext +from itertools import groupby +from typing import TYPE_CHECKING, Final, TypeAlias as _TypeAlias + +import mypy.state +from mypy.checker import FineGrainedDeferredNode +from mypy.errors import Errors +from mypy.nodes import Decorator, FuncDef, MypyFile, OverloadedFuncDef, TypeInfo +from mypy.options import Options +from mypy.plugin import ClassDefContext +from mypy.plugins import dataclasses as dataclasses_plugin +from mypy.semanal import ( + SemanticAnalyzer, + apply_semantic_analyzer_patches, + remove_imported_names_from_symtable, +) +from mypy.semanal_classprop import ( + add_type_promotion, + calculate_class_abstract_status, + calculate_class_vars, + check_protocol_status, +) +from mypy.semanal_infer import infer_decorator_signature_if_simple +from mypy.semanal_shared import find_dataclass_transform_spec +from mypy.semanal_typeargs import TypeArgumentAnalyzer + +if TYPE_CHECKING: + from mypy.build import Graph, State + + +Patches: _TypeAlias = list[tuple[int, Callable[[], None]]] + + +# If we perform this many iterations, raise an exception since we are likely stuck. +MAX_ITERATIONS: Final = 20 + + +# Number of passes over core modules before going on to the rest of the builtin SCC. +CORE_WARMUP: Final = 2 +core_modules: Final = [ + "typing", + "_collections_abc", + "builtins", + "abc", + "collections", + "collections.abc", +] + + +def semantic_analysis_for_scc(graph: Graph, scc: list[str], errors: Errors) -> None: + """Perform semantic analysis for all modules in a SCC (import cycle). + + Assume that reachability analysis has already been performed. + + The scc will be processed roughly in the order the modules are included + in the list. + """ + patches: Patches = [] + # Note that functions can't define new module-level attributes + # using 'global x', since module top levels are fully processed + # before functions. This limitation is unlikely to go away soon. + process_top_levels(graph, scc, patches) + process_functions(graph, scc, patches) + # We use patch callbacks to fix up things when we expect relatively few + # callbacks to be required. + apply_semantic_analyzer_patches(patches) + # Run class decorator hooks (they requite complete MROs and no placeholders). + apply_class_plugin_hooks(graph, scc, errors) + # This pass might need fallbacks calculated above and the results of hooks. + check_type_arguments(graph, scc, errors) + calculate_class_properties(graph, scc, errors) + check_blockers(graph, scc) + # Clean-up builtins, so that TypeVar etc. are not accessible without importing. + if "builtins" in scc: + cleanup_builtin_scc(graph["builtins"]) + + # Report TypeForm profiling stats + if len(scc) >= 1: + # Get manager from any state in the SCC (they all share the same manager) + manager = graph[scc[0]].manager + analyzer = manager.semantic_analyzer + manager.add_stats( + type_expression_parse_count=analyzer.type_expression_parse_count, + type_expression_full_parse_success_count=analyzer.type_expression_full_parse_success_count, + type_expression_full_parse_failure_count=analyzer.type_expression_full_parse_failure_count, + ) + + +def cleanup_builtin_scc(state: State) -> None: + """Remove imported names from builtins namespace. + + This way names imported from typing in builtins.pyi aren't available + by default (without importing them). We can only do this after processing + the whole SCC is finished, when the imported names aren't needed for + processing builtins.pyi itself. + """ + assert state.tree is not None + remove_imported_names_from_symtable(state.tree.names, "builtins") + + +def semantic_analysis_for_targets( + state: State, nodes: list[FineGrainedDeferredNode], graph: Graph +) -> None: + """Semantically analyze only selected nodes in a given module. + + This essentially mirrors the logic of semantic_analysis_for_scc() + except that we process only some targets. This is used in fine-grained + incremental mode, when propagating an update. + """ + patches: Patches = [] + if any(isinstance(n.node, MypyFile) for n in nodes): + # Process module top level first (if needed). + process_top_levels(graph, [state.id], patches) + analyzer = state.manager.semantic_analyzer + for n in nodes: + if isinstance(n.node, MypyFile): + # Already done above. + continue + process_top_level_function( + analyzer, state, state.id, n.node.fullname, n.node, n.active_typeinfo, patches + ) + apply_semantic_analyzer_patches(patches) + apply_class_plugin_hooks(graph, [state.id], state.manager.errors) + check_type_arguments_in_targets(nodes, state, state.manager.errors) + calculate_class_properties(graph, [state.id], state.manager.errors) + + +def process_top_levels(graph: Graph, scc: list[str], patches: Patches) -> None: + # Process top levels until everything has been bound. + + # Reverse order of the scc so the first modules in the original list will be + # be processed first. This helps with performance. + scc = list(reversed(scc)) # noqa: FURB187 intentional copy + + # Initialize ASTs and symbol tables. + for id in scc: + state = graph[id] + assert state.tree is not None + state.manager.semantic_analyzer.prepare_file(state.tree) + + # Initially all namespaces in the SCC are incomplete (well they are empty). + state.manager.incomplete_namespaces.update(scc) + + worklist = scc.copy() + # HACK: process core stuff first. This is mostly needed to support defining + # named tuples in builtin SCC. + if all(m in worklist for m in core_modules): + worklist += list(reversed(core_modules)) * CORE_WARMUP + final_iteration = False + iteration = 0 + analyzer = state.manager.semantic_analyzer + analyzer.deferral_debug_context.clear() + + while worklist: + iteration += 1 + if iteration > MAX_ITERATIONS: + # Just pick some module inside the current SCC for error context. + assert state.tree is not None + with analyzer.file_context(state.tree, state.options): + analyzer.report_hang() + break + if final_iteration: + # Give up. It's impossible to bind all names. + state.manager.incomplete_namespaces.clear() + all_deferred: list[str] = [] + any_progress = False + while worklist: + next_id = worklist.pop() + state = graph[next_id] + assert state.tree is not None + deferred, incomplete, progress = semantic_analyze_target( + next_id, next_id, state, state.tree, None, final_iteration, patches + ) + all_deferred += deferred + any_progress = any_progress or progress + if not incomplete: + state.manager.incomplete_namespaces.discard(next_id) + if final_iteration: + assert not all_deferred, "Must not defer during final iteration" + # Reverse to process the targets in the same order on every iteration. This avoids + # processing the same target twice in a row, which is inefficient. + worklist = list(reversed(all_deferred)) + final_iteration = not any_progress + # Functions/methods that define/infer attributes are processed as part of top-levels. + # We need to clear the locals for those between fine-grained iterations. + analyzer.saved_locals.clear() + + +def order_by_subclassing(targets: list[FullTargetInfo]) -> Iterator[FullTargetInfo]: + """Make sure that superclass methods are always processed before subclass methods. + + This algorithm is not very optimal, but it is simple and should work well for lists + that are already almost correctly ordered. + """ + + # First, group the targets by their TypeInfo (since targets are sorted by line, + # we know that each TypeInfo will appear as group key only once). + grouped = [(k, list(g)) for k, g in groupby(targets, key=lambda x: x[3])] + remaining_infos = {info for info, _ in grouped if info is not None} + + next_group = 0 + while grouped: + if next_group >= len(grouped): + # This should never happen, if there is an MRO cycle, it should be reported + # and fixed during top-level processing. + raise ValueError("Cannot order method targets by MRO") + next_info, group = grouped[next_group] + if next_info is None: + # Trivial case, not methods but functions, process them straight away. + yield from group + grouped.pop(next_group) + continue + if any(parent in remaining_infos for parent in next_info.mro[1:]): + # We cannot process this method group yet, try a next one. + next_group += 1 + continue + yield from group + grouped.pop(next_group) + remaining_infos.discard(next_info) + # Each time after processing a method group we should retry from start, + # since there may be some groups that are not blocked on parents anymore. + next_group = 0 + + +def process_functions(graph: Graph, scc: list[str], patches: Patches) -> None: + # Process functions. + all_targets = [] + for module in scc: + tree = graph[module].tree + assert tree is not None + # In principle, functions can be processed in arbitrary order, + # but _methods_ must be processed in the order they are defined, + # because some features (most notably partial types) depend on + # order of definitions on self. + # + # There can be multiple generated methods per line. Use target + # name as the second sort key to get a repeatable sort order. + targets = sorted(get_all_leaf_targets(tree), key=lambda x: (x[1].line, x[0])) + all_targets.extend( + [(module, target, node, active_type) for target, node, active_type in targets] + ) + + for module, target, node, active_type in order_by_subclassing(all_targets): + analyzer = graph[module].manager.semantic_analyzer + assert isinstance(node, (FuncDef, OverloadedFuncDef, Decorator)), node + process_top_level_function( + analyzer, graph[module], module, target, node, active_type, patches + ) + + +def process_top_level_function( + analyzer: SemanticAnalyzer, + state: State, + module: str, + target: str, + node: FuncDef | OverloadedFuncDef | Decorator, + active_type: TypeInfo | None, + patches: Patches, +) -> None: + """Analyze single top-level function or method. + + Process the body of the function (including nested functions) again and again, + until all names have been resolved (or iteration limit reached). + """ + # We need one more iteration after incomplete is False (e.g. to report errors, if any). + final_iteration = False + incomplete = True + # Start in the incomplete state (no missing names will be reported on first pass). + # Note that we use module name, since functions don't create qualified names. + deferred = [module] + analyzer.deferral_debug_context.clear() + analyzer.incomplete_namespaces.add(module) + iteration = 0 + while deferred: + iteration += 1 + if iteration == MAX_ITERATIONS: + # Just pick some module inside the current SCC for error context. + assert state.tree is not None + with analyzer.file_context(state.tree, state.options): + analyzer.report_hang() + break + if not (deferred or incomplete) or final_iteration: + # OK, this is one last pass, now missing names will be reported. + analyzer.incomplete_namespaces.discard(module) + deferred, incomplete, progress = semantic_analyze_target( + target, module, state, node, active_type, final_iteration, patches + ) + if not incomplete: + state.manager.incomplete_namespaces.discard(module) + if final_iteration: + assert not deferred, "Must not defer during final iteration" + if not progress: + final_iteration = True + + analyzer.incomplete_namespaces.discard(module) + # After semantic analysis is done, discard local namespaces + # to avoid memory hoarding. + analyzer.saved_locals.clear() + + +TargetInfo: _TypeAlias = tuple[ + str, MypyFile | FuncDef | OverloadedFuncDef | Decorator, TypeInfo | None +] + +# Same as above but includes module as first item. +FullTargetInfo: _TypeAlias = tuple[ + str, str, MypyFile | FuncDef | OverloadedFuncDef | Decorator, TypeInfo | None +] + + +def get_all_leaf_targets(file: MypyFile) -> list[TargetInfo]: + """Return all leaf targets in a symbol table (module-level and methods).""" + result: list[TargetInfo] = [] + for fullname, node, active_type in file.local_definitions(): + if isinstance(node.node, (FuncDef, OverloadedFuncDef, Decorator)): + result.append((fullname, node.node, active_type)) + return result + + +def semantic_analyze_target( + target: str, + module: str, + state: State, + node: MypyFile | FuncDef | OverloadedFuncDef | Decorator, + active_type: TypeInfo | None, + final_iteration: bool, + patches: Patches, +) -> tuple[list[str], bool, bool]: + """Semantically analyze a single target. + + Return tuple with these items: + - list of deferred targets + - was some definition incomplete (need to run another pass) + - were any new names defined (or placeholders replaced) + """ + state.manager.processed_targets.append((module, target)) + tree = state.tree + assert tree is not None + analyzer = state.manager.semantic_analyzer + # TODO: Move initialization to somewhere else + analyzer.global_decls = [set()] + analyzer.nonlocal_decls = [set()] + analyzer.globals = tree.names + analyzer.imports = set() + analyzer.progress = False + with state.wrap_context(check_blockers=False): + refresh_node = node + if isinstance(refresh_node, Decorator): + # Decorator expressions will be processed as part of the module top level. + refresh_node = refresh_node.func + analyzer.refresh_partial( + refresh_node, + patches, + final_iteration, + file_node=tree, + options=state.options, + active_type=active_type, + ) + if isinstance(node, Decorator): + infer_decorator_signature_if_simple(node, analyzer) + + # Clear out some stale data to avoid memory leaks and astmerge + # validity check confusion + analyzer.statement = None + del analyzer.cur_mod_node + + if analyzer.deferred: + return [target], analyzer.incomplete, analyzer.progress + else: + return [], analyzer.incomplete, analyzer.progress + + +def check_type_arguments(graph: Graph, scc: list[str], errors: Errors) -> None: + for module in scc: + state = graph[module] + assert state.tree + analyzer = TypeArgumentAnalyzer( + errors, + state.options, + state.tree.is_typeshed_file(state.options), + state.manager.semantic_analyzer.named_type, + ) + with state.wrap_context(): + with mypy.state.state.strict_optional_set(state.options.strict_optional): + state.tree.accept(analyzer) + + +def check_type_arguments_in_targets( + targets: list[FineGrainedDeferredNode], state: State, errors: Errors +) -> None: + """Check type arguments against type variable bounds and restrictions. + + This mirrors the logic in check_type_arguments() except that we process only + some targets. This is used in fine grained incremental mode. + """ + assert state.tree + analyzer = TypeArgumentAnalyzer( + errors, + state.options, + state.tree.is_typeshed_file(state.options), + state.manager.semantic_analyzer.named_type, + ) + with state.wrap_context(): + with mypy.state.state.strict_optional_set(state.options.strict_optional): + for target in targets: + func: FuncDef | OverloadedFuncDef | None = None + if isinstance(target.node, (FuncDef, OverloadedFuncDef)): + func = target.node + saved = (state.id, target.active_typeinfo, func) # module, class, function + with errors.scope.saved_scope(saved) if errors.scope else nullcontext(): + analyzer.recurse_into_functions = func is not None + target.node.accept(analyzer) + + +def apply_class_plugin_hooks(graph: Graph, scc: list[str], errors: Errors) -> None: + """Apply class plugin hooks within a SCC. + + We run these after to the main semantic analysis so that the hooks + don't need to deal with incomplete definitions such as placeholder + types. + + Note that some hooks incorrectly run during the main semantic + analysis pass, for historical reasons. + """ + num_passes = 0 + incomplete = True + # If we encounter a base class that has not been processed, we'll run another + # pass. This should eventually reach a fixed point. + while incomplete: + assert num_passes < 10, "Internal error: too many class plugin hook passes" + num_passes += 1 + incomplete = False + for module in scc: + state = graph[module] + tree = state.tree + assert tree + for _, node, _ in tree.local_definitions(): + if isinstance(node.node, TypeInfo): + if not apply_hooks_to_class( + state.manager.semantic_analyzer, + module, + node.node, + state.options, + tree, + errors, + ): + incomplete = True + + +def apply_hooks_to_class( + self: SemanticAnalyzer, + module: str, + info: TypeInfo, + options: Options, + file_node: MypyFile, + errors: Errors, +) -> bool: + # TODO: Move more class-related hooks here? + defn = info.defn + ok = True + for decorator in defn.decorators: + with self.file_context(file_node, options, info): + hook = None + + decorator_name = self.get_fullname_for_hook(decorator) + if decorator_name: + hook = self.plugin.get_class_decorator_hook_2(decorator_name) + # Special case: if the decorator is itself decorated with + # typing.dataclass_transform, apply the hook for the dataclasses plugin + # TODO: remove special casing here + if hook is None and find_dataclass_transform_spec(decorator): + hook = dataclasses_plugin.dataclass_class_maker_callback + + if hook: + ok = ok and hook(ClassDefContext(defn, decorator, self)) + + # Check if the class definition itself triggers a dataclass transform (via a parent class/ + # metaclass) + spec = find_dataclass_transform_spec(info) + if spec is not None: + with self.file_context(file_node, options, info): + # We can't use the normal hook because reason = defn, and ClassDefContext only accepts + # an Expression for reason + ok = ok and dataclasses_plugin.DataclassTransformer(defn, defn, spec, self).transform() + + return ok + + +def calculate_class_properties(graph: Graph, scc: list[str], errors: Errors) -> None: + builtins = graph["builtins"].tree + assert builtins + for module in scc: + state = graph[module] + tree = state.tree + assert tree + for _, node, _ in tree.local_definitions(): + if isinstance(node.node, TypeInfo): + with state.manager.semantic_analyzer.file_context(tree, state.options, node.node): + calculate_class_abstract_status(node.node, tree.is_stub, errors) + check_protocol_status(node.node, errors) + calculate_class_vars(node.node) + add_type_promotion( + node.node, tree.names, graph[module].options, builtins.names + ) + + +def check_blockers(graph: Graph, scc: list[str]) -> None: + for module in scc: + graph[module].check_blockers() diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_namedtuple.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/semanal_namedtuple.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..09d6dea082cf3f74cd8a332995664d1c20fd1e13 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/semanal_namedtuple.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_namedtuple.py b/micromamba_root/Lib/site-packages/mypy/semanal_namedtuple.py new file mode 100644 index 0000000000000000000000000000000000000000..9a51bced4885df9c46f2718929f0c1f94ca13478 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/semanal_namedtuple.py @@ -0,0 +1,726 @@ +"""Semantic analysis of named tuple definitions. + +This is conceptually part of mypy.semanal. +""" + +from __future__ import annotations + +import keyword +from collections.abc import Container, Iterator, Mapping +from contextlib import contextmanager +from typing import Final, cast + +from mypy.errorcodes import ARG_TYPE, ErrorCode +from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type +from mypy.messages import MessageBuilder +from mypy.nodes import ( + ARG_NAMED_OPT, + ARG_OPT, + ARG_POS, + MDEF, + Argument, + AssignmentStmt, + Block, + CallExpr, + ClassDef, + Context, + Decorator, + EllipsisExpr, + Expression, + ExpressionStmt, + FuncBase, + FuncDef, + ListExpr, + NamedTupleExpr, + NameExpr, + PassStmt, + PlaceholderNode, + RefExpr, + Statement, + StrExpr, + SymbolTable, + SymbolTableNode, + TempNode, + TupleExpr, + TypeInfo, + TypeVarExpr, + Var, + is_StrExpr_list, +) +from mypy.options import Options +from mypy.semanal_shared import ( + PRIORITY_FALLBACKS, + SemanticAnalyzerInterface, + calculate_tuple_fallback, + has_placeholder, + set_callable_name, +) +from mypy.types import ( + TYPED_NAMEDTUPLE_NAMES, + AnyType, + CallableType, + LiteralType, + TupleType, + Type, + TypeOfAny, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarType, + UnboundType, + has_type_vars, +) +from mypy.util import get_unique_redefinition_name + +# Matches "_prohibited" in typing.py, but adds __annotations__, which works at runtime but can't +# easily be supported in a static checker. +NAMEDTUPLE_PROHIBITED_NAMES: Final = ( + "__new__", + "__init__", + "__slots__", + "__getnewargs__", + "_fields", + "_field_defaults", + "_field_types", + "_make", + "_replace", + "_asdict", + "_source", + "__annotations__", +) + +NAMEDTUP_CLASS_ERROR: Final = ( + 'Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"' +) + +SELF_TVAR_NAME: Final = "_NT" + + +class NamedTupleAnalyzer: + def __init__( + self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder + ) -> None: + self.options = options + self.api = api + self.msg = msg + + def analyze_namedtuple_classdef( + self, defn: ClassDef, is_stub_file: bool, is_func_scope: bool + ) -> tuple[bool, TypeInfo | None]: + """Analyze if given class definition can be a named tuple definition. + + Return a tuple where first item indicates whether this can possibly be a named tuple, + and the second item is the corresponding TypeInfo (may be None if not ready and should be + deferred). + """ + for base_expr in defn.base_type_exprs: + if isinstance(base_expr, RefExpr): + self.api.accept(base_expr) + if base_expr.fullname in TYPED_NAMEDTUPLE_NAMES: + result = self.check_namedtuple_classdef(defn, is_stub_file) + if result is None: + # This is a valid named tuple, but some types are incomplete. + return True, None + items, types, default_items, statements = result + if is_func_scope and "@" not in defn.name: + defn.name += "@" + str(defn.line) + existing_info = None + if isinstance(defn.analyzed, NamedTupleExpr): + existing_info = defn.analyzed.info + info = self.build_namedtuple_typeinfo( + defn.name, items, types, default_items, defn.line, existing_info + ) + defn.analyzed = NamedTupleExpr(info, is_typed=True) + defn.analyzed.line = defn.line + defn.analyzed.column = defn.column + defn.defs.body = statements + # All done: this is a valid named tuple with all types known. + return True, info + # This can't be a valid named tuple. + return False, None + + def check_namedtuple_classdef( + self, defn: ClassDef, is_stub_file: bool + ) -> tuple[list[str], list[Type], dict[str, Expression], list[Statement]] | None: + """Parse and validate fields in named tuple class definition. + + Return a four tuple: + * field names + * field types + * field default values + * valid statements + or None, if any of the types are not ready. + """ + if len(defn.base_type_exprs) > 1: + self.fail("NamedTuple should be a single base", defn) + items: list[str] = [] + types: list[Type] = [] + default_items: dict[str, Expression] = {} + statements: list[Statement] = [] + for stmt in defn.defs.body: + statements.append(stmt) + if not isinstance(stmt, AssignmentStmt): + # Still allow pass or ... (for empty namedtuples). + if isinstance(stmt, PassStmt) or ( + isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr) + ): + continue + # Also allow methods, including decorated ones. + if isinstance(stmt, (Decorator, FuncBase)): + continue + # And docstrings. + if isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, StrExpr): + continue + statements.pop() + defn.removed_statements.append(stmt) + self.fail(NAMEDTUP_CLASS_ERROR, stmt) + elif len(stmt.lvalues) > 1 or not isinstance(stmt.lvalues[0], NameExpr): + # An assignment, but an invalid one. + statements.pop() + defn.removed_statements.append(stmt) + self.fail(NAMEDTUP_CLASS_ERROR, stmt) + else: + # Append name and type in this case... + name = stmt.lvalues[0].name + items.append(name) + if stmt.type is None: + types.append(AnyType(TypeOfAny.unannotated)) + else: + # We never allow recursive types at function scope. Although it is + # possible to support this for named tuples, it is still tricky, and + # it would be inconsistent with type aliases. + analyzed = self.api.anal_type( + stmt.type, + allow_placeholder=not self.api.is_func_scope(), + prohibit_self_type="NamedTuple item type", + prohibit_special_class_field_types="NamedTuple", + ) + if analyzed is None: + # Something is incomplete. We need to defer this named tuple. + return None + types.append(analyzed) + # ...despite possible minor failures that allow further analysis. + if name.startswith("_"): + self.fail( + f"NamedTuple field name cannot start with an underscore: {name}", stmt + ) + if stmt.type is None or hasattr(stmt, "new_syntax") and not stmt.new_syntax: + self.fail(NAMEDTUP_CLASS_ERROR, stmt) + elif isinstance(stmt.rvalue, TempNode): + # x: int assigns rvalue to TempNode(AnyType()) + if default_items: + self.fail( + "Non-default NamedTuple fields cannot follow default fields", stmt + ) + else: + default_items[name] = stmt.rvalue + if defn.keywords: + for_function = ' for "__init_subclass__" of "NamedTuple"' + for key in defn.keywords: + self.msg.unexpected_keyword_argument_for_function(for_function, key, defn) + return items, types, default_items, statements + + def check_namedtuple( + self, node: Expression, var_name: str | None, is_func_scope: bool + ) -> tuple[str | None, TypeInfo | None, list[TypeVarLikeType]]: + """Check if a call defines a namedtuple. + + The optional var_name argument is the name of the variable to + which this is assigned, if any. + + Return a tuple of two items: + * Internal name of the named tuple (e.g. the name passed as an argument to namedtuple) + or None if it is not a valid named tuple + * Corresponding TypeInfo, or None if not ready. + + If the definition is invalid but looks like a namedtuple, + report errors but return (some) TypeInfo. + """ + if not isinstance(node, CallExpr): + return None, None, [] + call = node + callee = call.callee + if not isinstance(callee, RefExpr): + return None, None, [] + fullname = callee.fullname + if fullname == "collections.namedtuple": + is_typed = False + elif fullname in TYPED_NAMEDTUPLE_NAMES: + is_typed = True + else: + return None, None, [] + result = self.parse_namedtuple_args(call, fullname) + if result: + items, types, defaults, typename, tvar_defs, ok = result + else: + # Error. Construct dummy return value. + if var_name: + name = var_name + if is_func_scope: + name += "@" + str(call.line) + else: + name = var_name = "namedtuple@" + str(call.line) + info = self.build_namedtuple_typeinfo(name, [], [], {}, node.line, None) + self.store_namedtuple_info(info, var_name, call, is_typed) + if name != var_name or is_func_scope: + # NOTE: we skip local namespaces since they are not serialized. + self.api.add_symbol_skip_local(name, info) + return var_name, info, [] + if not ok: + # This is a valid named tuple but some types are not ready. + return typename, None, [] + + # We use the variable name as the class name if it exists. If + # it doesn't, we use the name passed as an argument. We prefer + # the variable name because it should be unique inside a + # module, and so we don't need to disambiguate it with a line + # number. + if var_name: + name = var_name + else: + name = typename + + if var_name is None or is_func_scope: + # There are two special cases where need to give it a unique name derived + # from the line number: + # * This is a base class expression, since it often matches the class name: + # class NT(NamedTuple('NT', [...])): + # ... + # * This is a local (function or method level) named tuple, since + # two methods of a class can define a named tuple with the same name, + # and they will be stored in the same namespace (see below). + name += "@" + str(call.line) + if defaults: + default_items = { + arg_name: default for arg_name, default in zip(items[-len(defaults) :], defaults) + } + else: + default_items = {} + + existing_info = None + if isinstance(node.analyzed, NamedTupleExpr): + existing_info = node.analyzed.info + info = self.build_namedtuple_typeinfo( + name, items, types, default_items, node.line, existing_info + ) + + # If var_name is not None (i.e. this is not a base class expression), we always + # store the generated TypeInfo under var_name in the current scope, so that + # other definitions can use it. + if var_name: + self.store_namedtuple_info(info, var_name, call, is_typed) + else: + call.analyzed = NamedTupleExpr(info, is_typed=is_typed) + call.analyzed.set_line(call) + # There are three cases where we need to store the generated TypeInfo + # second time (for the purpose of serialization): + # * If there is a name mismatch like One = NamedTuple('Other', [...]) + # we also store the info under name 'Other@lineno', this is needed + # because classes are (de)serialized using their actual fullname, not + # the name of l.h.s. + # * If this is a method level named tuple. It can leak from the method + # via assignment to self attribute and therefore needs to be serialized + # (local namespaces are not serialized). + # * If it is a base class expression. It was not stored above, since + # there is no var_name (but it still needs to be serialized + # since it is in MRO of some class). + if name != var_name or is_func_scope: + # NOTE: we skip local namespaces since they are not serialized. + self.api.add_symbol_skip_local(name, info) + return typename, info, tvar_defs + + def store_namedtuple_info( + self, info: TypeInfo, name: str, call: CallExpr, is_typed: bool + ) -> None: + self.api.add_symbol(name, info, call) + call.analyzed = NamedTupleExpr(info, is_typed=is_typed) + call.analyzed.set_line(call) + + def parse_namedtuple_args( + self, call: CallExpr, fullname: str + ) -> None | (tuple[list[str], list[Type], list[Expression], str, list[TypeVarLikeType], bool]): + """Parse a namedtuple() call into data needed to construct a type. + + Returns a 6-tuple: + - List of argument names + - List of argument types + - List of default values + - First argument of namedtuple + - All typevars found in the field definition + - Whether all types are ready. + + Return None if the definition didn't typecheck. + """ + type_name = "NamedTuple" if fullname in TYPED_NAMEDTUPLE_NAMES else "namedtuple" + # TODO: Share code with check_argument_count in checkexpr.py? + args = call.args + if len(args) < 2: + self.fail(f'Too few arguments for "{type_name}()"', call) + return None + defaults: list[Expression] = [] + rename = False + if len(args) > 2: + # Typed namedtuple doesn't support additional arguments. + if fullname in TYPED_NAMEDTUPLE_NAMES: + self.fail('Too many arguments for "NamedTuple()"', call) + return None + for i, arg_name in enumerate(call.arg_names[2:], 2): + if arg_name == "defaults": + arg = args[i] + # We don't care what the values are, as long as the argument is an iterable + # and we can count how many defaults there are. + if isinstance(arg, (ListExpr, TupleExpr)): + defaults = list(arg.items) + else: + self.fail( + "List or tuple literal expected as the defaults argument to " + "{}()".format(type_name), + arg, + ) + elif arg_name == "rename": + arg = args[i] + if isinstance(arg, NameExpr) and arg.name in ("True", "False"): + rename = arg.name == "True" + else: + self.fail( + f'Boolean literal expected as the "rename" argument to {type_name}()', + arg, + code=ARG_TYPE, + ) + if call.arg_kinds[:2] != [ARG_POS, ARG_POS]: + self.fail(f'Unexpected arguments to "{type_name}()"', call) + return None + if not isinstance(args[0], StrExpr): + self.fail(f'"{type_name}()" expects a string literal as the first argument', call) + return None + typename = args[0].value + types: list[Type] = [] + tvar_defs = [] + if not isinstance(args[1], (ListExpr, TupleExpr)): + if fullname == "collections.namedtuple" and isinstance(args[1], StrExpr): + str_expr = args[1] + items = str_expr.value.replace(",", " ").split() + else: + self.fail( + 'List or tuple literal expected as the second argument to "{}()"'.format( + type_name + ), + call, + ) + return None + else: + listexpr = args[1] + if fullname == "collections.namedtuple": + # The fields argument contains just names, with implicit Any types. + if not is_StrExpr_list(listexpr.items): + self.fail('String literal expected as "namedtuple()" item', call) + return None + items = [item.value for item in listexpr.items] + else: + type_exprs = [ + t.items[1] + for t in listexpr.items + if isinstance(t, TupleExpr) and len(t.items) == 2 + ] + tvar_defs = self.api.get_and_bind_all_tvars(type_exprs) + # The fields argument contains (name, type) tuples. + result = self.parse_namedtuple_fields_with_types(listexpr.items, call) + if result is None: + # One of the types is not ready, defer. + return None + items, types, _, ok = result + if not ok: + return [], [], [], typename, [], False + if not types: + types = [AnyType(TypeOfAny.unannotated) for _ in items] + processed_items = [] + seen_names: set[str] = set() + for i, item in enumerate(items): + problem = self.check_namedtuple_field_name(item, seen_names) + if problem is None: + processed_items.append(item) + seen_names.add(item) + else: + if not rename: + self.fail(f'"{type_name}()" {problem}', call) + # Even if rename=False, we pretend that it is True. + # At runtime namedtuple creation would throw an error; + # applying the rename logic means we create a more sensible + # namedtuple. + new_name = f"_{i}" + processed_items.append(new_name) + seen_names.add(new_name) + + if len(defaults) > len(items): + self.fail(f'Too many defaults given in call to "{type_name}()"', call) + defaults = defaults[: len(items)] + return processed_items, types, defaults, typename, tvar_defs, True + + def parse_namedtuple_fields_with_types( + self, nodes: list[Expression], context: Context + ) -> tuple[list[str], list[Type], list[Expression], bool] | None: + """Parse typed named tuple fields. + + Return (names, types, defaults, whether types are all ready), or None if error occurred. + """ + items: list[str] = [] + types: list[Type] = [] + for item in nodes: + if isinstance(item, TupleExpr): + if len(item.items) != 2: + self.fail('Invalid "NamedTuple()" field definition', item) + return None + name, type_node = item.items + if isinstance(name, StrExpr): + items.append(name.value) + else: + self.fail('Invalid "NamedTuple()" field name', item) + return None + try: + type = expr_to_unanalyzed_type(type_node, self.options, self.api.is_stub_file) + except TypeTranslationError: + self.fail("Invalid field type", type_node) + return None + # We never allow recursive types at function scope. + analyzed = self.api.anal_type( + type, + allow_placeholder=not self.api.is_func_scope(), + prohibit_self_type="NamedTuple item type", + prohibit_special_class_field_types="NamedTuple", + ) + # Workaround #4987 and avoid introducing a bogus UnboundType + if isinstance(analyzed, UnboundType): + analyzed = AnyType(TypeOfAny.from_error) + # These should be all known, otherwise we would defer in visit_assignment_stmt(). + if analyzed is None: + return [], [], [], False + types.append(analyzed) + else: + self.fail('Tuple expected as "NamedTuple()" field', item) + return None + return items, types, [], True + + def build_namedtuple_typeinfo( + self, + name: str, + items: list[str], + types: list[Type], + default_items: Mapping[str, Expression], + line: int, + existing_info: TypeInfo | None, + ) -> TypeInfo: + strtype = self.api.named_type("builtins.str") + implicit_any = AnyType(TypeOfAny.special_form) + basetuple_type = self.api.named_type("builtins.tuple", [implicit_any]) + dictype = self.api.named_type("builtins.dict", [strtype, implicit_any]) + # Actual signature should return OrderedDict[str, Union[types]] + ordereddictype = self.api.named_type("builtins.dict", [strtype, implicit_any]) + fallback = self.api.named_type("builtins.tuple", [implicit_any]) + # Note: actual signature should accept an invariant version of Iterable[UnionType[types]]. + # but it can't be expressed. 'new' and 'len' should be callable types. + iterable_type = self.api.named_type_or_none("typing.Iterable", [implicit_any]) + function_type = self.api.named_type("builtins.function") + + literals: list[Type] = [LiteralType(item, strtype) for item in items] + match_args_type = TupleType(literals, basetuple_type) + + info = existing_info or self.api.basic_new_typeinfo(name, fallback, line) + info.is_named_tuple = True + tuple_base = TupleType(types, fallback) + if has_placeholder(tuple_base): + self.api.process_placeholder( + None, "NamedTuple item", info, force_progress=tuple_base != info.tuple_type + ) + info.update_tuple_type(tuple_base) + info.line = line + # For use by mypyc. + info.metadata["namedtuple"] = {"fields": items.copy()} + + # We can't calculate the complete fallback type until after semantic + # analysis, since otherwise base classes might be incomplete. Postpone a + # callback function that patches the fallback. + if not has_placeholder(tuple_base) and not has_type_vars(tuple_base): + self.api.schedule_patch( + PRIORITY_FALLBACKS, lambda: calculate_tuple_fallback(tuple_base) + ) + + def add_field( + var: Var, is_initialized_in_class: bool = False, is_property: bool = False + ) -> None: + var.info = info + var.is_initialized_in_class = is_initialized_in_class + var.is_property = is_property + var._fullname = f"{info.fullname}.{var.name}" + info.names[var.name] = SymbolTableNode(MDEF, var) + + fields = [Var(item, typ) for item, typ in zip(items, types)] + for var in fields: + add_field(var, is_property=True) + # We can't share Vars between fields and method arguments, since they + # have different full names (the latter are normally used as local variables + # in functions, so their full names are set to short names when generated methods + # are analyzed). + vars = [Var(item, typ) for item, typ in zip(items, types)] + + tuple_of_strings = TupleType([strtype for _ in items], basetuple_type) + add_field(Var("_fields", tuple_of_strings), is_initialized_in_class=True) + add_field(Var("_field_types", dictype), is_initialized_in_class=True) + add_field(Var("_field_defaults", dictype), is_initialized_in_class=True) + add_field(Var("_source", strtype), is_initialized_in_class=True) + add_field(Var("__annotations__", ordereddictype), is_initialized_in_class=True) + add_field(Var("__doc__", strtype), is_initialized_in_class=True) + if self.options.python_version >= (3, 10): + add_field(Var("__match_args__", match_args_type), is_initialized_in_class=True) + + assert info.tuple_type is not None # Set by update_tuple_type() above. + shared_self_type = TypeVarType( + name=SELF_TVAR_NAME, + fullname=f"{info.fullname}.{SELF_TVAR_NAME}", + # Namespace is patched per-method below. + id=self.api.tvar_scope.new_unique_func_id(), + values=[], + upper_bound=info.tuple_type, + default=AnyType(TypeOfAny.from_omitted_generics), + ) + + def add_method( + funcname: str, + ret: Type | None, # None means use (patched) self-type + args: list[Argument], + is_classmethod: bool = False, + is_new: bool = False, + ) -> None: + fullname = f"{info.fullname}.{funcname}" + self_type = shared_self_type.copy_modified( + id=TypeVarId(shared_self_type.id.raw_id, namespace=fullname) + ) + if ret is None: + ret = self_type + if is_classmethod or is_new: + first = [Argument(Var("_cls"), TypeType.make_normalized(self_type), None, ARG_POS)] + else: + first = [Argument(Var("_self"), self_type, None, ARG_POS)] + args = first + args + + types = [arg.type_annotation for arg in args] + items = [arg.variable.name for arg in args] + arg_kinds = [arg.kind for arg in args] + assert None not in types + signature = CallableType(cast(list[Type], types), arg_kinds, items, ret, function_type) + signature.variables = (self_type,) + func = FuncDef(funcname, args, Block([])) + func.info = info + func.is_class = is_classmethod + func.type = set_callable_name(signature, func) + func._fullname = fullname + func.line = line + if is_classmethod: + v = Var(funcname, func.type) + v.is_classmethod = True + v.info = info + v._fullname = func._fullname + func.is_decorated = True + dec = Decorator(func, [NameExpr("classmethod")], v) + dec.line = line + sym = SymbolTableNode(MDEF, dec) + else: + sym = SymbolTableNode(MDEF, func) + sym.plugin_generated = True + info.names[funcname] = sym + + add_method( + "_replace", + ret=None, + args=[Argument(var, var.type, EllipsisExpr(), ARG_NAMED_OPT) for var in vars], + ) + if self.options.python_version >= (3, 13): + add_method( + "__replace__", + ret=None, + args=[Argument(var, var.type, EllipsisExpr(), ARG_NAMED_OPT) for var in vars], + ) + + def make_init_arg(var: Var) -> Argument: + default = default_items.get(var.name, None) + kind = ARG_POS if default is None else ARG_OPT + return Argument(var, var.type, default, kind) + + add_method("__new__", ret=None, args=[make_init_arg(var) for var in vars], is_new=True) + add_method("_asdict", args=[], ret=ordereddictype) + add_method( + "_make", + ret=None, + is_classmethod=True, + args=[Argument(Var("iterable", iterable_type), iterable_type, None, ARG_POS)], + ) + + self_tvar_expr = TypeVarExpr( + SELF_TVAR_NAME, + info.fullname + "." + SELF_TVAR_NAME, + [], + info.tuple_type, + AnyType(TypeOfAny.from_omitted_generics), + ) + info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr) + return info + + @contextmanager + def save_namedtuple_body(self, named_tuple_info: TypeInfo) -> Iterator[None]: + """Preserve the generated body of class-based named tuple and then restore it. + + Temporarily clear the names dict so we don't get errors about duplicate names + that were already set in build_namedtuple_typeinfo (we already added the tuple + field names while generating the TypeInfo, and actual duplicates are + already reported). + """ + nt_names = named_tuple_info.names + named_tuple_info.names = SymbolTable() + + yield + + # Make sure we didn't use illegal names, then reset the names in the typeinfo. + for prohibited in NAMEDTUPLE_PROHIBITED_NAMES: + if prohibited in named_tuple_info.names: + if nt_names.get(prohibited) is named_tuple_info.names[prohibited]: + continue + ctx = named_tuple_info.names[prohibited].node + assert ctx is not None + self.fail(f'Cannot overwrite NamedTuple attribute "{prohibited}"', ctx) + + # Restore the names in the original symbol table. This ensures that the symbol + # table contains the field objects created by build_namedtuple_typeinfo. Exclude + # __doc__, which can legally be overwritten by the class. + for key, value in nt_names.items(): + if key in named_tuple_info.names: + if key == "__doc__": + continue + sym = named_tuple_info.names[key] + if isinstance(sym.node, (FuncBase, Decorator)) and not sym.plugin_generated: + # Keep user-defined methods as is. + continue + # Do not retain placeholders - we'll get back here if they cease to + # be placeholders later. If we keep placeholders alive, they may never + # be reached again, making it to cacheable symtable. + if not isinstance(sym.node, PlaceholderNode): + # Keep existing (user-provided) definitions under mangled names, so they + # get semantically analyzed. + r_key = get_unique_redefinition_name(key, named_tuple_info.names) + named_tuple_info.names[r_key] = sym + named_tuple_info.names[key] = value + + # Helpers + + def check_namedtuple_field_name(self, field: str, seen_names: Container[str]) -> str | None: + """Return None for valid fields, a string description for invalid ones.""" + if field in seen_names: + return f'has duplicate field name "{field}"' + elif not field.isidentifier(): + return f'field name "{field}" is not a valid identifier' + elif field.startswith("_"): + return f'field name "{field}" starts with an underscore' + elif keyword.iskeyword(field): + return f'field name "{field}" is a keyword' + return None + + def fail(self, msg: str, ctx: Context, code: ErrorCode | None = None) -> None: + self.api.fail(msg, ctx, code=code) diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_newtype.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/semanal_newtype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ca9ec454d8703893570ef7e984596341ea04142f Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/semanal_newtype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_newtype.py b/micromamba_root/Lib/site-packages/mypy/semanal_newtype.py new file mode 100644 index 0000000000000000000000000000000000000000..0c717b5d9a0e74efd0e96cc1b8094cc8c23fd2d6 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/semanal_newtype.py @@ -0,0 +1,273 @@ +"""Semantic analysis of NewType definitions. + +This is conceptually part of mypy.semanal (semantic analyzer pass 2). +""" + +from __future__ import annotations + +from mypy import errorcodes as codes +from mypy.errorcodes import ErrorCode +from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type +from mypy.messages import MessageBuilder, format_type +from mypy.nodes import ( + ARG_POS, + MDEF, + Argument, + AssignmentStmt, + Block, + CallExpr, + Context, + FuncDef, + NameExpr, + NewTypeExpr, + PlaceholderNode, + RefExpr, + StrExpr, + SymbolTableNode, + TypeInfo, + Var, +) +from mypy.options import Options +from mypy.semanal_shared import SemanticAnalyzerInterface, has_placeholder +from mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type +from mypy.types import ( + AnyType, + CallableType, + Instance, + NoneType, + PlaceholderType, + TupleType, + Type, + TypeOfAny, + get_proper_type, +) + + +class NewTypeAnalyzer: + def __init__( + self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder + ) -> None: + self.options = options + self.api = api + self.msg = msg + + def process_newtype_declaration(self, s: AssignmentStmt) -> bool: + """Check if s declares a NewType; if yes, store it in symbol table. + + Return True if it's a NewType declaration. The current target may be + deferred as a side effect if the base type is not ready, even if + the return value is True. + + The logic in this function mostly copies the logic for visit_class_def() + with a single (non-Generic) base. + """ + var_name, call = self.analyze_newtype_declaration(s) + if var_name is None or call is None: + return False + name = var_name + # OK, now we know this is a NewType. But the base type may be not ready yet, + # add placeholder as we do for ClassDef. + + if self.api.is_func_scope(): + name += "@" + str(s.line) + fullname = self.api.qualified_name(name) + + if not call.analyzed or isinstance(call.analyzed, NewTypeExpr) and not call.analyzed.info: + # Start from labeling this as a future class, as we do for normal ClassDefs. + placeholder = PlaceholderNode(fullname, s, s.line, becomes_typeinfo=True) + self.api.add_symbol(var_name, placeholder, s, can_defer=False) + + old_type, should_defer = self.check_newtype_args(var_name, call, s) + old_type = get_proper_type(old_type) + if not isinstance(call.analyzed, NewTypeExpr): + call.analyzed = NewTypeExpr(var_name, old_type, line=call.line, column=call.column) + else: + call.analyzed.old_type = old_type + if old_type is None: + if should_defer: + # Base type is not ready. + self.api.defer() + return True + + # Create the corresponding class definition if the aliased type is subtypeable + assert isinstance(call.analyzed, NewTypeExpr) + if isinstance(old_type, TupleType): + newtype_class_info = self.build_newtype_typeinfo( + name, old_type, old_type.partial_fallback, s.line, call.analyzed.info + ) + newtype_class_info.update_tuple_type(old_type) + elif isinstance(old_type, Instance): + if old_type.type.is_protocol: + self.fail("NewType cannot be used with protocol classes", s) + newtype_class_info = self.build_newtype_typeinfo( + name, old_type, old_type, s.line, call.analyzed.info + ) + else: + if old_type is not None: + message = "Argument 2 to NewType(...) must be subclassable (got {})" + self.fail( + message.format(format_type(old_type, self.options)), + s, + code=codes.VALID_NEWTYPE, + ) + # Otherwise the error was already reported. + old_type = AnyType(TypeOfAny.from_error) + object_type = self.api.named_type("builtins.object") + newtype_class_info = self.build_newtype_typeinfo( + name, old_type, object_type, s.line, call.analyzed.info + ) + newtype_class_info.fallback_to_any = True + + check_for_explicit_any( + old_type, self.options, self.api.is_typeshed_stub_file, self.msg, context=s + ) + + if self.options.disallow_any_unimported and has_any_from_unimported_type(old_type): + self.msg.unimported_type_becomes_any("Argument 2 to NewType(...)", old_type, s) + + # If so, add it to the symbol table. + assert isinstance(call.analyzed, NewTypeExpr) + # As we do for normal classes, create the TypeInfo only once, then just + # update base classes on next iterations (to get rid of placeholders there). + if not call.analyzed.info: + call.analyzed.info = newtype_class_info + else: + call.analyzed.info.bases = newtype_class_info.bases + self.api.add_symbol(var_name, call.analyzed.info, s) + if self.api.is_func_scope(): + self.api.add_symbol_skip_local(name, call.analyzed.info) + newtype_class_info.line = s.line + return True + + def analyze_newtype_declaration(self, s: AssignmentStmt) -> tuple[str | None, CallExpr | None]: + """Return the NewType call expression if `s` is a newtype declaration or None otherwise.""" + name, call = None, None + if ( + len(s.lvalues) == 1 + and isinstance(s.lvalues[0], NameExpr) + and isinstance(s.rvalue, CallExpr) + and isinstance(s.rvalue.callee, RefExpr) + and (s.rvalue.callee.fullname in ("typing.NewType", "typing_extensions.NewType")) + ): + name = s.lvalues[0].name + + if s.type: + self.fail("Cannot declare the type of a NewType declaration", s) + + names = self.api.current_symbol_table() + existing = names.get(name) + # Give a better error message than generic "Name already defined". + if ( + existing + and not isinstance(existing.node, PlaceholderNode) + and not s.rvalue.analyzed + ): + self.fail(f'Cannot redefine "{name}" as a NewType', s) + + # This dummy NewTypeExpr marks the call as sufficiently analyzed; it will be + # overwritten later with a fully complete NewTypeExpr if there are no other + # errors with the NewType() call. + call = s.rvalue + + return name, call + + def check_newtype_args( + self, name: str, call: CallExpr, context: Context + ) -> tuple[Type | None, bool]: + """Analyze base type in NewType call. + + Return a tuple (type, should defer). + """ + has_failed = False + args, arg_kinds = call.args, call.arg_kinds + if len(args) != 2 or arg_kinds[0] != ARG_POS or arg_kinds[1] != ARG_POS: + self.fail("NewType(...) expects exactly two positional arguments", context) + return None, False + + # Check first argument + if not isinstance(args[0], StrExpr): + self.fail("Argument 1 to NewType(...) must be a string literal", context) + has_failed = True + elif args[0].value != name: + msg = 'String argument 1 "{}" to NewType(...) does not match variable name "{}"' + self.fail(msg.format(args[0].value, name), context) + has_failed = True + + # Check second argument + msg = "Argument 2 to NewType(...) must be a valid type" + try: + unanalyzed_type = expr_to_unanalyzed_type(args[1], self.options, self.api.is_stub_file) + except TypeTranslationError: + self.fail(msg, context) + return None, False + + # We want to use our custom error message (see above), so we suppress + # the default error message for invalid types here. + old_type = get_proper_type( + self.api.anal_type( + unanalyzed_type, + report_invalid_types=False, + allow_placeholder=not self.api.is_func_scope(), + ) + ) + should_defer = False + if isinstance(old_type, PlaceholderType): + old_type = None + if old_type is None: + should_defer = True + + # The caller of this function assumes that if we return a Type, it's always + # a valid one. So, we translate AnyTypes created from errors into None. + if isinstance(old_type, AnyType) and old_type.is_from_error: + self.fail(msg, context) + return None, False + + return None if has_failed else old_type, should_defer + + def build_newtype_typeinfo( + self, + name: str, + old_type: Type, + base_type: Instance, + line: int, + existing_info: TypeInfo | None, + ) -> TypeInfo: + info = existing_info or self.api.basic_new_typeinfo(name, base_type, line) + info.bases = [base_type] # Update in case there were nested placeholders. + info.is_newtype = True + + # Add __init__ method + args = [ + Argument(Var("self"), NoneType(), None, ARG_POS), + self.make_argument("item", old_type), + ] + signature = CallableType( + arg_types=[Instance(info, []), old_type], + arg_kinds=[arg.kind for arg in args], + arg_names=["self", "item"], + ret_type=NoneType(), + fallback=self.api.named_type("builtins.function"), + name=name, + ) + init_func = FuncDef("__init__", args, Block([]), typ=signature) + init_func.info = info + init_func._fullname = info.fullname + ".__init__" + if not existing_info: + updated = True + else: + previous_sym = info.names["__init__"].node + assert isinstance(previous_sym, FuncDef) + updated = old_type != previous_sym.arguments[1].variable.type + info.names["__init__"] = SymbolTableNode(MDEF, init_func) + + if has_placeholder(old_type): + self.api.process_placeholder(None, "NewType base", info, force_progress=updated) + return info + + # Helpers + + def make_argument(self, name: str, type: Type) -> Argument: + return Argument(Var(name), type, None, ARG_POS) + + def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + self.api.fail(msg, ctx, code=code) diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_pass1.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/semanal_pass1.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..d7cf5042aa8bcaa14541687221a3a7b6b31f0202 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/semanal_pass1.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_pass1.py b/micromamba_root/Lib/site-packages/mypy/semanal_pass1.py new file mode 100644 index 0000000000000000000000000000000000000000..266fd236a01f622b22e69e427f8475e68cfb064a --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/semanal_pass1.py @@ -0,0 +1,159 @@ +"""Block/import reachability analysis.""" + +from __future__ import annotations + +from mypy.nodes import ( + AssertStmt, + AssignmentStmt, + Block, + ClassDef, + ExpressionStmt, + ForStmt, + FuncDef, + IfStmt, + Import, + ImportAll, + ImportFrom, + MatchStmt, + MypyFile, + ReturnStmt, +) +from mypy.options import Options +from mypy.reachability import ( + assert_will_always_fail, + infer_reachability_of_if_statement, + infer_reachability_of_match_statement, +) +from mypy.traverser import TraverserVisitor + + +class SemanticAnalyzerPreAnalysis(TraverserVisitor): + """Analyze reachability of blocks and imports and other local things. + + This runs before semantic analysis, so names have not been bound. Imports are + also not resolved yet, so we can only access the current module. + + This determines static reachability of blocks and imports due to version and + platform checks, among others. + + The main entry point is 'visit_file'. + + Reachability of imports needs to be determined very early in the build since + this affects which modules will ultimately be processed. + + Consider this example: + + import sys + + def do_stuff() -> None: + if sys.version_info >= (3, 10): + import xyz # Only available in Python 3.10+ + xyz.whatever() + ... + + The block containing 'import xyz' is unreachable in Python 3 mode. The import + shouldn't be processed in Python 3 mode, even if the module happens to exist. + """ + + def visit_file(self, file: MypyFile, fnam: str, mod_id: str, options: Options) -> None: + self.platform = options.platform + self.cur_mod_id = mod_id + self.cur_mod_node = file + self.options = options + self.is_global_scope = True + self.skipped_lines: set[int] = set() + + for i, defn in enumerate(file.defs): + defn.accept(self) + if isinstance(defn, AssertStmt) and assert_will_always_fail(defn, options): + # We've encountered an assert that's always false, + # e.g. assert sys.platform == 'lol'. Truncate the + # list of statements. This mutates file.defs too. + if i < len(file.defs) - 1: + next_def, last = file.defs[i + 1], file.defs[-1] + if last.end_line is not None: + # We are on a Python version recent enough to support end lines. + self.skipped_lines |= set(range(next_def.line, last.end_line + 1)) + file.imports = [ + i for i in file.imports if (i.line, i.column) <= (defn.line, defn.column) + ] + del file.defs[i + 1 :] + break + file.skipped_lines = self.skipped_lines + + def visit_func_def(self, node: FuncDef) -> None: + old_global_scope = self.is_global_scope + self.is_global_scope = False + super().visit_func_def(node) + self.is_global_scope = old_global_scope + file_node = self.cur_mod_node + if ( + self.is_global_scope + and file_node.is_stub + and node.name == "__getattr__" + and file_node.is_package_init_file() + ): + # __init__.pyi with __getattr__ means that any submodules are assumed + # to exist, even if there is no stub. Note that we can't verify that the + # return type is compatible, since we haven't bound types yet. + file_node.is_partial_stub_package = True + + def visit_class_def(self, node: ClassDef) -> None: + old_global_scope = self.is_global_scope + self.is_global_scope = False + super().visit_class_def(node) + self.is_global_scope = old_global_scope + + def visit_import_from(self, node: ImportFrom) -> None: + node.is_top_level = self.is_global_scope + super().visit_import_from(node) + + def visit_import_all(self, node: ImportAll) -> None: + node.is_top_level = self.is_global_scope + super().visit_import_all(node) + + def visit_import(self, node: Import) -> None: + node.is_top_level = self.is_global_scope + super().visit_import(node) + + def visit_if_stmt(self, s: IfStmt) -> None: + infer_reachability_of_if_statement(s, self.options) + for expr in s.expr: + expr.accept(self) + for node in s.body: + node.accept(self) + if s.else_body: + s.else_body.accept(self) + + def visit_block(self, b: Block) -> None: + if b.is_unreachable: + if b.end_line is not None: + # We are on a Python version recent enough to support end lines. + self.skipped_lines |= set(range(b.line, b.end_line + 1)) + return + super().visit_block(b) + + def visit_match_stmt(self, s: MatchStmt) -> None: + infer_reachability_of_match_statement(s, self.options) + for guard in s.guards: + if guard is not None: + guard.accept(self) + for body in s.bodies: + body.accept(self) + + # The remaining methods are an optimization: don't visit nested expressions + # of common statements, since they can have no effect. + + def visit_assignment_stmt(self, s: AssignmentStmt) -> None: + pass + + def visit_expression_stmt(self, s: ExpressionStmt) -> None: + pass + + def visit_return_stmt(self, s: ReturnStmt) -> None: + pass + + def visit_for_stmt(self, s: ForStmt) -> None: + s.body.accept(self) + if s.else_body is not None: + s.else_body.accept(self) diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_shared.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/semanal_shared.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ed1762f4faa906efaeeb55ad49a8ac183c3347be Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/semanal_shared.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_shared.py b/micromamba_root/Lib/site-packages/mypy/semanal_shared.py new file mode 100644 index 0000000000000000000000000000000000000000..a85d4ed00b5e678aa4dcd296a7525c7718708191 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/semanal_shared.py @@ -0,0 +1,495 @@ +"""Shared definitions used by different parts of semantic analysis.""" + +from __future__ import annotations + +from abc import abstractmethod +from collections.abc import Callable +from typing import Final, Literal, Protocol, overload + +from mypy_extensions import trait + +from mypy.errorcodes import LITERAL_REQ, ErrorCode +from mypy.nodes import ( + CallExpr, + ClassDef, + Context, + DataclassTransformSpec, + Decorator, + Expression, + FuncDef, + NameExpr, + Node, + OverloadedFuncDef, + RefExpr, + SymbolNode, + SymbolTable, + SymbolTableNode, + TypeInfo, +) +from mypy.plugin import SemanticAnalyzerPluginInterface +from mypy.tvar_scope import TypeVarLikeScope +from mypy.type_visitor import ANY_STRATEGY, BoolTypeQuery +from mypy.typeops import make_simplified_union +from mypy.types import ( + TPDICT_FB_NAMES, + AnyType, + FunctionLike, + Instance, + Parameters, + ParamSpecFlavor, + ParamSpecType, + PlaceholderType, + ProperType, + TupleType, + Type, + TypeOfAny, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + UnpackType, + flatten_nested_tuples, + get_proper_type, +) + +# Subclasses can override these Var attributes with incompatible types. This can also be +# set for individual attributes using 'allow_incompatible_override' of Var. +ALLOW_INCOMPATIBLE_OVERRIDE: Final = ("__slots__", "__deletable__", "__match_args__") + + +# Priorities for ordering of patches within the "patch" phase of semantic analysis +# (after the main pass): + +# Fix fallbacks (does subtype checks). +PRIORITY_FALLBACKS: Final = 1 + + +@trait +class SemanticAnalyzerCoreInterface: + """A core abstract interface to generic semantic analyzer functionality. + + This is implemented by both semantic analyzer passes 2 and 3. + """ + + @abstractmethod + def lookup_qualified( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + raise NotImplementedError + + @abstractmethod + def lookup_fully_qualified(self, fullname: str, /) -> SymbolTableNode: + raise NotImplementedError + + @abstractmethod + def lookup_fully_qualified_or_none(self, fullname: str, /) -> SymbolTableNode | None: + raise NotImplementedError + + @abstractmethod + def fail( + self, + msg: str, + ctx: Context, + serious: bool = False, + *, + blocker: bool = False, + code: ErrorCode | None = None, + ) -> None: + raise NotImplementedError + + @abstractmethod + def note(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + raise NotImplementedError + + @abstractmethod + def incomplete_feature_enabled(self, feature: str, ctx: Context) -> bool: + raise NotImplementedError + + @abstractmethod + def record_incomplete_ref(self) -> None: + raise NotImplementedError + + @abstractmethod + def defer(self, debug_context: Context | None = None, force_progress: bool = False) -> None: + raise NotImplementedError + + @abstractmethod + def is_incomplete_namespace(self, fullname: str) -> bool: + """Is a module or class namespace potentially missing some definitions?""" + raise NotImplementedError + + @property + @abstractmethod + def final_iteration(self) -> bool: + """Is this the final iteration of semantic analysis?""" + raise NotImplementedError + + @abstractmethod + def is_future_flag_set(self, flag: str) -> bool: + """Is the specific __future__ feature imported""" + raise NotImplementedError + + @property + @abstractmethod + def is_stub_file(self) -> bool: + raise NotImplementedError + + @abstractmethod + def is_func_scope(self) -> bool: + raise NotImplementedError + + @property + @abstractmethod + def type(self) -> TypeInfo | None: + raise NotImplementedError + + +@trait +class SemanticAnalyzerInterface(SemanticAnalyzerCoreInterface): + """A limited abstract interface to some generic semantic analyzer pass 2 functionality. + + We use this interface for various reasons: + + * Looser coupling + * Cleaner import graph + * Less need to pass around callback functions + """ + + tvar_scope: TypeVarLikeScope + + @abstractmethod + def lookup( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + raise NotImplementedError + + @abstractmethod + def named_type(self, fullname: str, args: list[Type] | None = None) -> Instance: + raise NotImplementedError + + @abstractmethod + def named_type_or_none(self, fullname: str, args: list[Type] | None = None) -> Instance | None: + raise NotImplementedError + + @abstractmethod + def accept(self, node: Node) -> None: + raise NotImplementedError + + @abstractmethod + def anal_type( + self, + typ: Type, + /, + *, + tvar_scope: TypeVarLikeScope | None = None, + allow_tuple_literal: bool = False, + allow_unbound_tvars: bool = False, + allow_typed_dict_special_forms: bool = False, + allow_placeholder: bool = False, + report_invalid_types: bool = True, + prohibit_self_type: str | None = None, + prohibit_special_class_field_types: str | None = None, + ) -> Type | None: + raise NotImplementedError + + @abstractmethod + def get_and_bind_all_tvars(self, type_exprs: list[Expression]) -> list[TypeVarLikeType]: + raise NotImplementedError + + @abstractmethod + def basic_new_typeinfo(self, name: str, basetype_or_fallback: Instance, line: int) -> TypeInfo: + raise NotImplementedError + + @abstractmethod + def schedule_patch(self, priority: int, patch: Callable[[], None]) -> None: + raise NotImplementedError + + @abstractmethod + def add_symbol_table_node(self, name: str, symbol: SymbolTableNode) -> bool: + """Add node to the current symbol table.""" + raise NotImplementedError + + @abstractmethod + def current_symbol_table(self) -> SymbolTable: + """Get currently active symbol table. + + May be module, class, or local namespace. + """ + raise NotImplementedError + + @abstractmethod + def add_symbol( + self, + name: str, + node: SymbolNode, + context: Context, + module_public: bool = True, + module_hidden: bool = False, + can_defer: bool = True, + ) -> bool: + """Add symbol to the current symbol table.""" + raise NotImplementedError + + @abstractmethod + def add_symbol_skip_local(self, name: str, node: SymbolNode) -> None: + """Add symbol to the current symbol table, skipping locals. + + This is used to store symbol nodes in a symbol table that + is going to be serialized (local namespaces are not serialized). + See implementation docstring for more details. + """ + raise NotImplementedError + + @abstractmethod + def parse_bool(self, expr: Expression) -> bool | None: + raise NotImplementedError + + @abstractmethod + def qualified_name(self, name: str) -> str: + raise NotImplementedError + + @property + @abstractmethod + def is_typeshed_stub_file(self) -> bool: + raise NotImplementedError + + @abstractmethod + def process_placeholder( + self, name: str | None, kind: str, ctx: Context, force_progress: bool = False + ) -> None: + raise NotImplementedError + + +def set_callable_name(sig: Type, fdef: FuncDef) -> ProperType: + sig = get_proper_type(sig) + if isinstance(sig, FunctionLike): + if fdef.info: + if fdef.info.fullname in TPDICT_FB_NAMES: + # Avoid exposing the internal _TypedDict name. + class_name = "TypedDict" + else: + class_name = fdef.info.name + return sig.with_name(f"{fdef.name} of {class_name}") + else: + return sig.with_name(fdef.name) + else: + return sig + + +def calculate_tuple_fallback(typ: TupleType) -> None: + """Calculate a precise item type for the fallback of a tuple type. + + This must be called only after the main semantic analysis pass, since joins + aren't available before that. + + Note that there is an apparent chicken and egg problem with respect + to verifying type arguments against bounds. Verifying bounds might + require fallbacks, but we might use the bounds to calculate the + fallbacks. In practice this is not a problem, since the worst that + can happen is that we have invalid type argument values, and these + can happen in later stages as well (they will generate errors, but + we don't prevent their existence). + """ + fallback = typ.partial_fallback + assert fallback.type.fullname == "builtins.tuple" + items = [] + for item in flatten_nested_tuples(typ.items): + # TODO: this duplicates some logic in typeops.tuple_fallback(). + if isinstance(item, UnpackType): + unpacked_type = get_proper_type(item.type) + if isinstance(unpacked_type, TypeVarTupleType): + unpacked_type = get_proper_type(unpacked_type.upper_bound) + if ( + isinstance(unpacked_type, Instance) + and unpacked_type.type.fullname == "builtins.tuple" + ): + items.append(unpacked_type.args[0]) + else: + # This is called before semanal_typeargs.py fixes broken unpacks, + # where the error should also be generated. + items.append(AnyType(TypeOfAny.from_error)) + else: + items.append(item) + fallback.args = (make_simplified_union(items),) + + +class _NamedTypeCallback(Protocol): + def __call__(self, fullname: str, args: list[Type] | None = None) -> Instance: ... + + +def paramspec_args( + name: str, + fullname: str, + id: TypeVarId, + *, + named_type_func: _NamedTypeCallback, + line: int = -1, + column: int = -1, + prefix: Parameters | None = None, +) -> ParamSpecType: + return ParamSpecType( + name, + fullname, + id, + flavor=ParamSpecFlavor.ARGS, + upper_bound=named_type_func("builtins.tuple", [named_type_func("builtins.object")]), + default=AnyType(TypeOfAny.from_omitted_generics), + line=line, + column=column, + prefix=prefix, + ) + + +def paramspec_kwargs( + name: str, + fullname: str, + id: TypeVarId, + *, + named_type_func: _NamedTypeCallback, + line: int = -1, + column: int = -1, + prefix: Parameters | None = None, +) -> ParamSpecType: + return ParamSpecType( + name, + fullname, + id, + flavor=ParamSpecFlavor.KWARGS, + upper_bound=named_type_func( + "builtins.dict", [named_type_func("builtins.str"), named_type_func("builtins.object")] + ), + default=AnyType(TypeOfAny.from_omitted_generics), + line=line, + column=column, + prefix=prefix, + ) + + +class HasPlaceholders(BoolTypeQuery): + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_placeholder_type(self, t: PlaceholderType) -> bool: + return True + + +def has_placeholder(typ: Type) -> bool: + """Check if a type contains any placeholder types (recursively).""" + return typ.accept(HasPlaceholders()) + + +def find_dataclass_transform_spec(node: Node | None) -> DataclassTransformSpec | None: + """ + Find the dataclass transform spec for the given node, if any exists. + + Per PEP 681 (https://peps.python.org/pep-0681/#the-dataclass-transform-decorator), dataclass + transforms can be specified in multiple ways, including decorator functions and + metaclasses/base classes. This function resolves the spec from any of these variants. + """ + + # The spec only lives on the function/class definition itself, so we need to unwrap down to that + # point + if isinstance(node, CallExpr): + # Like dataclasses.dataclass, transform-based decorators can be applied either with or + # without parameters; ie, both of these forms are accepted: + # + # @typing.dataclass_transform + # class Foo: ... + # @typing.dataclass_transform(eq=True, order=True, ...) + # class Bar: ... + # + # We need to unwrap the call for the second variant. + node = node.callee + + if isinstance(node, RefExpr): + node = node.node + + if isinstance(node, Decorator): + # typing.dataclass_transform usage must always result in a Decorator; it always uses the + # `@dataclass_transform(...)` syntax and never `@dataclass_transform` + node = node.func + + if isinstance(node, OverloadedFuncDef): + # The dataclass_transform decorator may be attached to any single overload, so we must + # search them all. + # Note that using more than one decorator is undefined behavior, so we can just take the + # first that we find. + for candidate in node.items: + spec = find_dataclass_transform_spec(candidate) + if spec is not None: + return spec + return find_dataclass_transform_spec(node.impl) + + # For functions, we can directly consult the AST field for the spec + if isinstance(node, FuncDef): + return node.dataclass_transform_spec + + if isinstance(node, ClassDef): + node = node.info + if isinstance(node, TypeInfo): + # Search all parent classes to see if any are decorated with `typing.dataclass_transform` + for base in node.mro[1:]: + if base.dataclass_transform_spec is not None: + return base.dataclass_transform_spec + + # Check if there is a metaclass that is decorated with `typing.dataclass_transform` + # + # Note that PEP 681 only discusses using a metaclass that is directly decorated with + # `typing.dataclass_transform`; subclasses thereof should be treated with dataclass + # semantics rather than as transforms: + # + # > If dataclass_transform is applied to a class, dataclass-like semantics will be assumed + # > for any class that directly or indirectly derives from the decorated class or uses the + # > decorated class as a metaclass. + # + # The wording doesn't make this entirely explicit, but Pyright (the reference + # implementation for this PEP) only handles directly-decorated metaclasses. + metaclass_type = node.metaclass_type + if metaclass_type is not None and metaclass_type.type.dataclass_transform_spec is not None: + return metaclass_type.type.dataclass_transform_spec + + return None + + +# Never returns `None` if a default is given +@overload +def require_bool_literal_argument( + api: SemanticAnalyzerInterface | SemanticAnalyzerPluginInterface, + expression: Expression, + name: str, + default: Literal[True, False], +) -> bool: ... + + +@overload +def require_bool_literal_argument( + api: SemanticAnalyzerInterface | SemanticAnalyzerPluginInterface, + expression: Expression, + name: str, + default: None = None, +) -> bool | None: ... + + +def require_bool_literal_argument( + api: SemanticAnalyzerInterface | SemanticAnalyzerPluginInterface, + expression: Expression, + name: str, + default: bool | None = None, +) -> bool | None: + """Attempt to interpret an expression as a boolean literal, and fail analysis if we can't.""" + value = parse_bool(expression) + if value is None: + api.fail( + f'"{name}" argument must be a True or False literal', expression, code=LITERAL_REQ + ) + return default + + return value + + +def parse_bool(expr: Expression) -> bool | None: + if isinstance(expr, NameExpr): + if expr.fullname == "builtins.True": + return True + if expr.fullname == "builtins.False": + return False + return None diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_typeargs.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/semanal_typeargs.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..76dc2e4a4f9a4ac5820ad399b06b2782ac8e2b64 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/semanal_typeargs.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_typeargs.py b/micromamba_root/Lib/site-packages/mypy/semanal_typeargs.py new file mode 100644 index 0000000000000000000000000000000000000000..0f62a4aa8b1a2ea8d71ef25988dc0c4d8b3d71df --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/semanal_typeargs.py @@ -0,0 +1,306 @@ +"""Verify properties of type arguments, like 'int' in C[int] being valid. + +This must happen after semantic analysis since there can be placeholder +types until the end of semantic analysis, and these break various type +operations, including subtype checks. +""" + +from __future__ import annotations + +from collections.abc import Callable + +from mypy import errorcodes as codes, message_registry +from mypy.errorcodes import ErrorCode +from mypy.errors import Errors +from mypy.message_registry import INVALID_PARAM_SPEC_LOCATION, INVALID_PARAM_SPEC_LOCATION_NOTE +from mypy.messages import format_type +from mypy.mixedtraverser import MixedTraverserVisitor +from mypy.nodes import Block, ClassDef, Context, FakeInfo, FuncItem, MypyFile +from mypy.options import Options +from mypy.scope import Scope +from mypy.subtypes import is_same_type, is_subtype +from mypy.types import ( + AnyType, + CallableType, + Instance, + Parameters, + ParamSpecType, + TupleType, + Type, + TypeAliasType, + TypeOfAny, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UnpackType, + flatten_nested_tuples, + get_proper_type, + get_proper_types, + split_with_prefix_and_suffix, +) +from mypy.typevartuples import erased_vars + + +class TypeArgumentAnalyzer(MixedTraverserVisitor): + def __init__( + self, + errors: Errors, + options: Options, + is_typeshed_file: bool, + named_type: Callable[[str, list[Type]], Instance], + ) -> None: + super().__init__() + self.errors = errors + self.options = options + self.is_typeshed_file = is_typeshed_file + self.named_type = named_type + self.scope = Scope() + # Should we also analyze function definitions, or only module top-levels? + self.recurse_into_functions = True + # Keep track of the type aliases already visited. This is needed to avoid + # infinite recursion on types like A = Union[int, List[A]]. + self.seen_aliases: set[TypeAliasType] = set() + + def visit_mypy_file(self, o: MypyFile) -> None: + self.errors.set_file(o.path, o.fullname, scope=self.scope, options=self.options) + with self.scope.module_scope(o.fullname): + super().visit_mypy_file(o) + + def visit_func(self, defn: FuncItem) -> None: + if not self.recurse_into_functions: + return + with self.scope.function_scope(defn): + super().visit_func(defn) + + def visit_class_def(self, defn: ClassDef) -> None: + with self.scope.class_scope(defn.info): + super().visit_class_def(defn) + + def visit_block(self, o: Block) -> None: + if not o.is_unreachable: + super().visit_block(o) + + def visit_type_alias_type(self, t: TypeAliasType) -> None: + super().visit_type_alias_type(t) + if t.is_recursive: + if t in self.seen_aliases: + # Avoid infinite recursion on recursive type aliases. + return + self.seen_aliases.add(t) + assert t.alias is not None, f"Unfixed type alias {t.type_ref}" + is_error, is_invalid = self.validate_args( + t.alias.name, tuple(t.args), t.alias.alias_tvars, t + ) + if is_invalid: + # If there is an arity error (e.g. non-Parameters used for ParamSpec etc.), + # then it is safer to erase the arguments completely, to avoid crashes later. + # TODO: can we move this logic to typeanal.py? + t.args = erased_vars(t.alias.alias_tvars, TypeOfAny.from_error) + if not is_error: + # If there was already an error for the alias itself, there is no point in checking + # the expansion, most likely it will result in the same kind of error. + if t.args: + # Since we always allow unbounded type variables in alias definitions, we need + # to verify the arguments satisfy the upper bounds of the expansion as well. + get_proper_type(t).accept(self) + if t.is_recursive: + self.seen_aliases.discard(t) + + def visit_tuple_type(self, t: TupleType) -> None: + t.items = flatten_nested_tuples(t.items) + for i, it in enumerate(t.items): + if self.check_non_paramspec(it, "tuple", t): + t.items[i] = AnyType(TypeOfAny.from_error) + + # We could also normalize Tuple[*tuple[X, ...]] -> tuple[X, ...] like in + # expand_type() but we can't do this here since it is not a translator visitor, + # and we need to return an Instance instead of TupleType. + super().visit_tuple_type(t) + + def visit_callable_type(self, t: CallableType) -> None: + super().visit_callable_type(t) + t.normalize_trivial_unpack() + + def visit_instance(self, t: Instance) -> None: + super().visit_instance(t) + # Type argument counts were checked in the main semantic analyzer pass. We assume + # that the counts are correct here. + info = t.type + if isinstance(info, FakeInfo): + return # https://github.com/python/mypy/issues/11079 + _, is_invalid = self.validate_args(info.name, t.args, info.defn.type_vars, t) + if is_invalid: + t.args = tuple(erased_vars(info.defn.type_vars, TypeOfAny.from_error)) + if t.type.fullname == "builtins.tuple" and len(t.args) == 1: + # Normalize Tuple[*Tuple[X, ...], ...] -> Tuple[X, ...] + arg = t.args[0] + if isinstance(arg, UnpackType): + unpacked = get_proper_type(arg.type) + if isinstance(unpacked, Instance): + assert unpacked.type.fullname == "builtins.tuple" + t.args = unpacked.args + + def check_non_paramspec(self, arg: Type, tv_kind: str, context: Context) -> bool: + if isinstance(arg, ParamSpecType): + self.fail( + INVALID_PARAM_SPEC_LOCATION.format(format_type(arg, self.options)), + context, + code=codes.VALID_TYPE, + ) + self.note( + INVALID_PARAM_SPEC_LOCATION_NOTE.format(arg.name), context, code=codes.VALID_TYPE + ) + return True + if isinstance(arg, Parameters): + self.fail( + f"Cannot use {format_type(arg, self.options)} for {tv_kind}," + " only for ParamSpec", + context, + code=codes.VALID_TYPE, + ) + return True + + return False + + def validate_args( + self, name: str, args: tuple[Type, ...], type_vars: list[TypeVarLikeType], ctx: Context + ) -> tuple[bool, bool]: + if any(isinstance(v, TypeVarTupleType) for v in type_vars): + prefix = next(i for (i, v) in enumerate(type_vars) if isinstance(v, TypeVarTupleType)) + tvt = type_vars[prefix] + assert isinstance(tvt, TypeVarTupleType) + start, middle, end = split_with_prefix_and_suffix( + tuple(args), prefix, len(type_vars) - prefix - 1 + ) + args = start + (TupleType(list(middle), tvt.tuple_fallback),) + end + + is_error = False + is_invalid = False + for arg, tvar in zip(args, type_vars): + context = ctx if arg.line < 0 else arg + if isinstance(tvar, TypeVarType): + if self.check_non_paramspec(arg, "regular type variable", context): + is_invalid = True + continue + + if self.in_type_alias_expr and isinstance(arg, TypeVarType): + # Type aliases are allowed to use unconstrained type variables + # error will be checked at substitution point. + continue + if tvar.values: + if isinstance(arg, TypeVarType): + arg_values = arg.values + if not arg_values: + is_error = True + self.fail( + message_registry.INVALID_TYPEVAR_AS_TYPEARG.format(arg.name, name), + context, + code=codes.TYPE_VAR, + ) + continue + else: + arg_values = [arg] + if self.check_type_var_values( + name, arg_values, tvar.name, tvar.values, context + ): + is_error = True + # Check against upper bound. Since it's object the vast majority of the time, + # add fast path to avoid a potentially slow subtype check. + upper_bound = tvar.upper_bound + object_upper_bound = ( + type(upper_bound) is Instance + and upper_bound.type.fullname == "builtins.object" + ) + if not object_upper_bound and not is_subtype(arg, upper_bound): + is_error = True + self.fail( + message_registry.INVALID_TYPEVAR_ARG_BOUND.format( + format_type(arg, self.options), + name, + format_type(upper_bound, self.options), + ), + context, + code=codes.TYPE_VAR, + ) + elif isinstance(tvar, ParamSpecType): + if not isinstance( + get_proper_type(arg), (ParamSpecType, Parameters, AnyType, UnboundType) + ): + is_invalid = True + self.fail( + "Can only replace ParamSpec with a parameter types list or" + f" another ParamSpec, got {format_type(arg, self.options)}", + context, + code=codes.VALID_TYPE, + ) + elif isinstance(tvar, TypeVarTupleType): + p_arg = get_proper_type(arg) + assert isinstance(p_arg, TupleType) + for it in p_arg.items: + if self.check_non_paramspec(it, "TypeVarTuple", context): + is_invalid = True + if is_invalid: + is_error = True + return is_error, is_invalid + + def visit_unpack_type(self, typ: UnpackType) -> None: + super().visit_unpack_type(typ) + proper_type = get_proper_type(typ.type) + if isinstance(proper_type, TupleType): + return + if isinstance(proper_type, TypeVarTupleType): + return + # TODO: this should probably be .has_base("builtins.tuple"), also elsewhere. This is + # tricky however, since this needs map_instance_to_supertype() available in many places. + if isinstance(proper_type, Instance) and proper_type.type.fullname == "builtins.tuple": + return + if not isinstance(proper_type, (UnboundType, AnyType)): + # Avoid extra errors if there were some errors already. Also interpret plain Any + # as tuple[Any, ...] (this is better for the code in type checker). + self.fail( + message_registry.INVALID_UNPACK.format(format_type(proper_type, self.options)), + typ.type, + code=codes.VALID_TYPE, + ) + typ.type = self.named_type("builtins.tuple", [AnyType(TypeOfAny.from_error)]) + + def check_type_var_values( + self, name: str, actuals: list[Type], arg_name: str, valids: list[Type], context: Context + ) -> bool: + if self.in_type_alias_expr: + # See testValidTypeAliasValues - we do not enforce typevar compatibility + # at the definition site. We check instantiation validity later. + return False + is_error = False + for actual in get_proper_types(actuals): + # We skip UnboundType here, since they may appear in defn.bases, + # the error will be caught when visiting info.bases, that have bound type + # variables. + if not isinstance(actual, (AnyType, UnboundType)) and not any( + is_same_type(actual, value) for value in valids + ): + is_error = True + if len(actuals) > 1 or not isinstance(actual, Instance): + self.fail( + message_registry.INVALID_TYPEVAR_ARG_VALUE.format(name), + context, + code=codes.TYPE_VAR, + ) + else: + class_name = f'"{name}"' + actual_type_name = f'"{actual.type.name}"' + self.fail( + message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format( + arg_name, class_name, actual_type_name + ), + context, + code=codes.TYPE_VAR, + ) + return is_error + + def fail(self, msg: str, context: Context, *, code: ErrorCode | None = None) -> None: + self.errors.report(context.line, context.column, msg, code=code) + + def note(self, msg: str, context: Context, *, code: ErrorCode | None = None) -> None: + self.errors.report(context.line, context.column, msg, severity="note", code=code) diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_typeddict.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/semanal_typeddict.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..7c6776c632e20d68c088f1dc5de497734cb4e117 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/semanal_typeddict.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/semanal_typeddict.py b/micromamba_root/Lib/site-packages/mypy/semanal_typeddict.py new file mode 100644 index 0000000000000000000000000000000000000000..3655e4c89dd4b9ef982c89cdc88897c6e34eda38 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/semanal_typeddict.py @@ -0,0 +1,631 @@ +"""Semantic analysis of TypedDict definitions.""" + +from __future__ import annotations + +from collections.abc import Collection +from typing import Final + +from mypy import errorcodes as codes, message_registry +from mypy.errorcodes import ErrorCode +from mypy.expandtype import expand_type +from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type +from mypy.message_registry import TYPEDDICT_OVERRIDE_MERGE +from mypy.messages import MessageBuilder +from mypy.nodes import ( + ARG_NAMED, + ARG_POS, + AssignmentStmt, + CallExpr, + ClassDef, + Context, + DictExpr, + EllipsisExpr, + Expression, + ExpressionStmt, + IndexExpr, + NameExpr, + PassStmt, + RefExpr, + Statement, + StrExpr, + TempNode, + TupleExpr, + TypeAlias, + TypedDictExpr, + TypeInfo, +) +from mypy.options import Options +from mypy.semanal_shared import ( + SemanticAnalyzerInterface, + has_placeholder, + require_bool_literal_argument, +) +from mypy.state import state +from mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type +from mypy.types import ( + TPDICT_NAMES, + AnyType, + ReadOnlyType, + RequiredType, + Type, + TypedDictType, + TypeOfAny, + TypeVarLikeType, + get_proper_type, +) + +TPDICT_CLASS_ERROR: Final = ( + 'Invalid statement in TypedDict definition; expected "field_name: field_type"' +) + + +class TypedDictAnalyzer: + def __init__( + self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder + ) -> None: + self.options = options + self.api = api + self.msg = msg + + def analyze_typeddict_classdef(self, defn: ClassDef) -> tuple[bool, TypeInfo | None]: + """Analyze a class that may define a TypedDict. + + Assume that base classes have been analyzed already. + + Note: Unlike normal classes, we won't create a TypeInfo until + the whole definition of the TypeDict (including the body and all + key names and types) is complete. This is mostly because we + store the corresponding TypedDictType in the TypeInfo. + + Return (is this a TypedDict, new TypeInfo). Specifics: + * If we couldn't finish due to incomplete reference anywhere in + the definition, return (True, None). + * If this is not a TypedDict, return (False, None). + """ + possible = False + for base_expr in defn.base_type_exprs: + if isinstance(base_expr, CallExpr): + base_expr = base_expr.callee + if isinstance(base_expr, IndexExpr): + base_expr = base_expr.base + if isinstance(base_expr, RefExpr): + self.api.accept(base_expr) + if base_expr.fullname in TPDICT_NAMES or self.is_typeddict(base_expr): + possible = True + if isinstance(base_expr.node, TypeInfo) and base_expr.node.is_final: + err = message_registry.CANNOT_INHERIT_FROM_FINAL + self.fail(err.format(base_expr.node.name).value, defn, code=err.code) + if not possible: + return False, None + existing_info = None + if isinstance(defn.analyzed, TypedDictExpr): + existing_info = defn.analyzed.info + + field_types: dict[str, Type] | None + if ( + len(defn.base_type_exprs) == 1 + and isinstance(defn.base_type_exprs[0], RefExpr) + and defn.base_type_exprs[0].fullname in TPDICT_NAMES + ): + # Building a new TypedDict + field_types, statements, required_keys, readonly_keys = ( + self.analyze_typeddict_classdef_fields(defn) + ) + if field_types is None: + return True, None # Defer + if self.api.is_func_scope() and "@" not in defn.name: + defn.name += "@" + str(defn.line) + info = self.build_typeddict_typeinfo( + defn.name, field_types, required_keys, readonly_keys, defn.line, existing_info + ) + defn.analyzed = TypedDictExpr(info) + defn.analyzed.line = defn.line + defn.analyzed.column = defn.column + defn.defs.body = statements + return True, info + + # Extending/merging existing TypedDicts + typeddict_bases: list[Expression] = [] + typeddict_bases_set = set() + for expr in defn.base_type_exprs: + ok, maybe_type_info, _ = self.check_typeddict(expr, None, False) + if ok and maybe_type_info is not None: + # expr is a CallExpr + info = maybe_type_info + typeddict_bases_set.add(info.fullname) + typeddict_bases.append(expr) + elif isinstance(expr, RefExpr) and expr.fullname in TPDICT_NAMES: + if "TypedDict" not in typeddict_bases_set: + typeddict_bases_set.add("TypedDict") + else: + self.fail('Duplicate base class "TypedDict"', defn) + elif ( + isinstance(expr, RefExpr) + and self.is_typeddict(expr) + or isinstance(expr, IndexExpr) + and self.is_typeddict(expr.base) + ): + info = self._parse_typeddict_base(expr, defn) + if info.fullname not in typeddict_bases_set: + typeddict_bases_set.add(info.fullname) + typeddict_bases.append(expr) + else: + self.fail(f'Duplicate base class "{info.name}"', defn) + else: + self.fail("All bases of a new TypedDict must be TypedDict types", defn) + + field_types = {} + required_keys = set() + readonly_keys = set() + # Iterate over bases in reverse order so that leftmost base class' keys take precedence + for base in reversed(typeddict_bases): + self.add_keys_and_types_from_base( + base, field_types, required_keys, readonly_keys, defn + ) + new_field_types, new_statements, new_required_keys, new_readonly_keys = ( + self.analyze_typeddict_classdef_fields(defn, oldfields=field_types) + ) + if new_field_types is None: + return True, None # Defer + field_types.update(new_field_types) + required_keys.update(new_required_keys) + readonly_keys.update(new_readonly_keys) + info = self.build_typeddict_typeinfo( + defn.name, field_types, required_keys, readonly_keys, defn.line, existing_info + ) + defn.analyzed = TypedDictExpr(info) + defn.analyzed.line = defn.line + defn.analyzed.column = defn.column + defn.defs.body = new_statements + return True, info + + def add_keys_and_types_from_base( + self, + base: Expression, + field_types: dict[str, Type], + required_keys: set[str], + readonly_keys: set[str], + ctx: Context, + ) -> None: + info = self._parse_typeddict_base(base, ctx) + base_args: list[Type] = [] + if isinstance(base, IndexExpr): + args = self.analyze_base_args(base, ctx) + if args is None: + return + base_args = args + + assert info.typeddict_type is not None + base_typed_dict = info.typeddict_type + base_items = base_typed_dict.items + valid_items = base_items.copy() + + # Always fix invalid bases to avoid crashes. + tvars = info.defn.type_vars + if len(base_args) != len(tvars): + any_kind = TypeOfAny.from_omitted_generics + if base_args: + self.fail(f'Invalid number of type arguments for "{info.name}"', ctx) + any_kind = TypeOfAny.from_error + base_args = [AnyType(any_kind) for _ in tvars] + + with state.strict_optional_set(self.options.strict_optional): + valid_items = self.map_items_to_base(valid_items, tvars, base_args) + for key in base_items: + if key in field_types: + self.fail(TYPEDDICT_OVERRIDE_MERGE.format(key), ctx) + + field_types.update(valid_items) + required_keys.update(base_typed_dict.required_keys) + readonly_keys.update(base_typed_dict.readonly_keys) + + def _parse_typeddict_base(self, base: Expression, ctx: Context) -> TypeInfo: + if isinstance(base, RefExpr): + if isinstance(base.node, TypeInfo): + return base.node + elif isinstance(base.node, TypeAlias): + # Only old TypeAlias / plain assignment, PEP695 `type` stmt + # cannot be used as a base class + target = get_proper_type(base.node.target) + assert isinstance(target, TypedDictType) + return target.fallback.type + else: + assert False + elif isinstance(base, IndexExpr): + assert isinstance(base.base, RefExpr) + return self._parse_typeddict_base(base.base, ctx) + else: + assert isinstance(base, CallExpr) + assert isinstance(base.analyzed, TypedDictExpr) + return base.analyzed.info + + def analyze_base_args(self, base: IndexExpr, ctx: Context) -> list[Type] | None: + """Analyze arguments of base type expressions as types. + + We need to do this, because normal base class processing happens after + the TypedDict special-casing (plus we get a custom error message). + """ + base_args = [] + if isinstance(base.index, TupleExpr): + args = base.index.items + else: + args = [base.index] + + for arg_expr in args: + try: + type = expr_to_unanalyzed_type(arg_expr, self.options, self.api.is_stub_file) + except TypeTranslationError: + self.fail("Invalid TypedDict type argument", ctx) + return None + analyzed = self.api.anal_type( + type, + allow_typed_dict_special_forms=True, + allow_placeholder=not self.api.is_func_scope(), + ) + if analyzed is None: + return None + base_args.append(analyzed) + return base_args + + def map_items_to_base( + self, valid_items: dict[str, Type], tvars: list[TypeVarLikeType], base_args: list[Type] + ) -> dict[str, Type]: + """Map item types to how they would look in their base with type arguments applied. + + Note it is safe to use expand_type() during semantic analysis, because it should never + (indirectly) call is_subtype(). + """ + mapped_items = {} + for key in valid_items: + type_in_base = valid_items[key] + if not tvars: + mapped_items[key] = type_in_base + continue + # TODO: simple zip can't be used for variadic types. + mapped_items[key] = expand_type( + type_in_base, {t.id: a for (t, a) in zip(tvars, base_args)} + ) + return mapped_items + + def analyze_typeddict_classdef_fields( + self, defn: ClassDef, oldfields: Collection[str] | None = None + ) -> tuple[dict[str, Type] | None, list[Statement], set[str], set[str]]: + """Analyze fields defined in a TypedDict class definition. + + This doesn't consider inherited fields (if any). Also consider totality, + if given. + + Return tuple with these items: + * Dict of key -> type (or None if found an incomplete reference -> deferral) + * List of statements from defn.defs.body that are legally allowed to be a + part of a TypedDict definition + * Set of required keys + """ + fields: dict[str, Type] = {} + readonly_keys = set[str]() + required_keys = set[str]() + statements: list[Statement] = [] + + total: bool | None = True + for key in defn.keywords: + if key == "total": + total = require_bool_literal_argument( + self.api, defn.keywords["total"], "total", True + ) + continue + for_function = ' for "__init_subclass__" of "TypedDict"' + self.msg.unexpected_keyword_argument_for_function(for_function, key, defn) + + for stmt in defn.defs.body: + if not isinstance(stmt, AssignmentStmt): + # Still allow pass or ... (for empty TypedDict's) and docstrings + if isinstance(stmt, PassStmt) or ( + isinstance(stmt, ExpressionStmt) + and isinstance(stmt.expr, (EllipsisExpr, StrExpr)) + ): + statements.append(stmt) + else: + defn.removed_statements.append(stmt) + self.fail(TPDICT_CLASS_ERROR, stmt) + elif len(stmt.lvalues) > 1 or not isinstance(stmt.lvalues[0], NameExpr): + # An assignment, but an invalid one. + defn.removed_statements.append(stmt) + self.fail(TPDICT_CLASS_ERROR, stmt) + else: + name = stmt.lvalues[0].name + if name in (oldfields or []): + self.fail(f'Overwriting TypedDict field "{name}" while extending', stmt) + if name in fields: + self.fail(f'Duplicate TypedDict key "{name}"', stmt) + continue + # Append stmt, name, and type in this case... + statements.append(stmt) + + field_type: Type + if stmt.unanalyzed_type is None: + field_type = AnyType(TypeOfAny.unannotated) + else: + analyzed = self.api.anal_type( + stmt.unanalyzed_type, + allow_typed_dict_special_forms=True, + allow_placeholder=not self.api.is_func_scope(), + prohibit_self_type="TypedDict item type", + prohibit_special_class_field_types="TypedDict", + ) + if analyzed is None: + return None, [], set(), set() # Need to defer + field_type = analyzed + if not has_placeholder(analyzed): + stmt.type = self.extract_meta_info(analyzed, stmt)[0] + + field_type, required, readonly = self.extract_meta_info(field_type) + fields[name] = field_type + + if (total or required is True) and required is not False: + required_keys.add(name) + if readonly: + readonly_keys.add(name) + + # ...despite possible minor failures that allow further analysis. + if stmt.type is None or hasattr(stmt, "new_syntax") and not stmt.new_syntax: + self.fail(TPDICT_CLASS_ERROR, stmt) + elif not isinstance(stmt.rvalue, TempNode): + # x: int assigns rvalue to TempNode(AnyType()) + self.fail("Right hand side values are not supported in TypedDict", stmt) + + return fields, statements, required_keys, readonly_keys + + def extract_meta_info( + self, typ: Type, context: Context | None = None + ) -> tuple[Type, bool | None, bool]: + """Unwrap all metadata types.""" + is_required = None # default, no modification + readonly = False # by default all is mutable + + seen_required = False + seen_readonly = False + while isinstance(typ, (RequiredType, ReadOnlyType)): + if isinstance(typ, RequiredType): + if context is not None and seen_required: + self.fail( + '"{}" type cannot be nested'.format( + "Required[]" if typ.required else "NotRequired[]" + ), + context, + code=codes.VALID_TYPE, + ) + is_required = typ.required + seen_required = True + typ = typ.item + if isinstance(typ, ReadOnlyType): + if context is not None and seen_readonly: + self.fail('"ReadOnly[]" type cannot be nested', context, code=codes.VALID_TYPE) + readonly = True + seen_readonly = True + typ = typ.item + return typ, is_required, readonly + + def check_typeddict( + self, node: Expression, var_name: str | None, is_func_scope: bool + ) -> tuple[bool, TypeInfo | None, list[TypeVarLikeType]]: + """Check if a call defines a TypedDict. + + The optional var_name argument is the name of the variable to + which this is assigned, if any. + + Return a pair (is it a typed dict, corresponding TypeInfo). + + If the definition is invalid but looks like a TypedDict, + report errors but return (some) TypeInfo. If some type is not ready, + return (True, None). + """ + if not isinstance(node, CallExpr): + return False, None, [] + call = node + callee = call.callee + if not isinstance(callee, RefExpr): + return False, None, [] + fullname = callee.fullname + if fullname not in TPDICT_NAMES: + return False, None, [] + res = self.parse_typeddict_args(call) + if res is None: + # This is a valid typed dict, but some type is not ready. + # The caller should defer this until next iteration. + return True, None, [] + name, items, types, total, tvar_defs, ok = res + if not ok: + # Error. Construct dummy return value. + if var_name: + name = var_name + if is_func_scope: + name += "@" + str(call.line) + else: + name = var_name = "TypedDict@" + str(call.line) + info = self.build_typeddict_typeinfo(name, {}, set(), set(), call.line, None) + else: + if var_name is not None and name != var_name: + self.fail( + 'First argument "{}" to TypedDict() does not match variable name "{}"'.format( + name, var_name + ), + node, + code=codes.NAME_MATCH, + ) + if name != var_name or is_func_scope: + # Give it a unique name derived from the line number. + name += "@" + str(call.line) + required_keys = { + field + for (field, t) in zip(items, types) + if (total or (isinstance(t, RequiredType) and t.required)) + and not (isinstance(t, RequiredType) and not t.required) + } + readonly_keys = { + field for (field, t) in zip(items, types) if isinstance(t, ReadOnlyType) + } + types = [ # unwrap Required[T] or ReadOnly[T] to just T + t.item if isinstance(t, (RequiredType, ReadOnlyType)) else t for t in types + ] + + # Perform various validations after unwrapping. + for t in types: + check_for_explicit_any( + t, self.options, self.api.is_typeshed_stub_file, self.msg, context=call + ) + if self.options.disallow_any_unimported: + for t in types: + if has_any_from_unimported_type(t): + self.msg.unimported_type_becomes_any("Type of a TypedDict key", t, call) + + existing_info = None + if isinstance(node.analyzed, TypedDictExpr): + existing_info = node.analyzed.info + info = self.build_typeddict_typeinfo( + name, + dict(zip(items, types)), + required_keys, + readonly_keys, + call.line, + existing_info, + ) + info.line = node.line + # Store generated TypeInfo under both names, see semanal_namedtuple for more details. + if name != var_name or is_func_scope: + self.api.add_symbol_skip_local(name, info) + if var_name: + self.api.add_symbol(var_name, info, node) + call.analyzed = TypedDictExpr(info) + call.analyzed.set_line(call) + return True, info, tvar_defs + + def parse_typeddict_args( + self, call: CallExpr + ) -> tuple[str, list[str], list[Type], bool, list[TypeVarLikeType], bool] | None: + """Parse typed dict call expression. + + Return names, types, totality, was there an error during parsing. + If some type is not ready, return None. + """ + # TODO: Share code with check_argument_count in checkexpr.py? + args = call.args + if len(args) < 2: + return self.fail_typeddict_arg("Too few arguments for TypedDict()", call) + if len(args) > 3: + return self.fail_typeddict_arg("Too many arguments for TypedDict()", call) + # TODO: Support keyword arguments + if call.arg_kinds not in ([ARG_POS, ARG_POS], [ARG_POS, ARG_POS, ARG_NAMED]): + return self.fail_typeddict_arg("Unexpected arguments to TypedDict()", call) + if len(args) == 3 and call.arg_names[2] != "total": + return self.fail_typeddict_arg( + f'Unexpected keyword argument "{call.arg_names[2]}" for "TypedDict"', call + ) + if not isinstance(args[0], StrExpr): + return self.fail_typeddict_arg( + "TypedDict() expects a string literal as the first argument", call + ) + if not isinstance(args[1], DictExpr): + return self.fail_typeddict_arg( + "TypedDict() expects a dictionary literal as the second argument", call + ) + total: bool | None = True + if len(args) == 3: + total = require_bool_literal_argument(self.api, call.args[2], "total") + if total is None: + return "", [], [], True, [], False + dictexpr = args[1] + tvar_defs = self.api.get_and_bind_all_tvars([t for k, t in dictexpr.items]) + res = self.parse_typeddict_fields_with_types(dictexpr.items) + if res is None: + # One of the types is not ready, defer. + return None + items, types, ok = res + assert total is not None + return args[0].value, items, types, total, tvar_defs, ok + + def parse_typeddict_fields_with_types( + self, dict_items: list[tuple[Expression | None, Expression]] + ) -> tuple[list[str], list[Type], bool] | None: + """Parse typed dict items passed as pairs (name expression, type expression). + + Return names, types, was there an error. If some type is not ready, return None. + """ + seen_keys = set() + items: list[str] = [] + types: list[Type] = [] + for field_name_expr, field_type_expr in dict_items: + if isinstance(field_name_expr, StrExpr): + key = field_name_expr.value + items.append(key) + if key in seen_keys: + self.fail(f'Duplicate TypedDict key "{key}"', field_name_expr) + seen_keys.add(key) + else: + name_context = field_name_expr or field_type_expr + self.fail_typeddict_arg("Invalid TypedDict() field name", name_context) + return [], [], False + try: + type = expr_to_unanalyzed_type( + field_type_expr, self.options, self.api.is_stub_file + ) + except TypeTranslationError: + self.fail_typeddict_arg("Use dict literal for nested TypedDict", field_type_expr) + return [], [], False + analyzed = self.api.anal_type( + type, + allow_typed_dict_special_forms=True, + allow_placeholder=not self.api.is_func_scope(), + prohibit_self_type="TypedDict item type", + prohibit_special_class_field_types="TypedDict", + ) + if analyzed is None: + return None + types.append(analyzed) + return items, types, True + + def fail_typeddict_arg( + self, message: str, context: Context + ) -> tuple[str, list[str], list[Type], bool, list[TypeVarLikeType], bool]: + self.fail(message, context) + return "", [], [], True, [], False + + def build_typeddict_typeinfo( + self, + name: str, + item_types: dict[str, Type], + required_keys: set[str], + readonly_keys: set[str], + line: int, + existing_info: TypeInfo | None, + ) -> TypeInfo: + # Prefer typing then typing_extensions if available. + fallback = ( + self.api.named_type_or_none("typing._TypedDict", []) + or self.api.named_type_or_none("typing_extensions._TypedDict", []) + or self.api.named_type_or_none("mypy_extensions._TypedDict", []) + ) + assert fallback is not None + info = existing_info or self.api.basic_new_typeinfo(name, fallback, line) + typeddict_type = TypedDictType(item_types, required_keys, readonly_keys, fallback) + if has_placeholder(typeddict_type): + self.api.process_placeholder( + None, "TypedDict item", info, force_progress=typeddict_type != info.typeddict_type + ) + info.update_typeddict_type(typeddict_type) + return info + + # Helpers + + def is_typeddict(self, expr: Expression) -> bool: + return isinstance(expr, RefExpr) and ( + isinstance(expr.node, TypeInfo) + and expr.node.typeddict_type is not None + or isinstance(expr.node, TypeAlias) + and isinstance(get_proper_type(expr.node.target), TypedDictType) + ) + + def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + self.api.fail(msg, ctx, code=code) + + def note(self, msg: str, ctx: Context) -> None: + self.api.note(msg, ctx) diff --git a/micromamba_root/Lib/site-packages/mypy/sharedparse.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/sharedparse.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..6cf7e0458bd097147caeaa20a8ebbfeeb254cb42 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/sharedparse.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/sharedparse.py b/micromamba_root/Lib/site-packages/mypy/sharedparse.py new file mode 100644 index 0000000000000000000000000000000000000000..71d1dee8f7d6e20c4daabdfcdf0b433a69e0be33 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/sharedparse.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +from typing import Final + +"""Shared logic between our three mypy parser files.""" + + +_NON_BINARY_MAGIC_METHODS: Final = { + "__abs__", + "__call__", + "__complex__", + "__contains__", + "__buffer__", + "__del__", + "__delattr__", + "__delitem__", + "__enter__", + "__exit__", + "__float__", + "__getattr__", + "__getattribute__", + "__getitem__", + "__hex__", + "__init__", + "__init_subclass__", + "__int__", + "__invert__", + "__iter__", + "__len__", + "__long__", + "__neg__", + "__new__", + "__oct__", + "__pos__", + "__release_buffer__", + "__repr__", + "__reversed__", + "__setattr__", + "__setitem__", + "__str__", +} + +MAGIC_METHODS_ALLOWING_KWARGS: Final = { + "__init__", + "__init_subclass__", + "__new__", + "__call__", + "__setattr__", +} + +BINARY_MAGIC_METHODS: Final = { + "__add__", + "__and__", + "__divmod__", + "__eq__", + "__floordiv__", + "__ge__", + "__gt__", + "__iadd__", + "__iand__", + "__idiv__", + "__ifloordiv__", + "__ilshift__", + "__imatmul__", + "__imod__", + "__imul__", + "__ior__", + "__ipow__", + "__irshift__", + "__isub__", + "__itruediv__", + "__ixor__", + "__le__", + "__lshift__", + "__lt__", + "__matmul__", + "__mod__", + "__mul__", + "__ne__", + "__or__", + "__pow__", + "__radd__", + "__rand__", + "__rdiv__", + "__rfloordiv__", + "__rlshift__", + "__rmatmul__", + "__rmod__", + "__rmul__", + "__ror__", + "__rpow__", + "__rrshift__", + "__rshift__", + "__rsub__", + "__rtruediv__", + "__rxor__", + "__sub__", + "__truediv__", + "__xor__", +} + +assert not (_NON_BINARY_MAGIC_METHODS & BINARY_MAGIC_METHODS) + +MAGIC_METHODS: Final = _NON_BINARY_MAGIC_METHODS | BINARY_MAGIC_METHODS + +MAGIC_METHODS_POS_ARGS_ONLY: Final = MAGIC_METHODS - MAGIC_METHODS_ALLOWING_KWARGS + + +def special_function_elide_names(name: str) -> bool: + return name in MAGIC_METHODS_POS_ARGS_ONLY + + +def argument_elide_name(name: str | None) -> bool: + return name is not None and name.startswith("__") and not name.endswith("__") diff --git a/micromamba_root/Lib/site-packages/mypy/solve.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/solve.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e10fec17aeddea111416b707c68b158e18523236 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/solve.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/solve.py b/micromamba_root/Lib/site-packages/mypy/solve.py new file mode 100644 index 0000000000000000000000000000000000000000..e3709106996cdc79beacb5b53e171bf5893edcc0 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/solve.py @@ -0,0 +1,598 @@ +"""Type inference constraint solving""" + +from __future__ import annotations + +from collections import defaultdict +from collections.abc import Iterable, Sequence +from typing import TypeAlias as _TypeAlias + +from mypy.constraints import SUBTYPE_OF, SUPERTYPE_OF, Constraint, infer_constraints, neg_op +from mypy.expandtype import expand_type +from mypy.graph_utils import prepare_sccs, strongly_connected_components, topsort +from mypy.join import join_type_list +from mypy.meet import meet_type_list, meet_types +from mypy.subtypes import is_subtype +from mypy.typeops import get_all_type_vars +from mypy.types import ( + AnyType, + Instance, + NoneType, + ParamSpecType, + ProperType, + TupleType, + Type, + TypeOfAny, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UninhabitedType, + UnionType, + UnpackType, + get_proper_type, +) +from mypy.typestate import type_state + +Bounds: _TypeAlias = "dict[TypeVarId, set[Type]]" +Graph: _TypeAlias = "set[tuple[TypeVarId, TypeVarId]]" +Solutions: _TypeAlias = "dict[TypeVarId, Type | None]" + + +def solve_constraints( + original_vars: Sequence[TypeVarLikeType], + constraints: list[Constraint], + strict: bool = True, + allow_polymorphic: bool = False, + skip_unsatisfied: bool = False, +) -> tuple[list[Type | None], list[TypeVarLikeType]]: + """Solve type constraints. + + Return the best type(s) for type variables; each type can be None if the value of + the variable could not be solved. + + If a variable has no constraints, if strict=True then arbitrarily + pick UninhabitedType as the value of the type variable. If strict=False, pick AnyType. + If allow_polymorphic=True, then use the full algorithm that can potentially return + free type variables in solutions (these require special care when applying). Otherwise, + use a simplified algorithm that just solves each type variable individually if possible. + + The skip_unsatisfied flag matches the same one in applytype.apply_generic_arguments(). + """ + vars = [tv.id for tv in original_vars] + if not vars: + return [], [] + + originals = {tv.id: tv for tv in original_vars} + extra_vars: list[TypeVarId] = [] + # Get additional type variables from generic actuals. + for c in constraints: + extra_vars.extend([v.id for v in c.extra_tvars if v.id not in vars + extra_vars]) + originals.update({v.id: v for v in c.extra_tvars if v.id not in originals}) + + if allow_polymorphic: + # Constraints inferred from unions require special handling in polymorphic inference. + constraints = skip_reverse_union_constraints(constraints) + + # Collect a list of constraints for each type variable. + cmap: dict[TypeVarId, list[Constraint]] = {tv: [] for tv in vars + extra_vars} + for con in constraints: + if con.type_var in vars + extra_vars: + cmap[con.type_var].append(con) + + if allow_polymorphic: + if constraints: + solutions, free_vars = solve_with_dependent( + vars + extra_vars, constraints, vars, originals + ) + else: + solutions = {} + free_vars = [] + else: + solutions = {} + free_vars = [] + for tv, cs in cmap.items(): + if not cs: + continue + lowers = [c.target for c in cs if c.op == SUPERTYPE_OF] + uppers = [c.target for c in cs if c.op == SUBTYPE_OF] + solution = solve_one(lowers, uppers) + + # Do not leak type variables in non-polymorphic solutions. + if solution is None or not get_vars( + solution, [tv for tv in extra_vars if tv not in vars] + ): + solutions[tv] = solution + + res: list[Type | None] = [] + for v in vars: + if v in solutions: + res.append(solutions[v]) + else: + # No constraints for type variable -- 'UninhabitedType' is the most specific type. + candidate: Type + if strict: + candidate = UninhabitedType() + candidate.ambiguous = True + else: + candidate = AnyType(TypeOfAny.special_form) + res.append(candidate) + + if not free_vars and not skip_unsatisfied: + # Most of the validation for solutions is done in applytype.py, but here we can + # quickly test solutions w.r.t. to upper bounds, and use the latter (if possible), + # if solutions are actually not valid (due to poor inference context). + res = pre_validate_solutions(res, original_vars, constraints) + + return res, free_vars + + +def solve_with_dependent( + vars: list[TypeVarId], + constraints: list[Constraint], + original_vars: list[TypeVarId], + originals: dict[TypeVarId, TypeVarLikeType], +) -> tuple[Solutions, list[TypeVarLikeType]]: + """Solve set of constraints that may depend on each other, like T <: List[S]. + + The whole algorithm consists of five steps: + * Propagate via linear constraints and use secondary constraints to get transitive closure + * Find dependencies between type variables, group them in SCCs, and sort topologically + * Check that all SCC are intrinsically linear, we can't solve (express) T <: List[T] + * Variables in leaf SCCs that don't have constant bounds are free (choose one per SCC) + * Solve constraints iteratively starting from leaves, updating bounds after each step. + """ + graph, lowers, uppers = transitive_closure(vars, constraints) + + dmap = compute_dependencies(vars, graph, lowers, uppers) + sccs = list(strongly_connected_components(set(vars), dmap)) + if not all(check_linear(scc, lowers, uppers) for scc in sccs): + return {}, [] + raw_batches = list(topsort(prepare_sccs(sccs, dmap))) + + free_vars = [] + free_solutions = {} + for scc in raw_batches[0]: + # If there are no bounds on this SCC, then the only meaningful solution we can + # express, is that each variable is equal to a new free variable. For example, + # if we have T <: S, S <: U, we deduce: T = S = U = . + if all(not lowers[tv] and not uppers[tv] for tv in scc): + best_free = choose_free([originals[tv] for tv in scc], original_vars) + if best_free: + # TODO: failing to choose may cause leaking type variables, + # we need to fail gracefully instead. + free_vars.append(best_free.id) + free_solutions[best_free.id] = best_free + + # Update lowers/uppers with free vars, so these can now be used + # as valid solutions. + for l, u in graph: + if l in free_vars: + lowers[u].add(free_solutions[l]) + if u in free_vars: + uppers[l].add(free_solutions[u]) + + # Flatten the SCCs that are independent, we can solve them together, + # since we don't need to update any targets in between. + batches = [] + for batch in raw_batches: + next_bc = [] + for scc in batch: + next_bc.extend(list(scc)) + batches.append(next_bc) + + solutions: dict[TypeVarId, Type | None] = {} + for flat_batch in batches: + res = solve_iteratively(flat_batch, graph, lowers, uppers) + solutions.update(res) + return solutions, [free_solutions[tv] for tv in free_vars] + + +def solve_iteratively( + batch: list[TypeVarId], graph: Graph, lowers: Bounds, uppers: Bounds +) -> Solutions: + """Solve transitive closure sequentially, updating upper/lower bounds after each step. + + Transitive closure is represented as a linear graph plus lower/upper bounds for each + type variable, see transitive_closure() docstring for details. + + We solve for type variables that appear in `batch`. If a bound is not constant (i.e. it + looks like T :> F[S, ...]), we substitute solutions found so far in the target F[S, ...] + after solving the batch. + + Importantly, after solving each variable in a batch, we move it from linear graph to + upper/lower bounds, this way we can guarantee consistency of solutions (see comment below + for an example when this is important). + """ + solutions = {} + s_batch = set(batch) + while s_batch: + for tv in sorted(s_batch, key=lambda x: x.raw_id): + if lowers[tv] or uppers[tv]: + solvable_tv = tv + break + else: + break + # Solve each solvable type variable separately. + s_batch.remove(solvable_tv) + result = solve_one(lowers[solvable_tv], uppers[solvable_tv]) + solutions[solvable_tv] = result + if result is None: + # TODO: support backtracking lower/upper bound choices and order within SCCs. + # (will require switching this function from iterative to recursive). + continue + + # Update the (transitive) bounds from graph if there is a solution. + # This is needed to guarantee solutions will never contradict the initial + # constraints. For example, consider {T <: S, T <: A, S :> B} with A :> B. + # If we would not update the uppers/lowers from graph, we would infer T = A, S = B + # which is not correct. + for l, u in graph.copy(): + if l == u: + continue + if l == solvable_tv: + lowers[u].add(result) + graph.remove((l, u)) + if u == solvable_tv: + uppers[l].add(result) + graph.remove((l, u)) + + # We can update uppers/lowers only once after solving the whole SCC, + # since uppers/lowers can't depend on type variables in the SCC + # (and we would reject such SCC as non-linear and therefore not solvable). + subs = {tv: s for (tv, s) in solutions.items() if s is not None} + for tv in lowers: + lowers[tv] = {expand_type(lt, subs) for lt in lowers[tv]} + for tv in uppers: + uppers[tv] = {expand_type(ut, subs) for ut in uppers[tv]} + return solutions + + +def _join_sorted_key(t: Type) -> int: + t = get_proper_type(t) + if isinstance(t, UnionType): + return -2 + if isinstance(t, NoneType): + return -1 + return 0 + + +def solve_one(lowers: Iterable[Type], uppers: Iterable[Type]) -> Type | None: + """Solve constraints by finding by using meets of upper bounds, and joins of lower bounds.""" + + candidate: Type | None = None + + # Filter out previous results of failed inference, they will only spoil the current pass... + new_uppers = [] + for u in uppers: + pu = get_proper_type(u) + if not isinstance(pu, UninhabitedType) or not pu.ambiguous: + new_uppers.append(u) + uppers = new_uppers + + # ...unless this is the only information we have, then we just pass it on. + lowers = list(lowers) + if not uppers and not lowers: + candidate = UninhabitedType() + candidate.ambiguous = True + return candidate + + bottom: Type | None = None + top: Type | None = None + + # Process each bound separately, and calculate the lower and upper + # bounds based on constraints. Note that we assume that the constraint + # targets do not have constraint references. + if type_state.infer_unions and lowers: + # This deviates from the general mypy semantics because + # recursive types are union-heavy in 95% of cases. + # Retain `None` when no bottoms were provided to avoid bogus `Never` inference. + bottom = UnionType.make_union(lowers) + else: + # The order of lowers is non-deterministic. + # We attempt to sort lowers because joins are non-associative. For instance: + # join(join(int, str), int | str) == join(object, int | str) == object + # join(int, join(str, int | str)) == join(int, int | str) == int | str + # Note that joins in theory should be commutative, but in practice some bugs mean this is + # also a source of non-deterministic type checking results. + sorted_lowers = sorted(lowers, key=_join_sorted_key) + if sorted_lowers: + bottom = join_type_list(sorted_lowers) + + for target in uppers: + if top is None: + top = target + else: + top = meet_types(top, target) + + p_top = get_proper_type(top) + p_bottom = get_proper_type(bottom) + if isinstance(p_top, AnyType) or isinstance(p_bottom, AnyType): + source_any = top if isinstance(p_top, AnyType) else bottom + assert isinstance(source_any, ProperType) and isinstance(source_any, AnyType) + return AnyType(TypeOfAny.from_another_any, source_any=source_any) + elif bottom is None: + if top: + candidate = top + else: + # No constraints for type variable + return None + elif top is None: + candidate = bottom + elif is_subtype(bottom, top): + candidate = bottom + else: + candidate = None + return candidate + + +def choose_free( + scc: list[TypeVarLikeType], original_vars: list[TypeVarId] +) -> TypeVarLikeType | None: + """Choose the best solution for an SCC containing only type variables. + + This is needed to preserve e.g. the upper bound in a situation like this: + def dec(f: Callable[[T], S]) -> Callable[[T], S]: ... + + @dec + def test(x: U) -> U: ... + + where U <: A. + """ + + if len(scc) == 1: + # Fast path, choice is trivial. + return scc[0] + + common_upper_bound = meet_type_list([t.upper_bound for t in scc]) + common_upper_bound_p = get_proper_type(common_upper_bound) + # We include None for when strict-optional is disabled. + if isinstance(common_upper_bound_p, (UninhabitedType, NoneType)): + # This will cause to infer Never, which is better than a free TypeVar + # that has an upper bound Never. + return None + + values: list[Type] = [] + for tv in scc: + if isinstance(tv, TypeVarType) and tv.values: + if values: + # It is too tricky to support multiple TypeVars with values + # within the same SCC. + return None + values = tv.values.copy() + + if values and not is_trivial_bound(common_upper_bound_p): + # If there are both values and upper bound present, we give up, + # since type variables having both are not supported. + return None + + # For convenience with current type application machinery, we use a stable + # choice that prefers the original type variables (not polymorphic ones) in SCC. + best = min(scc, key=lambda x: (x.id not in original_vars, x.id.raw_id)) + if isinstance(best, TypeVarType): + return best.copy_modified(values=values, upper_bound=common_upper_bound) + if is_trivial_bound(common_upper_bound_p, allow_tuple=True): + # TODO: support more cases for ParamSpecs/TypeVarTuples + return best + return None + + +def is_trivial_bound(tp: ProperType, allow_tuple: bool = False) -> bool: + if isinstance(tp, Instance) and tp.type.fullname == "builtins.tuple": + return allow_tuple and is_trivial_bound(get_proper_type(tp.args[0])) + return isinstance(tp, Instance) and tp.type.fullname == "builtins.object" + + +def find_linear(c: Constraint) -> tuple[bool, TypeVarId | None]: + """Find out if this constraint represent a linear relationship, return target id if yes.""" + if isinstance(c.origin_type_var, TypeVarType): + if isinstance(c.target, TypeVarType): + return True, c.target.id + if isinstance(c.origin_type_var, ParamSpecType): + if isinstance(c.target, ParamSpecType) and not c.target.prefix.arg_types: + return True, c.target.id + if isinstance(c.origin_type_var, TypeVarTupleType): + target = get_proper_type(c.target) + if isinstance(target, TupleType) and len(target.items) == 1: + item = target.items[0] + if isinstance(item, UnpackType) and isinstance(item.type, TypeVarTupleType): + return True, item.type.id + return False, None + + +def transitive_closure( + tvars: list[TypeVarId], constraints: list[Constraint] +) -> tuple[Graph, Bounds, Bounds]: + """Find transitive closure for given constraints on type variables. + + Transitive closure gives maximal set of lower/upper bounds for each type variable, + such that we cannot deduce any further bounds by chaining other existing bounds. + + The transitive closure is represented by: + * A set of lower and upper bounds for each type variable, where only constant and + non-linear terms are included in the bounds. + * A graph of linear constraints between type variables (represented as a set of pairs) + Such separation simplifies reasoning, and allows an efficient and simple incremental + transitive closure algorithm that we use here. + + For example if we have initial constraints [T <: S, S <: U, U <: int], the transitive + closure is given by: + * {} <: T <: {int} + * {} <: S <: {int} + * {} <: U <: {int} + * {T <: S, S <: U, T <: U} + """ + uppers: Bounds = defaultdict(set) + lowers: Bounds = defaultdict(set) + graph: Graph = {(tv, tv) for tv in tvars} + + remaining = set(constraints) + while remaining: + c = remaining.pop() + # Note that ParamSpec constraint P <: Q may be considered linear only if Q has no prefix, + # for cases like P <: Concatenate[T, Q] we should consider this non-linear and put {P} and + # {T, Q} into separate SCCs. Similarly, Ts <: Tuple[*Us] considered linear, while + # Ts <: Tuple[*Us, U] is non-linear. + is_linear, target_id = find_linear(c) + if is_linear and target_id in tvars: + assert target_id is not None + if c.op == SUBTYPE_OF: + lower, upper = c.type_var, target_id + else: + lower, upper = target_id, c.type_var + if (lower, upper) in graph: + continue + graph |= { + (l, u) for l in tvars for u in tvars if (l, lower) in graph and (upper, u) in graph + } + for u in tvars: + if (upper, u) in graph: + lowers[u] |= lowers[lower] + for l in tvars: + if (l, lower) in graph: + uppers[l] |= uppers[upper] + for lt in lowers[lower]: + for ut in uppers[upper]: + add_secondary_constraints(remaining, lt, ut) + elif c.op == SUBTYPE_OF: + if c.target in uppers[c.type_var]: + continue + for l in tvars: + if (l, c.type_var) in graph: + uppers[l].add(c.target) + for lt in lowers[c.type_var]: + add_secondary_constraints(remaining, lt, c.target) + else: + assert c.op == SUPERTYPE_OF + if c.target in lowers[c.type_var]: + continue + for u in tvars: + if (c.type_var, u) in graph: + lowers[u].add(c.target) + for ut in uppers[c.type_var]: + add_secondary_constraints(remaining, c.target, ut) + return graph, lowers, uppers + + +def add_secondary_constraints(cs: set[Constraint], lower: Type, upper: Type) -> None: + """Add secondary constraints inferred between lower and upper (in place).""" + if isinstance(get_proper_type(upper), UnionType) and isinstance( + get_proper_type(lower), UnionType + ): + # When both types are unions, this can lead to inferring spurious constraints, + # for example Union[T, int] <: S <: Union[T, int] may infer T <: int. + # To avoid this, just skip them for now. + return + # TODO: what if secondary constraints result in inference against polymorphic actual? + cs.update(set(infer_constraints(lower, upper, SUBTYPE_OF))) + cs.update(set(infer_constraints(upper, lower, SUPERTYPE_OF))) + + +def compute_dependencies( + tvars: list[TypeVarId], graph: Graph, lowers: Bounds, uppers: Bounds +) -> dict[TypeVarId, list[TypeVarId]]: + """Compute dependencies between type variables induced by constraints. + + If we have a constraint like T <: List[S], we say that T depends on S, since + we will need to solve for S first before we can solve for T. + """ + res = {} + for tv in tvars: + deps = set() + for lt in lowers[tv]: + deps |= get_vars(lt, tvars) + for ut in uppers[tv]: + deps |= get_vars(ut, tvars) + for other in tvars: + if other == tv: + continue + if (tv, other) in graph or (other, tv) in graph: + deps.add(other) + res[tv] = list(deps) + return res + + +def check_linear(scc: set[TypeVarId], lowers: Bounds, uppers: Bounds) -> bool: + """Check there are only linear constraints between type variables in SCC. + + Linear are constraints like T <: S (while T <: F[S] are non-linear). + """ + for tv in scc: + if any(get_vars(lt, list(scc)) for lt in lowers[tv]): + return False + if any(get_vars(ut, list(scc)) for ut in uppers[tv]): + return False + return True + + +def skip_reverse_union_constraints(cs: list[Constraint]) -> list[Constraint]: + """Avoid ambiguities for constraints inferred from unions during polymorphic inference. + + Polymorphic inference implicitly relies on assumption that a reverse of a linear constraint + is a linear constraint. This is however not true in presence of union types, for example + T :> Union[S, int] vs S <: T. Trying to solve such constraints would be detected ambiguous + as (T, S) form a non-linear SCC. However, simply removing the linear part results in a valid + solution T = Union[S, int], S = . A similar scenario is when we get T <: Union[T, int], + such constraints carry no information, and will equally confuse linearity check. + + TODO: a cleaner solution may be to avoid inferring such constraints in first place, but + this would require passing around a flag through all infer_constraints() calls. + """ + reverse_union_cs = set() + for c in cs: + p_target = get_proper_type(c.target) + if isinstance(p_target, UnionType): + for item in p_target.items: + if isinstance(item, TypeVarType): + if item == c.origin_type_var and c.op == SUBTYPE_OF: + reverse_union_cs.add(c) + continue + # These two forms are semantically identical, but are different from + # the point of view of Constraint.__eq__(). + reverse_union_cs.add(Constraint(item, neg_op(c.op), c.origin_type_var)) + reverse_union_cs.add(Constraint(c.origin_type_var, c.op, item)) + return [c for c in cs if c not in reverse_union_cs] + + +def get_vars(target: Type, vars: list[TypeVarId]) -> set[TypeVarId]: + """Find type variables for which we are solving in a target type.""" + return {tv.id for tv in get_all_type_vars(target)} & set(vars) + + +def pre_validate_solutions( + solutions: list[Type | None], + original_vars: Sequence[TypeVarLikeType], + constraints: list[Constraint], +) -> list[Type | None]: + """Check is each solution satisfies the upper bound of the corresponding type variable. + + If it doesn't satisfy the bound, check if bound itself satisfies all constraints, and + if yes, use it instead as a fallback solution. + """ + new_solutions: list[Type | None] = [] + for t, s in zip(original_vars, solutions): + if is_callable_protocol(t.upper_bound): + # This is really ad-hoc, but a proper fix would be much more complex, + # and otherwise this may cause crash in a relatively common scenario. + new_solutions.append(s) + continue + if s is not None and not is_subtype(s, t.upper_bound): + bound_satisfies_all = True + for c in constraints: + if c.op == SUBTYPE_OF and not is_subtype(t.upper_bound, c.target): + bound_satisfies_all = False + break + if c.op == SUPERTYPE_OF and not is_subtype(c.target, t.upper_bound): + bound_satisfies_all = False + break + if bound_satisfies_all: + new_solutions.append(t.upper_bound) + continue + new_solutions.append(s) + return new_solutions + + +def is_callable_protocol(t: Type) -> bool: + proper_t = get_proper_type(t) + if isinstance(proper_t, Instance) and proper_t.type.is_protocol: + return "__call__" in proper_t.type.protocol_members + return False diff --git a/micromamba_root/Lib/site-packages/mypy/split_namespace.py b/micromamba_root/Lib/site-packages/mypy/split_namespace.py new file mode 100644 index 0000000000000000000000000000000000000000..d1720cce82b04bde33c815ab97e96fd4df5835dd --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/split_namespace.py @@ -0,0 +1,35 @@ +"""Split namespace for argparse to allow separating options by prefix. + +We use this to direct some options to an Options object and some to a +regular namespace. +""" + +# In its own file largely because mypyc doesn't support its use of +# __getattr__/__setattr__ and has some issues with __dict__ + +from __future__ import annotations + +import argparse +from typing import Any + + +class SplitNamespace(argparse.Namespace): + def __init__(self, standard_namespace: object, alt_namespace: object, alt_prefix: str) -> None: + self.__dict__["_standard_namespace"] = standard_namespace + self.__dict__["_alt_namespace"] = alt_namespace + self.__dict__["_alt_prefix"] = alt_prefix + + def _get(self) -> tuple[Any, Any]: + return (self._standard_namespace, self._alt_namespace) + + def __setattr__(self, name: str, value: Any) -> None: + if name.startswith(self._alt_prefix): + setattr(self._alt_namespace, name[len(self._alt_prefix) :], value) + else: + setattr(self._standard_namespace, name, value) + + def __getattr__(self, name: str) -> Any: + if name.startswith(self._alt_prefix): + return getattr(self._alt_namespace, name[len(self._alt_prefix) :]) + else: + return getattr(self._standard_namespace, name) diff --git a/micromamba_root/Lib/site-packages/mypy/state.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/state.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..254e82da29c067d753bf5003f9576d479deea603 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/state.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/state.py b/micromamba_root/Lib/site-packages/mypy/state.py new file mode 100644 index 0000000000000000000000000000000000000000..a3055bf6b2085d7a230b7df8fa7fb153228312fe --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/state.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Final + +# These are global mutable state. Don't add anything here unless there's a very +# good reason. + + +class StrictOptionalState: + # Wrap this in a class since it's faster that using a module-level attribute. + + def __init__(self, strict_optional: bool) -> None: + # Value varies by file being processed + self.strict_optional = strict_optional + + @contextmanager + def strict_optional_set(self, value: bool) -> Iterator[None]: + saved = self.strict_optional + self.strict_optional = value + try: + yield + finally: + self.strict_optional = saved + + +state: Final = StrictOptionalState(strict_optional=True) +find_occurrences: tuple[str, str] | None = None diff --git a/micromamba_root/Lib/site-packages/mypy/stats.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/stats.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..83742c576d460bfb75de71e15d55deb0e3105e49 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/stats.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/stats.py b/micromamba_root/Lib/site-packages/mypy/stats.py new file mode 100644 index 0000000000000000000000000000000000000000..e3499d23456350cf39121b72231d53a57569bde8 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/stats.py @@ -0,0 +1,494 @@ +"""Utilities for calculating and reporting statistics about types.""" + +from __future__ import annotations + +import os +from collections import Counter +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Final + +from mypy import nodes +from mypy.argmap import map_formals_to_actuals +from mypy.nodes import ( + AssignmentExpr, + AssignmentStmt, + BreakStmt, + BytesExpr, + CallExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ContinueStmt, + EllipsisExpr, + Expression, + ExpressionStmt, + FloatExpr, + FuncDef, + Import, + ImportAll, + ImportFrom, + IndexExpr, + IntExpr, + MemberExpr, + MypyFile, + NameExpr, + Node, + OpExpr, + PassStmt, + RefExpr, + StrExpr, + TypeApplication, + UnaryExpr, + YieldFromExpr, +) +from mypy.traverser import TraverserVisitor +from mypy.type_visitor import ANY_STRATEGY, BoolTypeQuery +from mypy.typeanal import collect_all_inner_types +from mypy.types import ( + AnyType, + CallableType, + FunctionLike, + Instance, + TupleType, + Type, + TypeOfAny, + TypeVarType, + get_proper_type, + get_proper_types, +) +from mypy.util import correct_relative_import + +TYPE_EMPTY: Final = 0 +TYPE_UNANALYZED: Final = 1 # type of non-typechecked code +TYPE_PRECISE: Final = 2 +TYPE_IMPRECISE: Final = 3 +TYPE_ANY: Final = 4 + +precision_names: Final = ["empty", "unanalyzed", "precise", "imprecise", "any"] + + +class StatisticsVisitor(TraverserVisitor): + def __init__( + self, + inferred: bool, + filename: str, + modules: dict[str, MypyFile], + typemap: dict[Expression, Type] | None = None, + all_nodes: bool = False, + visit_untyped_defs: bool = True, + ) -> None: + self.inferred = inferred + self.filename = filename + self.modules = modules + self.typemap = typemap + self.all_nodes = all_nodes + self.visit_untyped_defs = visit_untyped_defs + + self.num_precise_exprs = 0 + self.num_imprecise_exprs = 0 + self.num_any_exprs = 0 + + self.num_simple_types = 0 + self.num_generic_types = 0 + self.num_tuple_types = 0 + self.num_function_types = 0 + self.num_typevar_types = 0 + self.num_complex_types = 0 + self.num_any_types = 0 + + self.line = -1 + + self.line_map: dict[int, int] = {} + + self.type_of_any_counter: Counter[int] = Counter() + self.any_line_map: dict[int, list[AnyType]] = {} + + # For each scope (top level/function), whether the scope was type checked + # (annotated function). + # + # TODO: Handle --check-untyped-defs + self.checked_scopes = [True] + + self.output: list[str] = [] + + TraverserVisitor.__init__(self) + + def visit_mypy_file(self, o: MypyFile) -> None: + self.cur_mod_node = o + self.cur_mod_id = o.fullname + super().visit_mypy_file(o) + + def visit_import_from(self, imp: ImportFrom) -> None: + self.process_import(imp) + + def visit_import_all(self, imp: ImportAll) -> None: + self.process_import(imp) + + def process_import(self, imp: ImportFrom | ImportAll) -> None: + import_id, ok = correct_relative_import( + self.cur_mod_id, imp.relative, imp.id, self.cur_mod_node.is_package_init_file() + ) + if ok and import_id in self.modules: + kind = TYPE_PRECISE + else: + kind = TYPE_ANY + self.record_line(imp.line, kind) + + def visit_import(self, imp: Import) -> None: + if all(id in self.modules for id, _ in imp.ids): + kind = TYPE_PRECISE + else: + kind = TYPE_ANY + self.record_line(imp.line, kind) + + def visit_func_def(self, o: FuncDef) -> None: + with self.enter_scope(o): + self.line = o.line + if len(o.expanded) > 1 and o.expanded != [o] * len(o.expanded): + if o in o.expanded: + print( + "{}:{}: ERROR: cycle in function expansion; skipping".format( + self.filename, o.line + ) + ) + return + for defn in o.expanded: + assert isinstance(defn, FuncDef) + self.visit_func_def(defn) + else: + if o.type: + assert isinstance(o.type, CallableType) + sig = o.type + arg_types = sig.arg_types + if sig.arg_names and sig.arg_names[0] == "self" and not self.inferred: + arg_types = arg_types[1:] + for arg in arg_types: + self.type(arg) + self.type(sig.ret_type) + elif self.all_nodes: + self.record_line(self.line, TYPE_ANY) + if not o.is_dynamic() or self.visit_untyped_defs: + super().visit_func_def(o) + + @contextmanager + def enter_scope(self, o: FuncDef) -> Iterator[None]: + self.checked_scopes.append(o.type is not None and self.checked_scopes[-1]) + yield None + self.checked_scopes.pop() + + def is_checked_scope(self) -> bool: + return self.checked_scopes[-1] + + def visit_class_def(self, o: ClassDef) -> None: + self.record_line(o.line, TYPE_PRECISE) # TODO: Look at base classes + # Override this method because we don't want to analyze base_type_exprs (base_type_exprs + # are base classes in a class declaration). + # While base_type_exprs are technically expressions, type analyzer does not visit them and + # they are not in the typemap. + for d in o.decorators: + d.accept(self) + o.defs.accept(self) + + def visit_type_application(self, o: TypeApplication) -> None: + self.line = o.line + for t in o.types: + self.type(t) + super().visit_type_application(o) + + def visit_assignment_stmt(self, o: AssignmentStmt) -> None: + self.line = o.line + if isinstance(o.rvalue, nodes.CallExpr) and isinstance( + o.rvalue.analyzed, nodes.TypeVarExpr + ): + # Type variable definition -- not a real assignment. + return + if o.type: + # If there is an explicit type, don't visit the l.h.s. as an expression + # to avoid double-counting and mishandling special forms. + self.type(o.type) + o.rvalue.accept(self) + return + elif self.inferred and not self.all_nodes: + # if self.all_nodes is set, lvalues will be visited later + for lvalue in o.lvalues: + if isinstance(lvalue, nodes.TupleExpr): + items = lvalue.items + else: + items = [lvalue] + for item in items: + if isinstance(item, RefExpr) and item.is_inferred_def: + if self.typemap is not None: + self.type(self.typemap.get(item)) + super().visit_assignment_stmt(o) + + def visit_expression_stmt(self, o: ExpressionStmt) -> None: + if isinstance(o.expr, (StrExpr, BytesExpr)): + # Docstring + self.record_line(o.line, TYPE_EMPTY) + else: + super().visit_expression_stmt(o) + + def visit_pass_stmt(self, o: PassStmt) -> None: + self.record_precise_if_checked_scope(o) + + def visit_break_stmt(self, o: BreakStmt) -> None: + self.record_precise_if_checked_scope(o) + + def visit_continue_stmt(self, o: ContinueStmt) -> None: + self.record_precise_if_checked_scope(o) + + def visit_name_expr(self, o: NameExpr) -> None: + if o.fullname in ("builtins.None", "builtins.True", "builtins.False", "builtins.Ellipsis"): + self.record_precise_if_checked_scope(o) + else: + self.process_node(o) + super().visit_name_expr(o) + + def visit_yield_from_expr(self, o: YieldFromExpr) -> None: + if o.expr: + o.expr.accept(self) + + def visit_call_expr(self, o: CallExpr) -> None: + self.process_node(o) + if o.analyzed: + o.analyzed.accept(self) + else: + o.callee.accept(self) + for a in o.args: + a.accept(self) + self.record_call_target_precision(o) + + def record_call_target_precision(self, o: CallExpr) -> None: + """Record precision of formal argument types used in a call.""" + if not self.typemap or o.callee not in self.typemap: + # Type not available. + return + callee_type = get_proper_type(self.typemap[o.callee]) + if isinstance(callee_type, CallableType): + self.record_callable_target_precision(o, callee_type) + else: + pass # TODO: Handle overloaded functions, etc. + + def record_callable_target_precision(self, o: CallExpr, callee: CallableType) -> None: + """Record imprecision caused by callee argument types. + + This only considers arguments passed in a call expression. Arguments + with default values that aren't provided in a call arguably don't + contribute to typing imprecision at the *call site* (but they + contribute at the function definition). + """ + assert self.typemap + typemap = self.typemap + actual_to_formal = map_formals_to_actuals( + o.arg_kinds, + o.arg_names, + callee.arg_kinds, + callee.arg_names, + lambda n: typemap[o.args[n]], + ) + for formals in actual_to_formal: + for n in formals: + formal = get_proper_type(callee.arg_types[n]) + if isinstance(formal, AnyType): + self.record_line(o.line, TYPE_ANY) + elif is_imprecise(formal): + self.record_line(o.line, TYPE_IMPRECISE) + + def visit_member_expr(self, o: MemberExpr) -> None: + self.process_node(o) + super().visit_member_expr(o) + + def visit_op_expr(self, o: OpExpr) -> None: + self.process_node(o) + super().visit_op_expr(o) + + def visit_comparison_expr(self, o: ComparisonExpr) -> None: + self.process_node(o) + super().visit_comparison_expr(o) + + def visit_index_expr(self, o: IndexExpr) -> None: + self.process_node(o) + super().visit_index_expr(o) + + def visit_assignment_expr(self, o: AssignmentExpr) -> None: + self.process_node(o) + super().visit_assignment_expr(o) + + def visit_unary_expr(self, o: UnaryExpr) -> None: + self.process_node(o) + super().visit_unary_expr(o) + + def visit_str_expr(self, o: StrExpr) -> None: + self.record_precise_if_checked_scope(o) + + def visit_bytes_expr(self, o: BytesExpr) -> None: + self.record_precise_if_checked_scope(o) + + def visit_int_expr(self, o: IntExpr) -> None: + self.record_precise_if_checked_scope(o) + + def visit_float_expr(self, o: FloatExpr) -> None: + self.record_precise_if_checked_scope(o) + + def visit_complex_expr(self, o: ComplexExpr) -> None: + self.record_precise_if_checked_scope(o) + + def visit_ellipsis(self, o: EllipsisExpr) -> None: + self.record_precise_if_checked_scope(o) + + # Helpers + + def process_node(self, node: Expression) -> None: + if self.all_nodes: + if self.typemap is not None: + self.line = node.line + self.type(self.typemap.get(node)) + + def record_precise_if_checked_scope(self, node: Node) -> None: + if isinstance(node, Expression) and self.typemap and node not in self.typemap: + kind = TYPE_UNANALYZED + elif self.is_checked_scope(): + kind = TYPE_PRECISE + else: + kind = TYPE_ANY + self.record_line(node.line, kind) + + def type(self, t: Type | None) -> None: + t = get_proper_type(t) + + if not t: + # If an expression does not have a type, it is often due to dead code. + # Don't count these because there can be an unanalyzed value on a line with other + # analyzed expressions, which overwrite the TYPE_UNANALYZED. + self.record_line(self.line, TYPE_UNANALYZED) + return + + if isinstance(t, AnyType) and is_special_form_any(t): + # TODO: What if there is an error in special form definition? + self.record_line(self.line, TYPE_PRECISE) + return + + if isinstance(t, AnyType): + self.log(" !! Any type around line %d" % self.line) + self.num_any_exprs += 1 + self.record_line(self.line, TYPE_ANY) + elif (not self.all_nodes and is_imprecise(t)) or (self.all_nodes and is_imprecise2(t)): + self.log(" !! Imprecise type around line %d" % self.line) + self.num_imprecise_exprs += 1 + self.record_line(self.line, TYPE_IMPRECISE) + else: + self.num_precise_exprs += 1 + self.record_line(self.line, TYPE_PRECISE) + + for typ in get_proper_types(collect_all_inner_types(t)) + [t]: + if isinstance(typ, AnyType): + typ = get_original_any(typ) + if is_special_form_any(typ): + continue + self.type_of_any_counter[typ.type_of_any] += 1 + self.num_any_types += 1 + if self.line in self.any_line_map: + self.any_line_map[self.line].append(typ) + else: + self.any_line_map[self.line] = [typ] + elif isinstance(typ, Instance): + if typ.args: + if any(is_complex(arg) for arg in typ.args): + self.num_complex_types += 1 + else: + self.num_generic_types += 1 + else: + self.num_simple_types += 1 + elif isinstance(typ, FunctionLike): + self.num_function_types += 1 + elif isinstance(typ, TupleType): + if any(is_complex(item) for item in typ.items): + self.num_complex_types += 1 + else: + self.num_tuple_types += 1 + elif isinstance(typ, TypeVarType): + self.num_typevar_types += 1 + + def log(self, string: str) -> None: + self.output.append(string) + + def record_line(self, line: int, precision: int) -> None: + self.line_map[line] = max(precision, self.line_map.get(line, TYPE_EMPTY)) + + +def dump_type_stats( + tree: MypyFile, + path: str, + modules: dict[str, MypyFile], + inferred: bool = False, + typemap: dict[Expression, Type] | None = None, +) -> None: + if is_special_module(path): + return + print(path) + visitor = StatisticsVisitor(inferred, filename=tree.fullname, modules=modules, typemap=typemap) + tree.accept(visitor) + for line in visitor.output: + print(line) + print(" ** precision **") + print(" precise ", visitor.num_precise_exprs) + print(" imprecise", visitor.num_imprecise_exprs) + print(" any ", visitor.num_any_exprs) + print(" ** kinds **") + print(" simple ", visitor.num_simple_types) + print(" generic ", visitor.num_generic_types) + print(" function ", visitor.num_function_types) + print(" tuple ", visitor.num_tuple_types) + print(" TypeVar ", visitor.num_typevar_types) + print(" complex ", visitor.num_complex_types) + print(" any ", visitor.num_any_types) + + +def is_special_module(path: str) -> bool: + return os.path.basename(path) in ("abc.pyi", "typing.pyi", "builtins.pyi") + + +def is_imprecise(t: Type) -> bool: + return t.accept(HasAnyQuery()) + + +class HasAnyQuery(BoolTypeQuery): + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_any(self, t: AnyType) -> bool: + return not is_special_form_any(t) + + +def is_imprecise2(t: Type) -> bool: + return t.accept(HasAnyQuery2()) + + +class HasAnyQuery2(HasAnyQuery): + def visit_callable_type(self, t: CallableType) -> bool: + # We don't want to flag references to functions with some Any + # argument types (etc.) since they generally don't mean trouble. + return False + + +def is_generic(t: Type) -> bool: + t = get_proper_type(t) + return isinstance(t, Instance) and bool(t.args) + + +def is_complex(t: Type) -> bool: + t = get_proper_type(t) + return is_generic(t) or isinstance(t, (FunctionLike, TupleType, TypeVarType)) + + +def is_special_form_any(t: AnyType) -> bool: + return get_original_any(t).type_of_any == TypeOfAny.special_form + + +def get_original_any(t: AnyType) -> AnyType: + if t.type_of_any == TypeOfAny.from_another_any: + assert t.source_any + assert t.source_any.type_of_any != TypeOfAny.from_another_any + t = t.source_any + return t diff --git a/micromamba_root/Lib/site-packages/mypy/strconv.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/strconv.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..105969d42bef3ec4d013c6873470ca6eb9bf91f4 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/strconv.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/strconv.py b/micromamba_root/Lib/site-packages/mypy/strconv.py new file mode 100644 index 0000000000000000000000000000000000000000..b26f1d8d71a8e4494c58837a080871fb48eeaa6f --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/strconv.py @@ -0,0 +1,707 @@ +"""Conversion of parse tree nodes to strings.""" + +from __future__ import annotations + +import os +import re +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any + +import mypy.nodes +from mypy.options import Options +from mypy.util import IdMapper, short_type +from mypy.visitor import NodeVisitor + +if TYPE_CHECKING: + import mypy.patterns + import mypy.types + + +class StrConv(NodeVisitor[str]): + """Visitor for converting a node to a human-readable string. + + For example, an MypyFile node from program '1' is converted into + something like this: + + MypyFile:1( + fnam + ExpressionStmt:1( + IntExpr(1))) + """ + + __slots__ = ["options", "show_ids", "id_mapper"] + + def __init__(self, *, show_ids: bool = False, options: Options) -> None: + self.options = options + self.show_ids = show_ids + self.id_mapper: IdMapper | None = None + if show_ids: + self.id_mapper = IdMapper() + + def stringify_type(self, t: mypy.types.Type) -> str: + import mypy.types + + return t.accept(mypy.types.TypeStrVisitor(id_mapper=self.id_mapper, options=self.options)) + + def get_id(self, o: object) -> int | None: + if self.id_mapper: + return self.id_mapper.id(o) + return None + + def format_id(self, o: object) -> str: + if self.id_mapper: + return f"<{self.get_id(o)}>" + else: + return "" + + def dump(self, nodes: Sequence[object], obj: mypy.nodes.Context) -> str: + """Convert a list of items to a multiline pretty-printed string. + + The tag is produced from the type name of obj and its line + number. See mypy.util.dump_tagged for a description of the nodes + argument. + """ + tag = short_type(obj) + ":" + str(obj.line) + if self.show_ids: + assert self.id_mapper is not None + tag += f"<{self.get_id(obj)}>" + return dump_tagged(nodes, tag, self) + + def func_helper(self, o: mypy.nodes.FuncItem) -> list[object]: + """Return a list in a format suitable for dump() that represents the + arguments and the body of a function. The caller can then decorate the + array with information specific to methods, global functions or + anonymous functions. + """ + args: list[mypy.nodes.Var | tuple[str, list[mypy.nodes.Node]]] = [] + extra: list[tuple[str, list[mypy.nodes.Var]]] = [] + for arg in o.arguments: + kind: mypy.nodes.ArgKind = arg.kind + if kind.is_required(): + args.append(arg.variable) + elif kind.is_optional(): + assert arg.initializer is not None + args.append(("default", [arg.variable, arg.initializer])) + elif kind == mypy.nodes.ARG_STAR: + extra.append(("VarArg", [arg.variable])) + elif kind == mypy.nodes.ARG_STAR2: + extra.append(("DictVarArg", [arg.variable])) + a: list[Any] = [] + if o.type_args: + for p in o.type_args: + a.append(self.type_param(p)) + if args: + a.append(("Args", args)) + if o.type: + a.append(o.type) + if o.is_generator: + a.append("Generator") + a.extend(extra) + a.append(o.body) + return a + + # Top-level structures + + def visit_mypy_file(self, o: mypy.nodes.MypyFile) -> str: + # Skip implicit definitions. + a: list[Any] = [o.defs] + if o.is_bom: + a.insert(0, "BOM") + # Omit path to special file with name "main". This is used to simplify + # test case descriptions; the file "main" is used by default in many + # test cases. + if o.path != "main": + # Insert path. Normalize directory separators to / to unify test + # case# output in all platforms. + a.insert(0, o.path.replace(os.getcwd() + os.sep, "").replace(os.sep, "/")) + if o.ignored_lines: + a.append("IgnoredLines(%s)" % ", ".join(str(line) for line in sorted(o.ignored_lines))) + return self.dump(a, o) + + def visit_import(self, o: mypy.nodes.Import) -> str: + a = [] + for id, as_id in o.ids: + if as_id is not None: + a.append(f"{id} : {as_id}") + else: + a.append(id) + return f"Import:{o.line}({', '.join(a)})" + + def visit_import_from(self, o: mypy.nodes.ImportFrom) -> str: + a = [] + for name, as_name in o.names: + if as_name is not None: + a.append(f"{name} : {as_name}") + else: + a.append(name) + return f"ImportFrom:{o.line}({'.' * o.relative + o.id}, [{', '.join(a)}])" + + def visit_import_all(self, o: mypy.nodes.ImportAll) -> str: + return f"ImportAll:{o.line}({'.' * o.relative + o.id})" + + # Definitions + + def visit_func_def(self, o: mypy.nodes.FuncDef) -> str: + a = self.func_helper(o) + a.insert(0, o.name) + arg_kinds = {arg.kind for arg in o.arguments} + if len(arg_kinds & {mypy.nodes.ARG_NAMED, mypy.nodes.ARG_NAMED_OPT}) > 0: + a.insert(1, f"MaxPos({o.max_pos})") + if o.is_coroutine: + a.insert(1, "Async") + if o.abstract_status in (mypy.nodes.IS_ABSTRACT, mypy.nodes.IMPLICITLY_ABSTRACT): + a.insert(-1, "Abstract") + if o.is_static: + a.insert(-1, "Static") + if o.is_class: + a.insert(-1, "Class") + if o.is_property: + a.insert(-1, "Property") + return self.dump(a, o) + + def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef) -> str: + a: Any = o.items.copy() + if o.type: + a.insert(0, o.type) + if o.impl: + a.insert(0, o.impl) + if o.is_static: + a.insert(-1, "Static") + if o.is_class: + a.insert(-1, "Class") + return self.dump(a, o) + + def visit_class_def(self, o: mypy.nodes.ClassDef) -> str: + a = [o.name, o.defs.body] + # Display base types unless they are implicitly just builtins.object + # (in this case base_type_exprs is empty). + if o.base_type_exprs: + if o.info and o.info.bases: + if len(o.info.bases) != 1 or o.info.bases[0].type.fullname != "builtins.object": + a.insert(1, ("BaseType", o.info.bases)) + else: + a.insert(1, ("BaseTypeExpr", o.base_type_exprs)) + if o.type_vars: + a.insert(1, ("TypeVars", o.type_vars)) + if o.metaclass: + a.insert(1, f"Metaclass({o.metaclass.accept(self)})") + if o.keywords: + keyword_items = [f"{k}={v.accept(self)}" for k, v in o.keywords.items()] + a.insert(1, f"Keywords({', '.join(keyword_items)})") + if o.decorators: + a.insert(1, ("Decorators", o.decorators)) + if o.info and o.info._promote: + a.insert(1, f"Promote([{','.join(self.stringify_type(p) for p in o.info._promote)}])") + if o.info and o.info.tuple_type: + a.insert(1, ("TupleType", [o.info.tuple_type])) + if o.info and o.info.fallback_to_any: + a.insert(1, "FallbackToAny") + if o.type_args: + for p in reversed(o.type_args): + a.insert(1, self.type_param(p)) + return self.dump(a, o) + + def visit_var(self, o: mypy.nodes.Var) -> str: + lst = "" + # Add :nil line number tag if no line number is specified to remain + # compatible with old test case descriptions that assume this. + if o.line < 0: + lst = ":nil" + return "Var" + lst + "(" + o.name + ")" + + def visit_global_decl(self, o: mypy.nodes.GlobalDecl) -> str: + return self.dump([o.names], o) + + def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl) -> str: + return self.dump([o.names], o) + + def visit_decorator(self, o: mypy.nodes.Decorator) -> str: + return self.dump([o.var, o.decorators, o.func], o) + + def visit_type_alias(self, o: mypy.nodes.TypeAlias, /) -> str: + return self.dump([o.name, o.target, o.alias_tvars, o.no_args], o) + + def visit_placeholder_node(self, o: mypy.nodes.PlaceholderNode, /) -> str: + return self.dump([o.fullname], o) + + # Statements + + def visit_block(self, o: mypy.nodes.Block) -> str: + return self.dump(o.body, o) + + def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt) -> str: + return self.dump([o.expr], o) + + def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt) -> str: + a: list[Any] = [] + if len(o.lvalues) > 1: + a = [("Lvalues", o.lvalues)] + else: + a = [o.lvalues[0]] + a.append(o.rvalue) + if o.type: + a.append(o.type) + return self.dump(a, o) + + def visit_operator_assignment_stmt(self, o: mypy.nodes.OperatorAssignmentStmt) -> str: + return self.dump([o.op, o.lvalue, o.rvalue], o) + + def visit_while_stmt(self, o: mypy.nodes.WhileStmt) -> str: + a: list[Any] = [o.expr, o.body] + if o.else_body: + a.append(("Else", o.else_body.body)) + return self.dump(a, o) + + def visit_for_stmt(self, o: mypy.nodes.ForStmt) -> str: + a: list[Any] = [] + if o.is_async: + a.append(("Async", "")) + a.append(o.index) + if o.index_type: + a.append(o.index_type) + a.extend([o.expr, o.body]) + if o.else_body: + a.append(("Else", o.else_body.body)) + return self.dump(a, o) + + def visit_return_stmt(self, o: mypy.nodes.ReturnStmt) -> str: + return self.dump([o.expr], o) + + def visit_if_stmt(self, o: mypy.nodes.IfStmt) -> str: + a: list[Any] = [] + for i in range(len(o.expr)): + a.append(("If", [o.expr[i]])) + a.append(("Then", o.body[i].body)) + + if not o.else_body: + return self.dump(a, o) + else: + return self.dump([a, ("Else", o.else_body.body)], o) + + def visit_break_stmt(self, o: mypy.nodes.BreakStmt) -> str: + return self.dump([], o) + + def visit_continue_stmt(self, o: mypy.nodes.ContinueStmt) -> str: + return self.dump([], o) + + def visit_pass_stmt(self, o: mypy.nodes.PassStmt) -> str: + return self.dump([], o) + + def visit_raise_stmt(self, o: mypy.nodes.RaiseStmt) -> str: + return self.dump([o.expr, o.from_expr], o) + + def visit_assert_stmt(self, o: mypy.nodes.AssertStmt) -> str: + if o.msg is not None: + return self.dump([o.expr, o.msg], o) + else: + return self.dump([o.expr], o) + + def visit_await_expr(self, o: mypy.nodes.AwaitExpr) -> str: + return self.dump([o.expr], o) + + def visit_del_stmt(self, o: mypy.nodes.DelStmt) -> str: + return self.dump([o.expr], o) + + def visit_try_stmt(self, o: mypy.nodes.TryStmt) -> str: + a: list[Any] = [o.body] + if o.is_star: + a.append("*") + + for i in range(len(o.vars)): + a.append(o.types[i]) + if o.vars[i]: + a.append(o.vars[i]) + a.append(o.handlers[i]) + + if o.else_body: + a.append(("Else", o.else_body.body)) + if o.finally_body: + a.append(("Finally", o.finally_body.body)) + + return self.dump(a, o) + + def visit_with_stmt(self, o: mypy.nodes.WithStmt) -> str: + a: list[Any] = [] + if o.is_async: + a.append(("Async", "")) + for i in range(len(o.expr)): + a.append(("Expr", [o.expr[i]])) + if o.target[i]: + a.append(("Target", [o.target[i]])) + if o.unanalyzed_type: + a.append(o.unanalyzed_type) + return self.dump(a + [o.body], o) + + def visit_match_stmt(self, o: mypy.nodes.MatchStmt) -> str: + a: list[Any] = [o.subject] + for i in range(len(o.patterns)): + a.append(("Pattern", [o.patterns[i]])) + if o.guards[i] is not None: + a.append(("Guard", [o.guards[i]])) + a.append(("Body", o.bodies[i].body)) + return self.dump(a, o) + + def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt) -> str: + a: list[Any] = [o.name] + for p in o.type_args: + a.append(self.type_param(p)) + a.append(o.value) + return self.dump(a, o) + + def type_param(self, p: mypy.nodes.TypeParam) -> list[Any]: + a: list[Any] = [] + if p.kind == mypy.nodes.PARAM_SPEC_KIND: + prefix = "**" + elif p.kind == mypy.nodes.TYPE_VAR_TUPLE_KIND: + prefix = "*" + else: + prefix = "" + a.append(prefix + p.name) + if p.upper_bound: + a.append(p.upper_bound) + if p.values: + a.append(("Values", p.values)) + if p.default: + a.append(("Default", [p.default])) + return [("TypeParam", a)] + + # Expressions + + # Simple expressions + + def visit_int_expr(self, o: mypy.nodes.IntExpr) -> str: + return f"IntExpr({o.value})" + + def visit_str_expr(self, o: mypy.nodes.StrExpr) -> str: + return f"StrExpr({self.str_repr(o.value)})" + + def visit_bytes_expr(self, o: mypy.nodes.BytesExpr) -> str: + return f"BytesExpr({self.str_repr(o.value)})" + + def str_repr(self, s: str) -> str: + s = re.sub(r"\\u[0-9a-fA-F]{4}", lambda m: "\\" + m.group(0), s) + return re.sub("[^\\x20-\\x7e]", lambda m: r"\u%.4x" % ord(m.group(0)), s) + + def visit_float_expr(self, o: mypy.nodes.FloatExpr) -> str: + return f"FloatExpr({o.value})" + + def visit_complex_expr(self, o: mypy.nodes.ComplexExpr) -> str: + return f"ComplexExpr({o.value})" + + def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr) -> str: + return "Ellipsis" + + def visit_star_expr(self, o: mypy.nodes.StarExpr) -> str: + return self.dump([o.expr], o) + + def visit_name_expr(self, o: mypy.nodes.NameExpr) -> str: + pretty = self.pretty_name( + o.name, o.kind, o.fullname, o.is_inferred_def or o.is_special_form, o.node + ) + if isinstance(o.node, mypy.nodes.Var) and o.node.is_final: + final_value = o.node.final_value + if final_value is not None: + pretty += f" = {o.node.final_value}" + return short_type(o) + "(" + pretty + ")" + + def pretty_name( + self, + name: str, + kind: int | None, + fullname: str | None, + is_inferred_def: bool, + target_node: mypy.nodes.Node | None = None, + ) -> str: + n = name + if is_inferred_def: + n += "*" + if target_node: + id = self.format_id(target_node) + else: + id = "" + if isinstance(target_node, mypy.nodes.MypyFile) and name == fullname: + n += id + elif kind == mypy.nodes.GDEF or (fullname != name and fullname): + # Append fully qualified name for global references. + n += f" [{fullname}{id}]" + elif kind == mypy.nodes.LDEF: + # Add tag to signify a local reference. + n += f" [l{id}]" + elif kind == mypy.nodes.MDEF: + # Add tag to signify a member reference. + n += f" [m{id}]" + else: + n += id + return n + + def visit_member_expr(self, o: mypy.nodes.MemberExpr) -> str: + pretty = self.pretty_name(o.name, o.kind, o.fullname, o.is_inferred_def, o.node) + return self.dump([o.expr, pretty], o) + + def visit_yield_expr(self, o: mypy.nodes.YieldExpr) -> str: + return self.dump([o.expr], o) + + def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr) -> str: + if o.expr: + return self.dump([o.expr.accept(self)], o) + else: + return self.dump([], o) + + def visit_call_expr(self, o: mypy.nodes.CallExpr) -> str: + if o.analyzed: + return o.analyzed.accept(self) + args: list[mypy.nodes.Expression] = [] + extra: list[str | tuple[str, list[Any]]] = [] + for i, kind in enumerate(o.arg_kinds): + if kind in [mypy.nodes.ARG_POS, mypy.nodes.ARG_STAR]: + args.append(o.args[i]) + if kind == mypy.nodes.ARG_STAR: + extra.append("VarArg") + elif kind == mypy.nodes.ARG_NAMED: + extra.append(("KwArgs", [o.arg_names[i], o.args[i]])) + elif kind == mypy.nodes.ARG_STAR2: + extra.append(("DictVarArg", [o.args[i]])) + else: + raise RuntimeError(f"unknown kind {kind}") + a: list[Any] = [o.callee, ("Args", args)] + return self.dump(a + extra, o) + + def visit_op_expr(self, o: mypy.nodes.OpExpr) -> str: + if o.analyzed: + return o.analyzed.accept(self) + return self.dump([o.op, o.left, o.right], o) + + def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr) -> str: + return self.dump([o.operators, o.operands], o) + + def visit_cast_expr(self, o: mypy.nodes.CastExpr) -> str: + return self.dump([o.expr, o.type], o) + + def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr) -> str: + return self.dump([o.type], o) + + def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr) -> str: + return self.dump([o.expr, o.type], o) + + def visit_reveal_expr(self, o: mypy.nodes.RevealExpr) -> str: + if o.kind == mypy.nodes.REVEAL_TYPE: + return self.dump([o.expr], o) + else: + # REVEAL_LOCALS + return self.dump([o.local_nodes], o) + + def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr) -> str: + return self.dump([o.target, o.value], o) + + def visit_unary_expr(self, o: mypy.nodes.UnaryExpr) -> str: + return self.dump([o.op, o.expr], o) + + def visit_list_expr(self, o: mypy.nodes.ListExpr) -> str: + return self.dump(o.items, o) + + def visit_dict_expr(self, o: mypy.nodes.DictExpr) -> str: + return self.dump([[k, v] for k, v in o.items], o) + + def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr) -> str: + items_repr: list[object] = [] + for item in o.items: + if isinstance(item, tuple): + value_expr, source, conversion, format_spec = item + interpolation: list[object] = [ + ("Value", [value_expr]), + f"Source({source!r})", + f"Conversion({conversion!r})", + ] + if format_spec is None: + interpolation.append("FormatSpec(None)") + else: + interpolation.append(("FormatSpec", [format_spec])) + items_repr.append(("Interpolation", interpolation)) + else: + items_repr.append(item) + return self.dump(items_repr, o) + + def visit_set_expr(self, o: mypy.nodes.SetExpr) -> str: + return self.dump(o.items, o) + + def visit_tuple_expr(self, o: mypy.nodes.TupleExpr) -> str: + return self.dump(o.items, o) + + def visit_index_expr(self, o: mypy.nodes.IndexExpr) -> str: + if o.analyzed: + return o.analyzed.accept(self) + return self.dump([o.base, o.index], o) + + def visit_super_expr(self, o: mypy.nodes.SuperExpr) -> str: + return self.dump([o.name, o.call], o) + + def visit_type_application(self, o: mypy.nodes.TypeApplication) -> str: + return self.dump([o.expr, ("Types", o.types)], o) + + def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr) -> str: + import mypy.types + + a: list[Any] = [] + if o.variance == mypy.nodes.COVARIANT: + a += ["Variance(COVARIANT)"] + if o.variance == mypy.nodes.CONTRAVARIANT: + a += ["Variance(CONTRAVARIANT)"] + if o.values: + a += [("Values", o.values)] + if not mypy.types.is_named_instance(o.upper_bound, "builtins.object"): + a += [f"UpperBound({self.stringify_type(o.upper_bound)})"] + return self.dump(a, o) + + def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr) -> str: + import mypy.types + + a: list[Any] = [] + if o.variance == mypy.nodes.COVARIANT: + a += ["Variance(COVARIANT)"] + if o.variance == mypy.nodes.CONTRAVARIANT: + a += ["Variance(CONTRAVARIANT)"] + if not mypy.types.is_named_instance(o.upper_bound, "builtins.object"): + a += [f"UpperBound({self.stringify_type(o.upper_bound)})"] + return self.dump(a, o) + + def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr) -> str: + import mypy.types + + a: list[Any] = [] + if o.variance == mypy.nodes.COVARIANT: + a += ["Variance(COVARIANT)"] + if o.variance == mypy.nodes.CONTRAVARIANT: + a += ["Variance(CONTRAVARIANT)"] + if not mypy.types.is_named_instance(o.upper_bound, "builtins.object"): + a += [f"UpperBound({self.stringify_type(o.upper_bound)})"] + return self.dump(a, o) + + def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr) -> str: + return f"TypeAliasExpr({self.stringify_type(o.node.target)})" + + def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr) -> str: + return f"NamedTupleExpr:{o.line}({o.info.name}, {self.stringify_type(o.info.tuple_type) if o.info.tuple_type is not None else None})" + + def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr) -> str: + return f"EnumCallExpr:{o.line}({o.info.name}, {o.items})" + + def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr) -> str: + return f"TypedDictExpr:{o.line}({o.info.name})" + + def visit__promote_expr(self, o: mypy.nodes.PromoteExpr) -> str: + return f"PromoteExpr:{o.line}({self.stringify_type(o.type)})" + + def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr) -> str: + return f"NewTypeExpr:{o.line}({o.name}, {self.dump([o.old_type], o)})" + + def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr) -> str: + a = self.func_helper(o) + return self.dump(a, o) + + def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr) -> str: + condlists = o.condlists if any(o.condlists) else None + return self.dump([o.left_expr, o.indices, o.sequences, condlists], o) + + def visit_list_comprehension(self, o: mypy.nodes.ListComprehension) -> str: + return self.dump([o.generator], o) + + def visit_set_comprehension(self, o: mypy.nodes.SetComprehension) -> str: + return self.dump([o.generator], o) + + def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension) -> str: + condlists = o.condlists if any(o.condlists) else None + return self.dump([o.key, o.value, o.indices, o.sequences, condlists], o) + + def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr) -> str: + return self.dump([("Condition", [o.cond]), o.if_expr, o.else_expr], o) + + def visit_slice_expr(self, o: mypy.nodes.SliceExpr) -> str: + a: list[Any] = [o.begin_index, o.end_index, o.stride] + if not a[0]: + a[0] = "" + if not a[1]: + a[1] = "" + return self.dump(a, o) + + def visit_temp_node(self, o: mypy.nodes.TempNode) -> str: + return self.dump([o.type], o) + + def visit_as_pattern(self, o: mypy.patterns.AsPattern) -> str: + return self.dump([o.pattern, o.name], o) + + def visit_or_pattern(self, o: mypy.patterns.OrPattern) -> str: + return self.dump(o.patterns, o) + + def visit_value_pattern(self, o: mypy.patterns.ValuePattern) -> str: + return self.dump([o.expr], o) + + def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern) -> str: + return self.dump([o.value], o) + + def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern) -> str: + return self.dump(o.patterns, o) + + def visit_starred_pattern(self, o: mypy.patterns.StarredPattern) -> str: + return self.dump([o.capture], o) + + def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern) -> str: + a: list[Any] = [] + for i in range(len(o.keys)): + a.append(("Key", [o.keys[i]])) + a.append(("Value", [o.values[i]])) + if o.rest is not None: + a.append(("Rest", [o.rest])) + return self.dump(a, o) + + def visit_class_pattern(self, o: mypy.patterns.ClassPattern) -> str: + a: list[Any] = [o.class_ref] + if len(o.positionals) > 0: + a.append(("Positionals", o.positionals)) + for i in range(len(o.keyword_keys)): + a.append(("Keyword", [o.keyword_keys[i], o.keyword_values[i]])) + + return self.dump(a, o) + + +def dump_tagged(nodes: Sequence[object], tag: str | None, str_conv: StrConv) -> str: + """Convert an array into a pretty-printed multiline string representation. + + The format is + tag( + item1.. + itemN) + Individual items are formatted like this: + - arrays are flattened + - pairs (str, array) are converted recursively, so that str is the tag + - other items are converted to strings and indented + """ + from mypy.types import Type, TypeStrVisitor + + a: list[str] = [] + if tag: + a.append(tag + "(") + for n in nodes: + if isinstance(n, list): + if n: + a.append(dump_tagged(n, None, str_conv)) + elif isinstance(n, tuple): + s = dump_tagged(n[1], n[0], str_conv) + a.append(indent(s, 2)) + elif isinstance(n, mypy.nodes.Node): + a.append(indent(n.accept(str_conv), 2)) + elif isinstance(n, Type): + a.append( + indent(n.accept(TypeStrVisitor(str_conv.id_mapper, options=str_conv.options)), 2) + ) + elif n is not None: + a.append(indent(str(n), 2)) + if tag: + a[-1] += ")" + return "\n".join(a) + + +def indent(s: str, n: int) -> str: + """Indent all the lines in s (separated by newlines) by n spaces.""" + s = " " * n + s + s = s.replace("\n", "\n" + " " * n) + return s diff --git a/micromamba_root/Lib/site-packages/mypy/stubdoc.py b/micromamba_root/Lib/site-packages/mypy/stubdoc.py new file mode 100644 index 0000000000000000000000000000000000000000..f0588343000a746c55c38894b42b29fa40e93e07 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/stubdoc.py @@ -0,0 +1,545 @@ +"""Parsing/inferring signatures from documentation. + +This module provides several functions to generate better stubs using +docstrings and Sphinx docs (.rst files). +""" + +from __future__ import annotations + +import contextlib +import io +import keyword +import re +import tokenize +from collections.abc import MutableMapping, MutableSequence, Sequence +from typing import Any, Final, NamedTuple, TypeAlias as _TypeAlias + +import mypy.util + +# Type alias for signatures strings in format ('func_name', '(arg, opt_arg=False)'). +Sig: _TypeAlias = tuple[str, str] + + +_TYPE_RE: Final = re.compile(r"^[a-zA-Z_][\w\[\], .\"\'|]*(\.[a-zA-Z_][\w\[\], ]*)*$") +_ARG_NAME_RE: Final = re.compile(r"\**[A-Za-z_][A-Za-z0-9_]*$") + + +def is_valid_type(s: str) -> bool: + """Try to determine whether a string might be a valid type annotation.""" + if s in ("True", "False", "retval"): + return False + if "," in s and "[" not in s: + return False + return _TYPE_RE.match(s) is not None + + +class ArgSig: + """Signature info for a single argument.""" + + def __init__( + self, + name: str, + type: str | None = None, + *, + default: bool = False, + default_value: str = "...", + ) -> None: + self.name = name + self.type = type + # Does this argument have a default value? + self.default = default + self.default_value = default_value + + def is_star_arg(self) -> bool: + return self.name.startswith("*") and not self.name.startswith("**") + + def is_star_kwarg(self) -> bool: + return self.name.startswith("**") + + def __repr__(self) -> str: + return "ArgSig(name={}, type={}, default={})".format( + repr(self.name), repr(self.type), repr(self.default) + ) + + def __eq__(self, other: Any) -> bool: + if isinstance(other, ArgSig): + return ( + self.name == other.name + and self.type == other.type + and self.default == other.default + and self.default_value == other.default_value + ) + return False + + +class FunctionSig(NamedTuple): + name: str + args: list[ArgSig] + ret_type: str | None + type_args: str = "" # TODO implement in stubgenc and remove the default + docstring: str | None = None + + def is_special_method(self) -> bool: + return bool( + self.name.startswith("__") + and self.name.endswith("__") + and self.args + and self.args[0].name in ("self", "cls") + ) + + def has_catchall_args(self) -> bool: + """Return if this signature has catchall args: (*args, **kwargs)""" + if self.args and self.args[0].name in ("self", "cls"): + args = self.args[1:] + else: + args = self.args + return ( + len(args) == 2 + and all(a.type in (None, "object", "Any", "typing.Any") for a in args) + and args[0].is_star_arg() + and args[1].is_star_kwarg() + ) + + def is_catchall_signature(self) -> bool: + """Return if this signature is the catchall identity: (*args, **kwargs) -> Any""" + return self.has_catchall_args() and self.ret_type in (None, "Any", "typing.Any") + + def format_sig( + self, + indent: str = "", + is_async: bool = False, + any_val: str | None = None, + docstring: str | None = None, + include_docstrings: bool = False, + ) -> str: + args: list[str] = [] + for arg in self.args: + arg_def = arg.name + + if arg_def in keyword.kwlist: + arg_def = "_" + arg_def + + if ( + arg.type is None + and any_val is not None + and arg.name not in ("self", "cls") + and not arg.name.startswith("*") + ): + arg_type: str | None = any_val + else: + arg_type = arg.type + if arg_type: + arg_def += ": " + arg_type + if arg.default: + arg_def += f" = {arg.default_value}" + + elif arg.default: + arg_def += f"={arg.default_value}" + + args.append(arg_def) + + retfield = "" + ret_type = self.ret_type if self.ret_type else any_val + if ret_type is not None: + retfield = " -> " + ret_type + + prefix = "async " if is_async else "" + sig = f"{indent}{prefix}def {self.name}{self.type_args}({', '.join(args)}){retfield}:" + # if this object has a docstring it's probably produced by a SignatureGenerator, so it + # takes precedence over the passed docstring, which acts as a fallback. + doc = (self.docstring or docstring) if include_docstrings else None + if doc: + suffix = f"\n{indent} {mypy.util.quote_docstring(doc)}" + else: + suffix = " ..." + return f"{sig}{suffix}" + + +# States of the docstring parser. +STATE_INIT: Final = 1 +STATE_FUNCTION_NAME: Final = 2 +STATE_ARGUMENT_LIST: Final = 3 +STATE_ARGUMENT_TYPE: Final = 4 +STATE_ARGUMENT_DEFAULT: Final = 5 +STATE_RETURN_VALUE: Final = 6 +STATE_OPEN_BRACKET: Final = 7 # For generic types. + + +class DocStringParser: + """Parse function signatures in documentation.""" + + def __init__(self, function_name: str) -> None: + # Only search for signatures of function with this name. + self.function_name = function_name + self.state = [STATE_INIT] + self.accumulator = "" + self.arg_type: str | None = None + self.arg_name = "" + self.arg_default: str | None = None + self.ret_type = "Any" + self.found = False + self.args: list[ArgSig] = [] + self.pos_only: int | None = None + self.keyword_only: int | None = None + # Valid signatures found so far. + self.signatures: list[FunctionSig] = [] + + def add_token(self, token: tokenize.TokenInfo) -> None: + """Process next token from the token stream.""" + if ( + token.type == tokenize.NAME + and token.string == self.function_name + and self.state[-1] == STATE_INIT + ): + self.state.append(STATE_FUNCTION_NAME) + + elif ( + token.type == tokenize.OP + and token.string == "(" + and self.state[-1] == STATE_FUNCTION_NAME + ): + self.state.pop() + self.accumulator = "" + self.found = True + self.state.append(STATE_ARGUMENT_LIST) + + elif self.state[-1] == STATE_FUNCTION_NAME: + # Reset state, function name not followed by '('. + self.state.pop() + + elif ( + token.type == tokenize.OP + and token.string in ("[", "(", "{") + and self.state[-1] != STATE_INIT + ): + self.accumulator += token.string + self.state.append(STATE_OPEN_BRACKET) + + elif ( + token.type == tokenize.OP + and token.string in ("]", ")", "}") + and self.state[-1] == STATE_OPEN_BRACKET + ): + self.accumulator += token.string + self.state.pop() + + elif ( + token.type == tokenize.OP + and token.string == ":" + and self.state[-1] == STATE_ARGUMENT_LIST + ): + self.arg_name = self.accumulator + self.accumulator = "" + self.state.append(STATE_ARGUMENT_TYPE) + + elif ( + token.type == tokenize.OP + and token.string == ":" + and self.state[-1] == STATE_ARGUMENT_TYPE + and self.accumulator == "" + ): + # We thought we were after the colon of an "arg_name: arg_type" + # stanza, so we were expecting an "arg_type" now. However, we ended + # up with "arg_name::" (with two colons). That's a C++ type name, + # not an argument name followed by a Python type. This function + # signature is malformed / invalid. + self.reset() + + elif ( + token.type == tokenize.OP + and token.string == "=" + and self.state[-1] in (STATE_ARGUMENT_LIST, STATE_ARGUMENT_TYPE) + ): + if self.state[-1] == STATE_ARGUMENT_TYPE: + self.arg_type = self.accumulator + self.state.pop() + else: + self.arg_name = self.accumulator + self.accumulator = "" + self.state.append(STATE_ARGUMENT_DEFAULT) + + elif ( + token.type == tokenize.OP + and token.string in (",", ")") + and self.state[-1] + in (STATE_ARGUMENT_LIST, STATE_ARGUMENT_DEFAULT, STATE_ARGUMENT_TYPE) + ): + if self.state[-1] == STATE_ARGUMENT_DEFAULT: + self.arg_default = self.accumulator + self.state.pop() + elif self.state[-1] == STATE_ARGUMENT_TYPE: + self.arg_type = self.accumulator + self.state.pop() + elif self.state[-1] == STATE_ARGUMENT_LIST: + if self.accumulator == "*": + if self.keyword_only is not None: + # Error condition: cannot have * twice + self.reset() + return + self.keyword_only = len(self.args) + self.accumulator = "" + else: + if self.accumulator.startswith("*"): + self.keyword_only = len(self.args) + 1 + self.arg_name = self.accumulator + if not ( + token.string == ")" and self.accumulator.strip() == "" + ) and not _ARG_NAME_RE.match(self.arg_name): + # Invalid argument name. + self.reset() + return + + if token.string == ")": + if ( + self.state[-1] == STATE_ARGUMENT_LIST + and self.keyword_only is not None + and self.keyword_only == len(self.args) + and not self.arg_name + ): + # Error condition: * must be followed by arguments + self.reset() + return + self.state.pop() + + # arg_name is empty when there are no args. e.g. func() + if self.arg_name: + if self.arg_type and not is_valid_type(self.arg_type): + # wrong type, use Any + self.args.append( + ArgSig(name=self.arg_name, type=None, default=bool(self.arg_default)) + ) + else: + self.args.append( + ArgSig( + name=self.arg_name, type=self.arg_type, default=bool(self.arg_default) + ) + ) + self.arg_name = "" + self.arg_type = None + self.arg_default = None + self.accumulator = "" + elif ( + token.type == tokenize.OP + and token.string == "/" + and self.state[-1] == STATE_ARGUMENT_LIST + ): + if token.string == "/": + if self.pos_only is not None or self.keyword_only is not None or not self.args: + # Error cases: + # - / shows up more than once + # - / shows up after * + # - / shows up before any arguments + self.reset() + return + self.pos_only = len(self.args) + self.state.append(STATE_ARGUMENT_TYPE) + self.accumulator = "" + + elif token.type == tokenize.OP and token.string == "->" and self.state[-1] == STATE_INIT: + self.accumulator = "" + self.state.append(STATE_RETURN_VALUE) + + # ENDMAKER is necessary for python 3.4 and 3.5. + elif token.type in (tokenize.NEWLINE, tokenize.ENDMARKER) and self.state[-1] in ( + STATE_INIT, + STATE_RETURN_VALUE, + ): + if self.state[-1] == STATE_RETURN_VALUE: + if not is_valid_type(self.accumulator): + self.reset() + return + self.ret_type = self.accumulator + self.accumulator = "" + self.state.pop() + + if self.found: + self.signatures.append( + FunctionSig(name=self.function_name, args=self.args, ret_type=self.ret_type) + ) + self.found = False + self.args = [] + self.ret_type = "Any" + # Leave state as INIT. + else: + self.accumulator += token.string + + def reset(self) -> None: + self.state = [STATE_INIT] + self.args = [] + self.found = False + self.accumulator = "" + + def get_signatures(self) -> list[FunctionSig]: + """Return sorted copy of the list of signatures found so far.""" + + def has_arg(name: str, signature: FunctionSig) -> bool: + return any(x.name == name for x in signature.args) + + def args_kwargs(signature: FunctionSig) -> bool: + return has_arg("*args", signature) and has_arg("**kwargs", signature) + + # Move functions with (*args, **kwargs) in their signature to last place. + return sorted(self.signatures, key=lambda x: 1 if args_kwargs(x) else 0) + + +def infer_sig_from_docstring(docstr: str | None, name: str) -> list[FunctionSig] | None: + """Convert function signature to list of FunctionSig + + Look for function signatures of function in docstring. Signature is a string of + the format () -> or perhaps without + the return type. + + Returns empty list, when no signature is found, one signature in typical case, + multiple signatures, if docstring specifies multiple signatures for overload functions. + Return None if the docstring is empty. + + Arguments: + * docstr: docstring + * name: name of function for which signatures are to be found + """ + if not (isinstance(docstr, str) and docstr): + return None + + state = DocStringParser(name) + # Return all found signatures, even if there is a parse error after some are found. + with contextlib.suppress(tokenize.TokenError): + try: + tokens = tokenize.tokenize(io.BytesIO(docstr.encode("utf-8")).readline) + for token in tokens: + state.add_token(token) + except IndentationError: + return None + sigs = state.get_signatures() + + def is_unique_args(sig: FunctionSig) -> bool: + """return true if function argument names are unique""" + return len(sig.args) == len({arg.name for arg in sig.args}) + + # Return only signatures that have unique argument names. Mypy fails on non-unique arg names. + return [sig for sig in sigs if is_unique_args(sig)] + + +def infer_arg_sig_from_anon_docstring(docstr: str) -> list[ArgSig]: + """Convert signature in form of "(self: TestClass, arg0: str='ada')" to List[TypedArgList].""" + ret = infer_sig_from_docstring("stub" + docstr, "stub") + if ret: + return ret[0].args + return [] + + +def infer_ret_type_sig_from_docstring(docstr: str, name: str) -> str | None: + """Convert signature in form of "func(self: TestClass, arg0) -> int" to their return type.""" + ret = infer_sig_from_docstring(docstr, name) + if ret: + return ret[0].ret_type + return None + + +def infer_ret_type_sig_from_anon_docstring(docstr: str) -> str | None: + """Convert signature in form of "(self: TestClass, arg0) -> int" to their return type.""" + lines = ["stub" + line.strip() for line in docstr.splitlines() if line.strip().startswith("(")] + return infer_ret_type_sig_from_docstring("".join(lines), "stub") + + +def parse_signature(sig: str) -> tuple[str, list[str], list[str]] | None: + """Split function signature into its name, positional an optional arguments. + + The expected format is "func_name(arg, opt_arg=False)". Return the name of function + and lists of positional and optional argument names. + """ + m = re.match(r"([.a-zA-Z0-9_]+)\(([^)]*)\)", sig) + if not m: + return None + name = m.group(1) + name = name.split(".")[-1] + arg_string = m.group(2) + if not arg_string.strip(): + # Simple case -- no arguments. + return name, [], [] + + args = [arg.strip() for arg in arg_string.split(",")] + positional = [] + optional = [] + i = 0 + while i < len(args): + # Accept optional arguments as in both formats: x=None and [x]. + if args[i].startswith("[") or "=" in args[i]: + break + positional.append(args[i].rstrip("[")) + i += 1 + if args[i - 1].endswith("["): + break + while i < len(args): + arg = args[i] + arg = arg.strip("[]") + arg = arg.split("=")[0] + optional.append(arg) + i += 1 + return name, positional, optional + + +def build_signature(positional: Sequence[str], optional: Sequence[str]) -> str: + """Build function signature from lists of positional and optional argument names.""" + args: MutableSequence[str] = [] + args.extend(positional) + for arg in optional: + if arg.startswith("*"): + args.append(arg) + else: + args.append(f"{arg}=...") + sig = f"({', '.join(args)})" + # Ad-hoc fixes. + sig = sig.replace("(self)", "") + return sig + + +def parse_all_signatures(lines: Sequence[str]) -> tuple[list[Sig], list[Sig]]: + """Parse all signatures in a given reST document. + + Return lists of found signatures for functions and classes. + """ + sigs = [] + class_sigs = [] + for line in lines: + line = line.strip() + m = re.match(r"\.\. *(function|method|class) *:: *[a-zA-Z_]", line) + if m: + sig = line.split("::")[1].strip() + parsed = parse_signature(sig) + if parsed: + name, fixed, optional = parsed + if m.group(1) != "class": + sigs.append((name, build_signature(fixed, optional))) + else: + class_sigs.append((name, build_signature(fixed, optional))) + + return sorted(sigs), sorted(class_sigs) + + +def find_unique_signatures(sigs: Sequence[Sig]) -> list[Sig]: + """Remove names with duplicate found signatures.""" + sig_map: MutableMapping[str, list[str]] = {} + for name, sig in sigs: + sig_map.setdefault(name, []).append(sig) + + result = [] + for name, name_sigs in sig_map.items(): + if len(set(name_sigs)) == 1: + result.append((name, name_sigs[0])) + return sorted(result) + + +def infer_prop_type_from_docstring(docstr: str | None) -> str | None: + """Check for Google/Numpy style docstring type annotation for a property. + + The docstring has the format ": ". + In the type string, we allow the following characters: + * dot: because sometimes classes are annotated using full path + * brackets: to allow type hints like List[int] + * comma/space: things like Tuple[int, int] + """ + if not docstr: + return None + test_str = r"^([a-zA-Z0-9_, \.\[\]]*): " + m = re.match(test_str, docstr) + return m.group(1) if m else None diff --git a/micromamba_root/Lib/site-packages/mypy/stubgen.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/stubgen.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e09ac5b371d48396b774c5bcb561298500c7f6bb Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/stubgen.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/stubgen.py b/micromamba_root/Lib/site-packages/mypy/stubgen.py new file mode 100644 index 0000000000000000000000000000000000000000..ce6335e9e34f98e6077065c013b1676877a731e2 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/stubgen.py @@ -0,0 +1,2055 @@ +#!/usr/bin/env python3 +"""Generator of dynamically typed draft stubs for arbitrary modules. + +The logic of this script can be split in three steps: +* parsing options and finding sources: + - use runtime imports be default (to find also C modules) + - or use mypy's mechanisms, if importing is prohibited +* (optionally) semantically analysing the sources using mypy (as a single set) +* emitting the stubs text: + - for Python modules: from ASTs using ASTStubGenerator + - for C modules using runtime introspection and (optionally) Sphinx docs + +During first and third steps some problematic files can be skipped, but any +blocking error during second step will cause the whole program to stop. + +Basic usage: + + $ stubgen foo.py bar.py some_directory + => Generate out/foo.pyi, out/bar.pyi, and stubs for some_directory (recursively). + + $ stubgen -m urllib.parse + => Generate out/urllib/parse.pyi. + + $ stubgen -p urllib + => Generate stubs for whole urllib package (recursively). + +For C modules, you can get more precise function signatures by parsing .rst (Sphinx) +documentation for extra information. For this, use the --doc-dir option: + + $ stubgen --doc-dir /Python-3.4.2/Doc/library -m curses + +Note: The generated stubs should be verified manually. + +TODO: + - maybe use .rst docs also for Python modules + - maybe export more imported names if there is no __all__ (this affects ssl.SSLError, for example) + - a quick and dirty heuristic would be to turn this on if a module has something like + 'from x import y as _y' + - we don't seem to always detect properties ('closed' in 'io', for example) +""" + +from __future__ import annotations + +import argparse +import keyword +import os +import os.path +import sys +import traceback +from collections.abc import Iterable, Iterator +from typing import Final + +import mypy.build +import mypy.mixedtraverser +import mypy.parse +import mypy.traverser +import mypy.util +import mypy.version +from mypy.build import build +from mypy.errors import CompileError, Errors +from mypy.find_sources import InvalidSourceList, create_source_list +from mypy.modulefinder import ( + BuildSource, + FindModuleCache, + ModuleNotFoundReason, + SearchPaths, + default_lib_path, +) +from mypy.moduleinspect import ModuleInspect, is_pyc_only +from mypy.nodes import ( + ARG_NAMED, + ARG_POS, + ARG_STAR, + ARG_STAR2, + IS_ABSTRACT, + NOT_ABSTRACT, + AssignmentStmt, + Block, + BytesExpr, + CallExpr, + CastExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + Decorator, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + Expression, + ExpressionStmt, + FloatExpr, + FuncBase, + FuncDef, + GeneratorExpr, + IfStmt, + Import, + ImportAll, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MemberExpr, + MypyFile, + NameExpr, + OpExpr, + OverloadedFuncDef, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + Statement, + StrExpr, + TemplateStrExpr, + TempNode, + TupleExpr, + TypeAliasStmt, + TypeInfo, + UnaryExpr, + Var, +) +from mypy.options import Options as MypyOptions +from mypy.plugins.dataclasses import DATACLASS_FIELD_SPECIFIERS +from mypy.semanal_shared import find_dataclass_transform_spec +from mypy.sharedparse import MAGIC_METHODS_POS_ARGS_ONLY +from mypy.stubdoc import ArgSig, FunctionSig +from mypy.stubgenc import InspectionStubGenerator, generate_stub_for_c_module +from mypy.stubutil import ( + TYPING_BUILTIN_REPLACEMENTS, + BaseStubGenerator, + CantImport, + ClassInfo, + FunctionContext, + common_dir_prefix, + fail_missing, + find_module_path_and_all_py3, + generate_guarded, + infer_method_arg_types, + infer_method_ret_type, + remove_misplaced_type_comments, + report_missing, + walk_packages, +) +from mypy.traverser import ( + all_yield_expressions, + has_return_statement, + has_yield_expression, + has_yield_from_expression, +) +from mypy.types import ( + DATACLASS_TRANSFORM_NAMES, + OVERLOAD_NAMES, + TPDICT_NAMES, + TYPE_VAR_LIKE_NAMES, + TYPED_NAMEDTUPLE_NAMES, + AnyType, + CallableType, + Instance, + TupleType, + Type, + UnboundType, + get_proper_type, +) +from mypy.visitor import NodeVisitor + +# Common ways of naming package containing vendored modules. +VENDOR_PACKAGES: Final = ["packages", "vendor", "vendored", "_vendor", "_vendored_packages"] + +# Avoid some file names that are unnecessary or likely to cause trouble (\n for end of path). +BLACKLIST: Final = [ + "/six.py\n", # Likely vendored six; too dynamic for us to handle + "/vendored/", # Vendored packages + "/vendor/", # Vendored packages + "/_vendor/", + "/_vendored_packages/", +] + +# These methods are expected to always return a non-trivial value. +METHODS_WITH_RETURN_VALUE: Final = { + "__ne__", + "__eq__", + "__lt__", + "__le__", + "__gt__", + "__ge__", + "__hash__", + "__iter__", +} + + +class Options: + """Represents stubgen options. + + This class is mutable to simplify testing. + """ + + def __init__( + self, + pyversion: tuple[int, int], + no_import: bool, + inspect: bool, + doc_dir: str, + search_path: list[str], + interpreter: str, + parse_only: bool, + ignore_errors: bool, + include_private: bool, + output_dir: str, + modules: list[str], + packages: list[str], + files: list[str], + verbose: bool, + quiet: bool, + export_less: bool, + include_docstrings: bool, + ) -> None: + # See parse_options for descriptions of the flags. + self.pyversion = pyversion + self.no_import = no_import + self.inspect = inspect + self.doc_dir = doc_dir + self.search_path = search_path + self.interpreter = interpreter + self.decointerpreter = interpreter + self.parse_only = parse_only + self.ignore_errors = ignore_errors + self.include_private = include_private + self.output_dir = output_dir + self.modules = modules + self.packages = packages + self.files = files + self.verbose = verbose + self.quiet = quiet + self.export_less = export_less + self.include_docstrings = include_docstrings + + +class StubSource: + """A single source for stub: can be a Python or C module. + + A simple extension of BuildSource that also carries the AST and + the value of __all__ detected at runtime. + """ + + def __init__( + self, module: str, path: str | None = None, runtime_all: list[str] | None = None + ) -> None: + self.source = BuildSource(path, module, None) + self.runtime_all = runtime_all + self.ast: MypyFile | None = None + + def __repr__(self) -> str: + return f"StubSource({self.source})" + + @property + def module(self) -> str: + return self.source.module + + @property + def path(self) -> str | None: + return self.source.path + + +# What was generated previously in the stub file. We keep track of these to generate +# nicely formatted output (add empty line between non-empty classes, for example). +EMPTY: Final = "EMPTY" +FUNC: Final = "FUNC" +CLASS: Final = "CLASS" +EMPTY_CLASS: Final = "EMPTY_CLASS" +VAR: Final = "VAR" +NOT_IN_ALL: Final = "NOT_IN_ALL" + +# Indicates that we failed to generate a reasonable output +# for a given node. These should be manually replaced by a user. + +ERROR_MARKER: Final = "" + + +class AliasPrinter(NodeVisitor[str]): + """Visitor used to collect type aliases _and_ type variable definitions. + + Visit r.h.s of the definition to get the string representation of type alias. + """ + + def __init__(self, stubgen: ASTStubGenerator) -> None: + self.stubgen = stubgen + super().__init__() + + def visit_call_expr(self, node: CallExpr) -> str: + # Call expressions are not usually types, but we also treat `X = TypeVar(...)` as a + # type alias that has to be preserved (even if TypeVar is not the same as an alias) + callee = node.callee.accept(self) + args = [] + for name, arg, kind in zip(node.arg_names, node.args, node.arg_kinds): + if kind == ARG_POS: + args.append(arg.accept(self)) + elif kind == ARG_STAR: + args.append("*" + arg.accept(self)) + elif kind == ARG_STAR2: + args.append("**" + arg.accept(self)) + elif kind == ARG_NAMED: + args.append(f"{name}={arg.accept(self)}") + else: + raise ValueError(f"Unknown argument kind {kind} in call") + return f"{callee}({', '.join(args)})" + + def _visit_ref_expr(self, node: NameExpr | MemberExpr) -> str: + fullname = self.stubgen.get_fullname(node) + if fullname in TYPING_BUILTIN_REPLACEMENTS: + return self.stubgen.add_name(TYPING_BUILTIN_REPLACEMENTS[fullname], require=False) + qualname = get_qualified_name(node) + self.stubgen.import_tracker.require_name(qualname) + return qualname + + def visit_name_expr(self, node: NameExpr) -> str: + return self._visit_ref_expr(node) + + def visit_member_expr(self, o: MemberExpr) -> str: + return self._visit_ref_expr(o) + + def _visit_literal_node( + self, node: StrExpr | BytesExpr | IntExpr | FloatExpr | ComplexExpr + ) -> str: + return repr(node.value) + + def visit_str_expr(self, node: StrExpr) -> str: + return self._visit_literal_node(node) + + def visit_bytes_expr(self, node: BytesExpr) -> str: + return f"b{self._visit_literal_node(node)}" + + def visit_int_expr(self, node: IntExpr) -> str: + return self._visit_literal_node(node) + + def visit_float_expr(self, node: FloatExpr) -> str: + return self._visit_literal_node(node) + + def visit_complex_expr(self, node: ComplexExpr) -> str: + return self._visit_literal_node(node) + + def visit_index_expr(self, node: IndexExpr) -> str: + base_fullname = self.stubgen.get_fullname(node.base) + if base_fullname == "typing.Union": + if isinstance(node.index, TupleExpr): + return " | ".join([item.accept(self) for item in node.index.items]) + return node.index.accept(self) + if base_fullname == "typing.Optional": + if isinstance(node.index, TupleExpr): + return self.stubgen.add_name("_typeshed.Incomplete") + return f"{node.index.accept(self)} | None" + base = node.base.accept(self) + index = node.index.accept(self) + if len(index) > 2 and index.startswith("(") and index.endswith(")"): + index = index[1:-1].rstrip(",") + return f"{base}[{index}]" + + def visit_tuple_expr(self, node: TupleExpr) -> str: + suffix = "," if len(node.items) == 1 else "" + return f"({', '.join(n.accept(self) for n in node.items)}{suffix})" + + def visit_list_expr(self, node: ListExpr) -> str: + return f"[{', '.join(n.accept(self) for n in node.items)}]" + + def visit_set_expr(self, node: SetExpr) -> str: + return f"{{{', '.join(n.accept(self) for n in node.items)}}}" + + def visit_dict_expr(self, o: DictExpr) -> str: + dict_items = [] + for key, value in o.items: + # This is currently only used for TypedDict where all keys are strings. + assert isinstance(key, StrExpr) + dict_items.append(f"{key.accept(self)}: {value.accept(self)}") + return f"{{{', '.join(dict_items)}}}" + + def visit_template_str_expr(self, o: TemplateStrExpr) -> str: + return self.stubgen.add_name("_typeshed.Incomplete") + + def visit_ellipsis(self, node: EllipsisExpr) -> str: + return "..." + + def visit_op_expr(self, o: OpExpr) -> str: + return f"{o.left.accept(self)} {o.op} {o.right.accept(self)}" + + def visit_unary_expr(self, o: UnaryExpr, /) -> str: + return f"{o.op}{o.expr.accept(self)}" + + def visit_slice_expr(self, o: SliceExpr, /) -> str: + blocks = [ + o.begin_index.accept(self) if o.begin_index is not None else "", + o.end_index.accept(self) if o.end_index is not None else "", + ] + if o.stride is not None: + blocks.append(o.stride.accept(self)) + return ":".join(blocks) + + def visit_star_expr(self, o: StarExpr) -> str: + return f"*{o.expr.accept(self)}" + + def visit_lambda_expr(self, o: LambdaExpr) -> str: + # TODO: Required for among other things dataclass.field default_factory + return self.stubgen.add_name("_typeshed.Incomplete") + + def _visit_unsupported_expr(self, o: object) -> str: + # Something we do not understand. + return self.stubgen.add_name("_typeshed.Incomplete") + + def visit_comparison_expr(self, o: ComparisonExpr) -> str: + return self._visit_unsupported_expr(o) + + def visit_cast_expr(self, o: CastExpr) -> str: + return self._visit_unsupported_expr(o) + + def visit_conditional_expr(self, o: ConditionalExpr) -> str: + return self._visit_unsupported_expr(o) + + def visit_list_comprehension(self, o: ListComprehension) -> str: + return self._visit_unsupported_expr(o) + + def visit_set_comprehension(self, o: SetComprehension) -> str: + return self._visit_unsupported_expr(o) + + def visit_dictionary_comprehension(self, o: DictionaryComprehension) -> str: + return self._visit_unsupported_expr(o) + + def visit_generator_expr(self, o: GeneratorExpr) -> str: + return self._visit_unsupported_expr(o) + + +def find_defined_names(file: MypyFile) -> set[str]: + finder = DefinitionFinder() + file.accept(finder) + return finder.names + + +def get_assigned_names(lvalues: Iterable[Expression]) -> Iterator[str]: + for lvalue in lvalues: + if isinstance(lvalue, NameExpr): + yield lvalue.name + elif isinstance(lvalue, TupleExpr): + yield from get_assigned_names(lvalue.items) + + +class DefinitionFinder(mypy.traverser.TraverserVisitor): + """Find names of things defined at the top level of a module.""" + + def __init__(self) -> None: + # Short names of things defined at the top level. + self.names: set[str] = set() + + def visit_class_def(self, o: ClassDef) -> None: + # Don't recurse into classes, as we only keep track of top-level definitions. + self.names.add(o.name) + + def visit_func_def(self, o: FuncDef) -> None: + # Don't recurse, as we only keep track of top-level definitions. + self.names.add(o.name) + + def visit_assignment_stmt(self, o: AssignmentStmt) -> None: + for name in get_assigned_names(o.lvalues): + self.names.add(name) + + def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None: + self.names.add(o.name.name) + + +def find_referenced_names(file: MypyFile) -> set[str]: + finder = ReferenceFinder() + file.accept(finder) + return finder.refs + + +def is_none_expr(expr: Expression) -> bool: + return isinstance(expr, NameExpr) and expr.name == "None" + + +class ReferenceFinder(mypy.mixedtraverser.MixedTraverserVisitor): + """Find all name references (both local and global).""" + + # TODO: Filter out local variable and class attribute references + + def __init__(self) -> None: + # Short names of things defined at the top level. + self.refs: set[str] = set() + + def visit_block(self, block: Block) -> None: + if not block.is_unreachable: + super().visit_block(block) + + def visit_name_expr(self, e: NameExpr) -> None: + self.refs.add(e.name) + + def visit_instance(self, t: Instance) -> None: + self.add_ref(t.type.name) + super().visit_instance(t) + + def visit_unbound_type(self, t: UnboundType) -> None: + if t.name: + self.add_ref(t.name) + + def visit_tuple_type(self, t: TupleType) -> None: + # Ignore fallback + for item in t.items: + item.accept(self) + + def visit_callable_type(self, t: CallableType) -> None: + # Ignore fallback + for arg in t.arg_types: + arg.accept(self) + t.ret_type.accept(self) + + def add_ref(self, fullname: str) -> None: + self.refs.add(fullname) + while "." in fullname: + fullname = fullname.rsplit(".", 1)[0] + self.refs.add(fullname) + + +class ASTStubGenerator(BaseStubGenerator, mypy.traverser.TraverserVisitor): + """Generate stub text from a mypy AST.""" + + def __init__( + self, + _all_: list[str] | None = None, + include_private: bool = False, + analyzed: bool = False, + export_less: bool = False, + include_docstrings: bool = False, + ) -> None: + super().__init__(_all_, include_private, export_less, include_docstrings) + self._decorators: list[str] = [] + # Stack of defined variables (per scope). + self._vars: list[list[str]] = [[]] + # What was generated previously in the stub file. + self._state = EMPTY + self._class_stack: list[ClassDef] = [] + # Was the tree semantically analysed before? + self.analyzed = analyzed + # Short names of methods defined in the body of the current class + self.method_names: set[str] = set() + self.processing_enum = False + self.processing_dataclass = False + self.dataclass_field_specifier: tuple[str, ...] = () + + @property + def _current_class(self) -> ClassDef | None: + return self._class_stack[-1] if self._class_stack else None + + def visit_mypy_file(self, o: MypyFile) -> None: + self.module_name = o.fullname # Current module being processed + self.path = o.path + self.set_defined_names(find_defined_names(o)) + self.referenced_names = find_referenced_names(o) + super().visit_mypy_file(o) + self.check_undefined_names() + + def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None: + """@property with setters and getters, @overload chain and some others.""" + overload_chain = False + for item in o.items: + if not isinstance(item, Decorator): + continue + if self.is_private_name(item.func.name, item.func.fullname): + continue + + self.process_decorator(item) + if not overload_chain: + self.visit_func_def(item.func) + if item.func.is_overload: + overload_chain = True + elif item.func.is_overload: + self.visit_func_def(item.func) + else: + # skip the overload implementation and clear the decorator we just processed + self.clear_decorators() + + def get_default_function_sig(self, func_def: FuncDef, ctx: FunctionContext) -> FunctionSig: + args = self._get_func_args(func_def, ctx) + retname = self._get_func_return(func_def, ctx) + type_args = self.format_type_args(func_def) + return FunctionSig(func_def.name, args, retname, type_args) + + def _get_func_args(self, o: FuncDef, ctx: FunctionContext) -> list[ArgSig]: + args: list[ArgSig] = [] + + # Ignore pos-only status of magic methods whose args names are elided by mypy at parse + actually_pos_only_args = o.name not in MAGIC_METHODS_POS_ARGS_ONLY + pos_only_marker_position = 0 # Where to insert "/", if any + for i, arg_ in enumerate(o.arguments): + var = arg_.variable + kind = arg_.kind + name = var.name + annotated_type = ( + o.unanalyzed_type.arg_types[i] + if isinstance(o.unanalyzed_type, CallableType) + else None + ) + # I think the name check is incorrect: there are libraries which + # name their 0th argument other than self/cls + is_self_arg = i == 0 and name == "self" + is_cls_arg = i == 0 and name == "cls" + typename: str | None = None + if annotated_type and not is_self_arg and not is_cls_arg: + # Luckily, an argument explicitly annotated with "Any" has + # type "UnboundType" and will not match. + if not isinstance(get_proper_type(annotated_type), AnyType): + typename = self.print_annotation(annotated_type) + + if actually_pos_only_args and arg_.pos_only: + pos_only_marker_position += 1 + + if kind.is_named() and not any(arg.name.startswith("*") for arg in args): + args.append(ArgSig("*")) + + default = "..." + if arg_.initializer: + if not typename: + typename = self.get_str_type_of_node(arg_.initializer, can_be_incomplete=False) + potential_default, valid = self.get_str_default_of_node(arg_.initializer) + if valid and len(potential_default) <= 200: + default = potential_default + elif kind == ARG_STAR: + name = f"*{name}" + elif kind == ARG_STAR2: + name = f"**{name}" + + args.append( + ArgSig(name, typename, default=bool(arg_.initializer), default_value=default) + ) + if pos_only_marker_position: + args.insert(pos_only_marker_position, ArgSig("/")) + + if ctx.class_info is not None and all( + arg.type is None and arg.default is False for arg in args + ): + new_args = infer_method_arg_types( + ctx.name, ctx.class_info.self_var, [arg.name for arg in args] + ) + + if ctx.name == "__exit__": + self.import_tracker.add_import("types") + self.import_tracker.require_name("types") + + if new_args is not None: + args = new_args + + return args + + def _get_func_return(self, o: FuncDef, ctx: FunctionContext) -> str | None: + if o.name != "__init__" and isinstance(o.unanalyzed_type, CallableType): + if isinstance(get_proper_type(o.unanalyzed_type.ret_type), AnyType): + # Luckily, a return type explicitly annotated with "Any" has + # type "UnboundType" and will enter the else branch. + return None # implicit Any + else: + return self.print_annotation(o.unanalyzed_type.ret_type) + if o.abstract_status == IS_ABSTRACT or o.name in METHODS_WITH_RETURN_VALUE: + # Always assume abstract methods return Any unless explicitly annotated. Also + # some dunder methods should not have a None return type. + return None # implicit Any + retname = infer_method_ret_type(o.name) + if retname is not None: + return retname + if has_yield_expression(o) or has_yield_from_expression(o): + generator_name = self.add_name("collections.abc.Generator") + yield_name = "None" + send_name: str | None = None + return_name: str | None = None + if has_yield_from_expression(o): + yield_name = send_name = self.add_name("_typeshed.Incomplete") + else: + for expr, in_assignment in all_yield_expressions(o): + if expr.expr is not None and not is_none_expr(expr.expr): + yield_name = self.add_name("_typeshed.Incomplete") + if in_assignment: + send_name = self.add_name("_typeshed.Incomplete") + if has_return_statement(o): + return_name = self.add_name("_typeshed.Incomplete") + if return_name is not None: + if send_name is None: + send_name = "None" + return f"{generator_name}[{yield_name}, {send_name}, {return_name}]" + elif send_name is not None: + return f"{generator_name}[{yield_name}, {send_name}]" + else: + return f"{generator_name}[{yield_name}]" + if not has_return_statement(o) and o.abstract_status == NOT_ABSTRACT: + return "None" + return None + + def _get_func_docstring(self, node: FuncDef) -> str | None: + if not node.body.body: + return None + expr = node.body.body[0] + if isinstance(expr, ExpressionStmt) and isinstance(expr.expr, StrExpr): + return expr.expr.value + return None + + def visit_func_def(self, o: FuncDef) -> None: + is_dataclass_generated = ( + self.analyzed and self.processing_dataclass and o.info.names[o.name].plugin_generated + ) + if is_dataclass_generated: + # Skip methods generated by the @dataclass decorator + return + if ( + self.is_private_name(o.name, o.fullname) + or self.is_not_in_all(o.name) + or (self.is_recorded_name(o.name) and not o.is_overload) + ): + self.clear_decorators() + return + if self.is_top_level() and self._state not in (EMPTY, FUNC): + self.add("\n") + if not self.is_top_level(): + self_inits = find_self_initializers(o) + for init, value, annotation in self_inits: + if init in self.method_names: + # Can't have both an attribute and a method/property with the same name. + continue + init_code = self.get_init(init, value, annotation) + if init_code: + self.add(init_code) + + if self._class_stack: + if len(o.arguments): + self_var = o.arguments[0].variable.name + else: + self_var = "self" + class_info: ClassInfo | None = None + for class_def in self._class_stack: + class_info = ClassInfo(class_def.name, self_var, parent=class_info) + else: + class_info = None + + ctx = FunctionContext( + module_name=self.module_name, + name=o.name, + docstring=self._get_func_docstring(o), + is_abstract=o.abstract_status != NOT_ABSTRACT, + class_info=class_info, + ) + + self.record_name(o.name) + + default_sig = self.get_default_function_sig(o, ctx) + sigs = self.get_signatures(default_sig, self.sig_generators, ctx) + + for output in self.format_func_def( + sigs, is_coroutine=o.is_coroutine, decorators=self._decorators, docstring=ctx.docstring + ): + self.add(output + "\n") + + self.clear_decorators() + self._state = FUNC + + def visit_decorator(self, o: Decorator) -> None: + if self.is_private_name(o.func.name, o.func.fullname): + return + self.process_decorator(o) + self.visit_func_def(o.func) + + def process_decorator(self, o: Decorator) -> None: + """Process a series of decorators. + + Only preserve certain special decorators such as @abstractmethod. + """ + o.func.is_overload = False + for decorator in o.original_decorators: + d = decorator + if isinstance(d, CallExpr): + d = d.callee + if not isinstance(d, (NameExpr, MemberExpr)): + continue + qualname = get_qualified_name(d) + fullname = self.get_fullname(d) + if fullname in ( + "builtins.property", + "builtins.staticmethod", + "builtins.classmethod", + "functools.cached_property", + ): + self.add_decorator(qualname, require_name=True) + elif fullname in ( + "asyncio.coroutine", + "asyncio.coroutines.coroutine", + "types.coroutine", + ): + o.func.is_awaitable_coroutine = True + self.add_decorator(qualname, require_name=True) + elif fullname == "abc.abstractmethod": + self.add_decorator(qualname, require_name=True) + o.func.abstract_status = IS_ABSTRACT + elif fullname in ( + "abc.abstractproperty", + "abc.abstractstaticmethod", + "abc.abstractclassmethod", + ): + abc_module = qualname.rpartition(".")[0] + if not abc_module: + self.import_tracker.add_import("abc") + builtin_decorator_replacement = fullname[len("abc.abstract") :] + self.add_decorator(builtin_decorator_replacement, require_name=False) + self.add_decorator(f"{abc_module or 'abc'}.abstractmethod", require_name=True) + o.func.abstract_status = IS_ABSTRACT + elif fullname in OVERLOAD_NAMES: + self.add_decorator(qualname, require_name=True) + o.func.is_overload = True + elif qualname.endswith((".setter", ".deleter")): + self.add_decorator(qualname, require_name=False) + elif fullname in DATACLASS_TRANSFORM_NAMES: + p = AliasPrinter(self) + self._decorators.append(f"@{decorator.accept(p)}") + elif isinstance(decorator, (NameExpr, MemberExpr)): + p = AliasPrinter(self) + self._decorators.append(f"@{decorator.accept(p)}") + + def get_fullname(self, expr: Expression) -> str: + """Return the expression's full name.""" + if ( + self.analyzed + and isinstance(expr, (NameExpr, MemberExpr)) + and expr.fullname + and not (isinstance(expr.node, Var) and expr.node.is_suppressed_import) + ): + return expr.fullname + name = get_qualified_name(expr) + return self.resolve_name(name) + + def visit_class_def(self, o: ClassDef) -> None: + self._class_stack.append(o) + self.method_names = find_method_names(o.defs.body) + sep: int | None = None + if self.is_top_level() and self._state != EMPTY: + sep = len(self._output) + self.add("\n") + decorators = self.get_class_decorators(o) + for d in decorators: + self.add(f"{self._indent}@{d}\n") + self.record_name(o.name) + base_types = self.get_base_types(o) + if base_types: + for base in base_types: + self.import_tracker.require_name(base) + if self.analyzed and o.info.is_enum: + self.processing_enum = True + if isinstance(o.metaclass, (NameExpr, MemberExpr)): + meta = o.metaclass.accept(AliasPrinter(self)) + base_types.append("metaclass=" + meta) + elif self.analyzed and o.info.is_abstract and not o.info.is_protocol: + base_types.append("metaclass=abc.ABCMeta") + self.import_tracker.add_import("abc") + self.import_tracker.require_name("abc") + bases = f"({', '.join(base_types)})" if base_types else "" + type_args = self.format_type_args(o) + self.add(f"{self._indent}class {o.name}{type_args}{bases}:\n") + self.indent() + if self._include_docstrings and o.docstring: + docstring = mypy.util.quote_docstring(o.docstring) + self.add(f"{self._indent}{docstring}\n") + n = len(self._output) + self._vars.append([]) + if self.analyzed and (spec := find_dataclass_transform_spec(o)): + self.processing_dataclass = True + self.dataclass_field_specifier = spec.field_specifiers + super().visit_class_def(o) + self.dedent() + self._vars.pop() + self._vars[-1].append(o.name) + if len(self._output) == n: + if self._state == EMPTY_CLASS and sep is not None: + self._output[sep] = "" + if not (self._include_docstrings and o.docstring): + self._output[-1] = self._output[-1][:-1] + " ...\n" + self._state = EMPTY_CLASS + else: + self._state = CLASS + self.method_names = set() + self.processing_dataclass = False + self.dataclass_field_specifier = () + self._class_stack.pop(-1) + self.processing_enum = False + + def get_base_types(self, cdef: ClassDef) -> list[str]: + """Get list of base classes for a class.""" + base_types: list[str] = [] + p = AliasPrinter(self) + for base in cdef.base_type_exprs + cdef.removed_base_type_exprs: + if isinstance(base, (NameExpr, MemberExpr)): + if self.get_fullname(base) != "builtins.object": + base_types.append(get_qualified_name(base)) + elif isinstance(base, IndexExpr): + base_types.append(base.accept(p)) + elif isinstance(base, CallExpr): + # namedtuple(typename, fields), NamedTuple(typename, fields) calls can + # be used as a base class. The first argument is a string literal that + # is usually the same as the class name. + # + # Note: + # A call-based named tuple as a base class cannot be safely converted to + # a class-based NamedTuple definition because class attributes defined + # in the body of the class inheriting from the named tuple call are not + # namedtuple fields at runtime. + if self.is_namedtuple(base): + nt_fields = self._get_namedtuple_fields(base) + assert isinstance(base.args[0], StrExpr) + typename = base.args[0].value + if nt_fields is None: + # Invalid namedtuple() call, cannot determine fields + base_types.append(self.add_name("_typeshed.Incomplete")) + continue + fields_str = ", ".join(f"({f!r}, {t})" for f, t in nt_fields) + namedtuple_name = self.add_name("typing.NamedTuple") + base_types.append(f"{namedtuple_name}({typename!r}, [{fields_str}])") + elif self.is_typed_namedtuple(base): + base_types.append(base.accept(p)) + else: + # At this point, we don't know what the base class is, so we + # just use Incomplete as the base class. + base_types.append(self.add_name("_typeshed.Incomplete")) + for name, value in cdef.keywords.items(): + if name == "metaclass": + continue # handled separately + processed_value = value.accept(p) or "..." # at least, don't crash + base_types.append(f"{name}={processed_value}") + return base_types + + def get_class_decorators(self, cdef: ClassDef) -> list[str]: + decorators: list[str] = [] + p = AliasPrinter(self) + for d in cdef.decorators: + if self.is_dataclass(d): + decorators.append(d.accept(p)) + self.import_tracker.require_name(get_qualified_name(d)) + self.processing_dataclass = True + if self.is_dataclass_transform(d): + decorators.append(d.accept(p)) + self.import_tracker.require_name(get_qualified_name(d)) + return decorators + + def is_dataclass(self, expr: Expression) -> bool: + if isinstance(expr, CallExpr): + expr = expr.callee + return self.get_fullname(expr) == "dataclasses.dataclass" + + def is_dataclass_transform(self, expr: Expression) -> bool: + if isinstance(expr, CallExpr): + expr = expr.callee + if self.get_fullname(expr) in DATACLASS_TRANSFORM_NAMES: + return True + if (spec := find_dataclass_transform_spec(expr)) is not None: + self.processing_dataclass = True + self.dataclass_field_specifier = spec.field_specifiers + return True + return False + + def visit_block(self, o: Block) -> None: + # Unreachable statements may be partially uninitialized and that may + # cause trouble. + if not o.is_unreachable: + super().visit_block(o) + + def visit_assignment_stmt(self, o: AssignmentStmt) -> None: + foundl = [] + + for lvalue in o.lvalues: + if isinstance(lvalue, NameExpr) and isinstance(o.rvalue, CallExpr): + if self.is_namedtuple(o.rvalue) or self.is_typed_namedtuple(o.rvalue): + self.process_namedtuple(lvalue, o.rvalue) + foundl.append(False) # state is updated in process_namedtuple + continue + if self.is_typeddict(o.rvalue): + self.process_typeddict(lvalue, o.rvalue) + foundl.append(False) # state is updated in process_typeddict + continue + if ( + isinstance(lvalue, NameExpr) + and self.is_alias_expression(o.rvalue) + and not self.is_private_name(lvalue.name) + ): + is_explicit_type_alias = ( + o.unanalyzed_type and getattr(o.type, "name", None) == "TypeAlias" + ) + if is_explicit_type_alias: + self.process_typealias(lvalue, o.rvalue, is_explicit_type_alias=True) + continue + + if not o.unanalyzed_type: + self.process_typealias(lvalue, o.rvalue) + continue + + if isinstance(lvalue, (TupleExpr, ListExpr)): + items = lvalue.items + if isinstance(o.unanalyzed_type, TupleType): # type: ignore[misc] + annotations: Iterable[Type | None] = o.unanalyzed_type.items + else: + annotations = [None] * len(items) + else: + items = [lvalue] + annotations = [o.unanalyzed_type] + sep = False + found = False + for item, annotation in zip(items, annotations): + if isinstance(item, NameExpr): + init = self.get_init(item.name, o.rvalue, annotation) + if init: + found = True + if not sep and self.is_top_level() and self._state not in (EMPTY, VAR): + init = "\n" + init + sep = True + self.add(init) + self.record_name(item.name) + foundl.append(found) + + if all(foundl): + self._state = VAR + + def is_namedtuple(self, expr: CallExpr) -> bool: + return self.get_fullname(expr.callee) == "collections.namedtuple" + + def is_typed_namedtuple(self, expr: CallExpr) -> bool: + return self.get_fullname(expr.callee) in TYPED_NAMEDTUPLE_NAMES + + def _get_namedtuple_fields(self, call: CallExpr) -> list[tuple[str, str]] | None: + if self.is_namedtuple(call): + fields_arg = call.args[1] + if isinstance(fields_arg, StrExpr): + field_names = fields_arg.value.replace(",", " ").split() + elif isinstance(fields_arg, (ListExpr, TupleExpr)): + field_names = [] + for field in fields_arg.items: + if not isinstance(field, StrExpr): + return None + field_names.append(field.value) + else: + return None # Invalid namedtuple fields type + if field_names: + incomplete = self.add_name("_typeshed.Incomplete") + return [(field_name, incomplete) for field_name in field_names] + else: + return [] + + elif self.is_typed_namedtuple(call): + fields_arg = call.args[1] + if not isinstance(fields_arg, (ListExpr, TupleExpr)): + return None + fields: list[tuple[str, str]] = [] + p = AliasPrinter(self) + for field in fields_arg.items: + if not (isinstance(field, TupleExpr) and len(field.items) == 2): + return None + field_name, field_type = field.items + if not isinstance(field_name, StrExpr): + return None + fields.append((field_name.value, field_type.accept(p))) + return fields + else: + return None # Not a named tuple call + + def process_namedtuple(self, lvalue: NameExpr, rvalue: CallExpr) -> None: + if self._state == CLASS: + self.add("\n") + + if not isinstance(rvalue.args[0], StrExpr): + self.annotate_as_incomplete(lvalue) + return + + fields = self._get_namedtuple_fields(rvalue) + if fields is None: + self.annotate_as_incomplete(lvalue) + return + bases = self.add_name("typing.NamedTuple") + # TODO: Add support for generic NamedTuples. Requires `Generic` as base class. + class_def = f"{self._indent}class {lvalue.name}({bases}):" + if len(fields) == 0: + self.add(f"{class_def} ...\n") + self._state = EMPTY_CLASS + else: + if self._state not in (EMPTY, CLASS): + self.add("\n") + self.add(f"{class_def}\n") + for f_name, f_type in fields: + self.add(f"{self._indent} {f_name}: {f_type}\n") + self._state = CLASS + + def is_typeddict(self, expr: CallExpr) -> bool: + return self.get_fullname(expr.callee) in TPDICT_NAMES + + def process_typeddict(self, lvalue: NameExpr, rvalue: CallExpr) -> None: + if self._state == CLASS: + self.add("\n") + + if not isinstance(rvalue.args[0], StrExpr): + self.annotate_as_incomplete(lvalue) + return + + items: list[tuple[str, Expression]] = [] + total: Expression | None = None + if len(rvalue.args) > 1 and rvalue.arg_kinds[1] == ARG_POS: + if not isinstance(rvalue.args[1], DictExpr): + self.annotate_as_incomplete(lvalue) + return + for attr_name, attr_type in rvalue.args[1].items: + if not isinstance(attr_name, StrExpr): + self.annotate_as_incomplete(lvalue) + return + items.append((attr_name.value, attr_type)) + if len(rvalue.args) > 2: + if rvalue.arg_kinds[2] != ARG_NAMED or rvalue.arg_names[2] != "total": + self.annotate_as_incomplete(lvalue) + return + total = rvalue.args[2] + else: + for arg_name, arg in zip(rvalue.arg_names[1:], rvalue.args[1:]): + if not isinstance(arg_name, str): + self.annotate_as_incomplete(lvalue) + return + if arg_name == "total": + total = arg + else: + items.append((arg_name, arg)) + p = AliasPrinter(self) + if any(not key.isidentifier() or keyword.iskeyword(key) for key, _ in items): + # Keep the call syntax if there are non-identifier or reserved keyword keys. + self.add(f"{self._indent}{lvalue.name} = {rvalue.accept(p)}\n") + self._state = VAR + else: + bases = self.add_name("typing_extensions.TypedDict") + # TODO: Add support for generic TypedDicts. Requires `Generic` as base class. + if total is not None: + bases += f", total={total.accept(p)}" + class_def = f"{self._indent}class {lvalue.name}({bases}):" + if len(items) == 0: + self.add(f"{class_def} ...\n") + self._state = EMPTY_CLASS + else: + if self._state not in (EMPTY, CLASS): + self.add("\n") + self.add(f"{class_def}\n") + for key, key_type in items: + self.add(f"{self._indent} {key}: {key_type.accept(p)}\n") + self._state = CLASS + + def annotate_as_incomplete(self, lvalue: NameExpr) -> None: + incomplete = self.add_name("_typeshed.Incomplete") + self.add(f"{self._indent}{lvalue.name}: {incomplete}\n") + self._state = VAR + + def is_alias_expression(self, expr: Expression, top_level: bool = True) -> bool: + """Return True for things that look like target for an alias. + + Used to know if assignments look like type aliases, function alias, + or module alias. + """ + # Assignment of TypeVar(...) and other typevar-likes are passed through + if isinstance(expr, CallExpr) and self.get_fullname(expr.callee) in TYPE_VAR_LIKE_NAMES: + return True + elif isinstance(expr, EllipsisExpr): + return not top_level + elif isinstance(expr, NameExpr): + if expr.name in ("True", "False"): + return False + elif expr.name == "None": + return not top_level + else: + return not self.is_private_name(expr.name) + elif isinstance(expr, MemberExpr) and self.analyzed: + # Also add function and module aliases. + return ( + top_level + and isinstance(expr.node, (FuncDef, Decorator, MypyFile)) + or isinstance(expr.node, TypeInfo) + ) and not self.is_private_member(expr.node.fullname) + elif isinstance(expr, IndexExpr) and ( + (isinstance(expr.base, NameExpr) and not self.is_private_name(expr.base.name)) + or ( # Also some known aliases that could be member expression + isinstance(expr.base, MemberExpr) + and not self.is_private_member(get_qualified_name(expr.base)) + and self.get_fullname(expr.base).startswith( + ("builtins.", "typing.", "typing_extensions.", "collections.abc.") + ) + ) + ): + if isinstance(expr.index, TupleExpr): + indices = expr.index.items + else: + indices = [expr.index] + if expr.base.name == "Callable" and len(indices) == 2: + args, ret = indices + if isinstance(args, EllipsisExpr): + indices = [ret] + elif isinstance(args, ListExpr): + indices = args.items + [ret] + else: + return False + return all(self.is_alias_expression(i, top_level=False) for i in indices) + elif isinstance(expr, OpExpr) and expr.op == "|": + return self.is_alias_expression( + expr.left, top_level=False + ) and self.is_alias_expression(expr.right, top_level=False) + else: + return False + + def process_typealias( + self, lvalue: NameExpr, rvalue: Expression, is_explicit_type_alias: bool = False + ) -> None: + p = AliasPrinter(self) + if is_explicit_type_alias: + self.import_tracker.require_name("TypeAlias") + self.add(f"{self._indent}{lvalue.name}: TypeAlias = {rvalue.accept(p)}\n") + else: + self.add(f"{self._indent}{lvalue.name} = {rvalue.accept(p)}\n") + self.record_name(lvalue.name) + self._vars[-1].append(lvalue.name) + + def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None: + """Type aliases defined with the `type` keyword (PEP 695).""" + p = AliasPrinter(self) + name = o.name.name + rvalue = o.value.expr() + type_args = self.format_type_args(o) + self.add(f"{self._indent}type {name}{type_args} = {rvalue.accept(p)}\n") + self.record_name(name) + self._vars[-1].append(name) + + def visit_if_stmt(self, o: IfStmt) -> None: + # Ignore if __name__ == '__main__'. + expr = o.expr[0] + if ( + isinstance(expr, ComparisonExpr) + and isinstance(expr.operands[0], NameExpr) + and isinstance(expr.operands[1], StrExpr) + and expr.operands[0].name == "__name__" + and "__main__" in expr.operands[1].value + ): + return + super().visit_if_stmt(o) + + def visit_import_all(self, o: ImportAll) -> None: + self.add_import_line(f"from {'.' * o.relative}{o.id} import *\n") + + def visit_import_from(self, o: ImportFrom) -> None: + exported_names: set[str] = set() + import_names = [] + module, relative = translate_module_name(o.id, o.relative) + if self.module_name: + full_module, ok = mypy.util.correct_relative_import( + self.module_name, relative, module, self.path.endswith(".__init__.py") + ) + if not ok: + full_module = module + else: + full_module = module + if module == "__future__": + return # Not preserved + for name, as_name in o.names: + if name == "six": + # Vendored six -- translate into plain 'import six'. + self.visit_import(Import([("six", None)])) + continue + if self.should_reexport(name, full_module, as_name is not None): + self.import_tracker.reexport(name) + as_name = name + import_names.append((name, as_name)) + self.import_tracker.add_import_from("." * relative + module, import_names) + self._vars[-1].extend(alias or name for name, alias in import_names) + for name, alias in import_names: + self.record_name(alias or name) + + if self._all_: + # Include "import from"s that import names defined in __all__. + names = [ + name + for name, alias in o.names + if name in self._all_ and alias is None and name not in self.IGNORED_DUNDERS + ] + exported_names.update(names) + + def visit_import(self, o: Import) -> None: + for id, as_id in o.ids: + self.import_tracker.add_import(id, as_id) + if as_id is None: + target_name = id.split(".")[0] + else: + target_name = as_id + self._vars[-1].append(target_name) + self.record_name(target_name) + + def get_init( + self, lvalue: str, rvalue: Expression, annotation: Type | None = None + ) -> str | None: + """Return initializer for a variable. + + Return None if we've generated one already or if the variable is internal. + """ + if lvalue in self._vars[-1]: + # We've generated an initializer already for this variable. + return None + # TODO: Only do this at module top level. + if self.is_private_name(lvalue) or self.is_not_in_all(lvalue): + return None + self._vars[-1].append(lvalue) + if annotation is not None: + typename = self.print_annotation(annotation) + if ( + isinstance(annotation, UnboundType) + and not annotation.args + and annotation.name == "Final" + and self.import_tracker.module_for.get("Final") in self.TYPING_MODULE_NAMES + ): + # Final without type argument is invalid in stubs. + final_arg = self.get_str_type_of_node(rvalue) + typename += f"[{final_arg}]" + elif self.processing_enum: + initializer, _ = self.get_str_default_of_node(rvalue) + return f"{self._indent}{lvalue} = {initializer}\n" + elif self.processing_dataclass: + # attribute without annotation is not a dataclass field, don't add annotation. + return f"{self._indent}{lvalue} = ...\n" + else: + typename = self.get_str_type_of_node(rvalue) + initializer = self.get_assign_initializer(rvalue) + return f"{self._indent}{lvalue}: {typename}{initializer}\n" + + def get_assign_initializer(self, rvalue: Expression) -> str: + """Does this rvalue need some special initializer value?""" + if not self._current_class: + return "" + # Current rules + # 1. Return `...` if we are dealing with `NamedTuple` or `dataclass` field and + # it has an existing default value + if ( + self._current_class.info + and self._current_class.info.is_named_tuple + and not isinstance(rvalue, TempNode) + ): + return " = ..." + if self.processing_dataclass: + if isinstance(rvalue, CallExpr): + fullname = self.get_fullname(rvalue.callee) + if fullname in (self.dataclass_field_specifier or DATACLASS_FIELD_SPECIFIERS): + p = AliasPrinter(self) + return f" = {rvalue.accept(p)}" + if not (isinstance(rvalue, TempNode) and rvalue.no_rhs): + return " = ..." + # TODO: support other possible cases, where initializer is important + + # By default, no initializer is required: + return "" + + def add_decorator(self, name: str, require_name: bool = False) -> None: + if require_name: + self.import_tracker.require_name(name) + self._decorators.append(f"@{name}") + + def clear_decorators(self) -> None: + self._decorators.clear() + + def is_private_member(self, fullname: str) -> bool: + parts = fullname.split(".") + return any(self.is_private_name(part) for part in parts) + + def get_str_type_of_node(self, rvalue: Expression, *, can_be_incomplete: bool = True) -> str: + rvalue = self.maybe_unwrap_unary_expr(rvalue) + + if isinstance(rvalue, IntExpr): + return "int" + if isinstance(rvalue, StrExpr): + return "str" + if isinstance(rvalue, BytesExpr): + return "bytes" + if isinstance(rvalue, FloatExpr): + return "float" + if isinstance(rvalue, ComplexExpr): # 1j + return "complex" + if isinstance(rvalue, OpExpr) and rvalue.op in ("-", "+"): # -1j + 1 + if isinstance(self.maybe_unwrap_unary_expr(rvalue.left), ComplexExpr) or isinstance( + self.maybe_unwrap_unary_expr(rvalue.right), ComplexExpr + ): + return "complex" + if isinstance(rvalue, NameExpr) and rvalue.name in ("True", "False"): + return "bool" + if can_be_incomplete: + return self.add_name("_typeshed.Incomplete") + else: + return "" + + def maybe_unwrap_unary_expr(self, expr: Expression) -> Expression: + """Unwrap (possibly nested) unary expressions. + + But, some unary expressions can change the type of expression. + While we want to preserve it. For example, `~True` is `int`. + So, we only allow a subset of unary expressions to be unwrapped. + """ + if not isinstance(expr, UnaryExpr): + return expr + + # First, try to unwrap `[+-]+ (int|float|complex)` expr: + math_ops = ("+", "-") + if expr.op in math_ops: + while isinstance(expr, UnaryExpr): + if expr.op not in math_ops or not isinstance( + expr.expr, (IntExpr, FloatExpr, ComplexExpr, UnaryExpr) + ): + break + expr = expr.expr + return expr + + # Next, try `not bool` expr: + if expr.op == "not": + while isinstance(expr, UnaryExpr): + if expr.op != "not" or not isinstance(expr.expr, (NameExpr, UnaryExpr)): + break + if isinstance(expr.expr, NameExpr) and expr.expr.name not in ("True", "False"): + break + expr = expr.expr + return expr + + # This is some other unary expr, we cannot do anything with it (yet?). + return expr + + def get_str_default_of_node(self, rvalue: Expression) -> tuple[str, bool]: + """Get a string representation of the default value of a node. + + Returns a 2-tuple of the default and whether or not it is valid. + """ + if isinstance(rvalue, NameExpr): + if rvalue.name in ("None", "True", "False"): + return rvalue.name, True + elif isinstance(rvalue, (IntExpr, FloatExpr)): + return f"{rvalue.value}", True + elif isinstance(rvalue, UnaryExpr): + if isinstance(rvalue.expr, (IntExpr, FloatExpr)): + return f"{rvalue.op}{rvalue.expr.value}", True + elif isinstance(rvalue, StrExpr): + return repr(rvalue.value), True + elif isinstance(rvalue, BytesExpr): + return "b" + repr(rvalue.value).replace("\\\\", "\\"), True + elif isinstance(rvalue, TupleExpr): + items_defaults = [] + for e in rvalue.items: + e_default, valid = self.get_str_default_of_node(e) + if not valid: + break + items_defaults.append(e_default) + else: + closing = ",)" if len(items_defaults) == 1 else ")" + default = "(" + ", ".join(items_defaults) + closing + return default, True + elif isinstance(rvalue, ListExpr): + items_defaults = [] + for e in rvalue.items: + e_default, valid = self.get_str_default_of_node(e) + if not valid: + break + items_defaults.append(e_default) + else: + default = "[" + ", ".join(items_defaults) + "]" + return default, True + elif isinstance(rvalue, SetExpr): + items_defaults = [] + for e in rvalue.items: + e_default, valid = self.get_str_default_of_node(e) + if not valid: + break + items_defaults.append(e_default) + else: + if items_defaults: + default = "{" + ", ".join(items_defaults) + "}" + return default, True + elif isinstance(rvalue, DictExpr): + items_defaults = [] + for k, v in rvalue.items: + if k is None: + break + k_default, k_valid = self.get_str_default_of_node(k) + v_default, v_valid = self.get_str_default_of_node(v) + if not (k_valid and v_valid): + break + items_defaults.append(f"{k_default}: {v_default}") + else: + default = "{" + ", ".join(items_defaults) + "}" + return default, True + return "...", False + + def should_reexport(self, name: str, full_module: str, name_is_alias: bool) -> bool: + is_private = self.is_private_name(name, full_module + "." + name) + if ( + not name_is_alias + and name not in self.referenced_names + and (not self._all_ or name in self.IGNORED_DUNDERS) + and not is_private + and full_module not in ("abc", "asyncio") + self.TYPING_MODULE_NAMES + ): + # An imported name that is never referenced in the module is assumed to be + # exported, unless there is an explicit __all__. Note that we need to special + # case 'abc' since some references are deleted during semantic analysis. + return True + return super().should_reexport(name, full_module, name_is_alias) + + +def find_method_names(defs: list[Statement]) -> set[str]: + # TODO: Traverse into nested definitions + result = set() + for defn in defs: + if isinstance(defn, FuncDef): + result.add(defn.name) + elif isinstance(defn, Decorator): + result.add(defn.func.name) + elif isinstance(defn, OverloadedFuncDef): + for item in defn.items: + result.update(find_method_names([item])) + return result + + +class SelfTraverser(mypy.traverser.TraverserVisitor): + def __init__(self) -> None: + self.results: list[tuple[str, Expression, Type | None]] = [] + + def visit_assignment_stmt(self, o: AssignmentStmt) -> None: + lvalue = o.lvalues[0] + if ( + isinstance(lvalue, MemberExpr) + and isinstance(lvalue.expr, NameExpr) + and lvalue.expr.name == "self" + ): + self.results.append((lvalue.name, o.rvalue, o.unanalyzed_type)) + + +def find_self_initializers(fdef: FuncBase) -> list[tuple[str, Expression, Type | None]]: + """Find attribute initializers in a method. + + Return a list of pairs (attribute name, r.h.s. expression). + """ + traverser = SelfTraverser() + fdef.accept(traverser) + return traverser.results + + +def get_qualified_name(o: Expression) -> str: + if isinstance(o, NameExpr): + return o.name + elif isinstance(o, MemberExpr): + return f"{get_qualified_name(o.expr)}.{o.name}" + else: + return ERROR_MARKER + + +def remove_blacklisted_modules(modules: list[StubSource]) -> list[StubSource]: + return [ + module for module in modules if module.path is None or not is_blacklisted_path(module.path) + ] + + +def split_pyc_from_py(modules: list[StubSource]) -> tuple[list[StubSource], list[StubSource]]: + py_modules = [] + pyc_modules = [] + for mod in modules: + if is_pyc_only(mod.path): + pyc_modules.append(mod) + else: + py_modules.append(mod) + return pyc_modules, py_modules + + +def is_blacklisted_path(path: str) -> bool: + return any(substr in (normalize_path_separators(path) + "\n") for substr in BLACKLIST) + + +def normalize_path_separators(path: str) -> str: + return path.replace("\\", "/") if sys.platform == "win32" else path + + +def collect_build_targets( + options: Options, mypy_opts: MypyOptions +) -> tuple[list[StubSource], list[StubSource], list[StubSource]]: + """Collect files for which we need to generate stubs. + + Return list of py modules, pyc modules, and C modules. + """ + if options.packages or options.modules: + if options.no_import: + py_modules = find_module_paths_using_search( + options.modules, options.packages, options.search_path, options.pyversion + ) + c_modules: list[StubSource] = [] + else: + # Using imports is the default, since we can also find C modules. + py_modules, c_modules = find_module_paths_using_imports( + options.modules, options.packages, options.verbose, options.quiet + ) + else: + # Use mypy native source collection for files and directories. + try: + source_list = create_source_list(options.files, mypy_opts) + except InvalidSourceList as e: + raise SystemExit(str(e)) from e + py_modules = [StubSource(m.module, m.path) for m in source_list] + c_modules = [] + + py_modules = remove_blacklisted_modules(py_modules) + pyc_mod, py_mod = split_pyc_from_py(py_modules) + return py_mod, pyc_mod, c_modules + + +def find_module_paths_using_imports( + modules: list[str], packages: list[str], verbose: bool, quiet: bool +) -> tuple[list[StubSource], list[StubSource]]: + """Find path and runtime value of __all__ (if possible) for modules and packages. + + This function uses runtime Python imports to get the information. + """ + with ModuleInspect() as inspect: + py_modules: list[StubSource] = [] + c_modules: list[StubSource] = [] + found = list(walk_packages(inspect, packages, verbose)) + modules = modules + found + modules = [ + mod for mod in modules if not is_non_library_module(mod) + ] # We don't want to run any tests or scripts + for mod in modules: + try: + result = find_module_path_and_all_py3(inspect, mod, verbose) + except CantImport as e: + tb = traceback.format_exc() + if verbose: + sys.stderr.write(tb) + if not quiet: + report_missing(mod, e.message, tb) + continue + if not result: + c_modules.append(StubSource(mod)) + else: + path, runtime_all = result + py_modules.append(StubSource(mod, path, runtime_all)) + return py_modules, c_modules + + +def is_non_library_module(module: str) -> bool: + """Does module look like a test module or a script?""" + if module.endswith( + ( + ".tests", + ".test", + ".testing", + "_tests", + "_test_suite", + "test_util", + "test_utils", + "test_base", + ".__main__", + ".conftest", # Used by pytest + ".setup", # Typically an install script + ) + ): + return True + if module.split(".")[-1].startswith("test_"): + return True + if ( + ".tests." in module + or ".test." in module + or ".testing." in module + or ".SelfTest." in module + ): + return True + return False + + +def translate_module_name(module: str, relative: int) -> tuple[str, int]: + for pkg in VENDOR_PACKAGES: + for alt in "six.moves", "six": + substr = f"{pkg}.{alt}" + if module.endswith("." + substr) or (module == substr and relative): + return alt, 0 + if "." + substr + "." in module: + return alt + "." + module.partition("." + substr + ".")[2], 0 + return module, relative + + +def find_module_paths_using_search( + modules: list[str], packages: list[str], search_path: list[str], pyversion: tuple[int, int] +) -> list[StubSource]: + """Find sources for modules and packages requested. + + This function just looks for source files at the file system level. + This is used if user passes --no-import, and will not find C modules. + Exit if some of the modules or packages can't be found. + """ + result: list[StubSource] = [] + typeshed_path = default_lib_path(mypy.build.default_data_dir(), pyversion, None) + search_paths = SearchPaths((".",) + tuple(search_path), (), (), tuple(typeshed_path)) + cache = FindModuleCache(search_paths, fscache=None, options=None) + for module in modules: + m_result = cache.find_module(module) + if isinstance(m_result, ModuleNotFoundReason): + fail_missing(module, m_result) + module_path = None + else: + module_path = m_result + result.append(StubSource(module, module_path)) + for package in packages: + p_result = cache.find_modules_recursive(package) + if p_result: + fail_missing(package, ModuleNotFoundReason.NOT_FOUND) + sources = [StubSource(m.module, m.path) for m in p_result] + result.extend(sources) + + result = [m for m in result if not is_non_library_module(m.module)] + + return result + + +def mypy_options(stubgen_options: Options) -> MypyOptions: + """Generate mypy options using the flag passed by user.""" + options = MypyOptions() + options.follow_imports = "skip" + options.incremental = False + options.ignore_errors = True + options.semantic_analysis_only = True + options.python_version = stubgen_options.pyversion + options.show_traceback = True + options.transform_source = remove_misplaced_type_comments + options.preserve_asts = True + options.include_docstrings = stubgen_options.include_docstrings + + # Override cache_dir if provided in the environment + environ_cache_dir = os.getenv("MYPY_CACHE_DIR", "") + if environ_cache_dir.strip(): + options.cache_dir = environ_cache_dir + options.cache_dir = os.path.expanduser(options.cache_dir) + + return options + + +def parse_source_file(mod: StubSource, mypy_options: MypyOptions) -> None: + """Parse a source file. + + On success, store AST in the corresponding attribute of the stub source. + If there are syntax errors, print them and exit. + """ + assert mod.path is not None, "Not found module was not skipped" + with open(mod.path, "rb") as f: + data = f.read() + source = mypy.util.decode_python_encoding(data) + errors = Errors(mypy_options) + mod.ast = mypy.parse.parse( + source, fnam=mod.path, module=mod.module, errors=errors, options=mypy_options + ) + mod.ast._fullname = mod.module + if errors.is_blockers(): + # Syntax error! + for m in errors.new_messages(): + sys.stderr.write(f"{m}\n") + sys.exit(1) + + +def generate_asts_for_modules( + py_modules: list[StubSource], parse_only: bool, mypy_options: MypyOptions, verbose: bool +) -> None: + """Use mypy to parse (and optionally analyze) source files.""" + if not py_modules: + return # Nothing to do here, but there may be C modules + if verbose: + print(f"Processing {len(py_modules)} files...") + if parse_only: + for mod in py_modules: + parse_source_file(mod, mypy_options) + return + # Perform full semantic analysis of the source set. + try: + res = build([module.source for module in py_modules], mypy_options) + except CompileError as e: + raise SystemExit(f"Critical error during semantic analysis: {e}") from e + + for mod in py_modules: + mod.ast = res.graph[mod.module].tree + # Use statically inferred __all__ if there is no runtime one. + if mod.runtime_all is None: + mod_names = res.manager.semantic_analyzer.modules[mod.module].names + if "__all__" in mod_names: + mod.runtime_all = [name for name, sym in mod_names.items() if sym.module_public] + + +def generate_stub_for_py_module( + mod: StubSource, + target: str, + *, + parse_only: bool = False, + inspect: bool = False, + include_private: bool = False, + export_less: bool = False, + include_docstrings: bool = False, + doc_dir: str = "", + all_modules: list[str], +) -> None: + """Use analysed (or just parsed) AST to generate type stub for single file. + + If directory for target doesn't exist it will created. Existing stub + will be overwritten. + """ + if inspect: + ngen = InspectionStubGenerator( + module_name=mod.module, + known_modules=all_modules, + _all_=mod.runtime_all, + doc_dir=doc_dir, + include_private=include_private, + export_less=export_less, + include_docstrings=include_docstrings, + ) + ngen.generate_module() + output = ngen.output() + + else: + gen = ASTStubGenerator( + mod.runtime_all, + include_private=include_private, + analyzed=not parse_only, + export_less=export_less, + include_docstrings=include_docstrings, + ) + assert mod.ast is not None, "This function must be used only with analyzed modules" + mod.ast.accept(gen) + output = gen.output() + + # Write output to file. + subdir = os.path.dirname(target) + if subdir and not os.path.isdir(subdir): + os.makedirs(subdir) + with open(target, "w", encoding="utf-8") as file: + file.write(output) + + +def generate_stubs(options: Options) -> None: + """Main entry point for the program.""" + mypy_opts = mypy_options(options) + py_modules, pyc_modules, c_modules = collect_build_targets(options, mypy_opts) + all_modules = py_modules + pyc_modules + c_modules + all_module_names = sorted(m.module for m in all_modules) + # Use parsed sources to generate stubs for Python modules. + generate_asts_for_modules(py_modules, options.parse_only, mypy_opts, options.verbose) + files = [] + for mod in py_modules + pyc_modules: + assert mod.path is not None, "Not found module was not skipped" + target = mod.module.replace(".", "/") + if os.path.basename(mod.path) in ["__init__.py", "__init__.pyc"]: + target += "/__init__.pyi" + else: + target += ".pyi" + target = os.path.join(options.output_dir, target) + files.append(target) + with generate_guarded(mod.module, target, options.ignore_errors, options.verbose): + generate_stub_for_py_module( + mod, + target, + parse_only=options.parse_only, + inspect=options.inspect or mod in pyc_modules, + include_private=options.include_private, + export_less=options.export_less, + include_docstrings=options.include_docstrings, + doc_dir=options.doc_dir, + all_modules=all_module_names, + ) + + # Separately analyse C modules using different logic. + for mod in c_modules: + if any(py_mod.module.startswith(mod.module + ".") for py_mod in all_modules): + target = mod.module.replace(".", "/") + "/__init__.pyi" + else: + target = mod.module.replace(".", "/") + ".pyi" + target = os.path.join(options.output_dir, target) + files.append(target) + with generate_guarded(mod.module, target, options.ignore_errors, options.verbose): + generate_stub_for_c_module( + mod.module, + target, + known_modules=all_module_names, + doc_dir=options.doc_dir, + include_private=options.include_private, + export_less=options.export_less, + include_docstrings=options.include_docstrings, + ) + num_modules = len(all_modules) + if not options.quiet and num_modules > 0: + print("Processed %d modules" % num_modules) + if len(files) == 1: + print(f"Generated {files[0]}") + else: + print(f"Generated files under {common_dir_prefix(files)}" + os.sep) + + +HEADER = """%(prog)s [-h] [more options, see -h] + [-m MODULE] [-p PACKAGE] [files ...]""" + +DESCRIPTION = """ +Generate draft stubs for modules. + +Stubs are generated in directory ./out, to avoid overriding files with +manual changes. This directory is assumed to exist. +""" + + +def parse_options(args: list[str]) -> Options: + parser = argparse.ArgumentParser( + prog="stubgen", usage=HEADER, description=DESCRIPTION, fromfile_prefix_chars="@" + ) + + parser.add_argument( + "--ignore-errors", + action="store_true", + help="ignore errors when trying to generate stubs for modules", + ) + parser.add_argument( + "--no-import", + action="store_true", + help="don't import the modules, just parse and analyze them " + "(doesn't work with C extension modules and might not " + "respect __all__)", + ) + parser.add_argument( + "--no-analysis", + "--parse-only", + dest="parse_only", + action="store_true", + help="don't perform semantic analysis of sources, just parse them " + "(only applies to Python modules, might affect quality of stubs. " + "Not compatible with --inspect-mode)", + ) + parser.add_argument( + "--inspect-mode", + dest="inspect", + action="store_true", + help="import and inspect modules instead of parsing source code." + "This is the default behavior for c modules and pyc-only packages, but " + "it is also useful for pure python modules with dynamically generated members.", + ) + parser.add_argument( + "--include-private", + action="store_true", + help="generate stubs for objects and members considered private " + "(single leading underscore and no trailing underscores)", + ) + parser.add_argument( + "--export-less", + action="store_true", + help="don't implicitly export all names imported from other modules in the same package", + ) + parser.add_argument( + "--include-docstrings", + action="store_true", + help="include existing docstrings with the stubs", + ) + parser.add_argument("-v", "--verbose", action="store_true", help="show more verbose messages") + parser.add_argument("-q", "--quiet", action="store_true", help="show fewer messages") + parser.add_argument( + "--doc-dir", + metavar="PATH", + default="", + help="use .rst documentation in PATH (this may result in " + "better stubs in some cases; consider setting this to " + "DIR/Python-X.Y.Z/Doc/library)", + ) + parser.add_argument( + "--search-path", + metavar="PATH", + default="", + help="specify module search directories, separated by ':' " + "(currently only used if --no-import is given)", + ) + parser.add_argument( + "-o", + "--output", + metavar="PATH", + dest="output_dir", + default="out", + help="change the output directory [default: %(default)s]", + ) + parser.add_argument( + "-m", + "--module", + action="append", + metavar="MODULE", + dest="modules", + default=[], + help="generate stub for module; can repeat for more modules", + ) + parser.add_argument( + "-p", + "--package", + action="append", + metavar="PACKAGE", + dest="packages", + default=[], + help="generate stubs for package recursively; can be repeated", + ) + parser.add_argument( + metavar="files", + nargs="*", + dest="files", + help="generate stubs for given files or directories", + ) + parser.add_argument( + "--version", action="version", version="%(prog)s " + mypy.version.__version__ + ) + + ns = parser.parse_args(args) + + pyversion = sys.version_info[:2] + ns.interpreter = sys.executable + + if ns.modules + ns.packages and ns.files: + parser.error("May only specify one of: modules/packages or files.") + if ns.quiet and ns.verbose: + parser.error("Cannot specify both quiet and verbose messages") + if ns.inspect and ns.parse_only: + parser.error("Cannot specify both --parse-only/--no-analysis and --inspect-mode") + + # Create the output folder if it doesn't already exist. + os.makedirs(ns.output_dir, exist_ok=True) + + return Options( + pyversion=pyversion, + no_import=ns.no_import, + inspect=ns.inspect, + doc_dir=ns.doc_dir, + search_path=ns.search_path.split(":"), + interpreter=ns.interpreter, + ignore_errors=ns.ignore_errors, + parse_only=ns.parse_only, + include_private=ns.include_private, + output_dir=ns.output_dir, + modules=ns.modules, + packages=ns.packages, + files=ns.files, + verbose=ns.verbose, + quiet=ns.quiet, + export_less=ns.export_less, + include_docstrings=ns.include_docstrings, + ) + + +def main(args: list[str] | None = None) -> None: + mypy.util.check_python_version("stubgen") + # Make sure that the current directory is in sys.path so that + # stubgen can be run on packages in the current directory. + if not ("" in sys.path or "." in sys.path): + sys.path.insert(0, "") + + options = parse_options(sys.argv[1:] if args is None else args) + generate_stubs(options) + + +if __name__ == "__main__": + main() diff --git a/micromamba_root/Lib/site-packages/mypy/stubgenc.py b/micromamba_root/Lib/site-packages/mypy/stubgenc.py new file mode 100644 index 0000000000000000000000000000000000000000..d86818adf2a4314ff15048cc09ec1e0a46e74b95 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/stubgenc.py @@ -0,0 +1,1046 @@ +#!/usr/bin/env python3 +"""Stub generator for C modules. + +The public interface is via the mypy.stubgen module. +""" + +from __future__ import annotations + +import enum +import glob +import importlib +import inspect +import keyword +import os.path +from collections.abc import Callable, Mapping +from types import FunctionType, ModuleType +from typing import Any + +from mypy.fastparse import parse_type_comment +from mypy.moduleinspect import is_c_module +from mypy.stubdoc import ( + ArgSig, + FunctionSig, + Sig, + find_unique_signatures, + infer_arg_sig_from_anon_docstring, + infer_prop_type_from_docstring, + infer_ret_type_sig_from_anon_docstring, + infer_ret_type_sig_from_docstring, + infer_sig_from_docstring, + parse_all_signatures, +) +from mypy.stubutil import ( + BaseStubGenerator, + ClassInfo, + FunctionContext, + SignatureGenerator, + infer_method_arg_types, + infer_method_ret_type, +) +from mypy.util import quote_docstring + + +class ExternalSignatureGenerator(SignatureGenerator): + def __init__( + self, func_sigs: dict[str, str] | None = None, class_sigs: dict[str, str] | None = None + ) -> None: + """ + Takes a mapping of function/method names to signatures and class name to + class signatures (usually corresponds to __init__). + """ + self.func_sigs = func_sigs or {} + self.class_sigs = class_sigs or {} + + @classmethod + def from_doc_dir(cls, doc_dir: str) -> ExternalSignatureGenerator: + """Instantiate from a directory of .rst files.""" + all_sigs: list[Sig] = [] + all_class_sigs: list[Sig] = [] + for path in glob.glob(f"{doc_dir}/*.rst"): + with open(path) as f: + loc_sigs, loc_class_sigs = parse_all_signatures(f.readlines()) + all_sigs += loc_sigs + all_class_sigs += loc_class_sigs + sigs = dict(find_unique_signatures(all_sigs)) + class_sigs = dict(find_unique_signatures(all_class_sigs)) + return ExternalSignatureGenerator(sigs, class_sigs) + + def get_function_sig( + self, default_sig: FunctionSig, ctx: FunctionContext + ) -> list[FunctionSig] | None: + # method: + if ( + ctx.class_info + and ctx.name in ("__new__", "__init__") + and ctx.name not in self.func_sigs + and ctx.class_info.name in self.class_sigs + ): + return [ + FunctionSig( + name=ctx.name, + args=infer_arg_sig_from_anon_docstring(self.class_sigs[ctx.class_info.name]), + ret_type=infer_method_ret_type(ctx.name), + ) + ] + + # function: + if ctx.name not in self.func_sigs: + return None + + inferred = [ + FunctionSig( + name=ctx.name, + args=infer_arg_sig_from_anon_docstring(self.func_sigs[ctx.name]), + ret_type=None, + ) + ] + if ctx.class_info: + return self.remove_self_type(inferred, ctx.class_info.self_var) + else: + return inferred + + def get_property_type(self, default_type: str | None, ctx: FunctionContext) -> str | None: + return None + + +class DocstringSignatureGenerator(SignatureGenerator): + def get_function_sig( + self, default_sig: FunctionSig, ctx: FunctionContext + ) -> list[FunctionSig] | None: + inferred = infer_sig_from_docstring(ctx.docstring, ctx.name) + if inferred: + assert ctx.docstring is not None + if is_pybind11_overloaded_function_docstring(ctx.docstring, ctx.name): + # Remove pybind11 umbrella (*args, **kwargs) for overloaded functions + del inferred[-1] + + if ctx.class_info: + if not inferred and ctx.name == "__init__": + # look for class-level constructor signatures of the form () + inferred = infer_sig_from_docstring(ctx.class_info.docstring, ctx.class_info.name) + if inferred: + inferred = [sig._replace(name="__init__") for sig in inferred] + return self.remove_self_type(inferred, ctx.class_info.self_var) + else: + return inferred + + def get_property_type(self, default_type: str | None, ctx: FunctionContext) -> str | None: + """Infer property type from docstring or docstring signature.""" + if ctx.docstring is not None: + inferred = infer_ret_type_sig_from_anon_docstring(ctx.docstring) + if inferred: + return inferred + inferred = infer_ret_type_sig_from_docstring(ctx.docstring, ctx.name) + if inferred: + return inferred + inferred = infer_prop_type_from_docstring(ctx.docstring) + return inferred + else: + return None + + +def is_pybind11_overloaded_function_docstring(docstring: str, name: str) -> bool: + return docstring.startswith(f"{name}(*args, **kwargs)\nOverloaded function.\n\n") + + +def generate_stub_for_c_module( + module_name: str, + target: str, + known_modules: list[str], + doc_dir: str = "", + *, + include_private: bool = False, + export_less: bool = False, + include_docstrings: bool = False, +) -> None: + """Generate stub for C module. + + Signature generators are called in order until a list of signatures is returned. The order + is: + - signatures inferred from .rst documentation (if given) + - simple runtime introspection (looking for docstrings and attributes + with simple builtin types) + - fallback based special method names or "(*args, **kwargs)" + + If directory for target doesn't exist it will be created. Existing stub + will be overwritten. + """ + subdir = os.path.dirname(target) + if subdir and not os.path.isdir(subdir): + os.makedirs(subdir) + + gen = InspectionStubGenerator( + module_name, + known_modules, + doc_dir, + include_private=include_private, + export_less=export_less, + include_docstrings=include_docstrings, + ) + gen.generate_module() + output = gen.output() + + with open(target, "w", encoding="utf-8") as file: + file.write(output) + + +class CFunctionStub: + """ + Class that mimics a C function in order to provide parseable docstrings. + """ + + def __init__(self, name: str, doc: str, is_abstract: bool = False) -> None: + self.__name__ = name + self.__doc__ = doc + self.__abstractmethod__ = is_abstract + + @classmethod + def _from_sig(cls, sig: FunctionSig, is_abstract: bool = False) -> CFunctionStub: + return CFunctionStub(sig.name, sig.format_sig()[:-4], is_abstract) + + @classmethod + def _from_sigs(cls, sigs: list[FunctionSig], is_abstract: bool = False) -> CFunctionStub: + return CFunctionStub( + sigs[0].name, "\n".join(sig.format_sig()[:-4] for sig in sigs), is_abstract + ) + + def __get__(self) -> None: # noqa: PLE0302 + """ + This exists to make this object look like a method descriptor and thus + return true for CStubGenerator.ismethod() + """ + pass + + +_Missing = enum.Enum("_Missing", "VALUE") + + +class InspectionStubGenerator(BaseStubGenerator): + """Stub generator that does not parse code. + + Generation is performed by inspecting the module's contents, and thus works + for highly dynamic modules, pyc files, and C modules (via the CStubGenerator + subclass). + """ + + def __init__( + self, + module_name: str, + known_modules: list[str], + doc_dir: str = "", + _all_: list[str] | None = None, + include_private: bool = False, + export_less: bool = False, + include_docstrings: bool = False, + module: ModuleType | None = None, + ) -> None: + self.doc_dir = doc_dir + if module is None: + self.module = importlib.import_module(module_name) + else: + self.module = module + self.is_c_module = is_c_module(self.module) + self.known_modules = known_modules + self.resort_members = self.is_c_module + super().__init__(_all_, include_private, export_less, include_docstrings) + self.module_name = module_name + if self.is_c_module: + # Add additional implicit imports. + # C-extensions are given more latitude since they do not import the typing module. + self.known_imports.update( + { + "typing": [ + "Any", + "Callable", + "ClassVar", + "Dict", + "Iterable", + "Iterator", + "List", + "Literal", + "NamedTuple", + "Optional", + "Tuple", + "Union", + ] + } + ) + + def get_default_function_sig(self, func: object, ctx: FunctionContext) -> FunctionSig: + argspec = None + if not self.is_c_module: + # Get the full argument specification of the function + try: + argspec = inspect.getfullargspec(func) + except TypeError: + # some callables cannot be inspected, e.g. functools.partial + pass + if argspec is None: + if ctx.class_info is not None: + # method: + return FunctionSig( + name=ctx.name, + args=infer_c_method_args(ctx.name, ctx.class_info.self_var), + ret_type=infer_method_ret_type(ctx.name), + ) + else: + # function: + return FunctionSig( + name=ctx.name, + args=[ArgSig(name="*args"), ArgSig(name="**kwargs")], + ret_type=None, + ) + + # Extract the function arguments, defaults, and varargs + args = argspec.args + defaults = argspec.defaults + varargs = argspec.varargs + kwargs = argspec.varkw + annotations = argspec.annotations + kwonlyargs = argspec.kwonlyargs + kwonlydefaults = argspec.kwonlydefaults + + def get_annotation(key: str) -> str | None: + if key not in annotations: + return None + argtype = annotations[key] + if argtype is None: + return "None" + if not isinstance(argtype, str): + return self.get_type_fullname(argtype) + return argtype + + arglist: list[ArgSig] = [] + + # Add the arguments to the signature + def add_args( + args: list[str], get_default_value: Callable[[int, str], object | _Missing] + ) -> None: + for i, arg in enumerate(args): + # Check if the argument has a default value + default_value = get_default_value(i, arg) + if default_value is not _Missing.VALUE: + if arg in annotations: + argtype = get_annotation(arg) + else: + argtype = self.get_type_annotation(default_value) + if argtype == "None": + # None is not a useful annotation, but we can infer that the arg + # is optional + incomplete = self.add_name("_typeshed.Incomplete") + argtype = f"{incomplete} | None" + + arglist.append(ArgSig(arg, argtype, default=True)) + else: + arglist.append(ArgSig(arg, get_annotation(arg), default=False)) + + def get_pos_default(i: int, _arg: str) -> Any | _Missing: + if defaults and i >= len(args) - len(defaults): + return defaults[i - (len(args) - len(defaults))] + else: + return _Missing.VALUE + + add_args(args, get_pos_default) + + # Add *args if present + if varargs: + arglist.append(ArgSig(f"*{varargs}", get_annotation(varargs))) + # if we have keyword only args, then we need to add "*" + elif kwonlyargs: + arglist.append(ArgSig("*")) + + def get_kw_default(_i: int, arg: str) -> Any | _Missing: + if kwonlydefaults and arg in kwonlydefaults: + return kwonlydefaults[arg] + else: + return _Missing.VALUE + + add_args(kwonlyargs, get_kw_default) + + # Add **kwargs if present + if kwargs: + arglist.append(ArgSig(f"**{kwargs}", get_annotation(kwargs))) + + # add types for known special methods + if ctx.class_info is not None and all( + arg.type is None and arg.default is False for arg in arglist + ): + new_args = infer_method_arg_types( + ctx.name, ctx.class_info.self_var, [arg.name for arg in arglist if arg.name] + ) + if new_args is not None: + arglist = new_args + + ret_type = get_annotation("return") or infer_method_ret_type(ctx.name) + return FunctionSig(ctx.name, arglist, ret_type) + + def get_sig_generators(self) -> list[SignatureGenerator]: + if not self.is_c_module: + return [] + else: + sig_generators: list[SignatureGenerator] = [DocstringSignatureGenerator()] + if self.doc_dir: + # Collect info from docs (if given). Always check these first. + sig_generators.insert(0, ExternalSignatureGenerator.from_doc_dir(self.doc_dir)) + return sig_generators + + def strip_or_import(self, type_name: str) -> str: + """Strips unnecessary module names from typ. + + If typ represents a type that is inside module or is a type coming from builtins, remove + module declaration from it. Return stripped name of the type. + + Arguments: + typ: name of the type + """ + local_modules = ["builtins", self.module_name] + parsed_type = parse_type_comment(type_name, 0, 0, None)[1] + assert parsed_type is not None, type_name + return self.print_annotation(parsed_type, self.known_modules, local_modules) + + def get_obj_module(self, obj: object) -> str | None: + """Return module name of the object.""" + return getattr(obj, "__module__", None) + + def is_defined_in_module(self, obj: object) -> bool: + """Check if object is considered defined in the current module.""" + module = self.get_obj_module(obj) + return module is None or module == self.module_name + + def generate_module(self) -> None: + all_items = self.get_members(self.module) + if self.resort_members: + all_items = sorted(all_items, key=lambda x: x[0]) + items = [] + for name, obj in all_items: + if inspect.ismodule(obj) and obj.__name__ in self.known_modules: + module_name = obj.__name__ + if module_name.startswith(self.module_name + "."): + # from {.rel_name} import {mod_name} as {name} + pkg_name, mod_name = module_name.rsplit(".", 1) + rel_module = pkg_name[len(self.module_name) :] or "." + self.import_tracker.add_import_from(rel_module, [(mod_name, name)]) + self.import_tracker.reexport(name) + else: + # import {module_name} as {name} + self.import_tracker.add_import(module_name, name) + self.import_tracker.reexport(name) + elif self.is_defined_in_module(obj) and not inspect.ismodule(obj): + # process this below + items.append((name, obj)) + else: + # from {obj_module} import {obj_name} + obj_module_name = self.get_obj_module(obj) + if obj_module_name: + self.import_tracker.add_import_from(obj_module_name, [(name, None)]) + if self.should_reexport(name, obj_module_name, name_is_alias=False): + self.import_tracker.reexport(name) + + self.set_defined_names({name for name, obj in all_items if not inspect.ismodule(obj)}) + + if self.resort_members: + functions: list[str] = [] + types: list[str] = [] + variables: list[str] = [] + else: + output: list[str] = [] + functions = types = variables = output + + for name, obj in items: + if self.is_function(obj): + self.generate_function_stub(name, obj, output=functions) + elif inspect.isclass(obj): + self.generate_class_stub(name, obj, output=types) + else: + self.generate_variable_stub(name, obj, output=variables) + + self._output = [] + + if self.resort_members: + for line in variables: + self._output.append(line + "\n") + for line in types: + if line.startswith("class") and self._output and self._output[-1]: + self._output.append("\n") + self._output.append(line + "\n") + if self._output and functions: + self._output.append("\n") + for line in functions: + self._output.append(line + "\n") + else: + for i, line in enumerate(output): + if ( + self._output + and line.startswith("class") + and ( + not self._output[-1].startswith("class") + or (len(output) > i + 1 and output[i + 1].startswith(" ")) + ) + ) or ( + self._output + and self._output[-1].startswith("def") + and not line.startswith("def") + ): + self._output.append("\n") + self._output.append(line + "\n") + self.check_undefined_names() + + def is_skipped_attribute(self, attr: str) -> bool: + return ( + attr + in ( + "__class__", + "__getattribute__", + "__str__", + "__repr__", + "__doc__", + "__dict__", + "__module__", + "__weakref__", + "__annotations__", + "__firstlineno__", + "__static_attributes__", + "__annotate__", + ) + or attr in self.IGNORED_DUNDERS + or is_pybind_skipped_attribute(attr) # For pickling + or keyword.iskeyword(attr) + ) + + def get_members(self, obj: object) -> list[tuple[str, Any]]: + obj_dict: Mapping[str, Any] = getattr(obj, "__dict__") # noqa: B009 + results = [] + for name in obj_dict: + if self.is_skipped_attribute(name): + continue + # Try to get the value via getattr + try: + value = getattr(obj, name) + except AttributeError: + continue + else: + results.append((name, value)) + return results + + def get_type_annotation(self, obj: object) -> str: + """ + Given an instance, return a string representation of its type that is valid + to use as a type annotation. + """ + if obj is None or obj is type(None): + return "None" + elif inspect.isclass(obj): + return f"type[{self.get_type_fullname(obj)}]" + elif isinstance(obj, FunctionType): + return self.add_name("typing.Callable") + elif isinstance(obj, ModuleType): + return self.add_name("types.ModuleType", require=False) + else: + return self.get_type_fullname(type(obj)) + + def is_function(self, obj: object) -> bool: + if self.is_c_module: + return inspect.isbuiltin(obj) + else: + return inspect.isfunction(obj) + + def is_method(self, class_info: ClassInfo, name: str, obj: object) -> bool: + if self.is_c_module: + return inspect.ismethoddescriptor(obj) or type(obj) in ( + type(str.index), + type(str.__add__), + type(str.__new__), + ) + else: + # this is valid because it is only called on members of a class + return inspect.isfunction(obj) + + def is_classmethod(self, class_info: ClassInfo, name: str, obj: object) -> bool: + if self.is_c_module: + return inspect.isbuiltin(obj) or type(obj).__name__ in ( + "classmethod", + "classmethod_descriptor", + ) + else: + return inspect.ismethod(obj) + + def is_staticmethod(self, class_info: ClassInfo | None, name: str, obj: object) -> bool: + if class_info is None: + return False + elif self.is_c_module: + raw_lookup: Mapping[str, Any] = getattr(class_info.cls, "__dict__") # noqa: B009 + raw_value = raw_lookup.get(name, obj) + return isinstance(raw_value, staticmethod) + else: + return isinstance(inspect.getattr_static(class_info.cls, name), staticmethod) + + @staticmethod + def is_abstract_method(obj: object) -> bool: + return getattr(obj, "__abstractmethod__", False) + + @staticmethod + def is_property(class_info: ClassInfo, name: str, obj: object) -> bool: + return inspect.isdatadescriptor(obj) or hasattr(obj, "fget") + + @staticmethod + def is_property_readonly(prop: Any) -> bool: + return hasattr(prop, "fset") and prop.fset is None + + def is_static_property(self, obj: object) -> bool: + """For c-modules, whether the property behaves like an attribute""" + if self.is_c_module: + # StaticProperty is from boost-python + return type(obj).__name__ in ("pybind11_static_property", "StaticProperty") + else: + return False + + def process_inferred_sigs(self, inferred: list[FunctionSig]) -> None: + for i, sig in enumerate(inferred): + for arg in sig.args: + if arg.type is not None: + arg.type = self.strip_or_import(arg.type) + if sig.ret_type is not None: + inferred[i] = sig._replace(ret_type=self.strip_or_import(sig.ret_type)) + + def generate_function_stub( + self, name: str, obj: object, *, output: list[str], class_info: ClassInfo | None = None + ) -> None: + """Generate stub for a single function or method. + + The result (always a single line) will be appended to 'output'. + If necessary, any required names will be added to 'imports'. + The 'class_name' is used to find signature of __init__ or __new__ in + 'class_sigs'. + """ + docstring: Any = getattr(obj, "__doc__", None) + if not isinstance(docstring, str): + docstring = None + + ctx = FunctionContext( + self.module_name, + name, + docstring=docstring, + is_abstract=self.is_abstract_method(obj), + class_info=class_info, + ) + if self.is_private_name(name, ctx.fullname) or self.is_not_in_all(name): + return + + self.record_name(ctx.name) + default_sig = self.get_default_function_sig(obj, ctx) + inferred = self.get_signatures(default_sig, self.sig_generators, ctx) + self.process_inferred_sigs(inferred) + + decorators = [] + if len(inferred) > 1: + decorators.append("@{}".format(self.add_name("typing.overload"))) + + if ctx.is_abstract: + decorators.append("@{}".format(self.add_name("abc.abstractmethod"))) + + if class_info is not None: + if self.is_staticmethod(class_info, name, obj): + decorators.append("@staticmethod") + else: + for sig in inferred: + if not sig.args or sig.args[0].name not in ("self", "cls"): + sig.args.insert(0, ArgSig(name=class_info.self_var)) + # a sig generator indicates @classmethod by specifying the cls arg. + if inferred[0].args and inferred[0].args[0].name == "cls": + decorators.append("@classmethod") + + docstring = self._indent_docstring(ctx.docstring) if ctx.docstring else None + output.extend(self.format_func_def(inferred, decorators=decorators, docstring=docstring)) + self._fix_iter(ctx, inferred, output) + + def _indent_docstring(self, docstring: str) -> str: + """Fix indentation of docstring extracted from pybind11 or other binding generators.""" + lines = docstring.splitlines(keepends=True) + indent = self._indent + " " + if len(lines) > 1: + if not all(line.startswith(indent) or not line.strip() for line in lines): + # if the docstring is not indented, then indent all but the first line + for i, line in enumerate(lines[1:]): + if line.strip(): + lines[i + 1] = indent + line + # if there's a trailing newline, add a final line to visually indent the quoted docstring + if lines[-1].endswith("\n"): + if len(lines) > 1: + lines.append(indent) + else: + lines[-1] = lines[-1][:-1] + return "".join(lines) + + def _fix_iter( + self, ctx: FunctionContext, inferred: list[FunctionSig], output: list[str] + ) -> None: + """Ensure that objects which implement old-style iteration via __getitem__ + are considered iterable. + """ + if ( + ctx.class_info + and ctx.class_info.cls is not None + and ctx.name == "__getitem__" + and "__iter__" not in ctx.class_info.cls.__dict__ + ): + item_type: str | None = None + for sig in inferred: + if sig.args and sig.args[-1].type == "int": + item_type = sig.ret_type + break + if item_type is None: + return + obj = CFunctionStub( + "__iter__", f"def __iter__(self) -> typing.Iterator[{item_type}]\n" + ) + self.generate_function_stub("__iter__", obj, output=output, class_info=ctx.class_info) + + def generate_property_stub( + self, + name: str, + raw_obj: object, + obj: object, + static_properties: list[str], + rw_properties: list[str], + ro_properties: list[str], + class_info: ClassInfo | None = None, + ) -> None: + """Generate property stub using introspection of 'obj'. + + Try to infer type from docstring, append resulting lines to 'output'. + + raw_obj : object before evaluation of descriptor (if any) + obj : object after evaluation of descriptor + """ + + docstring = getattr(raw_obj, "__doc__", None) + fget = getattr(raw_obj, "fget", None) + if fget: + alt_docstr = getattr(fget, "__doc__", None) + if alt_docstr and docstring: + docstring += "\n" + alt_docstr + elif alt_docstr: + docstring = alt_docstr + + ctx = FunctionContext( + self.module_name, name, docstring=docstring, is_abstract=False, class_info=class_info + ) + + if self.is_private_name(name, ctx.fullname) or self.is_not_in_all(name): + return + + self.record_name(ctx.name) + static = self.is_static_property(raw_obj) + readonly = self.is_property_readonly(raw_obj) + if static: + ret_type: str | None = self.strip_or_import(self.get_type_annotation(obj)) + else: + default_sig = self.get_default_function_sig(raw_obj, ctx) + ret_type = default_sig.ret_type + + inferred_type = self.get_property_type(ret_type, self.sig_generators, ctx) + if inferred_type is not None: + inferred_type = self.strip_or_import(inferred_type) + + if static: + classvar = self.add_name("typing.ClassVar") + trailing_comment = " # read-only" if readonly else "" + if inferred_type is None: + inferred_type = self.add_name("_typeshed.Incomplete") + + static_properties.append( + f"{self._indent}{name}: {classvar}[{inferred_type}] = ...{trailing_comment}" + ) + else: # regular property + if readonly: + docstring = self._indent_docstring(ctx.docstring) if ctx.docstring else None + ro_properties.append(f"{self._indent}@property") + sig = FunctionSig(name, [ArgSig("self")], inferred_type, docstring=docstring) + ro_properties.append( + sig.format_sig( + indent=self._indent, include_docstrings=self._include_docstrings + ) + ) + else: + if inferred_type is None: + inferred_type = self.add_name("_typeshed.Incomplete") + + rw_properties.append(f"{self._indent}{name}: {inferred_type}") + + def get_type_fullname(self, typ: type) -> str: + """Given a type, return a string representation""" + if typ is Any: + return "Any" + typename = getattr(typ, "__qualname__", typ.__name__) + module_name = self.get_obj_module(typ) + if module_name is None: + # This should not normally happen, but some types may resist our + # introspection attempts too hard. See + # https://github.com/python/mypy/issues/19031 + return "_typeshed.Incomplete" + if module_name != "builtins": + typename = f"{module_name}.{typename}" + return typename + + def get_base_types(self, obj: type) -> list[str]: + all_bases = type.mro(obj) + if all_bases[-1] is object: + # TODO: Is this always object? + del all_bases[-1] + # remove pybind11_object. All classes generated by pybind11 have pybind11_object in their MRO, + # which only overrides a few functions in object type + if all_bases and all_bases[-1].__name__ == "pybind11_object": + del all_bases[-1] + # remove the class itself + all_bases = all_bases[1:] + # Remove base classes of other bases as redundant. + bases: list[type] = [] + for base in all_bases: + if not any(issubclass(b, base) for b in bases): + bases.append(base) + return [self.strip_or_import(self.get_type_fullname(base)) for base in bases] + + def generate_class_stub( + self, class_name: str, cls: type, output: list[str], parent_class: ClassInfo | None = None + ) -> None: + """Generate stub for a single class using runtime introspection. + + The result lines will be appended to 'output'. If necessary, any + required names will be added to 'imports'. + """ + raw_lookup: Mapping[str, Any] = getattr(cls, "__dict__") # noqa: B009 + items = self.get_members(cls) + if self.resort_members: + items = sorted(items, key=lambda x: method_name_sort_key(x[0])) + names = {x[0] for x in items} + methods: list[str] = [] + types: list[str] = [] + static_properties: list[str] = [] + rw_properties: list[str] = [] + ro_properties: list[str] = [] + attrs: list[tuple[str, Any]] = [] + + self.record_name(class_name) + self.indent() + + class_info = ClassInfo( + class_name, "", getattr(cls, "__doc__", None), cls, parent=parent_class + ) + + for attr, value in items: + # use unevaluated descriptors when dealing with property inspection + raw_value = raw_lookup.get(attr, value) + if self.is_method(class_info, attr, value) or self.is_classmethod( + class_info, attr, value + ): + if attr == "__new__": + # TODO: We should support __new__. + if "__init__" in names: + # Avoid duplicate functions if both are present. + # But is there any case where .__new__() has a + # better signature than __init__() ? + continue + attr = "__init__" + # FIXME: make this nicer + if self.is_staticmethod(class_info, attr, value): + class_info.self_var = "" + elif self.is_classmethod(class_info, attr, value): + class_info.self_var = "cls" + else: + class_info.self_var = "self" + self.generate_function_stub(attr, value, output=methods, class_info=class_info) + elif self.is_property(class_info, attr, raw_value): + self.generate_property_stub( + attr, + raw_value, + value, + static_properties, + rw_properties, + ro_properties, + class_info, + ) + elif inspect.isclass(value) and self.is_defined_in_module(value): + self.generate_class_stub(attr, value, types, parent_class=class_info) + else: + attrs.append((attr, value)) + + for attr, value in attrs: + if attr == "__hash__" and value is None: + # special case for __hash__ + continue + prop_type_name = self.strip_or_import(self.get_type_annotation(value)) + classvar = self.add_name("typing.ClassVar") + static_properties.append(f"{self._indent}{attr}: {classvar}[{prop_type_name}] = ...") + + self.dedent() + + bases = self.get_base_types(cls) + if bases: + bases_str = "(%s)" % ", ".join(bases) + else: + bases_str = "" + + if class_info.docstring and self._include_docstrings: + doc = quote_docstring(self._indent_docstring(class_info.docstring)) + doc = f" {self._indent}{doc}" + docstring = doc.splitlines(keepends=False) + else: + docstring = [] + + if docstring or types or static_properties or rw_properties or methods or ro_properties: + output.append(f"{self._indent}class {class_name}{bases_str}:") + output.extend(docstring) + for line in types: + if ( + output + and output[-1] + and not output[-1].strip().startswith("class") + and line.strip().startswith("class") + ): + output.append("") + output.append(line) + output.extend(static_properties) + output.extend(rw_properties) + output.extend(methods) + output.extend(ro_properties) + else: + output.append(f"{self._indent}class {class_name}{bases_str}: ...") + + def generate_variable_stub(self, name: str, obj: object, output: list[str]) -> None: + """Generate stub for a single variable using runtime introspection. + + The result lines will be appended to 'output'. If necessary, any + required names will be added to 'imports'. + """ + if self.is_private_name(name, f"{self.module_name}.{name}") or self.is_not_in_all(name): + return + self.record_name(name) + type_str = self.strip_or_import(self.get_type_annotation(obj)) + output.append(f"{name}: {type_str}") + + +def method_name_sort_key(name: str) -> tuple[int, str]: + """Sort methods in classes in a typical order. + + I.e.: constructor, normal methods, special methods. + """ + if name in ("__new__", "__init__"): + return 0, name + if name.startswith("__") and name.endswith("__"): + return 2, name + return 1, name + + +def is_pybind_skipped_attribute(attr: str) -> bool: + return attr.startswith("__pybind11_module_local_") + + +def infer_c_method_args( + name: str, self_var: str = "self", arg_names: list[str] | None = None +) -> list[ArgSig]: + args: list[ArgSig] | None = None + if name.startswith("__") and name.endswith("__"): + name = name[2:-2] + if name in ( + "hash", + "iter", + "next", + "sizeof", + "copy", + "deepcopy", + "reduce", + "getinitargs", + "int", + "float", + "trunc", + "complex", + "bool", + "abs", + "bytes", + "dir", + "len", + "reversed", + "round", + "index", + "enter", + ): + args = [] + elif name == "getitem": + args = [ArgSig(name="index")] + elif name == "setitem": + args = [ArgSig(name="index"), ArgSig(name="object")] + elif name in ("delattr", "getattr"): + args = [ArgSig(name="name")] + elif name == "setattr": + args = [ArgSig(name="name"), ArgSig(name="value")] + elif name == "getstate": + args = [] + elif name == "setstate": + args = [ArgSig(name="state")] + elif name in ("eq", "ne", "lt", "le", "gt", "ge"): + args = [ArgSig(name="other", type="object")] + elif name in ( + "add", + "radd", + "sub", + "rsub", + "mul", + "rmul", + "mod", + "rmod", + "floordiv", + "rfloordiv", + "truediv", + "rtruediv", + "divmod", + "rdivmod", + "pow", + "rpow", + "xor", + "rxor", + "or", + "ror", + "and", + "rand", + "lshift", + "rlshift", + "rshift", + "rrshift", + "contains", + "delitem", + "iadd", + "iand", + "ifloordiv", + "ilshift", + "imod", + "imul", + "ior", + "ipow", + "irshift", + "isub", + "itruediv", + "ixor", + ): + args = [ArgSig(name="other")] + elif name in ("neg", "pos", "invert"): + args = [] + elif name == "get": + args = [ArgSig(name="instance"), ArgSig(name="owner")] + elif name == "set": + args = [ArgSig(name="instance"), ArgSig(name="value")] + elif name == "reduce_ex": + args = [ArgSig(name="protocol")] + elif name == "exit": + args = [ + ArgSig(name="type", type="type[BaseException] | None"), + ArgSig(name="value", type="BaseException | None"), + ArgSig(name="traceback", type="types.TracebackType | None"), + ] + if args is None: + args = infer_method_arg_types(name, self_var, arg_names) + else: + args = [ArgSig(name=self_var)] + args + if args is None: + args = [ArgSig(name="*args"), ArgSig(name="**kwargs")] + return args diff --git a/micromamba_root/Lib/site-packages/mypy/stubinfo.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/stubinfo.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..62984610ce86457b3688b87db68584237dd38cbc Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/stubinfo.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/stubinfo.py b/micromamba_root/Lib/site-packages/mypy/stubinfo.py new file mode 100644 index 0000000000000000000000000000000000000000..5c8423f1c4e3b6cbf7612967d580f17958bfa8bc --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/stubinfo.py @@ -0,0 +1,328 @@ +from __future__ import annotations + + +def is_module_from_legacy_bundled_package(module: str) -> bool: + top_level = module.split(".", 1)[0] + return top_level in legacy_bundled_packages + + +def stub_distribution_name(module: str) -> str | None: + top_level = module.split(".", 1)[0] + + dist = legacy_bundled_packages.get(top_level) + if dist: + return dist + dist = non_bundled_packages_flat.get(top_level) + if dist: + return dist + + if top_level in non_bundled_packages_namespace: + namespace = non_bundled_packages_namespace[top_level] + components = module.split(".") + for i in range(len(components), 0, -1): + module = ".".join(components[:i]) + dist = namespace.get(module) + if dist: + return dist + + return None + + +# Stubs for these third-party packages used to be shipped with mypy. +# +# Map package name to PyPI stub distribution name. +legacy_bundled_packages: dict[str, str] = { + "aiofiles": "types-aiofiles", + "bleach": "types-bleach", + "cachetools": "types-cachetools", + "click_spinner": "types-click-spinner", + "croniter": "types-croniter", + "dateparser": "types-dateparser", + "dateutil": "types-python-dateutil", + "decorator": "types-decorator", + "deprecated": "types-Deprecated", + "docutils": "types-docutils", + "first": "types-first", + "markdown": "types-Markdown", + "mock": "types-mock", + "paramiko": "types-paramiko", + "polib": "types-polib", + "pycurl": "types-pycurl", + "pymysql": "types-PyMySQL", + "pyrfc3339": "types-pyRFC3339", + "pytz": "types-pytz", + "requests": "types-requests", + "retry": "types-retry", + "simplejson": "types-simplejson", + "singledispatch": "types-singledispatch", + "six": "types-six", + "tabulate": "types-tabulate", + "toml": "types-toml", + "ujson": "types-ujson", + "waitress": "types-waitress", + "yaml": "types-PyYAML", +} + +# Map package name to PyPI stub distribution name from typeshed. +# Stubs for these packages were never bundled with mypy. Don't +# include packages that have a release that includes PEP 561 type +# information. +# +# Note that these packages are omitted for now: +# pika: typeshed's stubs are on PyPI as types-pika-ts. +# types-pika already exists on PyPI, and is more complete in many ways, +# but is a non-typeshed stubs package. +non_bundled_packages_flat: dict[str, str] = { + "_cffi_backend": "types-cffi", + "_jsonnet": "types-jsonnet", + "_win32typing": "types-pywin32", + "antlr4": "types-antlr4-python3-runtime", + "assertpy": "types-assertpy", + "atheris": "types-atheris", + "auth0": "types-auth0-python", + "authlib": "types-Authlib", + "aws_xray_sdk": "types-aws-xray-sdk", + "binaryornot": "types-binaryornot", + "boltons": "types-boltons", + "braintree": "types-braintree", + "bugbear": "types-flake8-bugbear", + "capturer": "types-capturer", + "cffi": "types-cffi", + "channels": "types-channels", + "chevron": "types-chevron", + "click_default_group": "types-click-default-group", + "click_log": "types-click-log", + "click_shell": "types-click-shell", + "click_web": "types-click-web", + "colorama": "types-colorama", + "colorful": "types-colorful", + "commctrl": "types-pywin32", + "consolemenu": "types-console-menu", + "convertdate": "types-convertdate", + "cronlog": "types-python-crontab", + "crontab": "types-python-crontab", + "crontabs": "types-python-crontab", + "dateparser_data": "types-dateparser", + "dde": "types-pywin32", + "defusedxml": "types-defusedxml", + "dirhash": "types-dirhash", + "django_filters": "types-django-filter", + "docker": "types-docker", + "dockerfile_parse": "types-dockerfile-parse", + "editdistance": "types-editdistance", + "entrypoints": "types-entrypoints", + "ephem": "types-ephem", + "et_xmlfile": "types-et_xmlfile", + "fanstatic": "types-fanstatic", + "farmhash": "types-pyfarmhash", + "flake8_builtins": "types-flake8-builtins", + "flake8_docstrings": "types-flake8-docstrings", + "flake8_rst_docstrings": "types-flake8-rst-docstrings", + "flake8_simplify": "types-flake8-simplify", + "flake8_typing_imports": "types-flake8-typing-imports", + "flake8": "types-flake8", + "flask_cors": "types-Flask-Cors", + "flask_migrate": "types-Flask-Migrate", + "flask_socketio": "types-Flask-SocketIO", + "fpdf": "types-fpdf2", + "gdb": "types-gdb", + "geopandas": "types-geopandas", + "gevent": "types-gevent", + "greenlet": "types-greenlet", + "grpc_channelz": "types-grpcio-channelz", + "grpc_health": "types-grpcio-health-checking", + "grpc_reflection": "types-grpcio-reflection", + "grpc_status": "types-grpcio-status", + "grpc": "types-grpcio", + "gunicorn": "types-gunicorn", + "hdbcli": "types-hdbcli", + "hnswlib": "types-hnswlib", + "html5lib": "types-html5lib", + "httplib2": "types-httplib2", + "hvac": "types-hvac", + "ibm_db": "types-ibm-db", + "icalendar": "types-icalendar", + "import_export": "types-django-import-export", + "inifile": "types-inifile", + "isapi": "types-pywin32", + "jack": "types-JACK-Client", + "jenkins": "types-python-jenkins", + "Jetson": "types-Jetson.GPIO", + "jks": "types-pyjks", + "jmespath": "types-jmespath", + "jose": "types-python-jose", + "jsonschema": "types-jsonschema", + "jwcrypto": "types-jwcrypto", + "keyboard": "types-keyboard", + "ldap3": "types-ldap3", + "lunardate": "types-lunardate", + "lupa": "types-lupa", + "lzstring": "types-lzstring", + "m3u8": "types-m3u8", + "management": "types-django-import-export", + "mmapfile": "types-pywin32", + "mmsystem": "types-pywin32", + "mypy_extensions": "types-mypy-extensions", + "MySQLdb": "types-mysqlclient", + "nanoid": "types-nanoid", + "nanoleafapi": "types-nanoleafapi", + "netaddr": "types-netaddr", + "netifaces": "types-netifaces", + "networkx": "types-networkx", + "nmap": "types-python-nmap", + "ntsecuritycon": "types-pywin32", + "oauthlib": "types-oauthlib", + "objgraph": "types-objgraph", + "odbc": "types-pywin32", + "olefile": "types-olefile", + "openpyxl": "types-openpyxl", + "opentracing": "types-opentracing", + "parsimonious": "types-parsimonious", + "passlib": "types-passlib", + "passpy": "types-passpy", + "peewee": "types-peewee", + "pep8ext_naming": "types-pep8-naming", + "perfmon": "types-pywin32", + "pexpect": "types-pexpect", + "playhouse": "types-peewee", + "pony": "types-pony", + "portpicker": "types-portpicker", + "psutil": "types-psutil", + "psycopg2": "types-psycopg2", + "punq": "types-punq", + "pyasn1": "types-pyasn1", + "pyaudio": "types-pyaudio", + "pyautogui": "types-PyAutoGUI", + "pycocotools": "types-pycocotools", + "pyflakes": "types-pyflakes", + "pygments": "types-Pygments", + "pyi_splash": "types-pyinstaller", + "PyInstaller": "types-pyinstaller", + "pyluach": "types-pyluach", + "pymeeus": "types-PyMeeus", + "pynput": "types-pynput", + "pyperclip": "types-pyperclip", + "pyscreeze": "types-PyScreeze", + "pysftp": "types-pysftp", + "pytest_lazyfixture": "types-pytest-lazy-fixture", + "python_http_client": "types-python-http-client", + "pythoncom": "types-pywin32", + "pythonwin": "types-pywin32", + "pywintypes": "types-pywin32", + "qrbill": "types-qrbill", + "qrcode": "types-qrcode", + "ratelimit": "types-ratelimit", + "regex": "types-regex", + "regutil": "types-pywin32", + "reportlab": "types-reportlab", + "requests_oauthlib": "types-requests-oauthlib", + "rfc3339_validator": "types-rfc3339-validator", + "RPi": "types-RPi.GPIO", + "s2clientprotocol": "types-s2clientprotocol", + "sass": "types-libsass", + "sassutils": "types-libsass", + "seaborn": "types-seaborn", + "send2trash": "types-Send2Trash", + "serial": "types-pyserial", + "servicemanager": "types-pywin32", + "setuptools": "types-setuptools", + "shapely": "types-shapely", + "simple_websocket": "types-simple-websocket", + "slumber": "types-slumber", + "socks": "types-PySocks", + "sockshandler": "types-PySocks", + "sspicon": "types-pywin32", + "str2bool": "types-str2bool", + "tensorflow": "types-tensorflow", + "tgcrypto": "types-TgCrypto", + "timer": "types-pywin32", + "toposort": "types-toposort", + "tqdm": "types-tqdm", + "translationstring": "types-translationstring", + "ttkthemes": "types-ttkthemes", + "tzdata": "types-tzdata", + "unidiff": "types-unidiff", + "untangle": "types-untangle", + "usersettings": "types-usersettings", + "uwsgi": "types-uWSGI", + "uwsgidecorators": "types-uWSGI", + "vobject": "types-vobject", + "watchpoints": "types-watchpoints", + "webencodings": "types-webencodings", + "webob": "types-WebOb", + "whatthepatch": "types-whatthepatch", + "win2kras": "types-pywin32", + "win32": "types-pywin32", + "win32api": "types-pywin32", + "win32clipboard": "types-pywin32", + "win32com": "types-pywin32", + "win32comext": "types-pywin32", + "win32con": "types-pywin32", + "win32console": "types-pywin32", + "win32cred": "types-pywin32", + "win32crypt": "types-pywin32", + "win32cryptcon": "types-pywin32", + "win32event": "types-pywin32", + "win32evtlog": "types-pywin32", + "win32evtlogutil": "types-pywin32", + "win32file": "types-pywin32", + "win32gui_struct": "types-pywin32", + "win32gui": "types-pywin32", + "win32help": "types-pywin32", + "win32inet": "types-pywin32", + "win32inetcon": "types-pywin32", + "win32job": "types-pywin32", + "win32lz": "types-pywin32", + "win32net": "types-pywin32", + "win32netcon": "types-pywin32", + "win32pdh": "types-pywin32", + "win32pdhquery": "types-pywin32", + "win32pipe": "types-pywin32", + "win32print": "types-pywin32", + "win32process": "types-pywin32", + "win32profile": "types-pywin32", + "win32ras": "types-pywin32", + "win32security": "types-pywin32", + "win32service": "types-pywin32", + "win32serviceutil": "types-pywin32", + "win32timezone": "types-pywin32", + "win32trace": "types-pywin32", + "win32transaction": "types-pywin32", + "win32ts": "types-pywin32", + "win32ui": "types-pywin32", + "win32uiole": "types-pywin32", + "win32verstamp": "types-pywin32", + "win32wnet": "types-pywin32", + "winerror": "types-pywin32", + "winioctlcon": "types-pywin32", + "winnt": "types-pywin32", + "winperf": "types-pywin32", + "winxpgui": "types-pywin32", + "winxptheme": "types-pywin32", + "workalendar": "types-workalendar", + "wtforms": "types-WTForms", + "wurlitzer": "types-wurlitzer", + "www_authenticate": "types-www-authenticate", + "xdg": "types-pyxdg", + "xdgenvpy": "types-xdgenvpy", + "Xlib": "types-python-xlib", + "xlrd": "types-xlrd", + "xmldiff": "types-xmldiff", + "xmltodict": "types-xmltodict", + "yt_dlp": "types-yt-dlp", + "zstd": "types-zstd", + "zxcvbn": "types-zxcvbn", + # Stub packages that are not from typeshed + # Since these can be installed automatically via --install-types, we have a high trust bar + # for additions here + "pandas": "pandas-stubs", # https://github.com/pandas-dev/pandas-stubs + "lxml": "lxml-stubs", # https://github.com/lxml/lxml-stubs + "scipy": "scipy-stubs", # https://github.com/scipy/scipy-stubs +} + + +non_bundled_packages_namespace: dict[str, dict[str, str]] = { + "backports": {"backports.ssl_match_hostname": "types-backports.ssl_match_hostname"}, + "google": {"google.cloud.ndb": "types-google-cloud-ndb", "google.protobuf": "types-protobuf"}, + "paho": {"paho.mqtt": "types-paho-mqtt"}, +} diff --git a/micromamba_root/Lib/site-packages/mypy/stubtest.py b/micromamba_root/Lib/site-packages/mypy/stubtest.py new file mode 100644 index 0000000000000000000000000000000000000000..4cf0de84d9890f01c10a5ea694385806d7434688 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/stubtest.py @@ -0,0 +1,2590 @@ +"""Tests for stubs. + +Verify that various things in stubs are consistent with how things behave at runtime. + +""" + +from __future__ import annotations + +import argparse +import collections.abc +import copy +import enum +import functools +import importlib +import inspect +import keyword +import os +import pkgutil +import re +import struct +import symtable +import sys +import traceback +import types +import typing +import typing_extensions +import warnings +from collections import defaultdict +from collections.abc import Iterator +from contextlib import redirect_stderr, redirect_stdout +from functools import singledispatch +from pathlib import Path +from typing import Any, Final, Generic, TypeVar, Union, get_origin +from typing_extensions import is_typeddict + +import mypy.build +import mypy.checkexpr +import mypy.erasetype +import mypy.modulefinder +import mypy.nodes +import mypy.state +import mypy.subtypes +import mypy.types +import mypy.version +from mypy import nodes +from mypy.config_parser import parse_config_file +from mypy.evalexpr import UNKNOWN, evaluate_expression +from mypy.maptype import map_instance_to_supertype +from mypy.options import Options +from mypy.util import FancyFormatter, bytes_to_human_readable_repr, is_dunder, plural_s + + +class Missing: + """Marker object for things that are missing (from a stub or the runtime).""" + + def __repr__(self) -> str: + return "MISSING" + + +MISSING: Final = Missing() + +T = TypeVar("T") +MaybeMissing: typing_extensions.TypeAlias = T | Missing + + +class Unrepresentable: + """Marker object for unrepresentable parameter defaults.""" + + def __repr__(self) -> str: + return "" + + +UNREPRESENTABLE: Final = Unrepresentable() + + +_formatter: Final = FancyFormatter(sys.stdout, sys.stderr, False) + + +def _style(message: str, **kwargs: Any) -> str: + """Wrapper around mypy.util for fancy formatting.""" + kwargs.setdefault("color", "none") + return _formatter.style(message, **kwargs) + + +def _truncate(message: str, length: int) -> str: + if len(message) > length: + return message[: length - 3] + "..." + return message + + +class StubtestFailure(Exception): + pass + + +class Error: + def __init__( + self, + object_path: list[str], + message: str, + stub_object: MaybeMissing[nodes.Node], + runtime_object: MaybeMissing[Any], + *, + stub_desc: str | None = None, + runtime_desc: str | None = None, + ) -> None: + """Represents an error found by stubtest. + + :param object_path: Location of the object with the error, + e.g. ``["module", "Class", "method"]`` + :param message: Error message + :param stub_object: The mypy node representing the stub + :param runtime_object: Actual object obtained from the runtime + :param stub_desc: Specialised description for the stub object, should you wish + :param runtime_desc: Specialised description for the runtime object, should you wish + + """ + self.object_path = object_path + self.object_desc = ".".join(object_path) + self.message = message + self.stub_object = stub_object + self.runtime_object = runtime_object + self.stub_desc = stub_desc or str(getattr(stub_object, "type", stub_object)) + + if runtime_desc is None: + runtime_sig = safe_inspect_signature(runtime_object) + if runtime_sig is None: + self.runtime_desc = _truncate(repr(runtime_object), 100) + else: + runtime_is_async = inspect.iscoroutinefunction(runtime_object) + description = describe_runtime_callable(runtime_sig, is_async=runtime_is_async) + self.runtime_desc = _truncate(description, 100) + else: + self.runtime_desc = runtime_desc + + def is_missing_stub(self) -> bool: + """Whether or not the error is for something missing from the stub.""" + return isinstance(self.stub_object, Missing) + + def is_positional_only_related(self) -> bool: + """Whether or not the error is for something being (or not being) positional-only.""" + # TODO: This is hacky, use error codes or something more resilient + return "should be positional" in self.message + + def is_disjoint_base_related(self) -> bool: + """Whether or not the error is related to @disjoint_base.""" + # TODO: This is hacky, use error codes or something more resilient + return "@disjoint_base" in self.message + + def is_private_type_check_only_related(self) -> bool: + """Whether or not the error is related to @type_check_only on private types.""" + # TODO: This is hacky, use error codes or something more resilient + return self.message.endswith('Maybe mark it as "@type_check_only"?') + + def get_description(self, concise: bool = False) -> str: + """Returns a description of the error. + + :param concise: Whether to return a concise, one-line description + + """ + if concise: + return _style(self.object_desc, bold=True) + " " + self.message + + stub_line = None + stub_file = None + if not isinstance(self.stub_object, Missing): + stub_line = self.stub_object.line + stub_node = get_stub(self.object_path[0]) + if stub_node is not None: + stub_file = stub_node.path or None + + stub_loc_str = "" + if stub_file: + stub_loc_str += f" in file {Path(stub_file)}" + if stub_line: + stub_loc_str += f"{':' if stub_file else ' at line '}{stub_line}" + + runtime_line = None + runtime_file = None + if not isinstance(self.runtime_object, Missing): + try: + runtime_line = inspect.getsourcelines(self.runtime_object)[1] + except (OSError, TypeError, SyntaxError): + pass + try: + runtime_file = inspect.getsourcefile(self.runtime_object) + except TypeError: + pass + + runtime_loc_str = "" + if runtime_file: + runtime_loc_str += f" in file {Path(runtime_file)}" + if runtime_line: + runtime_loc_str += f"{':' if runtime_file else ' at line '}{runtime_line}" + + output = [ + _style("error: ", color="red", bold=True), + _style(self.object_desc, bold=True), + " ", + self.message, + "\n", + "Stub:", + _style(stub_loc_str, dim=True), + "\n", + _style(self.stub_desc + "\n", color="blue", dim=True), + "Runtime:", + _style(runtime_loc_str, dim=True), + "\n", + _style(self.runtime_desc + "\n", color="blue", dim=True), + ] + return "".join(output) + + +# ==================== +# Core logic +# ==================== + + +def silent_import_module(module_name: str) -> types.ModuleType: + with open(os.devnull, "w") as devnull: + with warnings.catch_warnings(), redirect_stdout(devnull), redirect_stderr(devnull): + warnings.simplefilter("ignore") + runtime = importlib.import_module(module_name) + # Also run the equivalent of `from module import *` + # This could have the additional effect of loading not-yet-loaded submodules + # mentioned in __all__ + __import__(module_name, fromlist=["*"]) + return runtime + + +def test_module(module_name: str) -> Iterator[Error]: + """Tests a given module's stub against introspecting it at runtime. + + Requires the stub to have been built already, accomplished by a call to ``build_stubs``. + + :param module_name: The module to test + + """ + stub = get_stub(module_name) + if stub is None: + if not is_probably_private(module_name.split(".")[-1]): + runtime_desc = repr(sys.modules[module_name]) if module_name in sys.modules else "N/A" + yield Error( + [module_name], "failed to find stubs", MISSING, None, runtime_desc=runtime_desc + ) + return + + try: + runtime = silent_import_module(module_name) + except KeyboardInterrupt: + raise + except BaseException as e: + note = "" + if isinstance(e, ModuleNotFoundError): + note = " Maybe install the runtime package or alter PYTHONPATH?" + yield Error( + [module_name], f"failed to import.{note} {type(e).__name__}: {e}", stub, MISSING + ) + return + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + try: + yield from verify(stub, runtime, [module_name]) + except Exception as e: + bottom_frame = list(traceback.walk_tb(e.__traceback__))[-1][0] + bottom_module = bottom_frame.f_globals.get("__name__", "") + # Pass on any errors originating from stubtest or mypy + # These can occur expectedly, e.g. StubtestFailure + if bottom_module == "__main__" or bottom_module.split(".")[0] == "mypy": + raise + yield Error( + [module_name], + f"encountered unexpected error, {type(e).__name__}: {e}", + stub, + runtime, + stub_desc="N/A", + runtime_desc=( + "This is most likely the fault of something very dynamic in your library. " + "It's also possible this is a bug in stubtest.\nIf in doubt, please " + "open an issue at https://github.com/python/mypy\n\n" + + traceback.format_exc().strip() + ), + ) + + +@singledispatch +def verify( + stub: MaybeMissing[nodes.Node], runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + """Entry point for comparing a stub to a runtime object. + + We use single dispatch based on the type of ``stub``. + + :param stub: The mypy node representing a part of the stub + :param runtime: The runtime object corresponding to ``stub`` + + """ + yield Error(object_path, "is an unknown mypy node", stub, runtime) + + +def _verify_exported_names( + object_path: list[str], stub: nodes.MypyFile, runtime_all_as_set: set[str] +) -> Iterator[Error]: + # note that this includes the case the stub simply defines `__all__: list[str]` + assert "__all__" in stub.names + public_names_in_stub = {m for m, o in stub.names.items() if o.module_public} + names_in_stub_not_runtime = sorted(public_names_in_stub - runtime_all_as_set) + names_in_runtime_not_stub = sorted(runtime_all_as_set - public_names_in_stub) + if not (names_in_runtime_not_stub or names_in_stub_not_runtime): + return + yield Error( + object_path + ["__all__"], + ( + "names exported from the stub do not correspond to the names exported at runtime. " + "This is probably due to things being missing from the stub or an inaccurate `__all__` in the stub" + ), + # Pass in MISSING instead of the stub and runtime objects, as the line numbers aren't very + # relevant here, and it makes for a prettier error message + # This means this error will be ignored when using `--ignore-missing-stub`, which is + # desirable in at least the `names_in_runtime_not_stub` case + stub_object=MISSING, + runtime_object=MISSING, + stub_desc=(f"Names exported in the stub but not at runtime: {names_in_stub_not_runtime}"), + runtime_desc=( + f"Names exported at runtime but not in the stub: {names_in_runtime_not_stub}" + ), + ) + + +@functools.lru_cache +def _module_symbol_table(runtime: types.ModuleType) -> symtable.SymbolTable | None: + """Retrieve the symbol table for the module (or None on failure). + + 1) Use inspect to retrieve the source code of the module + 2) Use symtable to parse the source (and use what symtable knows for its purposes) + """ + try: + source = inspect.getsource(runtime) + except (OSError, TypeError, SyntaxError): + return None + + try: + return symtable.symtable(source, runtime.__name__, "exec") + except SyntaxError: + return None + + +@verify.register(nodes.MypyFile) +def verify_mypyfile( + stub: nodes.MypyFile, runtime: MaybeMissing[types.ModuleType], object_path: list[str] +) -> Iterator[Error]: + if isinstance(runtime, Missing): + yield Error(object_path, "is not present at runtime", stub, runtime) + return + if not isinstance(runtime, types.ModuleType): + # Can possibly happen: + yield Error(object_path, "is not a module", stub, runtime) # type: ignore[unreachable] + return + + runtime_all_as_set: set[str] | None + + if hasattr(runtime, "__all__"): + runtime_all_as_set = set(runtime.__all__) + if "__all__" in stub.names: + # Only verify the contents of the stub's __all__ + # if the stub actually defines __all__ + yield from _verify_exported_names(object_path, stub, runtime_all_as_set) + else: + yield Error(object_path + ["__all__"], "is not present in stub", MISSING, runtime) + else: + runtime_all_as_set = None + + # Check things in the stub + to_check = {m for m, o in stub.names.items() if not o.module_hidden} + + def _belongs_to_runtime(r: types.ModuleType, attr: str) -> bool: + """Heuristics to determine whether a name originates from another module.""" + obj = getattr(r, attr) + if isinstance(obj, types.ModuleType): + return False + + symbol_table = _module_symbol_table(r) + if symbol_table is not None: + try: + symbol = symbol_table.lookup(attr) + except KeyError: + pass + else: + if symbol.is_imported(): + # symtable says we got this from another module + return False + # But we can't just return True here, because symtable doesn't know about symbols + # that come from `from module import *` + if symbol.is_assigned(): + # symtable knows we assigned this symbol in the module + return True + + # The __module__ attribute is unreliable for anything except functions and classes, + # but it's our best guess at this point + try: + obj_mod = obj.__module__ + except Exception: + pass + else: + if isinstance(obj_mod, str): + return bool(obj_mod == r.__name__) + return True + + runtime_public_contents = ( + runtime_all_as_set + if runtime_all_as_set is not None + else { + m + for m in dir(runtime) + if not is_probably_private(m) + # Filter out objects that originate from other modules (best effort). Note that in the + # absence of __all__, we don't have a way to detect explicit / intentional re-exports + # at runtime + and _belongs_to_runtime(runtime, m) + } + ) + # Check all things declared in module's __all__, falling back to our best guess + to_check.update(runtime_public_contents) + to_check.difference_update(IGNORED_MODULE_DUNDERS) + + for entry in sorted(to_check): + stub_entry = stub.names[entry].node if entry in stub.names else MISSING + if entry in stub.names: + if xref := stub.names[entry].cross_ref: + orig_module = xref.rsplit(".", 1)[0] + elif isinstance(stub_entry, nodes.SymbolNode) and (name := stub_entry.fullname): + orig_module = name.rsplit(".", 1)[0] + else: + orig_module = None + + if orig_module and orig_module != stub.fullname and orig_module in _all_stubs: + # Skip re-exported names whose defining module will be checked separately. + continue + + if isinstance(stub_entry, nodes.MypyFile): + # Don't recursively check exported modules, since that leads to infinite recursion + continue + assert stub_entry is not None + if ( + is_probably_private(entry) + and not hasattr(runtime, entry) + and not isinstance(stub_entry, Missing) + and not _is_decoratable(stub_entry) + ): + # Skip private names that don't exist at runtime and which cannot + # be marked with @type_check_only. + continue + try: + runtime_entry = getattr(runtime, entry, MISSING) + except Exception: + # Catch all exceptions in case the runtime raises an unexpected exception + # from __getattr__ or similar. + continue + yield from verify(stub_entry, runtime_entry, object_path + [entry]) + + +def _is_decoratable(stub: nodes.SymbolNode) -> bool: + if not isinstance(stub, nodes.TypeInfo): + return False + if stub.is_newtype: + return False + if stub.typeddict_type is not None: + return all( + name.isidentifier() and not keyword.iskeyword(name) + for name in stub.typeddict_type.items.keys() + ) + return True + + +def _verify_final( + stub: nodes.TypeInfo, runtime: type[Any], object_path: list[str] +) -> Iterator[Error]: + try: + + class SubClass(runtime): # type: ignore[misc] + pass + + except TypeError: + # Enum classes are implicitly @final + if not stub.is_final and not issubclass(runtime, enum.Enum): + yield Error( + object_path, + "cannot be subclassed at runtime, but isn't marked with @final in the stub", + stub, + runtime, + stub_desc=repr(stub), + ) + except Exception: + # The class probably wants its subclasses to do something special. + # Examples: ctypes.Array, ctypes._SimpleCData + pass + + # Runtime class might be annotated with `@final`: + try: + runtime_final = getattr(runtime, "__final__", False) + except Exception: + runtime_final = False + + if runtime_final and not stub.is_final: + yield Error( + object_path, + "has `__final__` attribute, but isn't marked with @final in the stub", + stub, + runtime, + stub_desc=repr(stub), + ) + + +SIZEOF_PYOBJECT = struct.calcsize("P") + + +def _shape_differs(t1: type[object], t2: type[object]) -> bool: + """Check whether two types differ in shape. + + Mirrors the shape_differs() function in typeobject.c in CPython.""" + if sys.version_info >= (3, 12): + return t1.__basicsize__ != t2.__basicsize__ or t1.__itemsize__ != t2.__itemsize__ + else: + # CPython had more complicated logic before 3.12: + # https://github.com/python/cpython/blob/f3c6f882cddc8dc30320d2e73edf019e201394fc/Objects/typeobject.c#L2224 + # We attempt to mirror it here well enough to support the most common cases. + if t1.__itemsize__ or t2.__itemsize__: + return t1.__basicsize__ != t2.__basicsize__ or t1.__itemsize__ != t2.__itemsize__ + t_size = t1.__basicsize__ + if not t2.__weakrefoffset__ and t1.__weakrefoffset__ + SIZEOF_PYOBJECT == t_size: + t_size -= SIZEOF_PYOBJECT + if not t2.__dictoffset__ and t1.__dictoffset__ + SIZEOF_PYOBJECT == t_size: + t_size -= SIZEOF_PYOBJECT + if not t2.__weakrefoffset__ and t2.__weakrefoffset__ == t_size: + t_size -= SIZEOF_PYOBJECT + return t_size != t2.__basicsize__ + + +def _is_disjoint_base(typ: type[object]) -> bool: + """Return whether a type is a disjoint base at runtime, mirroring CPython's logic in typeobject.c. + + See PEP 800.""" + if typ is object: + return True + base = typ.__base__ + assert base is not None, f"Type {typ} has no base" + return _shape_differs(typ, base) + + +def _verify_disjoint_base( + stub: nodes.TypeInfo, runtime: type[object], object_path: list[str] +) -> Iterator[Error]: + is_disjoint_runtime = _is_disjoint_base(runtime) + # Don't complain about missing @disjoint_base if there are __slots__, because + # in that case we can infer that it's a disjoint base. + if ( + is_disjoint_runtime + and not stub.is_disjoint_base + and not runtime.__dict__.get("__slots__") + and not stub.is_final + and not (stub.is_enum and stub.enum_members) + ): + yield Error( + object_path, + "is a disjoint base at runtime, but isn't marked with @disjoint_base in the stub", + stub, + runtime, + stub_desc=repr(stub), + ) + elif stub.is_disjoint_base: + if not is_disjoint_runtime: + yield Error( + object_path, + "is marked with @disjoint_base in the stub, but isn't a disjoint base at runtime", + stub, + runtime, + stub_desc=repr(stub), + ) + if runtime.__dict__.get("__slots__"): + yield Error( + object_path, + "is marked as @disjoint_base, but also has slots; add __slots__ instead", + stub, + runtime, + stub_desc=repr(stub), + ) + elif stub.is_final: + yield Error( + object_path, + "is marked as @disjoint_base, but also marked as @final; remove @disjoint_base", + stub, + runtime, + stub_desc=repr(stub), + ) + elif stub.is_enum and stub.enum_members: + yield Error( + object_path, + "is marked as @disjoint_base, but is an enum with members, which is implicitly final; " + "remove @disjoint_base", + stub, + runtime, + stub_desc=repr(stub), + ) + + +def _verify_metaclass( + stub: nodes.TypeInfo, runtime: type[Any], object_path: list[str], *, is_runtime_typeddict: bool +) -> Iterator[Error]: + # We exclude protocols, because of how complex their implementation is in different versions of + # python. Enums are also hard, as are runtime TypedDicts; ignoring. + # TODO: check that metaclasses are identical? + if not stub.is_protocol and not stub.is_enum and not is_runtime_typeddict: + runtime_metaclass = type(runtime) + if runtime_metaclass is not type and stub.metaclass_type is None: + # This means that runtime has a custom metaclass, but a stub does not. + yield Error( + object_path, + "is inconsistent, metaclass differs", + stub, + runtime, + stub_desc="N/A", + runtime_desc=f"{runtime_metaclass}", + ) + elif ( + runtime_metaclass is type + and stub.metaclass_type is not None + # We ignore extra `ABCMeta` metaclass on stubs, this might be typing hack. + # We also ignore `builtins.type` metaclass as an implementation detail in mypy. + and not mypy.types.is_named_instance( + stub.metaclass_type, ("abc.ABCMeta", "builtins.type") + ) + ): + # This means that our stub has a metaclass that is not present at runtime. + yield Error( + object_path, + "metaclass mismatch", + stub, + runtime, + stub_desc=f"{stub.metaclass_type.type.fullname}", + runtime_desc="N/A", + ) + + +@verify.register(nodes.TypeInfo) +def verify_typeinfo( + stub: nodes.TypeInfo, + runtime: MaybeMissing[type[Any]], + object_path: list[str], + *, + is_alias_target: bool = False, +) -> Iterator[Error]: + if stub.is_type_check_only and not is_alias_target: + # This type only exists in stubs, we only check that the runtime part + # is missing. Other checks are not required. + if not isinstance(runtime, Missing): + yield Error( + object_path, + 'is marked as "@type_check_only", but also exists at runtime', + stub, + runtime, + stub_desc=repr(stub), + ) + return + + if isinstance(runtime, Missing): + msg = "is not present at runtime" + if is_probably_private(stub.name): + msg += '. Maybe mark it as "@type_check_only"?' + yield Error(object_path, msg, stub, runtime, stub_desc=repr(stub)) + return + if not isinstance(runtime, type): + # Yes, some runtime objects can be not types, no way to tell mypy about that. + yield Error(object_path, "is not a type", stub, runtime, stub_desc=repr(stub)) # type: ignore[unreachable] + return + + yield from _verify_final(stub, runtime, object_path) + yield from _verify_disjoint_base(stub, runtime, object_path) + is_runtime_typeddict = stub.typeddict_type is not None and is_typeddict(runtime) + yield from _verify_metaclass( + stub, runtime, object_path, is_runtime_typeddict=is_runtime_typeddict + ) + + # Check everything already defined on the stub class itself (i.e. not inherited) + # + # Filter out non-identifier names, as these are (hopefully always?) whacky/fictional things + # (like __mypy-replace or __mypy-post_init, etc.) that don't exist at runtime, + # and exist purely for internal mypy reasons + to_check = {name for name in stub.names if name.isidentifier()} + # Check all public things on the runtime class + to_check.update( + m for m in vars(runtime) if not is_probably_private(m) and m not in IGNORABLE_CLASS_DUNDERS + ) + # Special-case the __init__ method for Protocols and the __new__ method for TypedDicts + # + # TODO: On Python <3.11, __init__ methods on Protocol classes + # are silently discarded and replaced. + # However, this is not the case on Python 3.11+. + # Ideally, we'd figure out a good way of validating Protocol __init__ methods on 3.11+. + if stub.is_protocol: + to_check.discard("__init__") + if is_runtime_typeddict: + to_check.discard("__new__") + + for entry in sorted(to_check): + mangled_entry = entry + if entry.startswith("__") and not entry.endswith("__"): + mangled_entry = f"_{stub.name.lstrip('_')}{entry}" + stub_to_verify = next((t.names[entry].node for t in stub.mro if entry in t.names), MISSING) + assert stub_to_verify is not None + try: + try: + runtime_attr = getattr(runtime, mangled_entry) + except AttributeError: + runtime_attr = inspect.getattr_static(runtime, mangled_entry, MISSING) + except Exception: + # Catch all exceptions in case the runtime raises an unexpected exception + # from __getattr__ or similar. + continue + + # If it came from the metaclass, consider the runtime_attr to be MISSING + # for a more accurate message + if ( + runtime_attr is not MISSING + and type(runtime) is not runtime + and getattr(runtime_attr, "__objclass__", None) is type(runtime) + ): + runtime_attr = MISSING + + # __setattr__ and __delattr__ on object are a special case, + # so if we only have these methods inherited from there, pretend that + # we don't have them. See python/typeshed#7385. + if ( + entry in ("__setattr__", "__delattr__") + and runtime_attr is not MISSING + and runtime is not object + and getattr(runtime_attr, "__objclass__", None) is object + ): + runtime_attr = MISSING + + # Do not error for an object missing from the stub + # If the runtime object is a types.WrapperDescriptorType object + # and has a non-special dunder name. + # The vast majority of these are false positives. + if not ( + isinstance(stub_to_verify, Missing) + and isinstance(runtime_attr, types.WrapperDescriptorType) + and is_dunder(mangled_entry, exclude_special=True) + ): + yield from verify(stub_to_verify, runtime_attr, object_path + [entry]) + + +def _static_lookup_runtime(object_path: list[str]) -> MaybeMissing[Any]: + static_runtime = importlib.import_module(object_path[0]) + for entry in object_path[1:]: + try: + static_runtime = inspect.getattr_static(static_runtime, entry) + except AttributeError: + # This can happen with mangled names, ignore for now. + # TODO: pass more information about ancestors of nodes/objects to verify, so we don't + # have to do this hacky lookup. Would be useful in several places. + return MISSING + return static_runtime + + +def _verify_static_class_methods( + stub: nodes.FuncBase, runtime: Any, static_runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[str]: + if stub.name in ("__new__", "__init_subclass__", "__class_getitem__"): + # Special cased by Python, so don't bother checking + return + if inspect.isbuiltin(runtime): + # The isinstance checks don't work reliably for builtins, e.g. datetime.datetime.now, so do + # something a little hacky that seems to work well + probably_class_method = isinstance(getattr(runtime, "__self__", None), type) + if probably_class_method and not stub.is_class: + yield "runtime is a classmethod but stub is not" + if not probably_class_method and stub.is_class: + yield "stub is a classmethod but runtime is not" + return + + if static_runtime is MISSING: + return + + if isinstance(static_runtime, classmethod) and not stub.is_class: + yield "runtime is a classmethod but stub is not" + if not isinstance(static_runtime, classmethod) and stub.is_class: + yield "stub is a classmethod but runtime is not" + if isinstance(static_runtime, staticmethod) and not stub.is_static: + yield "runtime is a staticmethod but stub is not" + if not isinstance(static_runtime, staticmethod) and stub.is_static: + yield "stub is a staticmethod but runtime is not" + + +def _verify_arg_name( + stub_arg: nodes.Argument, runtime_arg: inspect.Parameter, function_name: str +) -> Iterator[str]: + """Checks whether argument names match.""" + # Ignore exact names for most dunder methods + if is_dunder(function_name, exclude_special=True): + return + + if ( + stub_arg.variable.name == runtime_arg.name + or stub_arg.variable.name.removeprefix("__") == runtime_arg.name + ): + return + + nonspecific_names = {"object", "args"} + if runtime_arg.name in nonspecific_names: + return + + def names_approx_match(a: str, b: str) -> bool: + a = a.strip("_") + b = b.strip("_") + return a.startswith(b) or b.startswith(a) or len(a) == 1 or len(b) == 1 + + # Be more permissive about names matching for positional-only arguments + if runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY and names_approx_match( + stub_arg.variable.name, runtime_arg.name + ): + return + # This comes up with namedtuples, so ignore + if stub_arg.variable.name == "_self": + return + yield ( + f'stub parameter "{stub_arg.variable.name}" ' + f'differs from runtime parameter "{runtime_arg.name}"' + ) + + +def _verify_arg_default_value( + stub_arg: nodes.Argument, runtime_arg: inspect.Parameter +) -> Iterator[str]: + """Checks whether argument default values are compatible.""" + if runtime_arg.default is not inspect.Parameter.empty: + if stub_arg.kind.is_required(): + yield ( + f'runtime parameter "{runtime_arg.name}" ' + "has a default value but stub parameter does not" + ) + else: + type_context = stub_arg.variable.type + runtime_type = get_mypy_type_of_runtime_value( + runtime_arg.default, type_context=type_context + ) + + # Fallback to the type annotation type if var type is missing. The type annotation + # is an UnboundType, but I don't know enough to know what the pros and cons here are. + # UnboundTypes have ugly question marks following them, so default to var type. + # Note we do this same fallback when constructing signatures in from_overloadedfuncdef + stub_type = stub_arg.variable.type or stub_arg.type_annotation + if isinstance(stub_type, mypy.types.TypeVarType): + stub_type = stub_type.upper_bound + if ( + runtime_type is not None + and stub_type is not None + # Avoid false positives for marker objects + and type(runtime_arg.default) is not object + # And ellipsis + and runtime_arg.default is not ... + and not is_subtype_helper(runtime_type, stub_type) + ): + yield ( + f'runtime parameter "{runtime_arg.name}" ' + f"has a default value of type {runtime_type}, " + f"which is incompatible with stub parameter type {stub_type}" + ) + if stub_arg.initializer is not None: + stub_default = evaluate_expression(stub_arg.initializer) + if ( + stub_default is not UNKNOWN + and stub_default is not ... + and runtime_arg.default is not UNREPRESENTABLE + ): + defaults_match = True + # We want the types to match exactly, e.g. in case the stub has + # True and the runtime has 1 (or vice versa). + if type(stub_default) is not type(runtime_arg.default): + defaults_match = False + else: + try: + defaults_match = bool(stub_default == runtime_arg.default) + except Exception: + # Exception can be raised in bool dunder method (e.g. numpy arrays) + # At this point, consider the default to be different, it is probably + # too complex to put in a stub anyway. + defaults_match = False + if not defaults_match: + yield ( + f'runtime parameter "{runtime_arg.name}" ' + f"has a default value of {runtime_arg.default!r}, " + f"which is different from stub parameter default {stub_default!r}" + ) + else: + if stub_arg.kind.is_optional(): + yield ( + f'stub parameter "{stub_arg.variable.name}" has a default value ' + f"but runtime parameter does not" + ) + + +def maybe_strip_cls(name: str, args: list[nodes.Argument]) -> list[nodes.Argument]: + if args and name in ("__init_subclass__", "__class_getitem__"): + # These are implicitly classmethods. If the stub chooses not to have @classmethod, we + # should remove the cls argument + if args[0].variable.name == "cls": + return args[1:] + return args + + +class Signature(Generic[T]): + def __init__(self) -> None: + self.pos: list[T] = [] + self.kwonly: dict[str, T] = {} + self.varpos: T | None = None + self.varkw: T | None = None + + def __str__(self) -> str: + def get_name(arg: Any) -> str: + if isinstance(arg, inspect.Parameter): + return arg.name + if isinstance(arg, nodes.Argument): + return arg.variable.name + raise AssertionError + + def get_type(arg: Any) -> str | None: + if isinstance(arg, inspect.Parameter): + return None + if isinstance(arg, nodes.Argument): + return str(arg.variable.type or arg.type_annotation) + raise AssertionError + + def has_default(arg: Any) -> bool: + if isinstance(arg, inspect.Parameter): + return arg.default is not inspect.Parameter.empty + if isinstance(arg, nodes.Argument): + return arg.kind.is_optional() + raise AssertionError + + def get_desc(arg: Any) -> str: + arg_type = get_type(arg) + return ( + get_name(arg) + + (f": {arg_type}" if arg_type else "") + + (" = ..." if has_default(arg) else "") + ) + + kw_only = sorted(self.kwonly.values(), key=lambda a: (has_default(a), get_name(a))) + ret = "def (" + ret += ", ".join( + [get_desc(arg) for arg in self.pos] + + (["*" + get_name(self.varpos)] if self.varpos else (["*"] if self.kwonly else [])) + + [get_desc(arg) for arg in kw_only] + + (["**" + get_name(self.varkw)] if self.varkw else []) + ) + ret += ")" + return ret + + @staticmethod + def from_funcitem(stub: nodes.FuncItem) -> Signature[nodes.Argument]: + stub_sig: Signature[nodes.Argument] = Signature() + stub_args = maybe_strip_cls(stub.name, stub.arguments) + for stub_arg in stub_args: + if stub_arg.kind.is_positional(): + stub_sig.pos.append(stub_arg) + elif stub_arg.kind.is_named(): + stub_sig.kwonly[stub_arg.variable.name] = stub_arg + elif stub_arg.kind == nodes.ARG_STAR: + stub_sig.varpos = stub_arg + elif stub_arg.kind == nodes.ARG_STAR2: + stub_sig.varkw = stub_arg + else: + raise AssertionError + return stub_sig + + @staticmethod + def from_inspect_signature(signature: inspect.Signature) -> Signature[inspect.Parameter]: + runtime_sig: Signature[inspect.Parameter] = Signature() + for runtime_arg in signature.parameters.values(): + if runtime_arg.kind in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ): + runtime_sig.pos.append(runtime_arg) + elif runtime_arg.kind == inspect.Parameter.KEYWORD_ONLY: + runtime_sig.kwonly[runtime_arg.name] = runtime_arg + elif runtime_arg.kind == inspect.Parameter.VAR_POSITIONAL: + runtime_sig.varpos = runtime_arg + elif runtime_arg.kind == inspect.Parameter.VAR_KEYWORD: + runtime_sig.varkw = runtime_arg + else: + raise AssertionError + return runtime_sig + + @staticmethod + def from_overloadedfuncdef(stub: nodes.OverloadedFuncDef) -> Signature[nodes.Argument]: + """Returns a Signature from an OverloadedFuncDef. + + If life were simple, to verify_overloadedfuncdef, we'd just verify_funcitem for each of its + items. Unfortunately, life isn't simple and overloads are pretty deceitful. So instead, we + try and combine the overload's items into a single signature that is compatible with any + lies it might try to tell. + + """ + # For most dunder methods, just assume all args are positional-only + assume_positional_only = is_dunder(stub.name, exclude_special=True) + + is_arg_pos_only: defaultdict[str, set[bool]] = defaultdict(set) + for func in map(_resolve_funcitem_from_decorator, stub.items): + assert func is not None, f"Failed to resolve decorated overload of {stub.fullname!r}" + args = maybe_strip_cls(stub.name, func.arguments) + for index, arg in enumerate(args): + if ( + arg.variable.name.startswith("__") + or arg.pos_only + or assume_positional_only + or arg.variable.name.strip("_") == "self" + or (index == 0 and arg.variable.name.strip("_") == "cls") + ): + is_arg_pos_only[arg.variable.name].add(True) + else: + is_arg_pos_only[arg.variable.name].add(False) + + all_args: dict[str, list[tuple[nodes.Argument, int]]] = {} + for func in map(_resolve_funcitem_from_decorator, stub.items): + assert func is not None, f"Failed to resolve decorated overload of {stub.fullname!r}" + args = maybe_strip_cls(stub.name, func.arguments) + for index, arg in enumerate(args): + # For positional-only args, we allow overloads to have different names for the same + # argument. To accomplish this, we just make up a fake index-based name. + # We can only use the index-based name if the argument is always + # positional only. Sometimes overloads have an arg as positional-only + # in some but not all branches of the overload. + name = arg.variable.name + if is_arg_pos_only[name] == {True}: + name = f"__{index}" + + all_args.setdefault(name, []).append((arg, index)) + + def get_position(arg_name: str) -> int: + # We just need this to return the positional args in the correct order. + return max(index for _, index in all_args[arg_name]) + + def get_type(arg_name: str) -> mypy.types.ProperType: + with mypy.state.state.strict_optional_set(True): + all_types = [ + arg.variable.type or arg.type_annotation for arg, _ in all_args[arg_name] + ] + return mypy.typeops.make_simplified_union([t for t in all_types if t]) + + def get_kind(arg_name: str) -> nodes.ArgKind: + kinds = {arg.kind for arg, _ in all_args[arg_name]} + if nodes.ARG_STAR in kinds: + return nodes.ARG_STAR + if nodes.ARG_STAR2 in kinds: + return nodes.ARG_STAR2 + # The logic here is based on two tenets: + # 1) If an arg is ever optional (or unspecified), it is optional + # 2) If an arg is ever positional, it is positional + is_opt = ( + len(all_args[arg_name]) < len(stub.items) + or nodes.ARG_OPT in kinds + or nodes.ARG_NAMED_OPT in kinds + ) + is_pos = nodes.ARG_OPT in kinds or nodes.ARG_POS in kinds + if is_opt: + return nodes.ARG_OPT if is_pos else nodes.ARG_NAMED_OPT + return nodes.ARG_POS if is_pos else nodes.ARG_NAMED + + sig: Signature[nodes.Argument] = Signature() + for arg_name in sorted(all_args, key=get_position): + # example_arg_name gives us a real name (in case we had a fake index-based name) + example_arg_name = all_args[arg_name][0][0].variable.name + arg = nodes.Argument( + nodes.Var(example_arg_name, get_type(arg_name)), + type_annotation=None, + initializer=None, + kind=get_kind(arg_name), + pos_only=all(arg.pos_only for arg, _ in all_args[arg_name]), + ) + if arg.kind.is_positional(): + sig.pos.append(arg) + elif arg.kind.is_named(): + sig.kwonly[arg.variable.name] = arg + elif arg.kind == nodes.ARG_STAR: + sig.varpos = arg + elif arg.kind == nodes.ARG_STAR2: + sig.varkw = arg + else: + raise AssertionError + return sig + + +def _verify_signature( + stub: Signature[nodes.Argument], + runtime: Signature[inspect.Parameter], + function_name: str, + warn_runtime_is_object_init: bool = False, +) -> Iterator[str]: + # Check positional arguments match up + for stub_arg, runtime_arg in zip(stub.pos, runtime.pos): + yield from _verify_arg_name(stub_arg, runtime_arg, function_name) + yield from _verify_arg_default_value(stub_arg, runtime_arg) + if ( + runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY + and not stub_arg.pos_only + and not stub_arg.variable.name.startswith("__") + and stub_arg.variable.name.strip("_") != "self" + and stub_arg.variable.name.strip("_") != "cls" + ): + yield ( + f'stub parameter "{stub_arg.variable.name}" should be positional-only ' + f'(add "/", e.g. "{runtime_arg.name}, /")' + ) + if ( + runtime_arg.kind != inspect.Parameter.POSITIONAL_ONLY + and (stub_arg.pos_only or stub_arg.variable.name.startswith("__")) + and not runtime_arg.name.startswith("__") + and stub_arg.variable.name.strip("_") != "self" + and stub_arg.variable.name.strip("_") != "cls" + and not is_dunder(function_name, exclude_special=True) # noisy for dunder methods + ): + yield ( + f'stub parameter "{stub_arg.variable.name}" should be positional or keyword ' + '(remove "/")' + ) + + # Check unmatched positional args + if len(stub.pos) > len(runtime.pos): + # There are cases where the stub exhaustively lists out the extra parameters the function + # would take through *args. Hence, a) if runtime accepts *args, we don't check whether the + # runtime has all of the stub's parameters, b) below, we don't enforce that the stub takes + # *args, since runtime logic may prevent arbitrary arguments from actually being accepted. + if runtime.varpos is None: + for stub_arg in stub.pos[len(runtime.pos) :]: + # If the variable is in runtime.kwonly, it's just mislabelled as not a + # keyword-only argument + if stub_arg.variable.name not in runtime.kwonly: + msg = f'runtime does not have parameter "{stub_arg.variable.name}"' + if runtime.varkw is not None: + msg += ". Maybe you forgot to make it keyword-only in the stub?" + elif warn_runtime_is_object_init: + msg += ". You may need to write stubs for __new__ instead of __init__." + yield msg + else: + yield f'stub parameter "{stub_arg.variable.name}" is not keyword-only' + if stub.varpos is not None: + yield f'runtime does not have *args parameter "{stub.varpos.variable.name}"' + elif len(stub.pos) < len(runtime.pos): + for runtime_arg in runtime.pos[len(stub.pos) :]: + if runtime_arg.name not in stub.kwonly: + if not _is_private_parameter(runtime_arg): + yield f'stub does not have parameter "{runtime_arg.name}"' + else: + yield f'runtime parameter "{runtime_arg.name}" is not keyword-only' + + # Checks involving *args + if len(stub.pos) <= len(runtime.pos) or runtime.varpos is None: + if stub.varpos is None and runtime.varpos is not None: + yield f'stub does not have *args parameter "{runtime.varpos.name}"' + if stub.varpos is not None and runtime.varpos is None: + yield f'runtime does not have *args parameter "{stub.varpos.variable.name}"' + + # Check keyword-only args + for arg in sorted(set(stub.kwonly) & set(runtime.kwonly)): + stub_arg, runtime_arg = stub.kwonly[arg], runtime.kwonly[arg] + yield from _verify_arg_name(stub_arg, runtime_arg, function_name) + yield from _verify_arg_default_value(stub_arg, runtime_arg) + + # Check unmatched keyword-only args + if runtime.varkw is None or not set(runtime.kwonly).issubset(set(stub.kwonly)): + # There are cases where the stub exhaustively lists out the extra parameters the function + # would take through **kwargs. Hence, a) if runtime accepts **kwargs (and the stub hasn't + # exhaustively listed out params), we don't check whether the runtime has all of the stub's + # parameters, b) below, we don't enforce that the stub takes **kwargs, since runtime logic + # may prevent arbitrary keyword arguments from actually being accepted. + for arg in sorted(set(stub.kwonly) - set(runtime.kwonly)): + if arg in {runtime_arg.name for runtime_arg in runtime.pos}: + # Don't report this if we've reported it before + if arg not in {runtime_arg.name for runtime_arg in runtime.pos[len(stub.pos) :]}: + yield f'runtime parameter "{arg}" is not keyword-only' + else: + msg = f'runtime does not have parameter "{arg}"' + if warn_runtime_is_object_init: + msg += ". You may need to write stubs for __new__ instead of __init__." + yield msg + + for arg in sorted(set(runtime.kwonly) - set(stub.kwonly)): + if arg in {stub_arg.variable.name for stub_arg in stub.pos}: + # Don't report this if we've reported it before + if not ( + runtime.varpos is None + and arg in {stub_arg.variable.name for stub_arg in stub.pos[len(runtime.pos) :]} + ): + yield f'stub parameter "{arg}" is not keyword-only' + else: + if not _is_private_parameter(runtime.kwonly[arg]): + yield f'stub does not have parameter "{arg}"' + + # Checks involving **kwargs + if stub.varkw is None and runtime.varkw is not None: + # As mentioned above, don't enforce that the stub takes **kwargs. + # Also check against positional parameters, to avoid a nitpicky message when an argument + # isn't marked as keyword-only + stub_pos_names = {stub_arg.variable.name for stub_arg in stub.pos} + # Ideally we'd do a strict subset check, but in practice the errors from that aren't useful + if not set(runtime.kwonly).issubset(set(stub.kwonly) | stub_pos_names): + yield f'stub does not have **kwargs parameter "{runtime.varkw.name}"' + if stub.varkw is not None and runtime.varkw is None: + yield f'runtime does not have **kwargs parameter "{stub.varkw.variable.name}"' + + +def _is_private_parameter(arg: inspect.Parameter) -> bool: + return ( + arg.name.startswith("_") + and not arg.name.startswith("__") + and arg.default is not inspect.Parameter.empty + ) + + +@verify.register(nodes.FuncItem) +def verify_funcitem( + stub: nodes.FuncItem, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + if isinstance(runtime, Missing): + yield Error(object_path, "is not present at runtime", stub, runtime) + return + + if not is_probably_a_function(runtime): + yield Error(object_path, "is not a function", stub, runtime) + if not callable(runtime): + return + + # Look the object up statically, to avoid binding by the descriptor protocol + static_runtime = _static_lookup_runtime(object_path) + + if isinstance(stub, nodes.FuncDef): + for error_text in _verify_abstract_status(stub, runtime): + yield Error(object_path, error_text, stub, runtime) + for error_text in _verify_final_method(stub, runtime, static_runtime): + yield Error(object_path, error_text, stub, runtime) + + for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path): + yield Error(object_path, "is inconsistent, " + message, stub, runtime) + + signature = safe_inspect_signature(runtime) + runtime_is_coroutine = inspect.iscoroutinefunction(runtime) + + if signature: + stub_sig = Signature.from_funcitem(stub) + runtime_sig = Signature.from_inspect_signature(signature) + runtime_sig_desc = describe_runtime_callable(signature, is_async=runtime_is_coroutine) + stub_desc = str(stub_sig) + else: + runtime_sig_desc, stub_desc = None, None + + # Don't raise an error if the stub is a coroutine, but the runtime isn't. + # That results in false positives. + # See https://github.com/python/typeshed/issues/7344 + if runtime_is_coroutine and not stub.is_coroutine: + yield Error( + object_path, + 'is an "async def" function at runtime, but not in the stub', + stub, + runtime, + stub_desc=stub_desc, + runtime_desc=runtime_sig_desc, + ) + + if not signature: + return + + for message in _verify_signature( + stub_sig, + runtime_sig, + function_name=stub.name, + warn_runtime_is_object_init=runtime is object.__init__, + ): + yield Error( + object_path, + "is inconsistent, " + message, + stub, + runtime, + runtime_desc=runtime_sig_desc, + ) + + +@verify.register(Missing) +def verify_missing( + stub: Missing, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + if runtime is MISSING: + return + yield Error(object_path, "is not present in stub", stub, runtime) + + +@verify.register(nodes.Var) +def verify_var( + stub: nodes.Var, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + if isinstance(runtime, Missing): + # Don't always yield an error here, because we often can't find instance variables + if len(object_path) <= 2: + yield Error(object_path, "is not present at runtime", stub, runtime) + return + + if ( + stub.is_initialized_in_class + and is_read_only_property(runtime) + and (stub.is_settable_property or not stub.is_property) + ): + yield Error(object_path, "is read-only at runtime but not in the stub", stub, runtime) + + runtime_type = get_mypy_type_of_runtime_value(runtime, type_context=stub.type) + note = "" + if ( + runtime_type is not None + and stub.type is not None + and not is_subtype_helper(runtime_type, stub.type) + ): + should_error = True + # Avoid errors when defining enums, since runtime_type is the enum itself, but we'd + # annotate it with the type of runtime.value + if isinstance(runtime, enum.Enum): + runtime_type = get_mypy_type_of_runtime_value(runtime.value) + if runtime_type is not None and is_subtype_helper(runtime_type, stub.type): + should_error = False + # We always allow setting the stub value to Ellipsis (...), but use + # _value_ type as a fallback if given. If a member is ... and _value_ + # type is given, all runtime types should be assignable to _value_. + proper_type = mypy.types.get_proper_type(stub.type) + if ( + isinstance(proper_type, mypy.types.Instance) + and proper_type.type.fullname in mypy.types.ELLIPSIS_TYPE_NAMES + ): + value_t = stub.info.get("_value_") + if value_t is None or value_t.type is None or runtime_type is None: + should_error = False + elif is_subtype_helper(runtime_type, value_t.type): + should_error = False + else: + note = " (incompatible '_value_')" + + if should_error: + yield Error( + object_path, + f"variable differs from runtime type {runtime_type}{note}", + stub, + runtime, + ) + elif stub.final_value is not None and stub.final_value != runtime: + yield Error( + object_path, + "is inconsistent, stub value for Final var differs from runtime value", + stub, + runtime, + stub_desc=repr(stub.final_value), + ) + + +@verify.register(nodes.OverloadedFuncDef) +def verify_overloadedfuncdef( + stub: nodes.OverloadedFuncDef, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + # TODO: support `@type_check_only` decorator + if isinstance(runtime, Missing): + yield Error(object_path, "is not present at runtime", stub, runtime) + return + + if stub.is_property: + # Any property with a setter is represented as an OverloadedFuncDef + if is_read_only_property(runtime): + yield Error(object_path, "is read-only at runtime but not in the stub", stub, runtime) + return + + if not is_probably_a_function(runtime): + yield Error(object_path, "is not a function", stub, runtime) + if not callable(runtime): + return + + # mypy doesn't allow overloads where one overload is abstract but another isn't, + # so it should be okay to just check whether the first overload is abstract or not. + # + # TODO: Mypy *does* allow properties where e.g. the getter is abstract but the setter is not; + # and any property with a setter is represented as an OverloadedFuncDef internally; + # not sure exactly what (if anything) we should do about that. + first_part = stub.items[0] + if isinstance(first_part, nodes.Decorator) and first_part.is_overload: + for msg in _verify_abstract_status(first_part.func, runtime): + yield Error(object_path, msg, stub, runtime) + + # Look the object up statically, to avoid binding by the descriptor protocol + static_runtime = _static_lookup_runtime(object_path) + + for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path): + yield Error(object_path, "is inconsistent, " + message, stub, runtime) + + # TODO: Should call _verify_final_method here, + # but overloaded final methods in stubs cause a stubtest crash: see #14950 + + signature = safe_inspect_signature(runtime) + if not signature: + return + + stub_sig = Signature.from_overloadedfuncdef(stub) + runtime_sig = Signature.from_inspect_signature(signature) + + for message in _verify_signature( + stub_sig, + runtime_sig, + function_name=stub.name, + warn_runtime_is_object_init=runtime is object.__init__, + ): + # TODO: This is a little hacky, but the addition here is super useful + if "has a default value of type" in message: + message += ( + ". This is often caused by overloads failing to account for explicitly passing " + "in the default value." + ) + yield Error( + object_path, + "is inconsistent, " + message, + stub, + runtime, + stub_desc=(str(stub.type)) + f"\nInferred signature: {stub_sig}", + runtime_desc="def " + str(signature), + ) + + +@verify.register(nodes.TypeVarExpr) +def verify_typevarexpr( + stub: nodes.TypeVarExpr, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + if isinstance(runtime, Missing): + # We seem to insert these typevars into NamedTuple stubs, but they + # don't exist at runtime. Just ignore! + if stub.name == "_NT": + return + yield Error(object_path, "is not present at runtime", stub, runtime) + return + if not isinstance(runtime, TypeVar): + yield Error(object_path, "is not a TypeVar", stub, runtime) + return + + +@verify.register(nodes.ParamSpecExpr) +def verify_paramspecexpr( + stub: nodes.ParamSpecExpr, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + if isinstance(runtime, Missing): + yield Error(object_path, "is not present at runtime", stub, runtime) + return + maybe_paramspec_types = ( + getattr(typing, "ParamSpec", None), + getattr(typing_extensions, "ParamSpec", None), + ) + paramspec_types = tuple(t for t in maybe_paramspec_types if t is not None) + if not paramspec_types or not isinstance(runtime, paramspec_types): + yield Error(object_path, "is not a ParamSpec", stub, runtime) + return + + +def _is_django_cached_property(runtime: Any) -> bool: # pragma: no cover + # This is a special case for + # https://docs.djangoproject.com/en/5.2/ref/utils/#django.utils.functional.cached_property + # This is needed in `django-stubs` project: + # https://github.com/typeddjango/django-stubs + if type(runtime).__name__ != "cached_property": + return False + try: + return bool(runtime.func) + except Exception: + return False + + +def _verify_readonly_property(stub: nodes.Decorator, runtime: Any) -> Iterator[str]: + assert stub.func.is_property + if isinstance(runtime, property): + yield from _verify_final_method(stub.func, runtime.fget, MISSING) + return + if isinstance(runtime, functools.cached_property): + yield from _verify_final_method(stub.func, runtime.func, MISSING) + return + if _is_django_cached_property(runtime): + yield from _verify_final_method(stub.func, runtime.func, MISSING) + return + if inspect.isdatadescriptor(runtime): + # It's enough like a property... + return + # Sometimes attributes pretend to be properties, for instance, to express that they + # are read only. So allowlist if runtime_type matches the return type of stub. + runtime_type = get_mypy_type_of_runtime_value(runtime) + func_type = ( + stub.func.type.ret_type if isinstance(stub.func.type, mypy.types.CallableType) else None + ) + if ( + runtime_type is not None + and func_type is not None + and is_subtype_helper(runtime_type, func_type) + ): + return + yield "is inconsistent, cannot reconcile @property on stub with runtime object" + + +def _verify_abstract_status(stub: nodes.FuncDef, runtime: Any) -> Iterator[str]: + stub_abstract = stub.abstract_status == nodes.IS_ABSTRACT + runtime_abstract = getattr(runtime, "__isabstractmethod__", False) + # The opposite can exist: some implementations omit `@abstractmethod` decorators + if runtime_abstract and not stub_abstract: + item_type = "property" if stub.is_property else "method" + yield f"is inconsistent, runtime {item_type} is abstract but stub is not" + + +def _verify_final_method( + stub: nodes.FuncDef, runtime: Any, static_runtime: MaybeMissing[Any] +) -> Iterator[str]: + if stub.is_final: + return + if getattr(runtime, "__final__", False) or ( + static_runtime is not MISSING and getattr(static_runtime, "__final__", False) + ): + yield "is decorated with @final at runtime, but not in the stub" + + +def _resolve_funcitem_from_decorator(dec: nodes.OverloadPart) -> nodes.FuncItem | None: + """Returns a FuncItem that corresponds to the output of the decorator. + + Returns None if we can't figure out what that would be. For convenience, this function also + accepts FuncItems. + """ + if isinstance(dec, nodes.FuncItem): + return dec + if dec.func.is_property: + return None + + def apply_decorator_to_funcitem( + decorator: nodes.Expression, func: nodes.FuncItem + ) -> nodes.FuncItem | None: + if ( + isinstance(decorator, nodes.CallExpr) + and isinstance(decorator.callee, nodes.RefExpr) + and decorator.callee.fullname in mypy.types.DEPRECATED_TYPE_NAMES + ): + return func + if not isinstance(decorator, nodes.RefExpr): + return None + if not decorator.fullname: + # Happens with namedtuple + return None + if ( + decorator.fullname in ("builtins.staticmethod", "abc.abstractmethod") + or decorator.fullname in mypy.types.OVERLOAD_NAMES + or decorator.fullname in mypy.types.OVERRIDE_DECORATOR_NAMES + or decorator.fullname in mypy.types.FINAL_DECORATOR_NAMES + ): + return func + if decorator.fullname == "builtins.classmethod": + if func.arguments[0].variable.name not in ("_cls", "cls", "mcs", "metacls"): + raise StubtestFailure( + f"unexpected class parameter name {func.arguments[0].variable.name!r} " + f"in {dec.fullname}" + ) + # FuncItem is written so that copy.copy() actually works, even when compiled + ret = copy.copy(func) + # Remove the cls argument, since it's not present in inspect.signature of classmethods + ret.arguments = ret.arguments[1:] + return ret + # Just give up on any other decorators. After excluding properties, we don't run into + # anything else when running on typeshed's stdlib. + return None + + func: nodes.FuncItem = dec.func + for decorator in dec.original_decorators: + resulting_func = apply_decorator_to_funcitem(decorator, func) + if resulting_func is None: + # We couldn't figure out how to apply the decorator by transforming nodes, so try to + # reconstitute a FuncDef from the resulting type of the decorator + # This is worse because e.g. we lose the values of defaults + dec_type = mypy.types.get_proper_type(dec.type) + callable_type = None + if isinstance(dec_type, mypy.types.Instance): + callable_type = mypy.subtypes.find_member( + "__call__", dec_type, dec_type, is_operator=True + ) + elif isinstance(dec_type, mypy.types.CallableType): + callable_type = dec_type + + callable_type = mypy.types.get_proper_type(callable_type) + if isinstance(callable_type, mypy.types.CallableType): + return _resolve_funcitem_from_callable_type(dec, callable_type) + return None + + func = resulting_func + return func + + +def _resolve_funcitem_from_callable_type( + dec: nodes.Decorator, typ: mypy.types.CallableType +) -> nodes.FuncDef | None: + if ( + typ.arg_kinds == [nodes.ARG_STAR, nodes.ARG_STAR2] + and (var_arg := typ.var_arg()) is not None + and isinstance(mypy.types.get_proper_type(var_arg.typ), mypy.types.AnyType) + and (var_kwarg := typ.kw_arg()) is not None + and isinstance(mypy.types.get_proper_type(var_kwarg.typ), mypy.types.AnyType) + ): + # There isn't a FuncDef we can invent corresponding to a Callable[..., T] + return None + + args: list[nodes.Argument] = [] + for i, (arg_type, arg_kind, arg_name) in enumerate( + zip(typ.arg_types, typ.arg_kinds, typ.arg_names, strict=True) + ): + var_name = arg_name if arg_name is not None else f"__arg{i}" + var = nodes.Var(var_name, arg_type) + pos_only = arg_name is None and arg_kind == nodes.ARG_POS + args.append( + nodes.Argument( + variable=var, + type_annotation=arg_type, + initializer=None, # CallableType doesn't store the values of defaults + kind=arg_kind, + pos_only=pos_only, + ) + ) + + if dec.func.is_class: + if not args: + return None + # Munge classmethods, similar to logic in _resolve_funcitem_from_decorator + if args[0].variable.name not in ("_cls", "cls", "mcs", "metacls"): + return None + args.pop(0) + + ret = nodes.FuncDef(name=typ.name or "", arguments=args, body=nodes.Block([]), typ=typ) + ret.is_class = dec.func.is_class + return ret + + +@verify.register(nodes.Decorator) +def verify_decorator( + stub: nodes.Decorator, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + if stub.func.is_type_check_only: + # This function only exists in stubs, we only check that the runtime part + # is missing. Other checks are not required. + if not isinstance(runtime, Missing): + yield Error( + object_path, + 'is marked as "@type_check_only", but also exists at runtime', + stub, + runtime, + stub_desc=repr(stub), + ) + return + + if isinstance(runtime, Missing): + yield Error(object_path, "is not present at runtime", stub, runtime) + return + if stub.func.is_property: + for message in _verify_readonly_property(stub, runtime): + yield Error(object_path, message, stub, runtime) + for message in _verify_abstract_status(stub.func, runtime): + yield Error(object_path, message, stub, runtime) + return + + func = _resolve_funcitem_from_decorator(stub) + if func is not None: + yield from verify(func, runtime, object_path) + + +@verify.register(nodes.TypeAlias) +def verify_typealias( + stub: nodes.TypeAlias, runtime: MaybeMissing[Any], object_path: list[str] +) -> Iterator[Error]: + stub_target = mypy.types.get_proper_type(stub.target) + stub_desc = f"Type alias for {stub_target}" + if isinstance(runtime, Missing): + yield Error(object_path, "is not present at runtime", stub, runtime, stub_desc=stub_desc) + return + runtime_origin = get_origin(runtime) or runtime + if isinstance(stub_target, mypy.types.Instance): + if not isinstance(runtime_origin, type): + yield Error( + object_path, + "is inconsistent, runtime is not a type", + stub, + runtime, + stub_desc=stub_desc, + ) + return + + stub_origin = stub_target.type + # Do our best to figure out the fullname of the runtime object... + runtime_name: object + try: + runtime_name = runtime_origin.__qualname__ + except AttributeError: + runtime_name = getattr(runtime_origin, "__name__", MISSING) + if isinstance(runtime_name, str): + runtime_module: object = getattr(runtime_origin, "__module__", MISSING) + if isinstance(runtime_module, str): + if runtime_module == "collections.abc" or ( + runtime_module == "re" and runtime_name in {"Match", "Pattern"} + ): + runtime_module = "typing" + runtime_fullname = f"{runtime_module}.{runtime_name}" + if re.fullmatch(rf"_?{re.escape(stub_origin.fullname)}", runtime_fullname): + # Okay, we're probably fine. + return + + # Okay, either we couldn't construct a fullname + # or the fullname of the stub didn't match the fullname of the runtime. + # Fallback to a full structural check of the runtime vis-a-vis the stub. + yield from verify_typeinfo(stub_origin, runtime_origin, object_path, is_alias_target=True) + return + if isinstance(stub_target, mypy.types.UnionType): + # complain if runtime is not a Union or UnionType + if runtime_origin is not Union and ( + not (sys.version_info >= (3, 10) and isinstance(runtime, types.UnionType)) + ): + yield Error(object_path, "is not a Union", stub, runtime, stub_desc=str(stub_target)) + # could check Union contents here... + return + if isinstance(stub_target, mypy.types.TupleType): + if tuple not in getattr(runtime_origin, "__mro__", ()): + yield Error( + object_path, "is not a subclass of tuple", stub, runtime, stub_desc=stub_desc + ) + # could check Tuple contents here... + return + if isinstance(stub_target, mypy.types.CallableType): + if runtime_origin is not collections.abc.Callable: + yield Error( + object_path, "is not a type alias for Callable", stub, runtime, stub_desc=stub_desc + ) + # could check Callable contents here... + return + if isinstance(stub_target, mypy.types.AnyType): + return + yield Error(object_path, "is not a recognised type alias", stub, runtime, stub_desc=stub_desc) + + +# ==================== +# Helpers +# ==================== + + +IGNORED_MODULE_DUNDERS: Final = frozenset( + { + "__file__", + "__doc__", + "__name__", + "__builtins__", + "__package__", + "__cached__", + "__loader__", + "__spec__", + "__annotations__", + "__conditional_annotations__", # 3.14+ + "__annotate__", + "__path__", # mypy adds __path__ to packages, but C packages don't have it + "__getattr__", # resulting behaviour might be typed explicitly + # Created by `warnings.warn`, does not make much sense to have in stubs: + "__warningregistry__", + # TODO: remove the following from this list + "__author__", + "__version__", + "__copyright__", + } +) + +IGNORABLE_CLASS_DUNDERS: Final = frozenset( + { + # Special attributes + "__dict__", + "__annotations__", + "__annotate__", + "__annotations_cache__", + "__annotate_func__", + "__text_signature__", + "__weakref__", + "__hash__", + "__getattr__", # resulting behaviour might be typed explicitly + "__setattr__", # defining this on a class can cause worse type checking + "__vectorcalloffset__", # undocumented implementation detail of the vectorcall protocol + "__firstlineno__", + "__static_attributes__", + "__classdictcell__", + # isinstance/issubclass hooks that type-checkers don't usually care about + "__instancecheck__", + "__subclasshook__", + "__subclasscheck__", + # python2 only magic methods: + "__cmp__", + "__nonzero__", + "__unicode__", + "__div__", + # cython methods + "__pyx_vtable__", + # Pickle methods + "__setstate__", + "__getstate__", + "__getnewargs__", + "__getinitargs__", + "__reduce_ex__", + "__reduce__", + "__slotnames__", # Cached names of slots added by `copyreg` module. + # ctypes weirdness + "__ctype_be__", + "__ctype_le__", + "__ctypes_from_outparam__", + # mypy limitations + "__abstractmethods__", # Classes with metaclass=ABCMeta inherit this attribute + "__new_member__", # If an enum defines __new__, the method is renamed as __new_member__ + "__dataclass_fields__", # Generated by dataclasses + "__dataclass_params__", # Generated by dataclasses + "__doc__", # mypy's semanal for namedtuples assumes this is str, not Optional[str] + # Added to all protocol classes on 3.12+ (or if using typing_extensions.Protocol) + "__protocol_attrs__", + "__callable_proto_members_only__", + "__non_callable_proto_members__", + # typing implementation details, consider removing some of these: + "__parameters__", + "__origin__", + "__args__", + "__orig_bases__", + "__final__", # Has a specialized check + # Consider removing __slots__? + "__slots__", + } +) + + +def is_probably_private(name: str) -> bool: + return name.startswith("_") and not is_dunder(name) + + +def is_probably_a_function(runtime: Any) -> bool: + return ( + isinstance( + runtime, + ( + types.FunctionType, + types.BuiltinFunctionType, + types.MethodType, + types.BuiltinMethodType, + ), + ) + or (inspect.ismethoddescriptor(runtime) and callable(runtime)) + or (isinstance(runtime, types.MethodWrapperType) and callable(runtime)) + ) + + +def is_read_only_property(runtime: object) -> bool: + return isinstance(runtime, property) and runtime.fset is None + + +def safe_inspect_signature(runtime: Any) -> inspect.Signature | None: + if ( + hasattr(runtime, "__name__") + and runtime.__name__ == "__init__" + and hasattr(runtime, "__text_signature__") + and runtime.__text_signature__ == "($self, /, *args, **kwargs)" + and hasattr(runtime, "__objclass__") + and hasattr(runtime.__objclass__, "__text_signature__") + and runtime.__objclass__.__text_signature__ is not None + ): + # This is an __init__ method with the generic C-class signature. + # In this case, the underlying class often has a better signature, + # which we can convert into an __init__ signature by adding in the + # self parameter. + try: + s = inspect.signature(runtime.__objclass__) + + parameter_kind: inspect._ParameterKind = inspect.Parameter.POSITIONAL_OR_KEYWORD + if s.parameters: + first_parameter = next(iter(s.parameters.values())) + if first_parameter.kind == inspect.Parameter.POSITIONAL_ONLY: + parameter_kind = inspect.Parameter.POSITIONAL_ONLY + return s.replace( + parameters=[inspect.Parameter("self", parameter_kind), *s.parameters.values()] + ) + except Exception: + pass + + if ( + hasattr(runtime, "__name__") + and runtime.__name__ == "__new__" + and hasattr(runtime, "__text_signature__") + and runtime.__text_signature__ == "($type, *args, **kwargs)" + and hasattr(runtime, "__self__") + and hasattr(runtime.__self__, "__text_signature__") + and runtime.__self__.__text_signature__ is not None + ): + # This is a __new__ method with the generic C-class signature. + # In this case, the underlying class often has a better signature, + # which we can convert into a __new__ signature by adding in the + # cls parameter. + + # If the attached class has a valid __init__, skip recovering a + # signature for this __new__ method. + has_init = False + if ( + hasattr(runtime.__self__, "__init__") + and hasattr(runtime.__self__.__init__, "__objclass__") + and runtime.__self__.__init__.__objclass__ is runtime.__self__ + ): + has_init = True + + if not has_init: + try: + s = inspect.signature(runtime.__self__) + parameter_kind = inspect.Parameter.POSITIONAL_OR_KEYWORD + if s.parameters: + first_parameter = next(iter(s.parameters.values())) + if first_parameter.kind == inspect.Parameter.POSITIONAL_ONLY: + parameter_kind = inspect.Parameter.POSITIONAL_ONLY + return s.replace( + parameters=[inspect.Parameter("cls", parameter_kind), *s.parameters.values()] + ) + except Exception: + pass + + try: + try: + return inspect.signature(runtime) + except ValueError: + if ( + hasattr(runtime, "__text_signature__") + and "" in runtime.__text_signature__ + ): + # Try to fix up the signature. Workaround for + # https://github.com/python/cpython/issues/87233 + sig = runtime.__text_signature__.replace("", "...") + sig = inspect._signature_fromstr(inspect.Signature, runtime, sig) # type: ignore[attr-defined] + assert isinstance(sig, inspect.Signature) + new_params = [ + ( + parameter.replace(default=UNREPRESENTABLE) + if parameter.default is ... + else parameter + ) + for parameter in sig.parameters.values() + ] + return sig.replace(parameters=new_params) + else: + raise + except Exception: + # inspect.signature throws ValueError all the time + # catch RuntimeError because of https://bugs.python.org/issue39504 + # catch TypeError because of https://github.com/python/typeshed/pull/5762 + # catch AttributeError because of inspect.signature(_curses.window.border) + return None + + +def describe_runtime_callable(signature: inspect.Signature, *, is_async: bool) -> str: + return f'{"async " if is_async else ""}def {signature}' + + +class _TypeCheckOnlyBaseMapper(mypy.types.TypeTranslator): + """Rewrites @type_check_only instances to the nearest runtime-visible base class.""" + + def visit_instance(self, t: mypy.types.Instance, /) -> mypy.types.Type: + instance = mypy.types.get_proper_type(super().visit_instance(t)) + assert isinstance(instance, mypy.types.Instance) + + if instance.type.is_type_check_only: + # find the nearest non-@type_check_only base class + for base_info in instance.type.mro[1:]: + if not base_info.is_type_check_only: + return map_instance_to_supertype(instance, base_info) + + msg = f"all base classes of {instance.type.fullname!r} are @type_check_only" + assert False, msg + + return instance + + def visit_type_alias_type(self, t: mypy.types.TypeAliasType, /) -> mypy.types.Type: + return t + + +_TYPE_CHECK_ONLY_BASE_MAPPER = _TypeCheckOnlyBaseMapper() + + +def _relax_type_check_only_type(typ: mypy.types.ProperType) -> mypy.types.ProperType: + return mypy.types.get_proper_type(typ.accept(_TYPE_CHECK_ONLY_BASE_MAPPER)) + + +def is_subtype_helper(left: mypy.types.Type, right: mypy.types.Type) -> bool: + """Checks whether ``left`` is a subtype of ``right``.""" + left = _relax_type_check_only_type(mypy.types.get_proper_type(left)) + right = _relax_type_check_only_type(mypy.types.get_proper_type(right)) + if ( + isinstance(left, mypy.types.LiteralType) + and isinstance(left.value, int) + and left.value in (0, 1) + and mypy.types.is_named_instance(right, "builtins.bool") + ): + # Pretend Literal[0, 1] is a subtype of bool to avoid unhelpful errors. + return True + + if isinstance(right, mypy.types.TypedDictType) and mypy.types.is_named_instance( + left, "builtins.dict" + ): + # Special case checks against TypedDicts + return True + + with mypy.state.state.strict_optional_set(True): + return mypy.subtypes.is_subtype(left, right) + + +def get_mypy_node_for_name(module: str, type_name: str) -> mypy.nodes.SymbolNode | None: + stub = get_stub(module) + if stub is None: + return None + if type_name not in stub.names: + return None + return stub.names[type_name].node + + +def get_mypy_type_of_runtime_value( + runtime: Any, type_context: mypy.types.Type | None = None +) -> mypy.types.Type | None: + """Returns a mypy type object representing the type of ``runtime``. + + Returns None if we can't find something that works. + + """ + if runtime is None: + return mypy.types.NoneType() + if isinstance(runtime, property): + # Give up on properties to avoid issues with things that are typed as attributes. + return None + + def anytype() -> mypy.types.AnyType: + return mypy.types.AnyType(mypy.types.TypeOfAny.unannotated) + + if isinstance( + runtime, + (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType), + ): + builtins = get_stub("builtins") + assert builtins is not None + type_info = builtins.names["function"].node + assert isinstance(type_info, nodes.TypeInfo) + fallback = mypy.types.Instance(type_info, [anytype()]) + signature = safe_inspect_signature(runtime) + if signature: + arg_types = [] + arg_kinds = [] + arg_names = [] + for arg in signature.parameters.values(): + arg_types.append(anytype()) + arg_names.append( + None if arg.kind == inspect.Parameter.POSITIONAL_ONLY else arg.name + ) + no_default = arg.default is inspect.Parameter.empty + if arg.kind == inspect.Parameter.POSITIONAL_ONLY: + arg_kinds.append(nodes.ARG_POS if no_default else nodes.ARG_OPT) + elif arg.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD: + arg_kinds.append(nodes.ARG_POS if no_default else nodes.ARG_OPT) + elif arg.kind == inspect.Parameter.KEYWORD_ONLY: + arg_kinds.append(nodes.ARG_NAMED if no_default else nodes.ARG_NAMED_OPT) + elif arg.kind == inspect.Parameter.VAR_POSITIONAL: + arg_kinds.append(nodes.ARG_STAR) + elif arg.kind == inspect.Parameter.VAR_KEYWORD: + arg_kinds.append(nodes.ARG_STAR2) + else: + raise AssertionError + else: + arg_types = [anytype(), anytype()] + arg_kinds = [nodes.ARG_STAR, nodes.ARG_STAR2] + arg_names = [None, None] + + return mypy.types.CallableType( + arg_types, + arg_kinds, + arg_names, + ret_type=anytype(), + fallback=fallback, + is_ellipsis_args=True, + ) + + skip_type_object_type = False + if type_context: + # Don't attempt to process the type object when context is generic + # This is related to issue #3737 + type_context = mypy.types.get_proper_type(type_context) + # Callable types with a generic return value + if isinstance(type_context, mypy.types.CallableType): + if isinstance(type_context.ret_type, mypy.types.TypeVarType): + skip_type_object_type = True + # Type[x] where x is generic + if isinstance(type_context, mypy.types.TypeType): + if isinstance(type_context.item, mypy.types.TypeVarType): + skip_type_object_type = True + + if isinstance(runtime, type) and not skip_type_object_type: + + def _named_type(name: str) -> mypy.types.Instance: + parts = name.rsplit(".", maxsplit=1) + node = get_mypy_node_for_name(parts[0], parts[1]) + assert isinstance(node, nodes.TypeInfo) + any_type = mypy.types.AnyType(mypy.types.TypeOfAny.special_form) + return mypy.types.Instance(node, [any_type] * len(node.defn.type_vars)) + + # Try and look up a stub for the runtime object itself + # The logic here is similar to ExpressionChecker.analyze_ref_expr + type_info = get_mypy_node_for_name(runtime.__module__, runtime.__name__) + if isinstance(type_info, nodes.TypeInfo): + result: mypy.types.Type | None = None + result = mypy.typeops.type_object_type(type_info, _named_type) + if mypy.checkexpr.is_type_type_context(type_context): + # This is the type in a type[] expression, so substitute type + # variables with Any. + result = mypy.erasetype.erase_typevars(result) + return result + + # Try and look up a stub for the runtime object's type + type_info = get_mypy_node_for_name(type(runtime).__module__, type(runtime).__name__) + if type_info is None: + return None + if isinstance(type_info, nodes.Var): + return type_info.type + if not isinstance(type_info, nodes.TypeInfo): + return None + + if isinstance(runtime, tuple): + # Special case tuples so we construct a valid mypy.types.TupleType + optional_items = [get_mypy_type_of_runtime_value(v) for v in runtime] + items = [(i if i is not None else anytype()) for i in optional_items] + fallback = mypy.types.Instance(type_info, [anytype()]) + return mypy.types.TupleType(items, fallback) + + fallback = mypy.types.Instance(type_info, [anytype() for _ in type_info.type_vars]) + if type(runtime) != runtime.__class__: + # Since `__class__` is redefined for an instance, we can't trust + # its `isinstance` checks, it can be dynamic. See #20919 + return fallback + + value: bool | int | str + if isinstance(runtime, enum.Enum) and isinstance(runtime.name, str): + value = runtime.name + elif isinstance(runtime, bytes): + value = bytes_to_human_readable_repr(runtime) + elif isinstance(runtime, (bool, int, str)): + value = runtime + else: + return fallback + + return mypy.types.LiteralType(value=value, fallback=fallback) + + +# ==================== +# Build and entrypoint +# ==================== + + +_all_stubs: dict[str, nodes.MypyFile] = {} + + +def build_stubs(modules: list[str], options: Options, find_submodules: bool = False) -> list[str]: + """Uses mypy to construct stub objects for the given modules. + + This sets global state that ``get_stub`` can access. + + Returns all modules we might want to check. If ``find_submodules`` is False, this is equal + to ``modules``. + + :param modules: List of modules to build stubs for. + :param options: Mypy options for finding and building stubs. + :param find_submodules: Whether to attempt to find submodules of the given modules as well. + + """ + data_dir = mypy.build.default_data_dir() + search_path = mypy.modulefinder.compute_search_paths([], options, data_dir) + find_module_cache = mypy.modulefinder.FindModuleCache( + search_path, fscache=None, options=options + ) + + all_modules = [] + sources = [] + for module in modules: + all_modules.append(module) + if not find_submodules: + module_path = find_module_cache.find_module(module) + if not isinstance(module_path, str): + # test_module will yield an error later when it can't find stubs + continue + sources.append(mypy.modulefinder.BuildSource(module_path, module, None)) + else: + found_sources = find_module_cache.find_modules_recursive(module) + sources.extend(found_sources) + # find submodules via mypy + all_modules.extend(s.module for s in found_sources if s.module not in all_modules) + # find submodules via pkgutil + try: + runtime = silent_import_module(module) + all_modules.extend( + m.name + for m in pkgutil.walk_packages(runtime.__path__, runtime.__name__ + ".") + if m.name not in all_modules + ) + except KeyboardInterrupt: + raise + except BaseException: + pass + + if sources: + try: + res = mypy.build.build(sources=sources, options=options) + except mypy.errors.CompileError as e: + raise StubtestFailure(f"failed mypy compile:\n{e}") from e + if res.errors: + raise StubtestFailure("mypy build errors:\n" + "\n".join(res.errors)) + + global _all_stubs + _all_stubs = res.files + + return all_modules + + +def get_stub(module: str) -> nodes.MypyFile | None: + """Returns a stub object for the given module, if we've built one.""" + return _all_stubs.get(module) + + +def get_typeshed_stdlib_modules( + custom_typeshed_dir: str | None, version_info: tuple[int, int] | None = None +) -> set[str]: + """Returns a list of stdlib modules in typeshed (for current Python version).""" + stdlib_py_versions = mypy.modulefinder.load_stdlib_py_versions(custom_typeshed_dir) + if version_info is None: + version_info = sys.version_info[0:2] + + def exists_in_version(module: str) -> bool: + assert version_info is not None + parts = module.split(".") + for i in range(len(parts), 0, -1): + current_module = ".".join(parts[:i]) + if current_module in stdlib_py_versions: + minver, maxver = stdlib_py_versions[current_module] + return version_info >= minver and (maxver is None or version_info <= maxver) + return False + + if custom_typeshed_dir: + typeshed_dir = Path(custom_typeshed_dir) + else: + typeshed_dir = Path(mypy.build.default_data_dir()) / "typeshed" + stdlib_dir = typeshed_dir / "stdlib" + + modules: set[str] = set() + for path in stdlib_dir.rglob("*.pyi"): + if path.stem == "__init__": + path = path.parent + module = ".".join(path.relative_to(stdlib_dir).parts[:-1] + (path.stem,)) + if exists_in_version(module): + modules.add(module) + return modules + + +def get_importable_stdlib_modules() -> set[str]: + """Return all importable stdlib modules at runtime.""" + importable_stdlib_modules: set[str] = set() + for module_name in sys.stdlib_module_names: + if module_name in ANNOYING_STDLIB_MODULES: + continue + + try: + runtime = silent_import_module(module_name) + except ImportError: + continue + else: + importable_stdlib_modules.add(module_name) + + try: + # some stdlib modules (e.g. `nt`) don't have __path__ set... + runtime_path = runtime.__path__ + runtime_name = runtime.__name__ + except AttributeError: + continue + + for submodule in pkgutil.walk_packages(runtime_path, runtime_name + "."): + submodule_name = submodule.name + + # There are many annoying *.__main__ stdlib modules, + # and including stubs for them isn't really that useful anyway: + # tkinter.__main__ opens a tkinter windows; unittest.__main__ raises SystemExit; etc. + # + # The idlelib.* submodules are similarly annoying in opening random tkinter windows, + # and we're unlikely to ever add stubs for idlelib in typeshed + # (see discussion in https://github.com/python/typeshed/pull/9193) + # + # test.* modules do weird things like raising exceptions in __del__ methods, + # leading to unraisable exceptions being logged to the terminal + # as a warning at the end of the stubtest run + if submodule_name.endswith(".__main__") or submodule_name.startswith( + ("idlelib.", "test.") + ): + continue + + try: + silent_import_module(submodule_name) + except KeyboardInterrupt: + raise + # importing multiprocessing.popen_forkserver on Windows raises AttributeError... + # some submodules also appear to raise SystemExit as well on some Python versions + # (not sure exactly which) + except BaseException: + continue + else: + importable_stdlib_modules.add(submodule_name) + + return importable_stdlib_modules + + +def get_allowlist_entries(allowlist_file: str) -> Iterator[str]: + def strip_comments(s: str) -> str: + try: + return s[: s.index("#")].strip() + except ValueError: + return s.strip() + + with open(allowlist_file) as f: + for line in f: + entry = strip_comments(line) + if entry: + yield entry + + +class _Arguments: + modules: list[str] + concise: bool + ignore_missing_stub: bool + ignore_positional_only: bool + ignore_disjoint_bases: bool + strict_type_check_only: bool + allowlist: list[str] + generate_allowlist: bool + ignore_unused_allowlist: bool + mypy_config_file: str | None + custom_typeshed_dir: str | None + check_typeshed: bool + version: str + show_traceback: bool + pdb: bool + + +# typeshed added a stub for __main__, but that causes stubtest to check itself +ANNOYING_STDLIB_MODULES: Final = frozenset({"antigravity", "this", "__main__", "_ios_support"}) + + +def test_stubs(args: _Arguments, use_builtins_fixtures: bool = False) -> int: + """This is stubtest! It's time to test the stubs!""" + # Load the allowlist. This is a series of strings corresponding to Error.object_desc + # Values in the dict will store whether we used the allowlist entry or not. + allowlist = { + entry: False + for allowlist_file in args.allowlist + for entry in get_allowlist_entries(allowlist_file) + } + allowlist_regexes = {entry: re.compile(entry) for entry in allowlist} + + # If we need to generate an allowlist, we store Error.object_desc for each error here. + generated_allowlist = set() + + modules = args.modules + if args.check_typeshed: + if args.modules: + print( + _style("error:", color="red", bold=True), + "cannot pass both --check-typeshed and a list of modules", + ) + return 1 + typeshed_modules = get_typeshed_stdlib_modules(args.custom_typeshed_dir) + runtime_modules = get_importable_stdlib_modules() + modules = sorted((typeshed_modules | runtime_modules) - ANNOYING_STDLIB_MODULES) + + if not modules: + print(_style("error:", color="red", bold=True), "no modules to check") + return 1 + + options = Options() + options.incremental = False + options.custom_typeshed_dir = args.custom_typeshed_dir + if options.custom_typeshed_dir: + options.abs_custom_typeshed_dir = os.path.abspath(options.custom_typeshed_dir) + options.config_file = args.mypy_config_file + options.use_builtins_fixtures = use_builtins_fixtures + options.show_traceback = args.show_traceback + options.pdb = args.pdb + options.pos_only_special_methods = False + + if options.config_file: + + def set_strict_flags() -> None: # not needed yet + return + + parse_config_file(options, set_strict_flags, options.config_file, sys.stdout, sys.stderr) + + def error_callback(msg: str) -> typing.NoReturn: + print(_style("error:", color="red", bold=True), msg) + sys.exit(1) + + def warning_callback(msg: str) -> None: + print(_style("warning:", color="yellow", bold=True), msg) + + options.process_error_codes(error_callback=error_callback) + options.process_incomplete_features( + error_callback=error_callback, warning_callback=warning_callback + ) + options.process_strict_bytes() + + try: + modules = build_stubs(modules, options, find_submodules=not args.check_typeshed) + except StubtestFailure as stubtest_failure: + print( + _style("error:", color="red", bold=True), + f"not checking stubs due to {stubtest_failure}", + ) + return 1 + + exit_code = 0 + error_count = 0 + for module in modules: + for error in test_module(module): + # Filter errors + if args.ignore_missing_stub and error.is_missing_stub(): + continue + if args.ignore_positional_only and error.is_positional_only_related(): + continue + if args.ignore_disjoint_bases and error.is_disjoint_base_related(): + continue + if not args.strict_type_check_only and error.is_private_type_check_only_related(): + continue + if error.object_desc in allowlist: + allowlist[error.object_desc] = True + continue + is_allowlisted = False + for w in allowlist: + if allowlist_regexes[w].fullmatch(error.object_desc): + allowlist[w] = True + is_allowlisted = True + break + if is_allowlisted: + continue + + # We have errors, so change exit code, and output whatever necessary + exit_code = 1 + if args.generate_allowlist: + generated_allowlist.add(error.object_desc) + continue + safe_print(error.get_description(concise=args.concise)) + error_count += 1 + + # Print unused allowlist entries + if not args.ignore_unused_allowlist: + for w in allowlist: + # Don't consider an entry unused if it regex-matches the empty string + # This lets us allowlist errors that don't manifest at all on some systems + if not allowlist[w] and not allowlist_regexes[w].fullmatch(""): + exit_code = 1 + error_count += 1 + print(f"note: unused allowlist entry {w}") + + # Print the generated allowlist + if args.generate_allowlist: + for e in sorted(generated_allowlist): + print(e) + exit_code = 0 + elif not args.concise: + if error_count: + print( + _style( + f"Found {error_count} error{plural_s(error_count)}" + f" (checked {len(modules)} module{plural_s(modules)})", + color="red", + bold=True, + ) + ) + else: + print( + _style( + f"Success: no issues found in {len(modules)} module{plural_s(modules)}", + color="green", + bold=True, + ) + ) + + return exit_code + + +def safe_print(text: str) -> None: + """Print a text replacing chars not representable in stdout encoding.""" + # If `sys.stdout` encoding is not the same as out (usually UTF8) string, + # if may cause painful crashes. I don't want to reconfigure `sys.stdout` + # to do `errors = "replace"` as that sounds scary. + out_encoding = sys.stdout.encoding + if out_encoding is not None: + # Can be None if stdout is replaced (including our own tests). This should be + # safe to omit if the actual stream doesn't care about encoding. + text = text.encode(out_encoding, errors="replace").decode(out_encoding, errors="replace") + print(text) + + +def parse_options(args: list[str]) -> _Arguments: + parser = argparse.ArgumentParser( + description="Compares stubs to objects introspected from the runtime." + ) + parser.add_argument("modules", nargs="*", help="Modules to test") + parser.add_argument( + "--concise", + action="store_true", + help="Makes stubtest's output more concise, one line per error", + ) + parser.add_argument( + "--ignore-missing-stub", + action="store_true", + help="Ignore errors for stub missing things that are present at runtime", + ) + parser.add_argument( + "--ignore-positional-only", + action="store_true", + help="Ignore errors for whether an argument should or shouldn't be positional-only", + ) + # TODO: Remove once PEP 800 is accepted + parser.add_argument( + "--ignore-disjoint-bases", + action="store_true", + help="Disable checks for PEP 800 @disjoint_base classes", + ) + parser.add_argument( + "--strict-type-check-only", + action="store_true", + help="Require @type_check_only on private types that are not present at runtime", + ) + parser.add_argument( + "--allowlist", + "--whitelist", + action="append", + metavar="FILE", + default=[], + help=( + "Use file as an allowlist. Can be passed multiple times to combine multiple " + "allowlists. Allowlists can be created with --generate-allowlist. Allowlists " + "support regular expressions." + ), + ) + parser.add_argument( + "--generate-allowlist", + "--generate-whitelist", + action="store_true", + help="Print an allowlist (to stdout) to be used with --allowlist", + ) + parser.add_argument( + "--ignore-unused-allowlist", + "--ignore-unused-whitelist", + action="store_true", + help="Ignore unused allowlist entries", + ) + parser.add_argument( + "--mypy-config-file", + metavar="FILE", + help=("Use specified mypy config file to determine mypy plugins and mypy path"), + ) + parser.add_argument( + "--custom-typeshed-dir", metavar="DIR", help="Use the custom typeshed in DIR" + ) + parser.add_argument( + "--check-typeshed", action="store_true", help="Check all stdlib modules in typeshed" + ) + parser.add_argument( + "--version", action="version", version="%(prog)s " + mypy.version.__version__ + ) + parser.add_argument("--pdb", action="store_true", help="Invoke pdb on fatal error") + parser.add_argument( + "--show-traceback", "--tb", action="store_true", help="Show traceback on fatal error" + ) + + return parser.parse_args(args, namespace=_Arguments()) + + +def main() -> int: + mypy.util.check_python_version("stubtest") + return test_stubs(parse_options(sys.argv[1:])) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/micromamba_root/Lib/site-packages/mypy/stubutil.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/stubutil.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..c77d77e51b0058518d66a44ab7b27d58221e70af Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/stubutil.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/stubutil.py b/micromamba_root/Lib/site-packages/mypy/stubutil.py new file mode 100644 index 0000000000000000000000000000000000000000..e8fcc4fc1829d547a4ea6dc1eb1939ca984a39b9 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/stubutil.py @@ -0,0 +1,895 @@ +"""Utilities for mypy.stubgen, mypy.stubgenc, and mypy.stubdoc modules.""" + +from __future__ import annotations + +import os.path +import re +import sys +import traceback +from abc import abstractmethod +from collections import defaultdict +from collections.abc import Iterable, Iterator, Mapping +from contextlib import contextmanager +from typing import Final, overload + +from mypy_extensions import mypyc_attr + +import mypy.options +from mypy.modulefinder import ModuleNotFoundReason +from mypy.moduleinspect import InspectError, ModuleInspect +from mypy.nodes import PARAM_SPEC_KIND, TYPE_VAR_TUPLE_KIND, ClassDef, FuncDef, TypeAliasStmt +from mypy.stubdoc import ArgSig, FunctionSig +from mypy.types import ( + AnyType, + NoneType, + Type, + TypeList, + TypeStrVisitor, + UnboundType, + UnionType, + UnpackType, +) + +# Modules that may fail when imported, or that may have side effects (fully qualified). +NOT_IMPORTABLE_MODULES: tuple[str, ...] = () + +# Typing constructs to be replaced by their builtin equivalents. +TYPING_BUILTIN_REPLACEMENTS: Final = { + # From typing + "typing.Text": "builtins.str", + "typing.Tuple": "builtins.tuple", + "typing.List": "builtins.list", + "typing.Dict": "builtins.dict", + "typing.Set": "builtins.set", + "typing.FrozenSet": "builtins.frozenset", + "typing.Type": "builtins.type", + # From typing_extensions + "typing_extensions.Text": "builtins.str", + "typing_extensions.Tuple": "builtins.tuple", + "typing_extensions.List": "builtins.list", + "typing_extensions.Dict": "builtins.dict", + "typing_extensions.Set": "builtins.set", + "typing_extensions.FrozenSet": "builtins.frozenset", + "typing_extensions.Type": "builtins.type", +} + + +class CantImport(Exception): + def __init__(self, module: str, message: str) -> None: + self.module = module + self.message = message + + +def walk_packages( + inspect: ModuleInspect, packages: list[str], verbose: bool = False +) -> Iterator[str]: + """Iterates through all packages and sub-packages in the given list. + + This uses runtime imports (in another process) to find both Python and C modules. + For Python packages we simply pass the __path__ attribute to pkgutil.walk_packages() to + get the content of the package (all subpackages and modules). However, packages in C + extensions do not have this attribute, so we have to roll out our own logic: recursively + find all modules imported in the package that have matching names. + """ + for package_name in packages: + if package_name in NOT_IMPORTABLE_MODULES: + print(f"{package_name}: Skipped (blacklisted)") + continue + if verbose: + print(f"Trying to import {package_name!r} for runtime introspection") + try: + prop = inspect.get_package_properties(package_name) + except InspectError: + if verbose: + tb = traceback.format_exc() + sys.stderr.write(tb) + report_missing(package_name) + continue + yield prop.name + if prop.is_c_module: + # Recursively iterate through the subpackages + yield from walk_packages(inspect, prop.subpackages, verbose) + else: + yield from prop.subpackages + + +def find_module_path_using_sys_path(module: str, sys_path: list[str]) -> str | None: + relative_candidates = ( + module.replace(".", "/") + ".py", + os.path.join(module.replace(".", "/"), "__init__.py"), + ) + for base in sys_path: + for relative_path in relative_candidates: + path = os.path.join(base, relative_path) + if os.path.isfile(path): + return path + return None + + +def find_module_path_and_all_py3( + inspect: ModuleInspect, module: str, verbose: bool +) -> tuple[str | None, list[str] | None] | None: + """Find module and determine __all__ for a Python 3 module. + + Return None if the module is a C or pyc-only module. + Return (module_path, __all__) if it is a Python module. + Raise CantImport if import failed. + """ + if module in NOT_IMPORTABLE_MODULES: + raise CantImport(module, "") + + # TODO: Support custom interpreters. + if verbose: + print(f"Trying to import {module!r} for runtime introspection") + try: + mod = inspect.get_package_properties(module) + except InspectError as e: + # Fall back to finding the module using sys.path. + path = find_module_path_using_sys_path(module, sys.path) + if path is None: + raise CantImport(module, str(e)) from e + return path, None + if mod.is_c_module: + return None + return mod.file, mod.all + + +@contextmanager +def generate_guarded( + mod: str, target: str, ignore_errors: bool = True, verbose: bool = False +) -> Iterator[None]: + """Ignore or report errors during stub generation. + + Optionally report success. + """ + if verbose: + print(f"Processing {mod}") + try: + yield + except Exception as e: + if not ignore_errors: + raise e + else: + # --ignore-errors was passed + print("Stub generation failed for", mod, file=sys.stderr) + else: + if verbose: + print(f"Created {target}") + + +def report_missing(mod: str, message: str | None = "", traceback: str = "") -> None: + if message: + message = " with error: " + message + print(f"{mod}: Failed to import, skipping{message}") + + +def fail_missing(mod: str, reason: ModuleNotFoundReason) -> None: + if reason is ModuleNotFoundReason.NOT_FOUND: + clarification = "(consider using --search-path)" + elif reason is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS: + clarification = "(module likely exists, but is not PEP 561 compatible)" + else: + clarification = f"(unknown reason '{reason}')" + raise SystemExit(f"Can't find module '{mod}' {clarification}") + + +@overload +def remove_misplaced_type_comments(source: bytes) -> bytes: ... + + +@overload +def remove_misplaced_type_comments(source: str) -> str: ... + + +def remove_misplaced_type_comments(source: str | bytes) -> str | bytes: + """Remove comments from source that could be understood as misplaced type comments. + + Normal comments may look like misplaced type comments, and since they cause blocking + parse errors, we want to avoid them. + """ + if isinstance(source, bytes): + # This gives us a 1-1 character code mapping, so it's roundtrippable. + text = source.decode("latin1") + else: + text = source + + # Remove something that looks like a variable type comment but that's by itself + # on a line, as it will often generate a parse error (unless it's # type: ignore). + text = re.sub(r'^[ \t]*# +type: +["\'a-zA-Z_].*$', "", text, flags=re.MULTILINE) + + # Remove something that looks like a function type comment after docstring, + # which will result in a parse error. + text = re.sub(r'""" *\n[ \t\n]*# +type: +\(.*$', '"""\n', text, flags=re.MULTILINE) + text = re.sub(r"''' *\n[ \t\n]*# +type: +\(.*$", "'''\n", text, flags=re.MULTILINE) + + # Remove something that looks like a badly formed function type comment. + text = re.sub(r"^[ \t]*# +type: +\([^()]+(\)[ \t]*)?$", "", text, flags=re.MULTILINE) + + if isinstance(source, bytes): + return text.encode("latin1") + else: + return text + + +def common_dir_prefix(paths: list[str]) -> str: + if not paths: + return "." + cur = os.path.dirname(os.path.normpath(paths[0])) + for path in paths[1:]: + while True: + path = os.path.dirname(os.path.normpath(path)) + if (cur + os.sep).startswith(path + os.sep): + cur = path + break + return cur or "." + + +class AnnotationPrinter(TypeStrVisitor): + """Visitor used to print existing annotations in a file. + + The main difference from TypeStrVisitor is a better treatment of + unbound types. + + Notes: + * This visitor doesn't add imports necessary for annotations, this is done separately + by ImportTracker. + * It can print all kinds of types, but the generated strings may not be valid (notably + callable types) since it prints the same string that reveal_type() does. + * For Instance types it prints the fully qualified names. + """ + + # TODO: Generate valid string representation for callable types. + # TODO: Use short names for Instances. + def __init__( + self, + stubgen: BaseStubGenerator, + known_modules: list[str] | None = None, + local_modules: list[str] | None = None, + ) -> None: + super().__init__(options=mypy.options.Options()) + self.stubgen = stubgen + self.known_modules = known_modules + self.local_modules = local_modules or ["builtins"] + + def visit_any(self, t: AnyType) -> str: + s = super().visit_any(t) + self.stubgen.import_tracker.require_name(s) + return s + + def visit_unbound_type(self, t: UnboundType) -> str: + s = t.name + fullname = self.stubgen.resolve_name(s) + if fullname == "typing.Union": + return " | ".join([item.accept(self) for item in t.args]) + if fullname == "typing.Optional": + if len(t.args) == 1: + return f"{t.args[0].accept(self)} | None" + return self.stubgen.add_name("_typeshed.Incomplete") + if fullname in TYPING_BUILTIN_REPLACEMENTS: + s = self.stubgen.add_name(TYPING_BUILTIN_REPLACEMENTS[fullname], require=True) + if self.known_modules is not None and "." in s: + # see if this object is from any of the modules that we're currently processing. + # reverse sort so that subpackages come before parents: e.g. "foo.bar" before "foo". + for module_name in self.local_modules + sorted(self.known_modules, reverse=True): + if s.startswith(module_name + "."): + if module_name in self.local_modules: + s = s[len(module_name) + 1 :] + arg_module = module_name + break + else: + arg_module = s[: s.rindex(".")] + if arg_module not in self.local_modules: + self.stubgen.import_tracker.add_import(arg_module, require=True) + elif s == "NoneType": + # when called without analysis all types are unbound, so this won't hit + # visit_none_type(). + s = "None" + else: + self.stubgen.import_tracker.require_name(s) + if t.args: + s += f"[{self.args_str(t.args)}]" + elif t.empty_tuple_index: + s += "[()]" + return s + + def visit_none_type(self, t: NoneType) -> str: + return "None" + + def visit_type_list(self, t: TypeList) -> str: + return f"[{self.list_str(t.items)}]" + + def visit_union_type(self, t: UnionType) -> str: + return " | ".join([item.accept(self) for item in t.items]) + + def visit_unpack_type(self, t: UnpackType) -> str: + if self.options.python_version >= (3, 11): + return f"*{t.type.accept(self)}" + return super().visit_unpack_type(t) + + def args_str(self, args: Iterable[Type]) -> str: + """Convert an array of arguments to strings and join the results with commas. + + The main difference from list_str is the preservation of quotes for string + arguments + """ + types = ["builtins.bytes", "builtins.str"] + res = [] + for arg in args: + arg_str = arg.accept(self) + if isinstance(arg, UnboundType) and arg.original_str_fallback in types: + res.append(f"'{arg_str}'") + else: + res.append(arg_str) + return ", ".join(res) + + +class ClassInfo: + def __init__( + self, + name: str, + self_var: str, + docstring: str | None = None, + cls: type | None = None, + parent: ClassInfo | None = None, + ) -> None: + self.name = name + self.self_var = self_var + self.docstring = docstring + self.cls = cls + self.parent = parent + + +class FunctionContext: + def __init__( + self, + module_name: str, + name: str, + docstring: str | None = None, + is_abstract: bool = False, + class_info: ClassInfo | None = None, + ) -> None: + self.module_name = module_name + self.name = name + self.docstring = docstring + self.is_abstract = is_abstract + self.class_info = class_info + self._fullname: str | None = None + + @property + def fullname(self) -> str: + if self._fullname is None: + if self.class_info: + parents = [] + class_info: ClassInfo | None = self.class_info + while class_info is not None: + parents.append(class_info.name) + class_info = class_info.parent + namespace = ".".join(reversed(parents)) + self._fullname = f"{self.module_name}.{namespace}.{self.name}" + else: + self._fullname = f"{self.module_name}.{self.name}" + return self._fullname + + +def infer_method_ret_type(name: str) -> str | None: + """Infer return types for known special methods""" + if name.startswith("__") and name.endswith("__"): + name = name[2:-2] + if name in ("float", "bool", "bytes", "int", "complex", "str"): + return name + # Note: __eq__ and co may return arbitrary types, but bool is good enough for stubgen. + elif name in ("eq", "ne", "lt", "le", "gt", "ge", "contains"): + return "bool" + elif name in ("len", "length_hint", "index", "hash", "sizeof", "trunc", "floor", "ceil"): + return "int" + elif name in ("format", "repr"): + return "str" + elif name in ("init", "setitem", "del", "delitem"): + return "None" + return None + + +def infer_method_arg_types( + name: str, self_var: str = "self", arg_names: list[str] | None = None +) -> list[ArgSig] | None: + """Infer argument types for known special methods""" + args: list[ArgSig] | None = None + if name.startswith("__") and name.endswith("__"): + if arg_names and len(arg_names) >= 1 and arg_names[0] == "self": + arg_names = arg_names[1:] + + name = name[2:-2] + if name == "exit": + if arg_names is None: + arg_names = ["type", "value", "traceback"] + if len(arg_names) == 3: + arg_types = [ + "type[BaseException] | None", + "BaseException | None", + "types.TracebackType | None", + ] + args = [ + ArgSig(name=arg_name, type=arg_type) + for arg_name, arg_type in zip(arg_names, arg_types) + ] + if args is not None: + return [ArgSig(name=self_var)] + args + return None + + +@mypyc_attr(allow_interpreted_subclasses=True) +class SignatureGenerator: + """Abstract base class for extracting a list of FunctionSigs for each function.""" + + def remove_self_type( + self, inferred: list[FunctionSig] | None, self_var: str + ) -> list[FunctionSig] | None: + """Remove type annotation from self/cls argument""" + if inferred: + for signature in inferred: + if signature.args: + if signature.args[0].name == self_var: + signature.args[0].type = None + return inferred + + @abstractmethod + def get_function_sig( + self, default_sig: FunctionSig, ctx: FunctionContext + ) -> list[FunctionSig] | None: + """Return a list of signatures for the given function. + + If no signature can be found, return None. If all of the registered SignatureGenerators + for the stub generator return None, then the default_sig will be used. + """ + pass + + @abstractmethod + def get_property_type(self, default_type: str | None, ctx: FunctionContext) -> str | None: + """Return the type of the given property""" + pass + + +class ImportTracker: + """Record necessary imports during stub generation.""" + + def __init__(self) -> None: + # module_for['foo'] has the module name where 'foo' was imported from, or None if + # 'foo' is a module imported directly; + # direct_imports['foo'] is the module path used when the name 'foo' was added to the + # namespace. + # reverse_alias['foo'] is the name that 'foo' had originally when imported with an + # alias; examples + # 'from pkg import mod' ==> module_for['mod'] == 'pkg' + # 'from pkg import mod as m' ==> module_for['m'] == 'pkg' + # ==> reverse_alias['m'] == 'mod' + # 'import pkg.mod as m' ==> module_for['m'] == None + # ==> reverse_alias['m'] == 'pkg.mod' + # 'import pkg.mod' ==> module_for['pkg'] == None + # ==> module_for['pkg.mod'] == None + # ==> direct_imports['pkg'] == 'pkg.mod' + # ==> direct_imports['pkg.mod'] == 'pkg.mod' + self.module_for: dict[str, str | None] = {} + self.direct_imports: dict[str, str] = {} + self.reverse_alias: dict[str, str] = {} + + # required_names is the set of names that are actually used in a type annotation + self.required_names: set[str] = set() + + # Names that should be reexported if they come from another module + self.reexports: set[str] = set() + + def add_import_from( + self, module: str, names: list[tuple[str, str | None]], require: bool = False + ) -> None: + for name, alias in names: + if alias: + # 'from {module} import {name} as {alias}' + self.module_for[alias] = module + self.reverse_alias[alias] = name + else: + # 'from {module} import {name}' + self.module_for[name] = module + self.reverse_alias.pop(name, None) + if require: + self.require_name(alias or name) + self.direct_imports.pop(alias or name, None) + + def add_import(self, module: str, alias: str | None = None, require: bool = False) -> None: + if alias: + # 'import {module} as {alias}' + assert "." not in alias # invalid syntax + self.module_for[alias] = None + self.reverse_alias[alias] = module + if require: + self.required_names.add(alias) + else: + # 'import {module}' + name = module + if require: + self.required_names.add(name) + # add module and its parent packages + while name: + self.module_for[name] = None + self.direct_imports[name] = module + self.reverse_alias.pop(name, None) + name = name.rpartition(".")[0] + + def require_name(self, name: str) -> None: + while name not in self.direct_imports and "." in name: + name = name.rsplit(".", 1)[0] + self.required_names.add(name) + + def reexport(self, name: str) -> None: + """Mark a given non qualified name as needed in __all__. + + This means that in case it comes from a module, it should be + imported with an alias even if the alias is the same as the name. + """ + self.require_name(name) + self.reexports.add(name) + + def import_lines(self) -> list[str]: + """The list of required import lines (as strings with python code). + + In order for a module be included in this output, an identifier must be both + 'required' via require_name() and 'imported' via add_import_from() + or add_import() + """ + result = [] + + # To summarize multiple names imported from a same module, we collect those + # in the `module_map` dictionary, mapping a module path to the list of names that should + # be imported from it. the names can also be alias in the form 'original as alias' + module_map: Mapping[str, list[str]] = defaultdict(list) + + for name in sorted( + self.required_names, + key=lambda n: (self.reverse_alias[n], n) if n in self.reverse_alias else (n, ""), + ): + # If we haven't seen this name in an import statement, ignore it + if name not in self.module_for: + continue + + m = self.module_for[name] + if m is not None: + # This name was found in a from ... import ... + # Collect the name in the module_map + if name in self.reverse_alias: + name = f"{self.reverse_alias[name]} as {name}" + elif name in self.reexports: + name = f"{name} as {name}" + module_map[m].append(name) + else: + # This name was found in an import ... + # We can already generate the import line + if name in self.reverse_alias: + source = self.reverse_alias[name] + result.append(f"import {source} as {name}\n") + elif name in self.reexports: + assert "." not in name # Because reexports only has nonqualified names + result.append(f"import {name} as {name}\n") + else: + result.append(f"import {name}\n") + + # Now generate all the from ... import ... lines collected in module_map + for module, names in sorted(module_map.items()): + result.append(f"from {module} import {', '.join(sorted(names))}\n") + return result + + +@mypyc_attr(allow_interpreted_subclasses=True) +class BaseStubGenerator: + # These names should be omitted from generated stubs. + IGNORED_DUNDERS: Final = { + "__all__", + "__author__", + "__about__", + "__copyright__", + "__email__", + "__license__", + "__summary__", + "__title__", + "__uri__", + "__str__", + "__repr__", + "__getstate__", + "__setstate__", + "__slots__", + "__builtins__", + "__cached__", + "__file__", + "__name__", + "__package__", + "__path__", + "__spec__", + "__loader__", + } + TYPING_MODULE_NAMES: Final = ("typing", "typing_extensions") + # Special-cased names that are implicitly exported from the stub (from m import y as y). + EXTRA_EXPORTED: Final = { + "pyasn1_modules.rfc2437.univ", + "pyasn1_modules.rfc2459.char", + "pyasn1_modules.rfc2459.univ", + } + + def __init__( + self, + _all_: list[str] | None = None, + include_private: bool = False, + export_less: bool = False, + include_docstrings: bool = False, + ) -> None: + # Best known value of __all__. + self._all_ = _all_ + self._include_private = include_private + self._include_docstrings = include_docstrings + # Disable implicit exports of package-internal imports? + self.export_less = export_less + self._import_lines: list[str] = [] + self._output: list[str] = [] + # Current indent level (indent is hardcoded to 4 spaces). + self._indent = "" + self._toplevel_names: list[str] = [] + self.import_tracker = ImportTracker() + # Top-level members + self.defined_names: set[str] = set() + self.sig_generators = self.get_sig_generators() + # populated by visit_mypy_file + self.module_name: str = "" + # These are "soft" imports for objects which might appear in annotations but not have + # a corresponding import statement. + self.known_imports = { + "_typeshed": ["Incomplete"], + "typing": ["Any", "TypeVar", "NamedTuple", "TypedDict"], + "collections.abc": ["Generator"], + "typing_extensions": ["ParamSpec", "TypeVarTuple"], + } + + def get_sig_generators(self) -> list[SignatureGenerator]: + return [] + + def resolve_name(self, name: str) -> str: + """Return the full name resolving imports and import aliases.""" + if "." not in name: + real_module = self.import_tracker.module_for.get(name) + real_short = self.import_tracker.reverse_alias.get(name, name) + if real_module is None and real_short not in self.defined_names: + real_module = "builtins" # not imported and not defined, must be a builtin + else: + name_module, real_short = name.split(".", 1) + real_module = self.import_tracker.reverse_alias.get(name_module, name_module) + resolved_name = real_short if real_module is None else f"{real_module}.{real_short}" + return resolved_name + + def add_name(self, fullname: str, require: bool = True) -> str: + """Add a name to be imported and return the name reference. + + The import will be internal to the stub (i.e don't reexport). + """ + module, name = fullname.rsplit(".", 1) + alias = "_" + name if name in self.defined_names else None + while alias in self.defined_names: + alias = "_" + alias + if module != "builtins" or alias: # don't import from builtins unless needed + self.import_tracker.add_import_from(module, [(name, alias)], require=require) + return alias or name + + def add_import_line(self, line: str) -> None: + """Add a line of text to the import section, unless it's already there.""" + if line not in self._import_lines: + self._import_lines.append(line) + + def get_imports(self) -> str: + """Return the import statements for the stub.""" + imports = "" + if self._import_lines: + imports += "".join(self._import_lines) + imports += "".join(self.import_tracker.import_lines()) + return imports + + def output(self) -> str: + """Return the text for the stub.""" + pieces: list[str] = [] + if imports := self.get_imports(): + pieces.append(imports) + if dunder_all := self.get_dunder_all(): + pieces.append(dunder_all) + if self._output: + pieces.append("".join(self._output)) + return "\n".join(pieces) + + def get_dunder_all(self) -> str: + """Return the __all__ list for the stub.""" + if self._all_: + # Note we emit all names in the runtime __all__ here, even if they + # don't actually exist. If that happens, the runtime has a bug, and + # it's not obvious what the correct behavior should be. We choose + # to reflect the runtime __all__ as closely as possible. + return f"__all__ = {self._all_!r}\n" + return "" + + def add(self, string: str) -> None: + """Add text to generated stub.""" + self._output.append(string) + + def is_top_level(self) -> bool: + """Are we processing the top level of a file?""" + return self._indent == "" + + def indent(self) -> None: + """Add one level of indentation.""" + self._indent += " " + + def dedent(self) -> None: + """Remove one level of indentation.""" + self._indent = self._indent[:-4] + + def record_name(self, name: str) -> None: + """Mark a name as defined. + + This only does anything if at the top level of a module. + """ + if self.is_top_level(): + self._toplevel_names.append(name) + + def is_recorded_name(self, name: str) -> bool: + """Has this name been recorded previously?""" + return self.is_top_level() and name in self._toplevel_names + + def set_defined_names(self, defined_names: set[str]) -> None: + self.defined_names = defined_names + # Names in __all__ are required + for name in self._all_ or (): + self.import_tracker.reexport(name) + + for pkg, imports in self.known_imports.items(): + for t in imports: + # require=False means that the import won't be added unless require_name() is called + # for the object during generation. + self.add_name(f"{pkg}.{t}", require=False) + + def check_undefined_names(self) -> None: + undefined_names = [name for name in self._all_ or [] if name not in self._toplevel_names] + if undefined_names: + if self._output: + self.add("\n") + self.add("# Names in __all__ with no definition:\n") + for name in sorted(undefined_names): + self.add(f"# {name}\n") + + def get_signatures( + self, + default_signature: FunctionSig, + sig_generators: list[SignatureGenerator], + func_ctx: FunctionContext, + ) -> list[FunctionSig]: + for sig_gen in sig_generators: + inferred = sig_gen.get_function_sig(default_signature, func_ctx) + if inferred: + return inferred + + return [default_signature] + + def get_property_type( + self, + default_type: str | None, + sig_generators: list[SignatureGenerator], + func_ctx: FunctionContext, + ) -> str | None: + for sig_gen in sig_generators: + inferred = sig_gen.get_property_type(default_type, func_ctx) + if inferred: + return inferred + + return default_type + + def format_func_def( + self, + sigs: list[FunctionSig], + is_coroutine: bool = False, + decorators: list[str] | None = None, + docstring: str | None = None, + ) -> list[str]: + lines: list[str] = [] + if decorators is None: + decorators = [] + + for signature in sigs: + # dump decorators, just before "def ..." + for deco in decorators: + lines.append(f"{self._indent}{deco}") + + lines.append( + signature.format_sig( + indent=self._indent, + is_async=is_coroutine, + docstring=docstring, + include_docstrings=self._include_docstrings, + ) + ) + return lines + + def format_type_args(self, o: TypeAliasStmt | FuncDef | ClassDef) -> str: + if not o.type_args: + return "" + p = AnnotationPrinter(self) + type_args_list: list[str] = [] + for type_arg in o.type_args: + if type_arg.kind == PARAM_SPEC_KIND: + prefix = "**" + elif type_arg.kind == TYPE_VAR_TUPLE_KIND: + prefix = "*" + else: + prefix = "" + if type_arg.upper_bound: + bound_or_values = f": {type_arg.upper_bound.accept(p)}" + elif type_arg.values: + bound_or_values = f": ({', '.join(v.accept(p) for v in type_arg.values)})" + else: + bound_or_values = "" + if type_arg.default: + default = f" = {type_arg.default.accept(p)}" + else: + default = "" + type_args_list.append(f"{prefix}{type_arg.name}{bound_or_values}{default}") + return "[" + ", ".join(type_args_list) + "]" + + def print_annotation( + self, + t: Type, + known_modules: list[str] | None = None, + local_modules: list[str] | None = None, + ) -> str: + printer = AnnotationPrinter(self, known_modules, local_modules) + return t.accept(printer) + + def is_not_in_all(self, name: str) -> bool: + if self.is_private_name(name): + return False + if self._all_: + return self.is_top_level() and name not in self._all_ + return False + + def is_private_name(self, name: str, fullname: str | None = None) -> bool: + if "__mypy-" in name: + return True # Never include mypy generated symbols + if self._include_private: + return False + if fullname in self.EXTRA_EXPORTED: + return False + if name == "_": + return False + if not name.startswith("_"): + return False + if self._all_ and name in self._all_: + return False + if name.startswith("__") and name.endswith("__"): + return name in self.IGNORED_DUNDERS + return True + + def should_reexport(self, name: str, full_module: str, name_is_alias: bool) -> bool: + if ( + not name_is_alias + and self.module_name + and (self.module_name + "." + name) in self.EXTRA_EXPORTED + ): + # Special case certain names that should be exported, against our general rules. + return True + if name_is_alias: + return False + if self.export_less: + return False + if not self.module_name: + return False + is_private = self.is_private_name(name, full_module + "." + name) + if is_private: + return False + top_level = full_module.split(".")[0] + self_top_level = self.module_name.split(".", 1)[0] + if top_level not in (self_top_level, "_" + self_top_level): + # Export imports from the same package, since we can't reliably tell whether they + # are part of the public API. + return False + if self._all_: + return name in self._all_ + return True diff --git a/micromamba_root/Lib/site-packages/mypy/subtypes.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/subtypes.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e87225bd9c26686ee35f377995aa5f2a09f24976 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/subtypes.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/subtypes.py b/micromamba_root/Lib/site-packages/mypy/subtypes.py new file mode 100644 index 0000000000000000000000000000000000000000..66d7a95eb42525b1be163ab2fbfdc547b3bd4280 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/subtypes.py @@ -0,0 +1,2318 @@ +from __future__ import annotations + +from collections.abc import Callable, Iterable, Iterator +from contextlib import contextmanager +from typing import Any, Final, TypeAlias as _TypeAlias, TypeVar, cast + +import mypy.applytype +import mypy.constraints +import mypy.typeops +from mypy.checker_state import checker_state +from mypy.erasetype import erase_type +from mypy.expandtype import ( + expand_self_type, + expand_type, + expand_type_by_instance, + freshen_function_type_vars, +) +from mypy.maptype import map_instance_to_supertype + +# Circular import; done in the function instead. +# import mypy.solve +from mypy.nodes import ( + ARG_STAR, + ARG_STAR2, + CONTRAVARIANT, + COVARIANT, + INVARIANT, + VARIANCE_NOT_READY, + Context, + Decorator, + FuncBase, + OverloadedFuncDef, + TypeInfo, + Var, +) +from mypy.options import Options +from mypy.state import state +from mypy.types import ( + MYPYC_NATIVE_INT_NAMES, + TUPLE_LIKE_INSTANCE_NAMES, + TYPED_NAMEDTUPLE_NAMES, + AnyType, + CallableType, + DeletedType, + ErasedType, + FormalArgument, + FunctionLike, + Instance, + LiteralType, + NoneType, + NormalizedCallableType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeType, + TypeVarTupleType, + TypeVarType, + TypeVisitor, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + find_unpack_in_list, + flatten_nested_unions, + get_proper_type, + is_named_instance, + split_with_prefix_and_suffix, +) +from mypy.types_utils import flatten_types +from mypy.typestate import SubtypeKind, type_state +from mypy.typevars import fill_typevars, fill_typevars_with_any + +# Flags for detected protocol members +IS_SETTABLE: Final = 1 +IS_CLASSVAR: Final = 2 +IS_CLASS_OR_STATIC: Final = 3 +IS_VAR: Final = 4 +IS_EXPLICIT_SETTER: Final = 5 + +TypeParameterChecker: _TypeAlias = Callable[[Type, Type, int, bool, "SubtypeContext"], bool] + + +class SubtypeContext: + def __init__( + self, + *, + # Non-proper subtype flags + ignore_type_params: bool = False, + ignore_pos_arg_names: bool = False, + ignore_declared_variance: bool = False, + # Supported for both proper and non-proper + always_covariant: bool = False, + ignore_promotions: bool = False, + # Proper subtype flags + erase_instances: bool = False, + keep_erased_types: bool = False, + options: Options | None = None, + ) -> None: + self.ignore_type_params = ignore_type_params + self.ignore_pos_arg_names = ignore_pos_arg_names + self.ignore_declared_variance = ignore_declared_variance + self.always_covariant = always_covariant + self.ignore_promotions = ignore_promotions + self.erase_instances = erase_instances + self.keep_erased_types = keep_erased_types + self.options = options + + def check_context(self, proper_subtype: bool) -> None: + # Historically proper and non-proper subtypes were defined using different helpers + # and different visitors. Check if flag values are such that we definitely support. + if proper_subtype: + assert not self.ignore_pos_arg_names and not self.ignore_declared_variance + else: + assert not self.erase_instances and not self.keep_erased_types + + +def is_subtype( + left: Type, + right: Type, + *, + subtype_context: SubtypeContext | None = None, + ignore_type_params: bool = False, + ignore_pos_arg_names: bool = False, + ignore_declared_variance: bool = False, + always_covariant: bool = False, + ignore_promotions: bool = False, + options: Options | None = None, +) -> bool: + """Is 'left' subtype of 'right'? + + Also consider Any to be a subtype of any type, and vice versa. This + recursively applies to components of composite types (List[int] is subtype + of List[Any], for example). + + type_parameter_checker is used to check the type parameters (for example, + A with B in is_subtype(C[A], C[B]). The default checks for subtype relation + between the type arguments (e.g., A and B), taking the variance of the + type var into account. + """ + if left == right: + return True + if subtype_context is None: + subtype_context = SubtypeContext( + ignore_type_params=ignore_type_params, + ignore_pos_arg_names=ignore_pos_arg_names, + ignore_declared_variance=ignore_declared_variance, + always_covariant=always_covariant, + ignore_promotions=ignore_promotions, + options=options, + ) + else: + assert ( + not ignore_type_params + and not ignore_pos_arg_names + and not ignore_declared_variance + and not always_covariant + and not ignore_promotions + and options is None + ), "Don't pass both context and individual flags" + if type_state.is_assumed_subtype(left, right): + return True + if mypy.typeops.is_recursive_pair(left, right): + # This case requires special care because it may cause infinite recursion. + # Our view on recursive types is known under a fancy name of iso-recursive mu-types. + # Roughly this means that a recursive type is defined as an alias where right hand side + # can refer to the type as a whole, for example: + # A = Union[int, Tuple[A, ...]] + # and an alias unrolled once represents the *same type*, in our case all these represent + # the same type: + # A + # Union[int, Tuple[A, ...]] + # Union[int, Tuple[Union[int, Tuple[A, ...]], ...]] + # The algorithm for subtyping is then essentially under the assumption that left <: right, + # check that get_proper_type(left) <: get_proper_type(right). On the example above, + # If we start with: + # A = Union[int, Tuple[A, ...]] + # B = Union[int, Tuple[B, ...]] + # When checking if A <: B we push pair (A, B) onto 'assuming' stack, then when after few + # steps we come back to initial call is_subtype(A, B) and immediately return True. + with pop_on_exit(type_state.get_assumptions(is_proper=False), left, right): + return _is_subtype(left, right, subtype_context, proper_subtype=False) + return _is_subtype(left, right, subtype_context, proper_subtype=False) + + +def is_proper_subtype( + left: Type, + right: Type, + *, + subtype_context: SubtypeContext | None = None, + ignore_promotions: bool = False, + erase_instances: bool = False, + keep_erased_types: bool = False, +) -> bool: + """Is left a proper subtype of right? + + For proper subtypes, there's no need to rely on compatibility due to + Any types. Every usable type is a proper subtype of itself. + + If erase_instances is True, erase left instance *after* mapping it to supertype + (this is useful for runtime isinstance() checks). If keep_erased_types is True, + do not consider ErasedType a subtype of all types (used by type inference against unions). + """ + if left == right: + return True + if subtype_context is None: + subtype_context = SubtypeContext( + ignore_promotions=ignore_promotions, + erase_instances=erase_instances, + keep_erased_types=keep_erased_types, + ) + else: + assert ( + not ignore_promotions and not erase_instances and not keep_erased_types + ), "Don't pass both context and individual flags" + if type_state.is_assumed_proper_subtype(left, right): + return True + if mypy.typeops.is_recursive_pair(left, right): + # Same as for non-proper subtype, see detailed comment there for explanation. + with pop_on_exit(type_state.get_assumptions(is_proper=True), left, right): + return _is_subtype(left, right, subtype_context, proper_subtype=True) + return _is_subtype(left, right, subtype_context, proper_subtype=True) + + +def is_equivalent( + a: Type, + b: Type, + *, + ignore_type_params: bool = False, + ignore_pos_arg_names: bool = False, + options: Options | None = None, + subtype_context: SubtypeContext | None = None, +) -> bool: + return is_subtype( + a, + b, + ignore_type_params=ignore_type_params, + ignore_pos_arg_names=ignore_pos_arg_names, + options=options, + subtype_context=subtype_context, + ) and is_subtype( + b, + a, + ignore_type_params=ignore_type_params, + ignore_pos_arg_names=ignore_pos_arg_names, + options=options, + subtype_context=subtype_context, + ) + + +def is_same_type( + a: Type, b: Type, ignore_promotions: bool = True, subtype_context: SubtypeContext | None = None +) -> bool: + """Are these types proper subtypes of each other? + + This means types may have different representation (e.g. an alias, or + a non-simplified union) but are semantically exchangeable in all contexts. + """ + # First, use fast path for some common types. This is performance-critical. + if ( + type(a) is Instance + and type(b) is Instance + and a.type == b.type + and len(a.args) == len(b.args) + and a.last_known_value is b.last_known_value + ): + return all(is_same_type(x, y) for x, y in zip(a.args, b.args)) + elif ( + isinstance(a, TypeVarType) + and isinstance(b, TypeVarType) + and a.id == b.id + and a.upper_bound == b.upper_bound + ): + return True + + # Note that using ignore_promotions=True (default) makes types like int and int64 + # considered not the same type (which is the case at runtime). + # Also Union[bool, int] (if it wasn't simplified before) will be different + # from plain int, etc. + return is_proper_subtype( + a, b, ignore_promotions=ignore_promotions, subtype_context=subtype_context + ) and is_proper_subtype( + b, a, ignore_promotions=ignore_promotions, subtype_context=subtype_context + ) + + +# This is a common entry point for subtyping checks (both proper and non-proper). +# Never call this private function directly, use the public versions. +def _is_subtype( + left: Type, right: Type, subtype_context: SubtypeContext, proper_subtype: bool +) -> bool: + subtype_context.check_context(proper_subtype) + orig_right = right + orig_left = left + left = get_proper_type(left) + right = get_proper_type(right) + + # Note: Unpack type should not be a subtype of Any, since it may represent + # multiple types. This should always go through the visitor, to check arity. + if ( + not proper_subtype + and isinstance(right, (AnyType, UnboundType, ErasedType)) + and not isinstance(left, UnpackType) + ): + # TODO: should we consider all types proper subtypes of UnboundType and/or + # ErasedType as we do for non-proper subtyping. + return True + + if isinstance(right, UnionType) and not isinstance(left, UnionType): + # Normally, when 'left' is not itself a union, the only way + # 'left' can be a subtype of the union 'right' is if it is a + # subtype of one of the items making up the union. + if proper_subtype: + is_subtype_of_item = any( + is_proper_subtype(orig_left, item, subtype_context=subtype_context) + for item in right.items + ) + else: + is_subtype_of_item = any( + is_subtype(orig_left, item, subtype_context=subtype_context) + for item in right.items + ) + # Recombine rhs literal types, to make an enum type a subtype + # of a union of all enum items as literal types. Only do it if + # the previous check didn't succeed, since recombining can be + # expensive. + # `bool` is a special case, because `bool` is `Literal[True, False]`. + if ( + not is_subtype_of_item + and isinstance(left, Instance) + and (left.type.is_enum or left.type.fullname == "builtins.bool") + ): + right = UnionType( + mypy.typeops.try_contracting_literals_in_union(flatten_nested_unions(right.items)) + ) + if proper_subtype: + is_subtype_of_item = any( + is_proper_subtype(orig_left, item, subtype_context=subtype_context) + for item in right.items + ) + else: + is_subtype_of_item = any( + is_subtype(orig_left, item, subtype_context=subtype_context) + for item in right.items + ) + # However, if 'left' is a type variable T, T might also have + # an upper bound which is itself a union. This case will be + # handled below by the SubtypeVisitor. We have to check both + # possibilities, to handle both cases like T <: Union[T, U] + # and cases like T <: B where B is the upper bound of T and is + # a union. (See #2314.) + if not isinstance(left, TypeVarType): + return is_subtype_of_item + elif is_subtype_of_item: + return True + # otherwise, fall through + return left.accept(SubtypeVisitor(orig_right, subtype_context, proper_subtype)) + + +def check_type_parameter( + left: Type, right: Type, variance: int, proper_subtype: bool, subtype_context: SubtypeContext +) -> bool: + # It is safe to consider empty collection literals and similar as covariant, since + # such type can't be stored in a variable, see checker.is_valid_inferred_type(). + if variance == INVARIANT: + p_left = get_proper_type(left) + if isinstance(p_left, UninhabitedType) and p_left.ambiguous: + variance = COVARIANT + # If variance hasn't been inferred yet, we are lenient and default to + # covariance. This shouldn't happen often, but it's very difficult to + # avoid these cases altogether. + if variance == COVARIANT or variance == VARIANCE_NOT_READY: + if proper_subtype: + return is_proper_subtype(left, right, subtype_context=subtype_context) + else: + return is_subtype(left, right, subtype_context=subtype_context) + elif variance == CONTRAVARIANT: + if proper_subtype: + return is_proper_subtype(right, left, subtype_context=subtype_context) + else: + return is_subtype(right, left, subtype_context=subtype_context) + else: + if proper_subtype: + # We pass ignore_promotions=False because it is a default for subtype checks. + # The actual value will be taken from the subtype_context, and it is whatever + # the original caller passed. + return is_same_type( + left, right, ignore_promotions=False, subtype_context=subtype_context + ) + else: + return is_equivalent(left, right, subtype_context=subtype_context) + + +class SubtypeVisitor(TypeVisitor[bool]): + __slots__ = ( + "right", + "orig_right", + "proper_subtype", + "subtype_context", + "options", + "_subtype_kind", + ) + + def __init__(self, right: Type, subtype_context: SubtypeContext, proper_subtype: bool) -> None: + self.right = get_proper_type(right) + self.orig_right = right + self.proper_subtype = proper_subtype + self.subtype_context = subtype_context + self.options = subtype_context.options + self._subtype_kind = SubtypeVisitor.build_subtype_kind(subtype_context, proper_subtype) + + @staticmethod + def build_subtype_kind(subtype_context: SubtypeContext, proper_subtype: bool) -> SubtypeKind: + return ( + state.strict_optional, + proper_subtype, + subtype_context.ignore_type_params, + subtype_context.ignore_pos_arg_names, + subtype_context.ignore_declared_variance, + subtype_context.always_covariant, + subtype_context.ignore_promotions, + subtype_context.erase_instances, + subtype_context.keep_erased_types, + ) + + def _is_subtype(self, left: Type, right: Type) -> bool: + if self.proper_subtype: + return is_proper_subtype(left, right, subtype_context=self.subtype_context) + return is_subtype(left, right, subtype_context=self.subtype_context) + + def _all_subtypes(self, lefts: Iterable[Type], rights: Iterable[Type]) -> bool: + return all(self._is_subtype(li, ri) for (li, ri) in zip(lefts, rights)) + + # visit_x(left) means: is left (which is an instance of X) a subtype of right? + + def visit_unbound_type(self, left: UnboundType) -> bool: + # This can be called if there is a bad type annotation. The result probably + # doesn't matter much but by returning True we simplify these bad types away + # from unions, which could filter out some bogus messages. + return True + + def visit_any(self, left: AnyType) -> bool: + return isinstance(self.right, AnyType) if self.proper_subtype else True + + def visit_none_type(self, left: NoneType) -> bool: + if state.strict_optional: + if isinstance(self.right, NoneType) or is_named_instance( + self.right, "builtins.object" + ): + return True + if isinstance(self.right, Instance) and self.right.type.is_protocol: + members = self.right.type.protocol_members + # None is compatible with Hashable (and other similar protocols). This is + # slightly sloppy since we don't check the signature of "__hash__". + # None is also compatible with `SupportsStr` protocol. + return not members or all(member in ("__hash__", "__str__") for member in members) + return False + else: + return True + + def visit_uninhabited_type(self, left: UninhabitedType) -> bool: + return True + + def visit_erased_type(self, left: ErasedType) -> bool: + # This may be encountered during type inference. The result probably doesn't + # matter much. + # TODO: it actually does matter, figure out more principled logic about this. + return not self.subtype_context.keep_erased_types + + def visit_deleted_type(self, left: DeletedType) -> bool: + return True + + def visit_instance(self, left: Instance) -> bool: + if left.type.fallback_to_any and not self.proper_subtype: + # NOTE: `None` is a *non-subclassable* singleton, therefore no class + # can by a subtype of it, even with an `Any` fallback. + # This special case is needed to treat descriptors in classes with + # dynamic base classes correctly, see #5456. + return not isinstance(self.right, NoneType) + right = self.right + if isinstance(right, TupleType) and right.partial_fallback.type.is_enum: + return self._is_subtype(left, mypy.typeops.tuple_fallback(right)) + if isinstance(right, TupleType): + if len(right.items) == 1: + # Non-normalized Tuple type (may be left after semantic analysis + # because semanal_typearg visitor is not a type translator). + item = right.items[0] + if isinstance(item, UnpackType): + unpacked = get_proper_type(item.type) + if isinstance(unpacked, Instance): + return self._is_subtype(left, unpacked) + if left.type.has_base(right.partial_fallback.type.fullname): + if not self.proper_subtype: + # Special cases to consider: + # * Plain tuple[Any, ...] instance is a subtype of all tuple types. + # * Foo[*tuple[Any, ...]] (normalized) instance is a subtype of all + # tuples with fallback to Foo (e.g. for variadic NamedTuples). + mapped = map_instance_to_supertype(left, right.partial_fallback.type) + if is_erased_instance(mapped): + if ( + mapped.type.fullname == "builtins.tuple" + or mapped.type.has_type_var_tuple_type + ): + return True + return False + if isinstance(right, TypeVarTupleType): + # tuple[Any, ...] is like Any in the world of tuples (see special case above). + if left.type.has_base("builtins.tuple"): + mapped = map_instance_to_supertype(left, right.tuple_fallback.type) + if isinstance(get_proper_type(mapped.args[0]), AnyType): + return not self.proper_subtype + if isinstance(right, Instance): + if type_state.is_cached_subtype_check(self._subtype_kind, left, right): + return True + if type_state.is_cached_negative_subtype_check(self._subtype_kind, left, right): + return False + if not self.subtype_context.ignore_promotions and not right.type.is_protocol: + for base in left.type.mro: + if base._promote and any( + self._is_subtype(p, self.right) for p in base._promote + ): + type_state.record_subtype_cache_entry(self._subtype_kind, left, right) + return True + # Special case: Low-level integer types are compatible with 'int'. We can't + # use promotions, since 'int' is already promoted to low-level integer types, + # and we can't have circular promotions. + if left.type.alt_promote and left.type.alt_promote.type is right.type: + return True + rname = right.type.fullname + # Always try a nominal check if possible, + # there might be errors that a user wants to silence *once*. + # NamedTuples are a special case, because `NamedTuple` is not listed + # in `TypeInfo.mro`, so when `(a: NamedTuple) -> None` is used, + # we need to check for `is_named_tuple` property + if ( + left.type.has_base(rname) + or rname == "builtins.object" + or ( + rname in TYPED_NAMEDTUPLE_NAMES + and any(l.is_named_tuple for l in left.type.mro) + ) + ) and not self.subtype_context.ignore_declared_variance: + # Map left type to corresponding right instances. + t = map_instance_to_supertype(left, right.type) + if self.subtype_context.erase_instances: + erased = erase_type(t) + assert isinstance(erased, Instance) + t = erased + nominal = True + if right.type.has_type_var_tuple_type: + # For variadic instances we simply find the correct type argument mappings, + # all the heavy lifting is done by the tuple subtyping. + assert right.type.type_var_tuple_prefix is not None + assert right.type.type_var_tuple_suffix is not None + prefix = right.type.type_var_tuple_prefix + suffix = right.type.type_var_tuple_suffix + tvt = right.type.defn.type_vars[prefix] + assert isinstance(tvt, TypeVarTupleType) + fallback = tvt.tuple_fallback + left_prefix, left_middle, left_suffix = split_with_prefix_and_suffix( + t.args, prefix, suffix + ) + right_prefix, right_middle, right_suffix = split_with_prefix_and_suffix( + right.args, prefix, suffix + ) + left_args = ( + left_prefix + (TupleType(list(left_middle), fallback),) + left_suffix + ) + right_args = ( + right_prefix + (TupleType(list(right_middle), fallback),) + right_suffix + ) + if not self.proper_subtype and is_erased_instance(t): + return True + if len(left_args) != len(right_args): + return False + type_params = zip(left_args, right_args, right.type.defn.type_vars) + else: + type_params = zip(t.args, right.args, right.type.defn.type_vars) + if not self.subtype_context.ignore_type_params: + tried_infer = False + for lefta, righta, tvar in type_params: + if isinstance(tvar, TypeVarType): + if tvar.variance == VARIANCE_NOT_READY and not tried_infer: + infer_class_variances(right.type) + tried_infer = True + if ( + self.subtype_context.always_covariant + and tvar.variance == INVARIANT + ): + variance = COVARIANT + else: + variance = tvar.variance + if not check_type_parameter( + lefta, righta, variance, self.proper_subtype, self.subtype_context + ): + nominal = False + else: + # TODO: everywhere else ParamSpecs are handled as invariant. + if not check_type_parameter( + lefta, righta, COVARIANT, self.proper_subtype, self.subtype_context + ): + nominal = False + if nominal: + type_state.record_subtype_cache_entry(self._subtype_kind, left, right) + else: + type_state.record_negative_subtype_cache_entry(self._subtype_kind, left, right) + return nominal + if right.type.is_protocol and is_protocol_implementation( + left, right, proper_subtype=self.proper_subtype, options=self.options + ): + return True + # We record negative cache entry here, and not in the protocol check like we do for + # positive cache, to avoid accidentally adding a type that is not a structural + # subtype, but is a nominal subtype (involving type: ignore override). + type_state.record_negative_subtype_cache_entry(self._subtype_kind, left, right) + return False + if isinstance(right, TypeType): + item = right.item + if isinstance(item, TupleType): + item = mypy.typeops.tuple_fallback(item) + # TODO: this is a bit arbitrary, we should only skip Any-related cases. + if not self.proper_subtype: + if is_named_instance(left, "builtins.type"): + return self._is_subtype(TypeType(AnyType(TypeOfAny.special_form)), right) + if left.type.is_metaclass(): + if isinstance(item, AnyType): + return True + if isinstance(item, Instance): + return is_named_instance(item, "builtins.object") + if isinstance(right, LiteralType) and left.last_known_value is not None: + return self._is_subtype(left.last_known_value, right) + if isinstance(right, FunctionLike): + # Special case: Instance can be a subtype of Callable / Overloaded. + call = find_member("__call__", left, left, is_operator=True) + if call: + return self._is_subtype(call, right) + return False + else: + return False + + def visit_type_var(self, left: TypeVarType) -> bool: + right = self.right + if isinstance(right, TypeVarType) and left.id == right.id: + # Fast path for most common case. + if left.upper_bound == right.upper_bound: + return True + # Corner case for self-types in classes generic in type vars + # with value restrictions. + if left.id.is_self(): + return True + return self._is_subtype(left.upper_bound, right.upper_bound) + if left.values and self._is_subtype(UnionType.make_union(left.values), right): + return True + return self._is_subtype(left.upper_bound, self.right) + + def visit_param_spec(self, left: ParamSpecType) -> bool: + right = self.right + if ( + isinstance(right, ParamSpecType) + and right.id == left.id + and right.flavor == left.flavor + ): + return self._is_subtype(left.prefix, right.prefix) + if isinstance(right, Parameters) and are_trivial_parameters(right): + return True + return self._is_subtype(left.upper_bound, self.right) + + def visit_type_var_tuple(self, left: TypeVarTupleType) -> bool: + right = self.right + if isinstance(right, TypeVarTupleType) and right.id == left.id: + return left.min_len >= right.min_len + return self._is_subtype(left.upper_bound, self.right) + + def visit_unpack_type(self, left: UnpackType) -> bool: + # TODO: Ideally we should not need this (since it is not a real type). + # Instead callers (upper level types) should handle it when it appears in type list. + if isinstance(self.right, UnpackType): + return self._is_subtype(left.type, self.right.type) + if isinstance(self.right, Instance) and self.right.type.fullname == "builtins.object": + return True + return False + + def visit_parameters(self, left: Parameters) -> bool: + if isinstance(self.right, Parameters): + return are_parameters_compatible( + left, + self.right, + is_compat=self._is_subtype, + # TODO: this should pass the current value, but then couple tests fail. + is_proper_subtype=False, + ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names, + ) + elif isinstance(self.right, Instance): + return self.right.type.fullname == "builtins.object" + else: + return False + + def visit_callable_type(self, left: CallableType) -> bool: + right = self.right + if isinstance(right, CallableType): + if left.type_guard is not None and right.type_guard is not None: + if not self._is_subtype(left.type_guard, right.type_guard): + return False + elif left.type_is is not None and right.type_is is not None: + # For TypeIs we have to check both ways; it is unsafe to pass + # a TypeIs[Child] when a TypeIs[Parent] is expected, because + # if the narrower returns False, we assume that the narrowed value is + # *not* a Parent. + if not self._is_subtype(left.type_is, right.type_is) or not self._is_subtype( + right.type_is, left.type_is + ): + return False + elif right.type_guard is not None and left.type_guard is None: + # This means that one function has `TypeGuard` and other does not. + # They are not compatible. See https://github.com/python/mypy/issues/11307 + return False + elif right.type_is is not None and left.type_is is None: + # Similarly, if one function has `TypeIs` and the other does not, + # they are not compatible. + return False + return is_callable_compatible( + left, + right, + is_compat=self._is_subtype, + is_proper_subtype=self.proper_subtype, + ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names, + strict_concatenate=( + (self.options.extra_checks or self.options.strict_concatenate) + if self.options + else False + ), + ) + elif isinstance(right, Overloaded): + return all(self._is_subtype(left, item) for item in right.items) + elif isinstance(right, Instance): + if right.type.is_protocol and "__call__" in right.type.protocol_members: + # OK, a callable can implement a protocol with a `__call__` member. + call = find_member("__call__", right, right, is_operator=True) + assert call is not None + if self._is_subtype(left, call): + if len(right.type.protocol_members) == 1: + return True + if is_protocol_implementation(left.fallback, right, skip=["__call__"]): + return True + if right.type.is_protocol and left.is_type_obj(): + ret_type = get_proper_type(left.ret_type) + if isinstance(ret_type, TupleType): + ret_type = mypy.typeops.tuple_fallback(ret_type) + if isinstance(ret_type, Instance) and is_protocol_implementation( + ret_type, right, proper_subtype=self.proper_subtype, class_obj=True + ): + return True + return self._is_subtype(left.fallback, right) + elif isinstance(right, TypeType): + # This is unsound, we don't check the __init__ signature. + return left.is_type_obj() and self._is_subtype(left.ret_type, right.item) + else: + return False + + def visit_tuple_type(self, left: TupleType) -> bool: + right = self.right + if isinstance(right, Instance): + if is_named_instance(right, "typing.Sized"): + return True + elif is_named_instance(right, TUPLE_LIKE_INSTANCE_NAMES): + if right.args: + iter_type = right.args[0] + else: + if self.proper_subtype: + return False + iter_type = AnyType(TypeOfAny.special_form) + if is_named_instance(right, "builtins.tuple") and isinstance( + get_proper_type(iter_type), AnyType + ): + # TODO: We shouldn't need this special case. This is currently needed + # for isinstance(x, tuple), though it's unclear why. + return True + for li in left.items: + if isinstance(li, UnpackType): + unpack = get_proper_type(li.type) + if isinstance(unpack, TypeVarTupleType): + unpack = get_proper_type(unpack.upper_bound) + assert ( + isinstance(unpack, Instance) + and unpack.type.fullname == "builtins.tuple" + ) + li = unpack.args[0] + if not self._is_subtype(li, iter_type): + return False + return True + elif self._is_subtype(left.partial_fallback, right) and self._is_subtype( + mypy.typeops.tuple_fallback(left), right + ): + return True + return False + elif isinstance(right, TupleType): + # If right has a variadic unpack this needs special handling. If there is a TypeVarTuple + # unpack, item count must coincide. If the left has variadic unpack but right + # doesn't have one, we will fall through to False down the line. + if self.variadic_tuple_subtype(left, right): + return True + if len(left.items) != len(right.items): + return False + if any(not self._is_subtype(l, r) for l, r in zip(left.items, right.items)): + return False + if is_named_instance(right.partial_fallback, "builtins.tuple"): + # No need to verify fallback. This is useful since the calculated fallback + # may be inconsistent due to how we calculate joins between unions vs. + # non-unions. For example, join(int, str) == object, whereas + # join(Union[int, C], Union[str, C]) == Union[int, str, C]. + return True + if is_named_instance(left.partial_fallback, "builtins.tuple"): + # Again, no need to verify. At this point we know the right fallback + # is a subclass of tuple, so if left is plain tuple, it cannot be a subtype. + return False + # At this point we know both fallbacks are non-tuple. + return self._is_subtype(left.partial_fallback, right.partial_fallback) + else: + return False + + def variadic_tuple_subtype(self, left: TupleType, right: TupleType) -> bool: + """Check subtyping between two potentially variadic tuples. + + Most non-trivial cases here are due to variadic unpacks like *tuple[X, ...], + we handle such unpacks as infinite unions Tuple[()] | Tuple[X] | Tuple[X, X] | ... + + Note: the cases where right is fixed or has *Ts unpack should be handled + by the caller. + """ + right_unpack_index = find_unpack_in_list(right.items) + if right_unpack_index is None: + # This case should be handled by the caller. + return False + right_unpack = right.items[right_unpack_index] + assert isinstance(right_unpack, UnpackType) + right_unpacked = get_proper_type(right_unpack.type) + if not isinstance(right_unpacked, Instance): + # This case should be handled by the caller. + return False + assert right_unpacked.type.fullname == "builtins.tuple" + right_item = right_unpacked.args[0] + right_prefix = right_unpack_index + right_suffix = len(right.items) - right_prefix - 1 + left_unpack_index = find_unpack_in_list(left.items) + if left_unpack_index is None: + # Simple case: left is fixed, simply find correct mapping to the right + # (effectively selecting item with matching length from an infinite union). + if len(left.items) < right_prefix + right_suffix: + return False + prefix, middle, suffix = split_with_prefix_and_suffix( + tuple(left.items), right_prefix, right_suffix + ) + if not all( + self._is_subtype(li, ri) for li, ri in zip(prefix, right.items[:right_prefix]) + ): + return False + if right_suffix and not all( + self._is_subtype(li, ri) for li, ri in zip(suffix, right.items[-right_suffix:]) + ): + return False + return all(self._is_subtype(li, right_item) for li in middle) + else: + if len(left.items) < len(right.items): + # There are some items on the left that will never have a matching length + # on the right. + return False + left_prefix = left_unpack_index + left_suffix = len(left.items) - left_prefix - 1 + left_unpack = left.items[left_unpack_index] + assert isinstance(left_unpack, UnpackType) + left_unpacked = get_proper_type(left_unpack.type) + if not isinstance(left_unpacked, Instance): + # *Ts unpack can't be split, except if it is all mapped to Anys or objects. + if self.is_top_type(right_item): + right_prefix_types, middle, right_suffix_types = split_with_prefix_and_suffix( + tuple(right.items), left_prefix, left_suffix + ) + if not all( + self.is_top_type(ri) or isinstance(ri, UnpackType) for ri in middle + ): + return False + # Also check the tails match as well. + return self._all_subtypes( + left.items[:left_prefix], right_prefix_types + ) and self._all_subtypes(left.items[-left_suffix:], right_suffix_types) + return False + assert left_unpacked.type.fullname == "builtins.tuple" + left_item = left_unpacked.args[0] + + # The most tricky case with two variadic unpacks we handle similar to union + # subtyping: *each* item on the left, must be a subtype of *some* item on the right. + # For this we first check the "asymptotic case", i.e. that both unpacks a subtypes, + # and then check subtyping for all finite overlaps. + if not self._is_subtype(left_item, right_item): + return False + max_overlap = max(0, right_prefix - left_prefix, right_suffix - left_suffix) + for overlap in range(max_overlap + 1): + repr_items = left.items[:left_prefix] + [left_item] * overlap + if left_suffix: + repr_items += left.items[-left_suffix:] + left_repr = left.copy_modified(items=repr_items) + if not self._is_subtype(left_repr, right): + return False + return True + + def is_top_type(self, typ: Type) -> bool: + if not self.proper_subtype and isinstance(get_proper_type(typ), AnyType): + return True + return is_named_instance(typ, "builtins.object") + + def visit_typeddict_type(self, left: TypedDictType) -> bool: + right = self.right + if isinstance(right, Instance): + return self._is_subtype(left.fallback, right) + elif isinstance(right, TypedDictType): + if left == right: + return True # Fast path + if not left.names_are_wider_than(right): + return False + for name, l, r in left.zip(right): + # TODO: should we pass on the full subtype_context here and below? + right_readonly = name in right.readonly_keys + if not right_readonly: + if self.proper_subtype: + check = is_same_type(l, r) + else: + check = is_equivalent( + l, + r, + ignore_type_params=self.subtype_context.ignore_type_params, + options=self.options, + ) + else: + # Read-only items behave covariantly + check = self._is_subtype(l, r) + if not check: + return False + # Non-required key is not compatible with a required key since + # indexing may fail unexpectedly if a required key is missing. + # Required key is not compatible with a non-read-only non-required + # key since the prior doesn't support 'del' but the latter should + # support it. + # Required key is compatible with a read-only non-required key. + required_differ = (name in left.required_keys) != (name in right.required_keys) + if not right_readonly and required_differ: + return False + # Readonly fields check: + # + # A = TypedDict('A', {'x': ReadOnly[int]}) + # B = TypedDict('B', {'x': int}) + # def reset_x(b: B) -> None: + # b['x'] = 0 + # + # So, `A` cannot be a subtype of `B`, while `B` can be a subtype of `A`, + # because you can use `B` everywhere you use `A`, but not the other way around. + if name in left.readonly_keys and name not in right.readonly_keys: + return False + # (NOTE: Fallbacks don't matter.) + return True + else: + return False + + def visit_literal_type(self, left: LiteralType) -> bool: + if isinstance(self.right, LiteralType): + return left == self.right + else: + return self._is_subtype(left.fallback, self.right) + + def visit_overloaded(self, left: Overloaded) -> bool: + right = self.right + if isinstance(right, Instance): + if right.type.is_protocol and "__call__" in right.type.protocol_members: + # same as for CallableType + call = find_member("__call__", right, right, is_operator=True) + assert call is not None + if self._is_subtype(left, call): + if len(right.type.protocol_members) == 1: + return True + if is_protocol_implementation(left.fallback, right, skip=["__call__"]): + return True + return self._is_subtype(left.fallback, right) + elif isinstance(right, CallableType): + for item in left.items: + if self._is_subtype(item, right): + return True + return False + elif isinstance(right, Overloaded): + if left == self.right: + # When it is the same overload, then the types are equal. + return True + + # Ensure each overload on the right side (the supertype) is accounted for. + previous_match_left_index = -1 + matched_overloads = set() + + for right_item in right.items: + found_match = False + + for left_index, left_item in enumerate(left.items): + subtype_match = self._is_subtype(left_item, right_item) + + # Order matters: we need to make sure that the index of + # this item is at least the index of the previous one. + if subtype_match and previous_match_left_index <= left_index: + previous_match_left_index = left_index + found_match = True + matched_overloads.add(left_index) + break + else: + # If this one overlaps with the supertype in any way, but it wasn't + # an exact match, then it's a potential error. + strict_concat = ( + (self.options.extra_checks or self.options.strict_concatenate) + if self.options + else False + ) + if left_index not in matched_overloads and ( + is_callable_compatible( + left_item, + right_item, + is_compat=self._is_subtype, + is_proper_subtype=self.proper_subtype, + ignore_return=True, + ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names, + strict_concatenate=strict_concat, + ) + or is_callable_compatible( + right_item, + left_item, + is_compat=self._is_subtype, + is_proper_subtype=self.proper_subtype, + ignore_return=True, + ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names, + strict_concatenate=strict_concat, + ) + ): + return False + + if not found_match: + return False + return True + elif isinstance(right, UnboundType): + return True + elif isinstance(right, TypeType): + # All the items must have the same type object status, so + # it's sufficient to query only (any) one of them. + # This is unsound, we don't check all the __init__ signatures. + return left.is_type_obj() and self._is_subtype(left.items[0], right) + else: + return False + + def visit_union_type(self, left: UnionType) -> bool: + if isinstance(self.right, Instance): + literal_types: set[Instance] = set() + # avoid redundant check for union of literals + for item in left.relevant_items(): + p_item = get_proper_type(item) + lit_type = mypy.typeops.simple_literal_type(p_item) + if lit_type is not None: + if lit_type in literal_types: + continue + literal_types.add(lit_type) + item = lit_type + if not self._is_subtype(item, self.orig_right): + return False + return True + + elif isinstance(self.right, UnionType): + # prune literals early to avoid nasty quadratic behavior which would otherwise arise when checking + # subtype relationships between slightly different narrowings of an Enum + # we achieve O(N+M) instead of O(N*M) + + fast_check: set[ProperType] = set() + + for item in flatten_types(self.right.relevant_items()): + p_item = get_proper_type(item) + fast_check.add(p_item) + if isinstance(p_item, Instance) and p_item.last_known_value is not None: + fast_check.add(p_item.last_known_value) + + for item in left.relevant_items(): + p_item = get_proper_type(item) + if p_item in fast_check: + continue + lit_type = mypy.typeops.simple_literal_type(p_item) + if lit_type in fast_check: + continue + if not self._is_subtype(item, self.orig_right): + return False + return True + + return all(self._is_subtype(item, self.orig_right) for item in left.items) + + def visit_partial_type(self, left: PartialType) -> bool: + # This is indeterminate as we don't really know the complete type yet. + if self.proper_subtype: + # TODO: What's the right thing to do here? + return False + if left.type is None: + # Special case, partial `None`. This might happen when defining + # class-level attributes with explicit `None`. + # We can still recover from this. + # https://github.com/python/mypy/issues/11105 + return self.visit_none_type(NoneType()) + raise RuntimeError(f'Partial type "{left}" cannot be checked with "issubtype()"') + + def visit_type_type(self, left: TypeType) -> bool: + right = self.right + if left.is_type_form: + if isinstance(right, TypeType): + if not right.is_type_form: + return False + return self._is_subtype(left.item, right.item) + if isinstance(right, Instance): + if right.type.fullname == "builtins.object": + return True + return False + return False + else: # not left.is_type_form + if isinstance(right, TypeType): + return self._is_subtype(left.item, right.item) + if isinstance(right, Overloaded) and right.is_type_obj(): + # Same as in other direction: if it's a constructor callable, all + # items should belong to the same class' constructor, so it's enough + # to check one of them. + return self._is_subtype(left, right.items[0]) + if isinstance(right, CallableType): + if self.proper_subtype and not right.is_type_obj(): + # We can't accept `Type[X]` as a *proper* subtype of Callable[P, X] + # since this will break transitivity of subtyping. + return False + # This is unsound, we don't check the __init__ signature. + return self._is_subtype(left.item, right.ret_type) + + if isinstance(right, Instance): + if right.type.fullname in ["builtins.object", "builtins.type"]: + # TODO: Strictly speaking, the type builtins.type is considered equivalent to + # Type[Any]. However, this would break the is_proper_subtype check in + # conditional_types for cases like isinstance(x, type) when the type + # of x is Type[int]. It's unclear what's the right way to address this. + return True + item = left.item + if isinstance(item, TypeVarType): + item = get_proper_type(item.upper_bound) + if isinstance(item, Instance): + if right.type.is_protocol and is_protocol_implementation( + item, right, proper_subtype=self.proper_subtype, class_obj=True + ): + return True + metaclass = item.type.metaclass_type + return metaclass is not None and self._is_subtype(metaclass, right) + return False + + def visit_type_alias_type(self, left: TypeAliasType) -> bool: + assert False, f"This should be never called, got {left}" + + +T = TypeVar("T", bound=Type) + + +@contextmanager +def pop_on_exit(stack: list[tuple[T, T]], left: T, right: T) -> Iterator[None]: + stack.append((left, right)) + yield + stack.pop() + + +def is_protocol_implementation( + left: Instance, + right: Instance, + proper_subtype: bool = False, + class_obj: bool = False, + skip: list[str] | None = None, + options: Options | None = None, +) -> bool: + """Check whether 'left' implements the protocol 'right'. + + If 'proper_subtype' is True, then check for a proper subtype. + Treat recursive protocols by using the 'assuming' structural subtype matrix + (in sparse representation, i.e. as a list of pairs (subtype, supertype)), + see also comment in nodes.TypeInfo. When we enter a check for classes + (A, P), defined as following:: + + class P(Protocol): + def f(self) -> P: ... + class A: + def f(self) -> A: ... + + this results in A being a subtype of P without infinite recursion. + On every false result, we pop the assumption, thus avoiding an infinite recursion + as well. + """ + assert right.type.is_protocol + if skip is None: + skip = [] + # We need to record this check to generate protocol fine-grained dependencies. + type_state.record_protocol_subtype_check(left.type, right.type) + # nominal subtyping currently ignores '__init__' and '__new__' signatures + members_not_to_check = {"__init__", "__new__"} + members_not_to_check.update(skip) + # Trivial check that circumvents the bug described in issue 9771: + if left.type.is_protocol: + members_right = set(right.type.protocol_members) - members_not_to_check + members_left = set(left.type.protocol_members) - members_not_to_check + if not members_right.issubset(members_left): + return False + assuming = right.type.assuming_proper if proper_subtype else right.type.assuming + for l, r in reversed(assuming): + if l == left and r == right: + return True + with pop_on_exit(assuming, left, right): + for member in right.type.protocol_members: + if member in members_not_to_check: + continue + ignore_names = member != "__call__" # __call__ can be passed kwargs + # The third argument below indicates to what self type is bound. + # We always bind self to the subtype. (Similarly to nominal types). + supertype = find_member(member, right, left) + assert supertype is not None + + subtype = mypy.typeops.get_protocol_member(left, member, class_obj) + # Useful for debugging: + # print(member, 'of', left, 'has type', subtype) + # print(member, 'of', right, 'has type', supertype) + if not subtype: + return False + if not proper_subtype: + # Nominal check currently ignores arg names + # NOTE: If we ever change this, be sure to also change the call to + # SubtypeVisitor.build_subtype_kind(...) down below. + is_compat = is_subtype( + subtype, supertype, ignore_pos_arg_names=ignore_names, options=options + ) + else: + is_compat = is_proper_subtype(subtype, supertype) + if not is_compat: + return False + if isinstance(get_proper_type(subtype), NoneType) and isinstance( + get_proper_type(supertype), CallableType + ): + # We want __hash__ = None idiom to work even without --strict-optional + return False + subflags = get_member_flags(member, left, class_obj=class_obj) + superflags = get_member_flags(member, right) + if IS_SETTABLE in superflags: + # Check opposite direction for settable attributes. + if IS_EXPLICIT_SETTER in superflags: + supertype = find_member(member, right, left, is_lvalue=True) + if IS_EXPLICIT_SETTER in subflags: + subtype = mypy.typeops.get_protocol_member( + left, member, class_obj, is_lvalue=True + ) + # At this point we know attribute is present on subtype, otherwise we + # would return False above. + assert supertype is not None and subtype is not None + if not is_subtype(supertype, subtype, options=options): + return False + if IS_SETTABLE in superflags and IS_SETTABLE not in subflags: + return False + if not class_obj: + if IS_SETTABLE not in superflags: + if IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags: + return False + elif (IS_CLASSVAR in subflags) != (IS_CLASSVAR in superflags): + return False + else: + if IS_VAR in superflags and IS_CLASSVAR not in subflags: + # Only class variables are allowed for class object access. + return False + if IS_CLASSVAR in superflags: + # This can be never matched by a class object. + return False + # This rule is copied from nominal check in checker.py + if IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags: + return False + + if not proper_subtype: + # Nominal check currently ignores arg names, but __call__ is special for protocols + ignore_names = right.type.protocol_members != ["__call__"] + else: + ignore_names = False + subtype_kind = SubtypeVisitor.build_subtype_kind( + subtype_context=SubtypeContext(ignore_pos_arg_names=ignore_names), + proper_subtype=proper_subtype, + ) + type_state.record_subtype_cache_entry(subtype_kind, left, right) + return True + + +def find_member( + name: str, + itype: Instance, + subtype: Type, + *, + is_operator: bool = False, + class_obj: bool = False, + is_lvalue: bool = False, +) -> Type | None: + type_checker = checker_state.type_checker + if type_checker is None: + # Unfortunately, there are many scenarios where someone calls is_subtype() before + # type checking phase. In this case we fallback to old (incomplete) logic. + # TODO: reduce number of such cases (e.g. semanal_typeargs, post-semanal plugins). + return find_member_simple( + name, itype, subtype, is_operator=is_operator, class_obj=class_obj, is_lvalue=is_lvalue + ) + + # We don't use ATTR_DEFINED error code below (since missing attributes can cause various + # other error codes), instead we perform quick node lookup with all the fallbacks. + info = itype.type + sym = info.get(name) + node = sym.node if sym else None + if not node: + name_not_found = True + if ( + name not in ["__getattr__", "__setattr__", "__getattribute__"] + and not is_operator + and not class_obj + and itype.extra_attrs is None # skip ModuleType.__getattr__ + ): + for method_name in ("__getattribute__", "__getattr__"): + method = info.get_method(method_name) + if method and method.info.fullname != "builtins.object": + name_not_found = False + break + if name_not_found: + if info.fallback_to_any or class_obj and info.meta_fallback_to_any: + return AnyType(TypeOfAny.special_form) + if itype.extra_attrs and name in itype.extra_attrs.attrs: + return itype.extra_attrs.attrs[name] + return None + + from mypy.checkmember import ( + MemberContext, + analyze_class_attribute_access, + analyze_instance_member_access, + ) + + mx = MemberContext( + is_lvalue=is_lvalue, + is_super=False, + is_operator=is_operator, + original_type=TypeType.make_normalized(itype) if class_obj else itype, + self_type=TypeType.make_normalized(subtype) if class_obj else subtype, + context=Context(), # all errors are filtered, but this is a required argument + chk=type_checker, + suppress_errors=True, + # This is needed to avoid infinite recursion in situations involving protocols like + # class P(Protocol[T]): + # def combine(self, other: P[S]) -> P[Tuple[T, S]]: ... + # Normally we call freshen_all_functions_type_vars() during attribute access, + # to avoid type variable id collisions, but for protocols this means we can't + # use the assumption stack, that will grow indefinitely. + # TODO: find a cleaner solution that doesn't involve massive perf impact. + preserve_type_var_ids=True, + ) + with type_checker.msg.filter_errors(filter_deprecated=True): + if class_obj: + fallback = itype.type.metaclass_type or mx.named_type("builtins.type") + return analyze_class_attribute_access(itype, name, mx, mcs_fallback=fallback) + else: + return analyze_instance_member_access(name, itype, mx, info) + + +def find_member_simple( + name: str, + itype: Instance, + subtype: Type, + *, + is_operator: bool = False, + class_obj: bool = False, + is_lvalue: bool = False, +) -> Type | None: + """Find the type of member by 'name' in 'itype's TypeInfo. + + Find the member type after applying type arguments from 'itype', and binding + 'self' to 'subtype'. Return None if member was not found. + """ + info = itype.type + method = info.get_method(name) + if method: + if isinstance(method, Decorator): + return find_node_type(method.var, itype, subtype, class_obj=class_obj) + if method.is_property: + assert isinstance(method, OverloadedFuncDef) + dec = method.items[0] + assert isinstance(dec, Decorator) + # Pass on is_lvalue flag as this may be a property with different setter type. + return find_node_type( + dec.var, itype, subtype, class_obj=class_obj, is_lvalue=is_lvalue + ) + return find_node_type(method, itype, subtype, class_obj=class_obj) + else: + # don't have such method, maybe variable or decorator? + node = info.get(name) + v = node.node if node else None + if isinstance(v, Var): + return find_node_type(v, itype, subtype, class_obj=class_obj) + if ( + not v + and name not in ["__getattr__", "__setattr__", "__getattribute__"] + and not is_operator + and not class_obj + and itype.extra_attrs is None # skip ModuleType.__getattr__ + ): + for method_name in ("__getattribute__", "__getattr__"): + # Normally, mypy assumes that instances that define __getattr__ have all + # attributes with the corresponding return type. If this will produce + # many false negatives, then this could be prohibited for + # structural subtyping. + method = info.get_method(method_name) + if method and method.info.fullname != "builtins.object": + if isinstance(method, Decorator): + getattr_type = get_proper_type(find_node_type(method.var, itype, subtype)) + else: + getattr_type = get_proper_type(find_node_type(method, itype, subtype)) + if isinstance(getattr_type, CallableType): + return getattr_type.ret_type + return getattr_type + if itype.type.fallback_to_any or class_obj and itype.type.meta_fallback_to_any: + return AnyType(TypeOfAny.special_form) + if isinstance(v, TypeInfo): + # PEP 544 doesn't specify anything about such use cases. So we just try + # to do something meaningful (at least we should not crash). + return TypeType(fill_typevars_with_any(v)) + if itype.extra_attrs and name in itype.extra_attrs.attrs: + return itype.extra_attrs.attrs[name] + return None + + +def get_member_flags(name: str, itype: Instance, class_obj: bool = False) -> set[int]: + """Detect whether a member 'name' is settable, whether it is an + instance or class variable, and whether it is class or static method. + + The flags are defined as following: + * IS_SETTABLE: whether this attribute can be set, not set for methods and + non-settable properties; + * IS_CLASSVAR: set if the variable is annotated as 'x: ClassVar[t]'; + * IS_CLASS_OR_STATIC: set for methods decorated with @classmethod or + with @staticmethod. + """ + info = itype.type + method = info.get_method(name) + setattr_meth = info.get_method("__setattr__") + if method: + if isinstance(method, Decorator): + if method.var.is_staticmethod or method.var.is_classmethod: + return {IS_CLASS_OR_STATIC} + elif method.var.is_property: + return {IS_VAR} + elif method.is_property: # this could be settable property + assert isinstance(method, OverloadedFuncDef) + dec = method.items[0] + assert isinstance(dec, Decorator) + if dec.var.is_settable_property or setattr_meth: + flags = {IS_VAR, IS_SETTABLE} + if dec.var.setter_type is not None: + flags.add(IS_EXPLICIT_SETTER) + return flags + else: + return {IS_VAR} + return set() # Just a regular method + node = info.get(name) + if not node: + if setattr_meth: + return {IS_SETTABLE} + if itype.extra_attrs and name in itype.extra_attrs.attrs: + flags = set() + if name not in itype.extra_attrs.immutable: + flags.add(IS_SETTABLE) + return flags + return set() + v = node.node + # just a variable + if isinstance(v, Var): + if v.is_property: + return {IS_VAR} + flags = {IS_VAR} + if not v.is_final: + flags.add(IS_SETTABLE) + # TODO: define cleaner rules for class vs instance variables. + if v.is_classvar and not is_descriptor(v.type): + flags.add(IS_CLASSVAR) + if class_obj and v.is_inferred: + flags.add(IS_CLASSVAR) + return flags + return set() + + +def is_descriptor(typ: Type | None) -> bool: + typ = get_proper_type(typ) + if isinstance(typ, Instance): + return typ.type.get("__get__") is not None + if isinstance(typ, UnionType): + return all(is_descriptor(item) for item in typ.relevant_items()) + return False + + +def find_node_type( + node: Var | FuncBase, + itype: Instance, + subtype: Type, + class_obj: bool = False, + is_lvalue: bool = False, +) -> Type: + """Find type of a variable or method 'node' (maybe also a decorated method). + Apply type arguments from 'itype', and bind 'self' to 'subtype'. + """ + from mypy.typeops import bind_self + + if isinstance(node, FuncBase): + typ: Type | None = mypy.typeops.function_type( + node, fallback=Instance(itype.type.mro[-1], []) + ) + else: + # This part and the one below are simply copies of the logic from checkmember.py. + if node.is_settable_property and is_lvalue: + typ = node.setter_type + if typ is None and node.is_ready: + typ = node.type + else: + typ = node.type + if typ is not None: + typ = expand_self_type(node, typ, subtype) + p_typ = get_proper_type(typ) + if typ is None: + return AnyType(TypeOfAny.from_error) + # We don't need to bind 'self' for static methods, since there is no 'self'. + if isinstance(node, FuncBase) or ( + isinstance(p_typ, FunctionLike) + and node.is_initialized_in_class + and not node.is_staticmethod + ): + assert isinstance(p_typ, FunctionLike) + if class_obj and not ( + node.is_class if isinstance(node, FuncBase) else node.is_classmethod + ): + # Don't bind instance methods on class objects. + signature = p_typ + else: + signature = bind_self( + p_typ, subtype, is_classmethod=isinstance(node, Var) and node.is_classmethod + ) + if node.is_property and not class_obj: + assert isinstance(signature, CallableType) + if ( + isinstance(node, Var) + and node.is_settable_property + and is_lvalue + and node.setter_type is not None + ): + typ = signature.arg_types[0] + else: + typ = signature.ret_type + else: + typ = signature + itype = map_instance_to_supertype(itype, node.info) + typ = expand_type_by_instance(typ, itype) + return typ + + +def non_method_protocol_members(tp: TypeInfo) -> list[str]: + """Find all non-callable members of a protocol.""" + + assert tp.is_protocol + result: list[str] = [] + anytype = AnyType(TypeOfAny.special_form) + instance = Instance(tp, [anytype] * len(tp.defn.type_vars)) + + for member in tp.protocol_members: + typ = get_proper_type(find_member(member, instance, instance)) + if not isinstance(typ, (Overloaded, CallableType)): + result.append(member) + return result + + +def is_callable_compatible( + left: CallableType, + right: CallableType, + *, + is_compat: Callable[[Type, Type], bool], + is_proper_subtype: bool, + is_compat_return: Callable[[Type, Type], bool] | None = None, + ignore_return: bool = False, + ignore_pos_arg_names: bool = False, + check_args_covariantly: bool = False, + allow_partial_overlap: bool = False, + strict_concatenate: bool = False, +) -> bool: + """Is the left compatible with the right, using the provided compatibility check? + + is_compat: + The check we want to run against the parameters. + + is_compat_return: + The check we want to run against the return type. + If None, use the 'is_compat' check. + + check_args_covariantly: + If true, check if the left's args is compatible with the right's + instead of the other way around (contravariantly). + + This function is mostly used to check if the left is a subtype of the right which + is why the default is to check the args contravariantly. However, it's occasionally + useful to check the args using some other check, so we leave the variance + configurable. + + For example, when checking the validity of overloads, it's useful to see if + the first overload alternative has more precise arguments than the second. + We would want to check the arguments covariantly in that case. + + Note! The following two function calls are NOT equivalent: + + is_callable_compatible(f, g, is_compat=is_subtype, check_args_covariantly=False) + is_callable_compatible(g, f, is_compat=is_subtype, check_args_covariantly=True) + + The two calls are similar in that they both check the function arguments in + the same direction: they both run `is_subtype(argument_from_g, argument_from_f)`. + + However, the two calls differ in which direction they check things like + keyword arguments. For example, suppose f and g are defined like so: + + def f(x: int, *y: int) -> int: ... + def g(x: int) -> int: ... + + In this case, the first call will succeed and the second will fail: f is a + valid stand-in for g but not vice-versa. + + allow_partial_overlap: + By default this function returns True if and only if *all* calls to left are + also calls to right (with respect to the provided 'is_compat' function). + + If this parameter is set to 'True', we return True if *there exists at least one* + call to left that's also a call to right. + + In other words, we perform an existential check instead of a universal one; + we require left to only overlap with right instead of being a subset. + + For example, suppose we set 'is_compat' to some subtype check and compare following: + + f(x: float, y: str = "...", *args: bool) -> str + g(*args: int) -> str + + This function would normally return 'False': f is not a subtype of g. + However, we would return True if this parameter is set to 'True': the two + calls are compatible if the user runs "f_or_g(3)". In the context of that + specific call, the two functions effectively have signatures of: + + f2(float) -> str + g2(int) -> str + + Here, f2 is a valid subtype of g2 so we return True. + + Specifically, if this parameter is set this function will: + + - Ignore optional arguments on either the left or right that have no + corresponding match. + - No longer mandate optional arguments on either side are also optional + on the other. + - No longer mandate that if right has a *arg or **kwarg that left must also + have the same. + + Note: when this argument is set to True, this function becomes "symmetric" -- + the following calls are equivalent: + + is_callable_compatible(f, g, + is_compat=some_check, + check_args_covariantly=False, + allow_partial_overlap=True) + is_callable_compatible(g, f, + is_compat=some_check, + check_args_covariantly=True, + allow_partial_overlap=True) + + If the 'some_check' function is also symmetric, the two calls would be equivalent + whether or not we check the args covariantly. + """ + # Normalize both types before comparing them. + left = left.with_unpacked_kwargs().with_normalized_var_args() + right = right.with_unpacked_kwargs().with_normalized_var_args() + + if is_compat_return is None: + is_compat_return = is_compat + + # If either function is implicitly typed, ignore positional arg names too + if left.implicit or right.implicit: + ignore_pos_arg_names = True + + # Non-type cannot be a subtype of type. + if right.is_type_obj() and not left.is_type_obj() and not allow_partial_overlap: + return False + + # A callable L is a subtype of a generic callable R if L is a + # subtype of every type obtained from R by substituting types for + # the variables of R. We can check this by simply leaving the + # generic variables of R as type variables, effectively varying + # over all possible values. + + # It's okay even if these variables share ids with generic + # type variables of L, because generating and solving + # constraints for the variables of L to make L a subtype of R + # (below) treats type variables on the two sides as independent. + if left.variables: + # Apply generic type variables away in left via type inference. + unified = unify_generic_callable(left, right, ignore_return=ignore_return) + if unified is None: + return False + left = unified + + # Check return types. + if not ignore_return and not is_compat_return(left.ret_type, right.ret_type): + return False + + if check_args_covariantly: + is_compat = flip_compat_check(is_compat) + + if not strict_concatenate and (left.from_concatenate or right.from_concatenate): + strict_concatenate_check = False + else: + strict_concatenate_check = True + + return are_parameters_compatible( + left, + right, + is_compat=is_compat, + is_proper_subtype=is_proper_subtype, + ignore_pos_arg_names=ignore_pos_arg_names, + allow_partial_overlap=allow_partial_overlap, + strict_concatenate_check=strict_concatenate_check, + ) + + +def are_trivial_parameters(param: Parameters | NormalizedCallableType) -> bool: + param_star = param.var_arg() + param_star2 = param.kw_arg() + return ( + param.arg_kinds == [ARG_STAR, ARG_STAR2] + and param_star is not None + and isinstance(get_proper_type(param_star.typ), AnyType) + and param_star2 is not None + and isinstance(get_proper_type(param_star2.typ), AnyType) + ) + + +def is_trivial_suffix(param: Parameters | NormalizedCallableType) -> bool: + param_star = param.var_arg() + param_star2 = param.kw_arg() + return ( + param.arg_kinds[-2:] == [ARG_STAR, ARG_STAR2] + and param_star is not None + and isinstance(get_proper_type(param_star.typ), AnyType) + and param_star2 is not None + and isinstance(get_proper_type(param_star2.typ), AnyType) + ) + + +def are_parameters_compatible( + left: Parameters | NormalizedCallableType, + right: Parameters | NormalizedCallableType, + *, + is_compat: Callable[[Type, Type], bool], + is_proper_subtype: bool, + ignore_pos_arg_names: bool = False, + allow_partial_overlap: bool = False, + strict_concatenate_check: bool = False, +) -> bool: + """Helper function for is_callable_compatible, used for Parameter compatibility""" + if right.is_ellipsis_args and not is_proper_subtype: + return True + + left_star = left.var_arg() + left_star2 = left.kw_arg() + right_star = right.var_arg() + right_star2 = right.kw_arg() + + # Treat "def _(*a: Any, **kw: Any) -> X" similarly to "Callable[..., X]" + if are_trivial_parameters(right) and not is_proper_subtype: + return True + trivial_suffix = is_trivial_suffix(right) and not is_proper_subtype + + trivial_vararg_suffix = False + if ( + right.arg_kinds[-1:] == [ARG_STAR] + and isinstance(get_proper_type(right.arg_types[-1]), AnyType) + and not is_proper_subtype + and all(k.is_positional(star=True) for k in left.arg_kinds) + ): + # Similar to how (*Any, **Any) is considered a supertype of all callables, we consider + # (*Any) a supertype of all callables with positional arguments. This is needed in + # particular because we often refuse to try type inference if actual type is not + # a subtype of erased template type. + trivial_vararg_suffix = True + + # Match up corresponding arguments and check them for compatibility. In + # every pair (argL, argR) of corresponding arguments from L and R, argL must + # be "more general" than argR if L is to be a subtype of R. + + # Arguments are corresponding if they either share a name, share a position, + # or both. If L's corresponding argument is ambiguous, L is not a subtype of R. + + # If left has one corresponding argument by name and another by position, + # consider them to be one "merged" argument (and not ambiguous) if they're + # both optional, they're name-only and position-only respectively, and they + # have the same type. This rule allows functions with (*args, **kwargs) to + # properly stand in for the full domain of formal arguments that they're + # used for in practice. + + # Every argument in R must have a corresponding argument in L, and every + # required argument in L must have a corresponding argument in R. + + # Phase 1: Confirm every argument in R has a corresponding argument in L. + + # Phase 1a: If left and right can both accept an infinite number of args, + # their types must be compatible. + # + # Furthermore, if we're checking for compatibility in all cases, + # we confirm that if R accepts an infinite number of arguments, + # L must accept the same. + def _incompatible(left_arg: FormalArgument | None, right_arg: FormalArgument | None) -> bool: + if right_arg is None: + return False + if left_arg is None: + return not allow_partial_overlap and not trivial_suffix + return not is_compat(right_arg.typ, left_arg.typ) + + if ( + _incompatible(left_star, right_star) + and not trivial_vararg_suffix + or _incompatible(left_star2, right_star2) + ): + return False + + # Phase 1b: Check non-star args: for every arg right can accept, left must + # also accept. The only exception is if we are allowing partial + # overlaps: in that case, we ignore optional args on the right. + for right_arg in right.formal_arguments(): + left_arg = mypy.typeops.callable_corresponding_argument(left, right_arg) + if left_arg is None: + if allow_partial_overlap and not right_arg.required: + continue + return False + if not are_args_compatible( + left_arg, + right_arg, + is_compat, + ignore_pos_arg_names=ignore_pos_arg_names, + allow_partial_overlap=allow_partial_overlap, + allow_imprecise_kinds=right.imprecise_arg_kinds, + ): + return False + + if trivial_suffix: + # For trivial right suffix we *only* check that every non-star right argument + # has a valid match on the left. + return True + + # Phase 1c: Check var args. Right has an infinite series of optional positional + # arguments. Get all further positional args of left, and make sure + # they're more general than the corresponding member in right. + # TODO: handle suffix in UnpackType (i.e. *args: *Tuple[Ts, X, Y]). + if right_star is not None and not trivial_vararg_suffix: + # Synthesize an anonymous formal argument for the right + right_by_position = right.try_synthesizing_arg_from_vararg(None) + assert right_by_position is not None + + i = right_star.pos + assert i is not None + while i < len(left.arg_kinds) and left.arg_kinds[i].is_positional(): + if allow_partial_overlap and left.arg_kinds[i].is_optional(): + break + + left_by_position = left.argument_by_position(i) + assert left_by_position is not None + + if not are_args_compatible( + left_by_position, + right_by_position, + is_compat, + ignore_pos_arg_names=ignore_pos_arg_names, + allow_partial_overlap=allow_partial_overlap, + ): + return False + i += 1 + + # Phase 1d: Check kw args. Right has an infinite series of optional named + # arguments. Get all further named args of left, and make sure + # they're more general than the corresponding member in right. + if right_star2 is not None: + right_names = {name for name in right.arg_names if name is not None} + left_only_names = set() + for name, kind in zip(left.arg_names, left.arg_kinds): + if ( + name is None + or kind.is_star() + or name in right_names + or not strict_concatenate_check + ): + continue + left_only_names.add(name) + + # Synthesize an anonymous formal argument for the right + right_by_name = right.try_synthesizing_arg_from_kwarg(None) + assert right_by_name is not None + + for name in left_only_names: + left_by_name = left.argument_by_name(name) + assert left_by_name is not None + + if allow_partial_overlap and not left_by_name.required: + continue + + if not are_args_compatible( + left_by_name, + right_by_name, + is_compat, + ignore_pos_arg_names=ignore_pos_arg_names, + allow_partial_overlap=allow_partial_overlap, + ): + return False + + # Phase 2: Left must not impose additional restrictions. + # (Every required argument in L must have a corresponding argument in R) + # Note: we already checked the *arg and **kwarg arguments in phase 1a. + for left_arg in left.formal_arguments(): + right_by_name = ( + right.argument_by_name(left_arg.name) if left_arg.name is not None else None + ) + + right_by_pos = ( + right.argument_by_position(left_arg.pos) if left_arg.pos is not None else None + ) + + # If the left hand argument corresponds to two right-hand arguments, + # neither of them can be required. + if ( + right_by_name is not None + and right_by_pos is not None + and right_by_name != right_by_pos + and (right_by_pos.required or right_by_name.required) + and strict_concatenate_check + and not right.imprecise_arg_kinds + ): + return False + + # All *required* left-hand arguments must have a corresponding + # right-hand argument. Optional args do not matter. + if left_arg.required and right_by_pos is None and right_by_name is None: + return False + + return True + + +def are_args_compatible( + left: FormalArgument, + right: FormalArgument, + is_compat: Callable[[Type, Type], bool], + *, + ignore_pos_arg_names: bool, + allow_partial_overlap: bool, + allow_imprecise_kinds: bool = False, +) -> bool: + if left.required and right.required: + # If both arguments are required allow_partial_overlap has no effect. + allow_partial_overlap = False + + def is_different( + left_item: object | None, right_item: object | None, allow_overlap: bool + ) -> bool: + """Checks if the left and right items are different. + + If the right item is unspecified (e.g. if the right callable doesn't care + about what name or position its arg has), we default to returning False. + + If we're allowing partial overlap, we also default to returning False + if the left callable also doesn't care.""" + if right_item is None: + return False + if allow_overlap and left_item is None: + return False + return left_item != right_item + + # If right has a specific name it wants this argument to be, left must + # have the same. + if is_different(left.name, right.name, allow_partial_overlap): + # But pay attention to whether we're ignoring positional arg names + if not ignore_pos_arg_names or right.pos is None: + return False + + # If right is at a specific position, left must have the same. + # TODO: partial overlap logic is flawed for positions. + # We disable it to avoid false positives at a cost of few false negatives. + if is_different(left.pos, right.pos, allow_overlap=False) and not allow_imprecise_kinds: + return False + + # If right's argument is optional, left's must also be + # (unless we're relaxing the checks to allow potential + # rather than definite compatibility). + if not allow_partial_overlap and not right.required and left.required: + return False + + # If we're allowing partial overlaps and neither arg is required, + # the types don't actually need to be the same + if allow_partial_overlap and not left.required and not right.required: + return True + + # Left must have a more general type + return is_compat(right.typ, left.typ) + + +def flip_compat_check(is_compat: Callable[[Type, Type], bool]) -> Callable[[Type, Type], bool]: + def new_is_compat(left: Type, right: Type) -> bool: + return is_compat(right, left) + + return new_is_compat + + +def unify_generic_callable( + type: NormalizedCallableType, + target: NormalizedCallableType, + ignore_return: bool, + return_constraint_direction: int | None = None, +) -> NormalizedCallableType | None: + """Try to unify a generic callable type with another callable type. + + Return unified CallableType if successful; otherwise, return None. + """ + import mypy.solve + + if set(type.type_var_ids()) & {v.id for v in mypy.typeops.get_all_type_vars(target)}: + # Overload overlap check does nasty things like unifying in opposite direction. + # This can easily create type variable clashes, so we need to refresh. + type = freshen_function_type_vars(type) + + if return_constraint_direction is None: + return_constraint_direction = mypy.constraints.SUBTYPE_OF + + constraints: list[mypy.constraints.Constraint] = [] + # There is some special logic for inference in callables, so better use them + # as wholes instead of picking separate arguments. + cs = mypy.constraints.infer_constraints( + type.copy_modified(ret_type=UninhabitedType()), + target.copy_modified(ret_type=UninhabitedType()), + mypy.constraints.SUBTYPE_OF, + skip_neg_op=True, + ) + constraints.extend(cs) + if not ignore_return: + c = mypy.constraints.infer_constraints( + type.ret_type, target.ret_type, return_constraint_direction + ) + constraints.extend(c) + inferred_vars, _ = mypy.solve.solve_constraints( + type.variables, constraints, allow_polymorphic=True + ) + if None in inferred_vars: + return None + non_none_inferred_vars = cast(list[Type], inferred_vars) + had_errors = False + + def report(*args: Any) -> None: + nonlocal had_errors + had_errors = True + + # This function may be called by the solver, so we need to allow erased types here. + # We anyway allow checking subtyping between other types containing + # (probably also because solver needs subtyping). See also comment in + # ExpandTypeVisitor.visit_erased_type(). + applied = mypy.applytype.apply_generic_arguments( + type, non_none_inferred_vars, report, context=target + ) + if had_errors: + return None + return cast(NormalizedCallableType, applied) + + +def try_restrict_literal_union(t: UnionType, s: Type) -> list[Type] | None: + """Return the items of t, excluding any occurrence of s, if and only if + - t only contains simple literals + - s is a simple literal + + Otherwise, returns None + """ + ps = get_proper_type(s) + if not mypy.typeops.is_simple_literal(ps): + return None + + new_items: list[Type] = [] + for i in t.relevant_items(): + pi = get_proper_type(i) + if not mypy.typeops.is_simple_literal(pi): + return None + if pi != ps: + new_items.append(i) + return new_items + + +def restrict_subtype_away(t: Type, s: Type, *, consider_runtime_isinstance: bool = True) -> Type: + """Return t minus s for runtime type assertions. + + If we can't determine a precise result, return a supertype of the + ideal result (just t is a valid result). + + This is used for type inference of runtime type checks such as + isinstance(). Currently, this just removes elements of a union type. + """ + p_t = get_proper_type(t) + if isinstance(p_t, UnionType): + new_items = try_restrict_literal_union(p_t, s) + if new_items is None: + new_items = [ + restrict_subtype_away( + item, s, consider_runtime_isinstance=consider_runtime_isinstance + ) + for item in p_t.relevant_items() + ] + return UnionType.make_union( + [item for item in new_items if not isinstance(get_proper_type(item), UninhabitedType)] + ) + elif isinstance(p_t, TypeVarType): + return p_t.copy_modified(upper_bound=restrict_subtype_away(p_t.upper_bound, s)) + + if consider_runtime_isinstance: + if covers_at_runtime(t, s): + return UninhabitedType() + else: + return t + else: + if is_proper_subtype(t, s, ignore_promotions=True): + return UninhabitedType() + if is_proper_subtype(t, s, ignore_promotions=True, erase_instances=True): + return UninhabitedType() + return t + + +def covers_at_runtime(item: Type, supertype: Type) -> bool: + """Will isinstance(item, supertype) always return True at runtime?""" + item = get_proper_type(item) + supertype = get_proper_type(supertype) + + # Since runtime type checks will ignore type arguments, erase the types. + if not (isinstance(supertype, FunctionLike) and supertype.is_type_obj()): + supertype = erase_type(supertype) + if is_proper_subtype( + erase_type(item), supertype, ignore_promotions=True, erase_instances=True + ): + return True + if isinstance(supertype, Instance): + if supertype.type.is_protocol: + # TODO: Implement more robust support for runtime isinstance() checks, see issue #3827. + if is_proper_subtype(item, supertype, ignore_promotions=True): + return True + if isinstance(item, TypedDictType): + # Special case useful for selecting TypedDicts from unions using isinstance(x, dict). + if supertype.type.fullname == "builtins.dict": + return True + elif isinstance(item, TypeVarType): + if is_proper_subtype(item.upper_bound, supertype, ignore_promotions=True): + return True + elif isinstance(item, Instance) and supertype.type.fullname == "builtins.int": + # "int" covers all native int types + if item.type.fullname in MYPYC_NATIVE_INT_NAMES: + return True + # TODO: Add more special cases. + return False + + +def is_more_precise(left: Type, right: Type, *, ignore_promotions: bool = False) -> bool: + """Check if left is a more precise type than right. + + A left is a proper subtype of right, left is also more precise than + right. Also, if right is Any, left is more precise than right, for + any left. + """ + # TODO Should List[int] be more precise than List[Any]? + right = get_proper_type(right) + if isinstance(right, AnyType): + return True + return is_proper_subtype(left, right, ignore_promotions=ignore_promotions) + + +def all_non_object_members(info: TypeInfo) -> set[str]: + members = set(info.names) + for base in info.mro[1:-1]: + members.update(base.names) + return members + + +def infer_variance(info: TypeInfo, i: int) -> bool: + """Infer the variance of the ith type variable of a generic class. + + Return True if successful. This can fail if some inferred types aren't ready. + """ + object_type = Instance(info.mro[-1], []) + + for variance in COVARIANT, CONTRAVARIANT, INVARIANT: + tv = info.defn.type_vars[i] + assert isinstance(tv, TypeVarType) + if tv.variance != VARIANCE_NOT_READY: + continue + tv.variance = variance + co = True + contra = True + tvar = info.defn.type_vars[i] + self_type = fill_typevars(info) + for member in all_non_object_members(info): + # __mypy-replace is an implementation detail of the dataclass plugin + if member in ("__init__", "__new__", "__mypy-replace"): + continue + + if isinstance(self_type, TupleType): + self_type = mypy.typeops.tuple_fallback(self_type) + flags = get_member_flags(member, self_type) + settable = IS_SETTABLE in flags + + node = info[member].node + if isinstance(node, Var): + if node.type is None: + tv.variance = VARIANCE_NOT_READY + return False + if has_underscore_prefix(member): + # Special case to avoid false positives (and to pass conformance tests) + settable = False + + # TODO: handle settable properties with setter type different from getter. + typ = find_member(member, self_type, self_type) + if typ: + # It's okay for a method in a generic class with a contravariant type + # variable to return a generic instance of the class, if it doesn't involve + # variance (i.e. values of type variables are propagated). Our normal rules + # would disallow this. Replace such return types with 'Any' to allow this. + # + # This could probably be more lenient (e.g. allow self type be nested, don't + # require all type arguments to be identical to self_type), but this will + # hopefully cover the vast majority of such cases, including Self. + typ = erase_return_self_types(typ, self_type) + + typ2 = expand_type(typ, {tvar.id: object_type}) + if not is_subtype(typ, typ2): + co = False + if not is_subtype(typ2, typ): + contra = False + if settable: + co = False + + # Infer variance from base classes, in case they have explicit variances + for base in info.bases: + base2 = expand_type(base, {tvar.id: object_type}) + if not is_subtype(base, base2): + co = False + if not is_subtype(base2, base): + contra = False + + if co: + v = COVARIANT + elif contra: + v = CONTRAVARIANT + else: + v = INVARIANT + if v == variance: + break + tv.variance = VARIANCE_NOT_READY + return True + + +def has_underscore_prefix(name: str) -> bool: + return name.startswith("_") and not (name.startswith("__") and name.endswith("__")) + + +def infer_class_variances(info: TypeInfo) -> bool: + if not info.defn.type_args: + return True + tvs = info.defn.type_vars + success = True + for i, tv in enumerate(tvs): + if isinstance(tv, TypeVarType) and tv.variance == VARIANCE_NOT_READY: + if not infer_variance(info, i): + success = False + return success + + +def erase_return_self_types(typ: Type, self_type: Instance) -> Type: + """If a typ is function-like and returns self_type, replace return type with Any.""" + proper_type = get_proper_type(typ) + if isinstance(proper_type, CallableType): + ret = get_proper_type(proper_type.ret_type) + if isinstance(ret, Instance) and ret == self_type: + return proper_type.copy_modified(ret_type=AnyType(TypeOfAny.implementation_artifact)) + elif isinstance(proper_type, Overloaded): + return Overloaded( + [ + cast(CallableType, erase_return_self_types(it, self_type)) + for it in proper_type.items + ] + ) + return typ + + +def is_erased_instance(t: Instance) -> bool: + """Is this an instance where all args are Any types?""" + if not t.args: + return False + for arg in t.args: + if isinstance(arg, UnpackType): + unpacked = get_proper_type(arg.type) + if not isinstance(unpacked, Instance): + return False + assert unpacked.type.fullname == "builtins.tuple" + if not isinstance(get_proper_type(unpacked.args[0]), AnyType): + return False + elif not isinstance(get_proper_type(arg), AnyType): + return False + return True diff --git a/micromamba_root/Lib/site-packages/mypy/suggestions.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/suggestions.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..14a69a4ad7389c2456381d6b82ee01edcd523859 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/suggestions.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/suggestions.py b/micromamba_root/Lib/site-packages/mypy/suggestions.py new file mode 100644 index 0000000000000000000000000000000000000000..39a220e34091e91cadeaff6f3dcde13dd2345b94 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/suggestions.py @@ -0,0 +1,1068 @@ +"""Mechanisms for inferring function types based on callsites. + +Currently works by collecting all argument types at callsites, +synthesizing a list of possible function types from that, trying them +all, and picking the one with the fewest errors that we think is the +"best". + +Can return JSON that pyannotate can use to apply the annotations to code. + +There are a bunch of TODOs here: + * Maybe want a way to surface the choices not selected?? + * We can generate an exponential number of type suggestions, and probably want + a way to not always need to check them all. + * Our heuristics for what types to try are primitive and not yet + supported by real practice. + * More! + +Other things: + * This is super brute force. Could we integrate with the typechecker + more to understand more about what is going on? + * Like something with tracking constraints/unification variables? + * No understanding of type variables at *all* +""" + +from __future__ import annotations + +import itertools +import json +import os +import sys +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from typing import NamedTuple, TypedDict, TypeVar, cast + +from mypy.argmap import map_actuals_to_formals +from mypy.build import Graph, State +from mypy.checkexpr import has_any_type +from mypy.find_sources import InvalidSourceList, SourceFinder +from mypy.join import join_type_list +from mypy.meet import meet_type_list +from mypy.modulefinder import PYTHON_EXTENSIONS +from mypy.nodes import ( + ARG_STAR, + ARG_STAR2, + ArgKind, + CallExpr, + Decorator, + Expression, + FuncDef, + MypyFile, + RefExpr, + ReturnStmt, + SymbolNode, + SymbolTable, + TypeInfo, + Var, +) +from mypy.options import Options +from mypy.plugin import FunctionContext, MethodContext, Plugin +from mypy.server.update import FineGrainedBuildManager +from mypy.state import state +from mypy.traverser import TraverserVisitor +from mypy.typeops import bind_self, make_simplified_union +from mypy.types import ( + AnyType, + CallableType, + FunctionLike, + Instance, + NoneType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeStrVisitor, + TypeTranslator, + TypeVarType, + UninhabitedType, + UnionType, + get_proper_type, +) +from mypy.types_utils import is_overlapping_none, remove_optional +from mypy.util import split_target + + +class PyAnnotateSignature(TypedDict): + return_type: str + arg_types: list[str] + + +class Callsite(NamedTuple): + path: str + line: int + arg_kinds: list[list[ArgKind]] + callee_arg_names: list[str | None] + arg_names: list[list[str | None]] + arg_types: list[list[Type]] + + +class SuggestionPlugin(Plugin): + """Plugin that records all calls to a given target.""" + + def __init__(self, target: str) -> None: + if target.endswith((".__new__", ".__init__")): + target = target.rsplit(".", 1)[0] + + self.target = target + # List of call sites found by dmypy suggest: + # (path, line, , , ) + self.mystery_hits: list[Callsite] = [] + + def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None: + if fullname == self.target: + return self.log + else: + return None + + def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: + if fullname == self.target: + return self.log + else: + return None + + def log(self, ctx: FunctionContext | MethodContext) -> Type: + self.mystery_hits.append( + Callsite( + ctx.api.path, + ctx.context.line, + ctx.arg_kinds, + ctx.callee_arg_names, + ctx.arg_names, + ctx.arg_types, + ) + ) + return ctx.default_return_type + + +# NOTE: We could make this a bunch faster by implementing a StatementVisitor that skips +# traversing into expressions +class ReturnFinder(TraverserVisitor): + """Visitor for finding all types returned from a function.""" + + def __init__(self, typemap: dict[Expression, Type]) -> None: + self.typemap = typemap + self.return_types: list[Type] = [] + + def visit_return_stmt(self, o: ReturnStmt) -> None: + if o.expr is not None and o.expr in self.typemap: + self.return_types.append(self.typemap[o.expr]) + + def visit_func_def(self, o: FuncDef) -> None: + # Skip nested functions + pass + + +def get_return_types(typemap: dict[Expression, Type], func: FuncDef) -> list[Type]: + """Find all the types returned by return statements in func.""" + finder = ReturnFinder(typemap) + func.body.accept(finder) + return finder.return_types + + +class ArgUseFinder(TraverserVisitor): + """Visitor for finding all the types of arguments that each arg is passed to. + + This is extremely simple minded but might be effective anyways. + """ + + def __init__(self, func: FuncDef, typemap: dict[Expression, Type]) -> None: + self.typemap = typemap + self.arg_types: dict[SymbolNode, list[Type]] = {arg.variable: [] for arg in func.arguments} + + def visit_call_expr(self, o: CallExpr) -> None: + if not any(isinstance(e, RefExpr) and e.node in self.arg_types for e in o.args): + return + + typ = get_proper_type(self.typemap.get(o.callee)) + if not isinstance(typ, CallableType): + return + + formal_to_actual = map_actuals_to_formals( + o.arg_kinds, + o.arg_names, + typ.arg_kinds, + typ.arg_names, + lambda n: AnyType(TypeOfAny.special_form), + ) + + for i, args in enumerate(formal_to_actual): + for arg_idx in args: + arg = o.args[arg_idx] + if isinstance(arg, RefExpr) and arg.node in self.arg_types: + self.arg_types[arg.node].append(typ.arg_types[i]) + + +def get_arg_uses(typemap: dict[Expression, Type], func: FuncDef) -> list[list[Type]]: + """Find all the types of arguments that each arg is passed to. + + For example, given + def foo(x: int) -> None: ... + def bar(x: str) -> None: ... + def test(x, y): + foo(x) + bar(y) + + this will return [[int], [str]]. + """ + finder = ArgUseFinder(func, typemap) + func.body.accept(finder) + return [finder.arg_types[arg.variable] for arg in func.arguments] + + +class SuggestionFailure(Exception): + pass + + +def is_explicit_any(typ: AnyType) -> bool: + # Originally I wanted to count as explicit anything derived from an explicit any, but that + # seemed too strict in some testing. + # return (typ.type_of_any == TypeOfAny.explicit + # or (typ.source_any is not None and typ.source_any.type_of_any == TypeOfAny.explicit)) + # Important question: what should we do with source_any stuff? Does that count? + # And actually should explicit anys count at all?? Maybe not! + return typ.type_of_any == TypeOfAny.explicit + + +def is_implicit_any(typ: Type) -> bool: + typ = get_proper_type(typ) + return isinstance(typ, AnyType) and not is_explicit_any(typ) + + +def _arg_accepts_function(typ: ProperType) -> bool: + return ( + # TypeVar / Callable + isinstance(typ, (TypeVarType, CallableType)) + or + # Protocol with __call__ + isinstance(typ, Instance) + and typ.type.is_protocol + and typ.type.get_method("__call__") is not None + ) + + +class SuggestionEngine: + """Engine for finding call sites and suggesting signatures.""" + + def __init__( + self, + fgmanager: FineGrainedBuildManager, + *, + json: bool, + no_errors: bool = False, + no_any: bool = False, + flex_any: float | None = None, + use_fixme: str | None = None, + max_guesses: int | None = None, + ) -> None: + self.fgmanager = fgmanager + self.manager = fgmanager.manager + self.plugin = self.manager.plugin + self.graph = fgmanager.graph + self.finder = SourceFinder(self.manager.fscache, self.manager.options) + + self.give_json = json + self.no_errors = no_errors + self.flex_any = flex_any + if no_any: + self.flex_any = 1.0 + + self.max_guesses = max_guesses or 64 + self.use_fixme = use_fixme + + def suggest(self, function: str) -> str: + """Suggest an inferred type for function.""" + mod, func_name, node = self.find_node(function) + + with self.restore_after(mod): + with self.with_export_types(): + suggestion = self.get_suggestion(mod, node) + + if self.give_json: + return self.json_suggestion(mod, func_name, node, suggestion) + else: + return self.format_signature(suggestion) + + def suggest_callsites(self, function: str) -> str: + """Find a list of call sites of function.""" + mod, _, node = self.find_node(function) + with self.restore_after(mod): + callsites, _ = self.get_callsites(node) + + return "\n".join( + dedup( + [ + f"{path}:{line}: {self.format_args(arg_kinds, arg_names, arg_types)}" + for path, line, arg_kinds, _, arg_names, arg_types in callsites + ] + ) + ) + + @contextmanager + def restore_after(self, module: str) -> Iterator[None]: + """Context manager that reloads a module after executing the body. + + This should undo any damage done to the module state while mucking around. + """ + try: + yield + finally: + self.reload(self.graph[module]) + + @contextmanager + def with_export_types(self) -> Iterator[None]: + """Context manager that enables the export_types flag in the body. + + This causes type information to be exported into the manager's all_types variable. + """ + old = self.manager.options.export_types + self.manager.options.export_types = True + try: + yield + finally: + self.manager.options.export_types = old + + def get_trivial_type(self, fdef: FuncDef) -> CallableType: + """Generate a trivial callable type from a func def, with all Anys""" + # The Anys are marked as being from the suggestion engine + # since they need some special treatment (specifically, + # constraint generation ignores them.) + return CallableType( + [AnyType(TypeOfAny.suggestion_engine) for _ in fdef.arg_kinds], + fdef.arg_kinds, + fdef.arg_names, + AnyType(TypeOfAny.suggestion_engine), + self.named_type("builtins.function"), + ) + + def get_starting_type(self, fdef: FuncDef) -> CallableType: + if isinstance(fdef.type, CallableType): + return make_suggestion_anys(fdef.type) + else: + return self.get_trivial_type(fdef) + + def get_args( + self, + is_method: bool, + base: CallableType, + defaults: list[Type | None], + callsites: list[Callsite], + uses: list[list[Type]], + ) -> list[list[Type]]: + """Produce a list of type suggestions for each argument type.""" + types: list[list[Type]] = [] + for i in range(len(base.arg_kinds)): + # Make self args Any but this will get overridden somewhere in the checker + if i == 0 and is_method: + types.append([AnyType(TypeOfAny.suggestion_engine)]) + continue + + all_arg_types = [] + for call in callsites: + for typ in call.arg_types[i - is_method]: + # Collect all the types except for implicit anys + if not is_implicit_any(typ): + all_arg_types.append(typ) + all_use_types = [] + for typ in uses[i]: + # Collect all the types except for implicit anys + if not is_implicit_any(typ): + all_use_types.append(typ) + # Add in any default argument types + default = defaults[i] + if default: + all_arg_types.append(default) + if all_use_types: + all_use_types.append(default) + + arg_types = [] + + if all_arg_types and all( + isinstance(get_proper_type(tp), NoneType) for tp in all_arg_types + ): + arg_types.append( + UnionType.make_union([all_arg_types[0], AnyType(TypeOfAny.explicit)]) + ) + elif all_arg_types: + arg_types.extend(generate_type_combinations(all_arg_types)) + else: + arg_types.append(AnyType(TypeOfAny.explicit)) + + if all_use_types: + # This is a meet because the type needs to be compatible with all the uses + arg_types.append(meet_type_list(all_use_types)) + + types.append(arg_types) + return types + + def get_default_arg_types(self, fdef: FuncDef) -> list[Type | None]: + return [ + self.manager.all_types[arg.initializer] if arg.initializer else None + for arg in fdef.arguments + ] + + def get_guesses( + self, + is_method: bool, + base: CallableType, + defaults: list[Type | None], + callsites: list[Callsite], + uses: list[list[Type]], + ) -> list[CallableType]: + """Compute a list of guesses for a function's type. + + This focuses just on the argument types, and doesn't change the provided return type. + """ + options = self.get_args(is_method, base, defaults, callsites, uses) + + # Take the first `max_guesses` guesses. + product = itertools.islice(itertools.product(*options), 0, self.max_guesses) + return [refine_callable(base, base.copy_modified(arg_types=list(x))) for x in product] + + def get_callsites(self, func: FuncDef) -> tuple[list[Callsite], list[str]]: + """Find all call sites of a function.""" + new_type = self.get_starting_type(func) + + collector_plugin = SuggestionPlugin(func.fullname) + + self.plugin._plugins.insert(0, collector_plugin) + try: + errors = self.try_type(func, new_type) + finally: + self.plugin._plugins.pop(0) + + return collector_plugin.mystery_hits, errors + + def filter_options( + self, guesses: list[CallableType], is_method: bool, ignore_return: bool + ) -> list[CallableType]: + """Apply any configured filters to the possible guesses. + + Currently the only option is filtering based on Any prevalance.""" + return [ + t + for t in guesses + if self.flex_any is None + or any_score_callable(t, is_method, ignore_return) >= self.flex_any + ] + + def find_best(self, func: FuncDef, guesses: list[CallableType]) -> tuple[CallableType, int]: + """From a list of possible function types, find the best one. + + For best, we want the fewest errors, then the best "score" from score_callable. + """ + if not guesses: + raise SuggestionFailure("No guesses that match criteria!") + errors = {guess: self.try_type(func, guess) for guess in guesses} + best = min(guesses, key=lambda s: (count_errors(errors[s]), self.score_callable(s))) + return best, count_errors(errors[best]) + + def get_guesses_from_parent(self, node: FuncDef) -> list[CallableType]: + """Try to get a guess of a method type from a parent class.""" + if not node.info: + return [] + + for parent in node.info.mro[1:]: + pnode = parent.names.get(node.name) + if pnode and isinstance(pnode.node, (FuncDef, Decorator)): + typ = get_proper_type(pnode.node.type) + # FIXME: Doesn't work right with generic types + if isinstance(typ, CallableType) and len(typ.arg_types) == len(node.arguments): + # Return the first thing we find, since it probably doesn't make sense + # to grab things further up in the chain if an earlier parent has it. + return [typ] + + return [] + + def get_suggestion(self, mod: str, node: FuncDef) -> PyAnnotateSignature: + """Compute a suggestion for a function. + + Return the type and whether the first argument should be ignored. + """ + graph = self.graph + callsites, orig_errors = self.get_callsites(node) + uses = get_arg_uses(self.manager.all_types, node) + + if self.no_errors and orig_errors: + raise SuggestionFailure("Function does not typecheck.") + + is_method = bool(node.info) and node.has_self_or_cls_argument + + with state.strict_optional_set(graph[mod].options.strict_optional): + guesses = self.get_guesses( + is_method, + self.get_starting_type(node), + self.get_default_arg_types(node), + callsites, + uses, + ) + guesses += self.get_guesses_from_parent(node) + guesses = self.filter_options(guesses, is_method, ignore_return=True) + best, _ = self.find_best(node, guesses) + + # Now try to find the return type! + self.try_type(node, best) + returns = get_return_types(self.manager.all_types, node) + with state.strict_optional_set(graph[mod].options.strict_optional): + if returns: + ret_types = generate_type_combinations(returns) + else: + ret_types = [NoneType()] + + guesses = [best.copy_modified(ret_type=refine_type(best.ret_type, t)) for t in ret_types] + guesses = self.filter_options(guesses, is_method, ignore_return=False) + best, errors = self.find_best(node, guesses) + + if self.no_errors and errors: + raise SuggestionFailure("No annotation without errors") + + return self.pyannotate_signature(mod, is_method, best) + + def format_args( + self, + arg_kinds: list[list[ArgKind]], + arg_names: list[list[str | None]], + arg_types: list[list[Type]], + ) -> str: + args: list[str] = [] + for i in range(len(arg_types)): + for kind, name, typ in zip(arg_kinds[i], arg_names[i], arg_types[i]): + arg = self.format_type(None, typ) + if kind == ARG_STAR: + arg = "*" + arg + elif kind == ARG_STAR2: + arg = "**" + arg + elif kind.is_named(): + if name: + arg = f"{name}={arg}" + args.append(arg) + return f"({', '.join(args)})" + + def find_node(self, key: str) -> tuple[str, str, FuncDef]: + """From a target name, return module/target names and the func def. + + The 'key' argument can be in one of two formats: + * As the function full name, e.g., package.module.Cls.method + * As the function location as file and line separated by column, + e.g., path/to/file.py:42 + """ + # TODO: Also return OverloadedFuncDef -- currently these are ignored. + node: SymbolNode | None = None + if ":" in key: + # A colon might be part of a drive name on Windows (like `C:/foo/bar`) + # and is also used as a delimiter between file path and lineno. + # If a colon is there for any of those reasons, it must be a file+line + # reference. + platform_key_count = 2 if sys.platform == "win32" else 1 + if key.count(":") > platform_key_count: + raise SuggestionFailure( + "Malformed location for function: {}. Must be either" + " package.module.Class.method or path/to/file.py:line".format(key) + ) + file, line = key.rsplit(":", 1) + if not line.isdigit(): + raise SuggestionFailure(f"Line number must be a number. Got {line}") + line_number = int(line) + modname, node = self.find_node_by_file_and_line(file, line_number) + tail = node.fullname[len(modname) + 1 :] # add one to account for '.' + else: + target = split_target(self.fgmanager.graph, key) + if not target: + raise SuggestionFailure(f"Cannot find module for {key}") + modname, tail = target + node = self.find_node_by_module_and_name(modname, tail) + + if isinstance(node, Decorator): + node = self.extract_from_decorator(node) + if not node: + raise SuggestionFailure(f"Object {key} is a decorator we can't handle") + + if not isinstance(node, FuncDef): + raise SuggestionFailure(f"Object {key} is not a function") + + return modname, tail, node + + def find_node_by_module_and_name(self, modname: str, tail: str) -> SymbolNode | None: + """Find symbol node by module id and qualified name. + + Raise SuggestionFailure if can't find one. + """ + tree = self.ensure_loaded(self.fgmanager.graph[modname]) + + # N.B. This is reimplemented from update's lookup_target + # basically just to produce better error messages. + + names: SymbolTable = tree.names + + # Look through any classes + components = tail.split(".") + for i, component in enumerate(components[:-1]): + if component not in names: + raise SuggestionFailure( + "Unknown class {}.{}".format(modname, ".".join(components[: i + 1])) + ) + node: SymbolNode | None = names[component].node + if not isinstance(node, TypeInfo): + raise SuggestionFailure( + "Object {}.{} is not a class".format(modname, ".".join(components[: i + 1])) + ) + names = node.names + + # Look for the actual function/method + funcname = components[-1] + if funcname not in names: + key = modname + "." + tail + raise SuggestionFailure( + "Unknown {} {}".format("method" if len(components) > 1 else "function", key) + ) + return names[funcname].node + + def find_node_by_file_and_line(self, file: str, line: int) -> tuple[str, SymbolNode]: + """Find symbol node by path to file and line number. + + Find the first function declared *before or on* the line number. + + Return module id and the node found. Raise SuggestionFailure if can't find one. + """ + if not any(file.endswith(ext) for ext in PYTHON_EXTENSIONS): + raise SuggestionFailure("Source file is not a Python file") + try: + modname, _ = self.finder.crawl_up(os.path.normpath(file)) + except InvalidSourceList as e: + raise SuggestionFailure("Invalid source file name: " + file) from e + if modname not in self.graph: + raise SuggestionFailure("Unknown module: " + modname) + # We must be sure about any edits in this file as this might affect the line numbers. + tree = self.ensure_loaded(self.fgmanager.graph[modname], force=True) + node: SymbolNode | None = None + closest_line: int | None = None + # TODO: Handle nested functions. + for _, sym, _ in tree.local_definitions(): + if isinstance(sym.node, (FuncDef, Decorator)): + sym_line = sym.node.line + # TODO: add support for OverloadedFuncDef. + else: + continue + + # We want the closest function above the specified line + if sym_line <= line and (closest_line is None or sym_line > closest_line): + closest_line = sym_line + node = sym.node + if not node: + raise SuggestionFailure(f"Cannot find a function at line {line}") + return modname, node + + def extract_from_decorator(self, node: Decorator) -> FuncDef | None: + for dec in node.decorators: + typ = None + if isinstance(dec, RefExpr) and isinstance(dec.node, (Var, FuncDef)): + typ = get_proper_type(dec.node.type) + elif ( + isinstance(dec, CallExpr) + and isinstance(dec.callee, RefExpr) + and isinstance(dec.callee.node, (Decorator, FuncDef, Var)) + and isinstance((call_tp := get_proper_type(dec.callee.node.type)), CallableType) + ): + typ = get_proper_type(call_tp.ret_type) + + if isinstance(typ, Instance): + call_method = typ.type.get_method("__call__") + if isinstance(call_method, FuncDef) and isinstance(call_method.type, FunctionLike): + typ = bind_self(call_method.type, None) + + if not isinstance(typ, FunctionLike): + return None + for ct in typ.items: + if not ( + len(ct.arg_types) == 1 + and _arg_accepts_function(get_proper_type(ct.arg_types[0])) + and ct.arg_types[0] == ct.ret_type + ): + return None + + return node.func + + def try_type(self, func: FuncDef, typ: ProperType) -> list[str]: + """Recheck a function while assuming it has type typ. + + Return all error messages. + """ + old = func.unanalyzed_type + # During reprocessing, unanalyzed_type gets copied to type (by aststrip). + # We set type to None to ensure that the type always changes during + # reprocessing. + func.type = None + func.unanalyzed_type = typ + try: + res = self.fgmanager.trigger(func.fullname) + # if res: + # print('===', typ) + # print('\n'.join(res)) + return res + finally: + func.unanalyzed_type = old + + def reload(self, state: State) -> list[str]: + """Recheck the module given by state.""" + assert state.path is not None + self.fgmanager.flush_cache() + return self.fgmanager.update([(state.id, state.path)], []) + + def ensure_loaded(self, state: State, force: bool = False) -> MypyFile: + """Make sure that the module represented by state is fully loaded.""" + if not state.tree or state.tree.is_cache_skeleton or force: + self.reload(state) + assert state.tree is not None + return state.tree + + def named_type(self, s: str) -> Instance: + return self.manager.semantic_analyzer.named_type(s) + + def json_suggestion( + self, mod: str, func_name: str, node: FuncDef, suggestion: PyAnnotateSignature + ) -> str: + """Produce a json blob for a suggestion suitable for application by pyannotate.""" + # pyannotate irritatingly drops class names for class and static methods + if node.is_class or node.is_static: + func_name = func_name.split(".", 1)[-1] + + # pyannotate works with either paths relative to where the + # module is rooted or with absolute paths. We produce absolute + # paths because it is simpler. + path = os.path.abspath(self.graph[mod].xpath) + + obj = { + "signature": suggestion, + "line": node.line, + "path": path, + "func_name": func_name, + "samples": 0, + } + return json.dumps([obj], sort_keys=True) + + def pyannotate_signature( + self, cur_module: str | None, is_method: bool, typ: CallableType + ) -> PyAnnotateSignature: + """Format a callable type as a pyannotate dict""" + start = int(is_method) + return { + "arg_types": [self.format_type(cur_module, t) for t in typ.arg_types[start:]], + "return_type": self.format_type(cur_module, typ.ret_type), + } + + def format_signature(self, sig: PyAnnotateSignature) -> str: + """Format a callable type in a way suitable as an annotation... kind of""" + return f"({', '.join(sig['arg_types'])}) -> {sig['return_type']}" + + def format_type(self, cur_module: str | None, typ: Type) -> str: + if self.use_fixme and isinstance(get_proper_type(typ), AnyType): + return self.use_fixme + return typ.accept(TypeFormatter(cur_module, self.graph, self.manager.options)) + + def score_type(self, t: Type, arg_pos: bool) -> int: + """Generate a score for a type that we use to pick which type to use. + + Lower is better, prefer non-union/non-any types. Don't penalize optionals. + """ + t = get_proper_type(t) + if isinstance(t, AnyType): + return 20 + if arg_pos and isinstance(t, NoneType): + return 20 + if isinstance(t, UnionType): + if any(isinstance(get_proper_type(x), AnyType) for x in t.items): + return 20 + if any(has_any_type(x) for x in t.items): + return 15 + if not is_overlapping_none(t): + return 10 + if isinstance(t, CallableType) and (has_any_type(t) or is_tricky_callable(t)): + return 10 + return 0 + + def score_callable(self, t: CallableType) -> int: + return sum(self.score_type(x, arg_pos=True) for x in t.arg_types) + self.score_type( + t.ret_type, arg_pos=False + ) + + +def any_score_type(ut: Type, arg_pos: bool) -> float: + """Generate a very made up number representing the Anyness of a type. + + Higher is better, 1.0 is max + """ + t = get_proper_type(ut) + if isinstance(t, AnyType) and t.type_of_any != TypeOfAny.suggestion_engine: + return 0 + if isinstance(t, NoneType) and arg_pos: + return 0.5 + if isinstance(t, UnionType): + if any(isinstance(get_proper_type(x), AnyType) for x in t.items): + return 0.5 + if any(has_any_type(x) for x in t.items): + return 0.25 + if isinstance(t, CallableType) and is_tricky_callable(t): + return 0.5 + if has_any_type(t): + return 0.5 + + return 1.0 + + +def any_score_callable(t: CallableType, is_method: bool, ignore_return: bool) -> float: + # Ignore the first argument of methods + scores = [any_score_type(x, arg_pos=True) for x in t.arg_types[int(is_method) :]] + # Return type counts twice (since it spreads type information), unless it is + # None in which case it does not count at all. (Though it *does* still count + # if there are no arguments.) + if not isinstance(get_proper_type(t.ret_type), NoneType) or not scores: + ret = 1.0 if ignore_return else any_score_type(t.ret_type, arg_pos=False) + scores += [ret, ret] + + return sum(scores) / len(scores) + + +def is_tricky_callable(t: CallableType) -> bool: + """Is t a callable that we need to put a ... in for syntax reasons?""" + return t.is_ellipsis_args or any(k.is_star() or k.is_named() for k in t.arg_kinds) + + +class TypeFormatter(TypeStrVisitor): + """Visitor used to format types""" + + # TODO: Probably a lot + def __init__(self, module: str | None, graph: Graph, options: Options) -> None: + super().__init__(options=options) + self.module = module + self.graph = graph + + def visit_any(self, t: AnyType) -> str: + if t.missing_import_name: + return t.missing_import_name + else: + return "Any" + + def visit_instance(self, t: Instance) -> str: + s = t.type.fullname or t.type.name or None + if s is None: + return "" + + mod_obj = split_target(self.graph, s) + assert mod_obj + mod, obj = mod_obj + + # If a class is imported into the current module, rewrite the reference + # to point to the current module. This helps the annotation tool avoid + # inserting redundant imports when a type has been reexported. + if self.module: + parts = obj.split(".") # need to split the object part if it is a nested class + tree = self.graph[self.module].tree + if tree and parts[0] in tree.names and mod not in tree.names: + mod = self.module + + if (mod, obj) == ("builtins", "tuple"): + mod, obj = "typing", "Tuple[" + t.args[0].accept(self) + ", ...]" + elif t.args: + obj += f"[{self.list_str(t.args)}]" + + if mod_obj == ("builtins", "unicode"): + return "Text" + elif mod == "builtins": + return obj + else: + delim = "." if "." not in obj else ":" + return mod + delim + obj + + def visit_tuple_type(self, t: TupleType) -> str: + if t.partial_fallback and t.partial_fallback.type: + fallback_name = t.partial_fallback.type.fullname + if fallback_name != "builtins.tuple": + return t.partial_fallback.accept(self) + s = self.list_str(t.items) + return f"Tuple[{s}]" + + def visit_uninhabited_type(self, t: UninhabitedType) -> str: + return "Any" + + def visit_typeddict_type(self, t: TypedDictType) -> str: + return t.fallback.accept(self) + + def visit_union_type(self, t: UnionType) -> str: + if len(t.items) == 2 and is_overlapping_none(t): + s = remove_optional(t).accept(self) + return f"{s} | None" + else: + return super().visit_union_type(t) + + def visit_callable_type(self, t: CallableType) -> str: + # TODO: use extended callables? + if is_tricky_callable(t): + arg_str = "..." + else: + # Note: for default arguments, we just assume that they + # are required. This isn't right, but neither is the + # other thing, and I suspect this will produce more better + # results than falling back to `...` + args = [typ.accept(self) for typ in t.arg_types] + arg_str = f"[{', '.join(args)}]" + + return f"Callable[{arg_str}, {t.ret_type.accept(self)}]" + + +TType = TypeVar("TType", bound=Type) + + +def make_suggestion_anys(t: TType) -> TType: + """Make all anys in the type as coming from the suggestion engine. + + This keeps those Anys from influencing constraint generation, + which allows us to do better when refining types. + """ + return cast(TType, t.accept(MakeSuggestionAny())) + + +class MakeSuggestionAny(TypeTranslator): + def visit_any(self, t: AnyType) -> Type: + if not t.missing_import_name: + return t.copy_modified(type_of_any=TypeOfAny.suggestion_engine) + else: + return t + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + return t.copy_modified(args=[a.accept(self) for a in t.args]) + + +def generate_type_combinations(types: list[Type]) -> list[Type]: + """Generate possible combinations of a list of types. + + mypy essentially supports two different ways to do this: joining the types + and unioning the types. We try both. + """ + joined_type = join_type_list(types) + union_type = make_simplified_union(types) + if joined_type == union_type: + return [joined_type] + else: + return [joined_type, union_type] + + +def count_errors(msgs: list[str]) -> int: + return len([x for x in msgs if " error: " in x]) + + +def refine_type(ti: Type, si: Type) -> Type: + """Refine `ti` by replacing Anys in it with information taken from `si` + + This basically works by, when the types have the same structure, + traversing both of them in parallel and replacing Any on the left + with whatever the type on the right is. If the types don't have the + same structure (or aren't supported), the left type is chosen. + + For example: + refine(Any, T) = T, for all T + refine(float, int) = float + refine(List[Any], List[int]) = List[int] + refine(Dict[int, Any], Dict[Any, int]) = Dict[int, int] + refine(Tuple[int, Any], Tuple[Any, int]) = Tuple[int, int] + + refine(Callable[[Any], Any], Callable[[int], int]) = Callable[[int], int] + refine(Callable[..., int], Callable[[int, float], Any]) = Callable[[int, float], int] + + refine(Optional[Any], int) = Optional[int] + refine(Optional[Any], Optional[int]) = Optional[int] + refine(Optional[Any], Union[int, str]) = Optional[Union[int, str]] + refine(Optional[List[Any]], List[int]) = List[int] + + """ + t = get_proper_type(ti) + s = get_proper_type(si) + + if isinstance(t, AnyType): + # If s is also an Any, we return if it is a missing_import Any + return t if isinstance(s, AnyType) and t.missing_import_name else s + + if isinstance(t, Instance) and isinstance(s, Instance) and t.type == s.type: + return t.copy_modified(args=[refine_type(ta, sa) for ta, sa in zip(t.args, s.args)]) + + if ( + isinstance(t, TupleType) + and isinstance(s, TupleType) + and t.partial_fallback == s.partial_fallback + and len(t.items) == len(s.items) + ): + return t.copy_modified(items=[refine_type(ta, sa) for ta, sa in zip(t.items, s.items)]) + + if isinstance(t, CallableType) and isinstance(s, CallableType): + return refine_callable(t, s) + + if isinstance(t, UnionType): + return refine_union(t, s) + + # TODO: Refining of builtins.tuple, Type? + + return t + + +def refine_union(t: UnionType, s: ProperType) -> Type: + """Refine a union type based on another type. + + This is done by refining every component of the union against the + right hand side type (or every component of its union if it is + one). If an element of the union is successfully refined, we drop it + from the union in favor of the refined versions. + """ + # Don't try to do any union refining if the types are already the + # same. This prevents things like refining Optional[Any] against + # itself and producing None. + if t == s: + return t + + rhs_items = s.items if isinstance(s, UnionType) else [s] + + new_items = [] + for lhs in t.items: + refined = False + for rhs in rhs_items: + new = refine_type(lhs, rhs) + if new != lhs: + new_items.append(new) + refined = True + if not refined: + new_items.append(lhs) + + # Turn strict optional on when simplifying the union since we + # don't want to drop Nones. + with state.strict_optional_set(True): + return make_simplified_union(new_items) + + +def refine_callable(t: CallableType, s: CallableType) -> CallableType: + """Refine a callable based on another. + + See comments for refine_type. + """ + if t.fallback != s.fallback: + return t + + if t.is_ellipsis_args and not is_tricky_callable(s): + return s.copy_modified(ret_type=refine_type(t.ret_type, s.ret_type)) + + if is_tricky_callable(t) or t.arg_kinds != s.arg_kinds: + return t + + return t.copy_modified( + arg_types=[refine_type(ta, sa) for ta, sa in zip(t.arg_types, s.arg_types)], + ret_type=refine_type(t.ret_type, s.ret_type), + ) + + +T = TypeVar("T") + + +def dedup(old: list[T]) -> list[T]: + new: list[T] = [] + for x in old: + if x not in new: + new.append(x) + return new diff --git a/micromamba_root/Lib/site-packages/mypy/traverser.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/traverser.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..3ed8b14e6f53f2fdab5312cbcdb142f563577ca6 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/traverser.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/traverser.py b/micromamba_root/Lib/site-packages/mypy/traverser.py new file mode 100644 index 0000000000000000000000000000000000000000..6fdb54298f85c42e872b1acf35e4981f717cc0f7 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/traverser.py @@ -0,0 +1,1105 @@ +"""Generic node traverser visitor""" + +from __future__ import annotations + +from mypy_extensions import mypyc_attr, trait + +from mypy.nodes import ( + REVEAL_TYPE, + AssertStmt, + AssertTypeExpr, + AssignmentExpr, + AssignmentStmt, + AwaitExpr, + Block, + BreakStmt, + BytesExpr, + CallExpr, + CastExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + ContinueStmt, + Decorator, + DelStmt, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + EnumCallExpr, + Expression, + ExpressionStmt, + FloatExpr, + ForStmt, + FuncBase, + FuncDef, + FuncItem, + GeneratorExpr, + GlobalDecl, + IfStmt, + Import, + ImportAll, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MatchStmt, + MemberExpr, + MypyFile, + NamedTupleExpr, + NameExpr, + NewTypeExpr, + Node, + NonlocalDecl, + OperatorAssignmentStmt, + OpExpr, + OverloadedFuncDef, + ParamSpecExpr, + PassStmt, + PromoteExpr, + RaiseStmt, + ReturnStmt, + RevealExpr, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + StrExpr, + SuperExpr, + TemplateStrExpr, + TempNode, + TryStmt, + TupleExpr, + TypeAlias, + TypeAliasExpr, + TypeAliasStmt, + TypeApplication, + TypedDictExpr, + TypeFormExpr, + TypeVarExpr, + TypeVarTupleExpr, + UnaryExpr, + Var, + WhileStmt, + WithStmt, + YieldExpr, + YieldFromExpr, +) +from mypy.patterns import ( + AsPattern, + ClassPattern, + MappingPattern, + OrPattern, + SequencePattern, + SingletonPattern, + StarredPattern, + ValuePattern, +) +from mypy.visitor import NodeVisitor + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class TraverserVisitor(NodeVisitor[None]): + """A parse tree visitor that traverses the parse tree during visiting. + + It does not perform any actions outside the traversal. Subclasses + should override visit methods to perform actions during + traversal. Calling the superclass method allows reusing the + traversal implementation. + + TODO: split this into more limited visitor (e.g. statements-only etc). + This will improve performance since in many cases we don't need to recurse + all the way down in various visitors that subclass this. + """ + + def __init__(self) -> None: + pass + + # Visit methods + + def visit_mypy_file(self, o: MypyFile, /) -> None: + for d in o.defs: + d.accept(self) + + def visit_block(self, block: Block, /) -> None: + for s in block.body: + s.accept(self) + + def visit_func(self, o: FuncItem, /) -> None: + if o.arguments is not None: + for arg in o.arguments: + init = arg.initializer + if init is not None: + init.accept(self) + + for arg in o.arguments: + self.visit_var(arg.variable) + + o.body.accept(self) + + def visit_func_def(self, o: FuncDef, /) -> None: + self.visit_func(o) + + def visit_overloaded_func_def(self, o: OverloadedFuncDef, /) -> None: + for item in o.items: + item.accept(self) + if o.impl: + o.impl.accept(self) + + def visit_class_def(self, o: ClassDef, /) -> None: + for d in o.decorators: + d.accept(self) + for base in o.base_type_exprs: + base.accept(self) + if o.metaclass: + o.metaclass.accept(self) + for v in o.keywords.values(): + v.accept(self) + o.defs.accept(self) + if o.analyzed: + o.analyzed.accept(self) + + def visit_decorator(self, o: Decorator, /) -> None: + o.func.accept(self) + o.var.accept(self) + for decorator in o.decorators: + decorator.accept(self) + + def visit_expression_stmt(self, o: ExpressionStmt, /) -> None: + o.expr.accept(self) + + def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None: + o.rvalue.accept(self) + for l in o.lvalues: + l.accept(self) + + def visit_operator_assignment_stmt(self, o: OperatorAssignmentStmt, /) -> None: + o.rvalue.accept(self) + o.lvalue.accept(self) + + def visit_while_stmt(self, o: WhileStmt, /) -> None: + o.expr.accept(self) + o.body.accept(self) + if o.else_body: + o.else_body.accept(self) + + def visit_for_stmt(self, o: ForStmt, /) -> None: + o.index.accept(self) + o.expr.accept(self) + o.body.accept(self) + if o.else_body: + o.else_body.accept(self) + + def visit_return_stmt(self, o: ReturnStmt, /) -> None: + if o.expr is not None: + o.expr.accept(self) + + def visit_assert_stmt(self, o: AssertStmt, /) -> None: + if o.expr is not None: + o.expr.accept(self) + if o.msg is not None: + o.msg.accept(self) + + def visit_del_stmt(self, o: DelStmt, /) -> None: + if o.expr is not None: + o.expr.accept(self) + + def visit_if_stmt(self, o: IfStmt, /) -> None: + for e in o.expr: + e.accept(self) + for b in o.body: + b.accept(self) + if o.else_body: + o.else_body.accept(self) + + def visit_raise_stmt(self, o: RaiseStmt, /) -> None: + if o.expr is not None: + o.expr.accept(self) + if o.from_expr is not None: + o.from_expr.accept(self) + + def visit_try_stmt(self, o: TryStmt, /) -> None: + o.body.accept(self) + for i in range(len(o.types)): + tp = o.types[i] + if tp is not None: + tp.accept(self) + o.handlers[i].accept(self) + for v in o.vars: + if v is not None: + v.accept(self) + if o.else_body is not None: + o.else_body.accept(self) + if o.finally_body is not None: + o.finally_body.accept(self) + + def visit_with_stmt(self, o: WithStmt, /) -> None: + for i in range(len(o.expr)): + o.expr[i].accept(self) + targ = o.target[i] + if targ is not None: + targ.accept(self) + o.body.accept(self) + + def visit_match_stmt(self, o: MatchStmt, /) -> None: + o.subject.accept(self) + for i in range(len(o.patterns)): + o.patterns[i].accept(self) + guard = o.guards[i] + if guard is not None: + guard.accept(self) + o.bodies[i].accept(self) + + def visit_type_alias_stmt(self, o: TypeAliasStmt, /) -> None: + o.name.accept(self) + o.value.accept(self) + + def visit_member_expr(self, o: MemberExpr, /) -> None: + o.expr.accept(self) + + def visit_yield_from_expr(self, o: YieldFromExpr, /) -> None: + o.expr.accept(self) + + def visit_yield_expr(self, o: YieldExpr, /) -> None: + if o.expr: + o.expr.accept(self) + + def visit_call_expr(self, o: CallExpr, /) -> None: + o.callee.accept(self) + for a in o.args: + a.accept(self) + if o.analyzed: + o.analyzed.accept(self) + + def visit_op_expr(self, o: OpExpr, /) -> None: + o.left.accept(self) + o.right.accept(self) + if o.analyzed is not None: + o.analyzed.accept(self) + + def visit_comparison_expr(self, o: ComparisonExpr, /) -> None: + for operand in o.operands: + operand.accept(self) + + def visit_slice_expr(self, o: SliceExpr, /) -> None: + if o.begin_index is not None: + o.begin_index.accept(self) + if o.end_index is not None: + o.end_index.accept(self) + if o.stride is not None: + o.stride.accept(self) + + def visit_cast_expr(self, o: CastExpr, /) -> None: + o.expr.accept(self) + + def visit_type_form_expr(self, o: TypeFormExpr, /) -> None: + pass + + def visit_assert_type_expr(self, o: AssertTypeExpr, /) -> None: + o.expr.accept(self) + + def visit_reveal_expr(self, o: RevealExpr, /) -> None: + if o.kind == REVEAL_TYPE: + assert o.expr is not None + o.expr.accept(self) + else: + # RevealLocalsExpr doesn't have an inner expression + pass + + def visit_assignment_expr(self, o: AssignmentExpr, /) -> None: + o.target.accept(self) + o.value.accept(self) + + def visit_unary_expr(self, o: UnaryExpr, /) -> None: + o.expr.accept(self) + + def visit_list_expr(self, o: ListExpr, /) -> None: + for item in o.items: + item.accept(self) + + def visit_tuple_expr(self, o: TupleExpr, /) -> None: + for item in o.items: + item.accept(self) + + def visit_dict_expr(self, o: DictExpr, /) -> None: + for k, v in o.items: + if k is not None: + k.accept(self) + v.accept(self) + + def visit_template_str_expr(self, o: TemplateStrExpr, /) -> None: + for item in o.items: + if isinstance(item, tuple): + item[0].accept(self) + if item[3] is not None: + item[3].accept(self) + else: + item.accept(self) + + def visit_set_expr(self, o: SetExpr, /) -> None: + for item in o.items: + item.accept(self) + + def visit_index_expr(self, o: IndexExpr, /) -> None: + o.base.accept(self) + o.index.accept(self) + if o.analyzed: + o.analyzed.accept(self) + + def visit_generator_expr(self, o: GeneratorExpr, /) -> None: + for index, sequence, conditions in zip(o.indices, o.sequences, o.condlists): + sequence.accept(self) + index.accept(self) + for cond in conditions: + cond.accept(self) + o.left_expr.accept(self) + + def visit_dictionary_comprehension(self, o: DictionaryComprehension, /) -> None: + for index, sequence, conditions in zip(o.indices, o.sequences, o.condlists): + sequence.accept(self) + index.accept(self) + for cond in conditions: + cond.accept(self) + o.key.accept(self) + o.value.accept(self) + + def visit_list_comprehension(self, o: ListComprehension, /) -> None: + o.generator.accept(self) + + def visit_set_comprehension(self, o: SetComprehension, /) -> None: + o.generator.accept(self) + + def visit_conditional_expr(self, o: ConditionalExpr, /) -> None: + o.cond.accept(self) + o.if_expr.accept(self) + o.else_expr.accept(self) + + def visit_type_application(self, o: TypeApplication, /) -> None: + o.expr.accept(self) + + def visit_lambda_expr(self, o: LambdaExpr, /) -> None: + self.visit_func(o) + + def visit_star_expr(self, o: StarExpr, /) -> None: + o.expr.accept(self) + + def visit_await_expr(self, o: AwaitExpr, /) -> None: + o.expr.accept(self) + + def visit_super_expr(self, o: SuperExpr, /) -> None: + o.call.accept(self) + + def visit_as_pattern(self, o: AsPattern, /) -> None: + if o.pattern is not None: + o.pattern.accept(self) + if o.name is not None: + o.name.accept(self) + + def visit_or_pattern(self, o: OrPattern, /) -> None: + for p in o.patterns: + p.accept(self) + + def visit_value_pattern(self, o: ValuePattern, /) -> None: + o.expr.accept(self) + + def visit_sequence_pattern(self, o: SequencePattern, /) -> None: + for p in o.patterns: + p.accept(self) + + def visit_starred_pattern(self, o: StarredPattern, /) -> None: + if o.capture is not None: + o.capture.accept(self) + + def visit_mapping_pattern(self, o: MappingPattern, /) -> None: + for key in o.keys: + key.accept(self) + for value in o.values: + value.accept(self) + if o.rest is not None: + o.rest.accept(self) + + def visit_class_pattern(self, o: ClassPattern, /) -> None: + o.class_ref.accept(self) + for p in o.positionals: + p.accept(self) + for v in o.keyword_values: + v.accept(self) + + def visit_import(self, o: Import, /) -> None: + for a in o.assignments: + a.accept(self) + + def visit_import_from(self, o: ImportFrom, /) -> None: + for a in o.assignments: + a.accept(self) + + # leaf nodes + def visit_name_expr(self, o: NameExpr, /) -> None: + return None + + def visit_str_expr(self, o: StrExpr, /) -> None: + return None + + def visit_int_expr(self, o: IntExpr, /) -> None: + return None + + def visit_float_expr(self, o: FloatExpr, /) -> None: + return None + + def visit_bytes_expr(self, o: BytesExpr, /) -> None: + return None + + def visit_ellipsis(self, o: EllipsisExpr, /) -> None: + return None + + def visit_var(self, o: Var, /) -> None: + return None + + def visit_continue_stmt(self, o: ContinueStmt, /) -> None: + return None + + def visit_pass_stmt(self, o: PassStmt, /) -> None: + return None + + def visit_break_stmt(self, o: BreakStmt, /) -> None: + return None + + def visit_temp_node(self, o: TempNode, /) -> None: + return None + + def visit_nonlocal_decl(self, o: NonlocalDecl, /) -> None: + return None + + def visit_global_decl(self, o: GlobalDecl, /) -> None: + return None + + def visit_import_all(self, o: ImportAll, /) -> None: + return None + + def visit_type_var_expr(self, o: TypeVarExpr, /) -> None: + return None + + def visit_paramspec_expr(self, o: ParamSpecExpr, /) -> None: + return None + + def visit_type_var_tuple_expr(self, o: TypeVarTupleExpr, /) -> None: + return None + + def visit_type_alias_expr(self, o: TypeAliasExpr, /) -> None: + return None + + def visit_type_alias(self, o: TypeAlias, /) -> None: + return None + + def visit_namedtuple_expr(self, o: NamedTupleExpr, /) -> None: + return None + + def visit_typeddict_expr(self, o: TypedDictExpr, /) -> None: + return None + + def visit_newtype_expr(self, o: NewTypeExpr, /) -> None: + return None + + def visit__promote_expr(self, o: PromoteExpr, /) -> None: + return None + + def visit_complex_expr(self, o: ComplexExpr, /) -> None: + return None + + def visit_enum_call_expr(self, o: EnumCallExpr, /) -> None: + return None + + def visit_singleton_pattern(self, o: SingletonPattern, /) -> None: + return None + + +class ExtendedTraverserVisitor(TraverserVisitor): + """This is a more flexible traverser. + + In addition to the base traverser it: + * has visit_ methods for leaf nodes + * has common method that is called for all nodes + * allows skipping recursing into a node + + Note that this traverser still doesn't visit some internal + mypy constructs like _promote expression and Var. + """ + + def visit(self, o: Node) -> bool: + # If returns True, will continue to nested nodes. + return True + + def visit_mypy_file(self, o: MypyFile, /) -> None: + if not self.visit(o): + return + super().visit_mypy_file(o) + + # Module structure + + def visit_import(self, o: Import, /) -> None: + if not self.visit(o): + return + super().visit_import(o) + + def visit_import_from(self, o: ImportFrom, /) -> None: + if not self.visit(o): + return + super().visit_import_from(o) + + def visit_import_all(self, o: ImportAll, /) -> None: + if not self.visit(o): + return + super().visit_import_all(o) + + # Definitions + + def visit_func_def(self, o: FuncDef, /) -> None: + if not self.visit(o): + return + super().visit_func_def(o) + + def visit_overloaded_func_def(self, o: OverloadedFuncDef, /) -> None: + if not self.visit(o): + return + super().visit_overloaded_func_def(o) + + def visit_class_def(self, o: ClassDef, /) -> None: + if not self.visit(o): + return + super().visit_class_def(o) + + def visit_global_decl(self, o: GlobalDecl, /) -> None: + if not self.visit(o): + return + super().visit_global_decl(o) + + def visit_nonlocal_decl(self, o: NonlocalDecl, /) -> None: + if not self.visit(o): + return + super().visit_nonlocal_decl(o) + + def visit_decorator(self, o: Decorator, /) -> None: + if not self.visit(o): + return + super().visit_decorator(o) + + def visit_type_alias(self, o: TypeAlias, /) -> None: + if not self.visit(o): + return + super().visit_type_alias(o) + + # Statements + + def visit_block(self, block: Block, /) -> None: + if not self.visit(block): + return + super().visit_block(block) + + def visit_expression_stmt(self, o: ExpressionStmt, /) -> None: + if not self.visit(o): + return + super().visit_expression_stmt(o) + + def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None: + if not self.visit(o): + return + super().visit_assignment_stmt(o) + + def visit_operator_assignment_stmt(self, o: OperatorAssignmentStmt, /) -> None: + if not self.visit(o): + return + super().visit_operator_assignment_stmt(o) + + def visit_while_stmt(self, o: WhileStmt, /) -> None: + if not self.visit(o): + return + super().visit_while_stmt(o) + + def visit_for_stmt(self, o: ForStmt, /) -> None: + if not self.visit(o): + return + super().visit_for_stmt(o) + + def visit_return_stmt(self, o: ReturnStmt, /) -> None: + if not self.visit(o): + return + super().visit_return_stmt(o) + + def visit_assert_stmt(self, o: AssertStmt, /) -> None: + if not self.visit(o): + return + super().visit_assert_stmt(o) + + def visit_del_stmt(self, o: DelStmt, /) -> None: + if not self.visit(o): + return + super().visit_del_stmt(o) + + def visit_if_stmt(self, o: IfStmt, /) -> None: + if not self.visit(o): + return + super().visit_if_stmt(o) + + def visit_break_stmt(self, o: BreakStmt, /) -> None: + if not self.visit(o): + return + super().visit_break_stmt(o) + + def visit_continue_stmt(self, o: ContinueStmt, /) -> None: + if not self.visit(o): + return + super().visit_continue_stmt(o) + + def visit_pass_stmt(self, o: PassStmt, /) -> None: + if not self.visit(o): + return + super().visit_pass_stmt(o) + + def visit_raise_stmt(self, o: RaiseStmt, /) -> None: + if not self.visit(o): + return + super().visit_raise_stmt(o) + + def visit_try_stmt(self, o: TryStmt, /) -> None: + if not self.visit(o): + return + super().visit_try_stmt(o) + + def visit_with_stmt(self, o: WithStmt, /) -> None: + if not self.visit(o): + return + super().visit_with_stmt(o) + + def visit_match_stmt(self, o: MatchStmt, /) -> None: + if not self.visit(o): + return + super().visit_match_stmt(o) + + # Expressions (default no-op implementation) + + def visit_int_expr(self, o: IntExpr, /) -> None: + if not self.visit(o): + return + super().visit_int_expr(o) + + def visit_str_expr(self, o: StrExpr, /) -> None: + if not self.visit(o): + return + super().visit_str_expr(o) + + def visit_bytes_expr(self, o: BytesExpr, /) -> None: + if not self.visit(o): + return + super().visit_bytes_expr(o) + + def visit_float_expr(self, o: FloatExpr, /) -> None: + if not self.visit(o): + return + super().visit_float_expr(o) + + def visit_complex_expr(self, o: ComplexExpr, /) -> None: + if not self.visit(o): + return + super().visit_complex_expr(o) + + def visit_ellipsis(self, o: EllipsisExpr, /) -> None: + if not self.visit(o): + return + super().visit_ellipsis(o) + + def visit_star_expr(self, o: StarExpr, /) -> None: + if not self.visit(o): + return + super().visit_star_expr(o) + + def visit_name_expr(self, o: NameExpr, /) -> None: + if not self.visit(o): + return + super().visit_name_expr(o) + + def visit_member_expr(self, o: MemberExpr, /) -> None: + if not self.visit(o): + return + super().visit_member_expr(o) + + def visit_yield_from_expr(self, o: YieldFromExpr, /) -> None: + if not self.visit(o): + return + super().visit_yield_from_expr(o) + + def visit_yield_expr(self, o: YieldExpr, /) -> None: + if not self.visit(o): + return + super().visit_yield_expr(o) + + def visit_call_expr(self, o: CallExpr, /) -> None: + if not self.visit(o): + return + super().visit_call_expr(o) + + def visit_op_expr(self, o: OpExpr, /) -> None: + if not self.visit(o): + return + super().visit_op_expr(o) + + def visit_comparison_expr(self, o: ComparisonExpr, /) -> None: + if not self.visit(o): + return + super().visit_comparison_expr(o) + + def visit_cast_expr(self, o: CastExpr, /) -> None: + if not self.visit(o): + return + super().visit_cast_expr(o) + + def visit_type_form_expr(self, o: TypeFormExpr, /) -> None: + if not self.visit(o): + return + super().visit_type_form_expr(o) + + def visit_assert_type_expr(self, o: AssertTypeExpr, /) -> None: + if not self.visit(o): + return + super().visit_assert_type_expr(o) + + def visit_reveal_expr(self, o: RevealExpr, /) -> None: + if not self.visit(o): + return + super().visit_reveal_expr(o) + + def visit_super_expr(self, o: SuperExpr, /) -> None: + if not self.visit(o): + return + super().visit_super_expr(o) + + def visit_assignment_expr(self, o: AssignmentExpr, /) -> None: + if not self.visit(o): + return + super().visit_assignment_expr(o) + + def visit_unary_expr(self, o: UnaryExpr, /) -> None: + if not self.visit(o): + return + super().visit_unary_expr(o) + + def visit_list_expr(self, o: ListExpr, /) -> None: + if not self.visit(o): + return + super().visit_list_expr(o) + + def visit_dict_expr(self, o: DictExpr, /) -> None: + if not self.visit(o): + return + super().visit_dict_expr(o) + + def visit_template_str_expr(self, o: TemplateStrExpr, /) -> None: + if not self.visit(o): + return + super().visit_template_str_expr(o) + + def visit_tuple_expr(self, o: TupleExpr, /) -> None: + if not self.visit(o): + return + super().visit_tuple_expr(o) + + def visit_set_expr(self, o: SetExpr, /) -> None: + if not self.visit(o): + return + super().visit_set_expr(o) + + def visit_index_expr(self, o: IndexExpr, /) -> None: + if not self.visit(o): + return + super().visit_index_expr(o) + + def visit_type_application(self, o: TypeApplication, /) -> None: + if not self.visit(o): + return + super().visit_type_application(o) + + def visit_lambda_expr(self, o: LambdaExpr, /) -> None: + if not self.visit(o): + return + super().visit_lambda_expr(o) + + def visit_list_comprehension(self, o: ListComprehension, /) -> None: + if not self.visit(o): + return + super().visit_list_comprehension(o) + + def visit_set_comprehension(self, o: SetComprehension, /) -> None: + if not self.visit(o): + return + super().visit_set_comprehension(o) + + def visit_dictionary_comprehension(self, o: DictionaryComprehension, /) -> None: + if not self.visit(o): + return + super().visit_dictionary_comprehension(o) + + def visit_generator_expr(self, o: GeneratorExpr, /) -> None: + if not self.visit(o): + return + super().visit_generator_expr(o) + + def visit_slice_expr(self, o: SliceExpr, /) -> None: + if not self.visit(o): + return + super().visit_slice_expr(o) + + def visit_conditional_expr(self, o: ConditionalExpr, /) -> None: + if not self.visit(o): + return + super().visit_conditional_expr(o) + + def visit_type_var_expr(self, o: TypeVarExpr, /) -> None: + if not self.visit(o): + return + super().visit_type_var_expr(o) + + def visit_paramspec_expr(self, o: ParamSpecExpr, /) -> None: + if not self.visit(o): + return + super().visit_paramspec_expr(o) + + def visit_type_var_tuple_expr(self, o: TypeVarTupleExpr, /) -> None: + if not self.visit(o): + return + super().visit_type_var_tuple_expr(o) + + def visit_type_alias_expr(self, o: TypeAliasExpr, /) -> None: + if not self.visit(o): + return + super().visit_type_alias_expr(o) + + def visit_namedtuple_expr(self, o: NamedTupleExpr, /) -> None: + if not self.visit(o): + return + super().visit_namedtuple_expr(o) + + def visit_enum_call_expr(self, o: EnumCallExpr, /) -> None: + if not self.visit(o): + return + super().visit_enum_call_expr(o) + + def visit_typeddict_expr(self, o: TypedDictExpr, /) -> None: + if not self.visit(o): + return + super().visit_typeddict_expr(o) + + def visit_newtype_expr(self, o: NewTypeExpr, /) -> None: + if not self.visit(o): + return + super().visit_newtype_expr(o) + + def visit_await_expr(self, o: AwaitExpr, /) -> None: + if not self.visit(o): + return + super().visit_await_expr(o) + + # Patterns + + def visit_as_pattern(self, o: AsPattern, /) -> None: + if not self.visit(o): + return + super().visit_as_pattern(o) + + def visit_or_pattern(self, o: OrPattern, /) -> None: + if not self.visit(o): + return + super().visit_or_pattern(o) + + def visit_value_pattern(self, o: ValuePattern, /) -> None: + if not self.visit(o): + return + super().visit_value_pattern(o) + + def visit_singleton_pattern(self, o: SingletonPattern, /) -> None: + if not self.visit(o): + return + super().visit_singleton_pattern(o) + + def visit_sequence_pattern(self, o: SequencePattern, /) -> None: + if not self.visit(o): + return + super().visit_sequence_pattern(o) + + def visit_starred_pattern(self, o: StarredPattern, /) -> None: + if not self.visit(o): + return + super().visit_starred_pattern(o) + + def visit_mapping_pattern(self, o: MappingPattern, /) -> None: + if not self.visit(o): + return + super().visit_mapping_pattern(o) + + def visit_class_pattern(self, o: ClassPattern, /) -> None: + if not self.visit(o): + return + super().visit_class_pattern(o) + + +class ReturnSeeker(TraverserVisitor): + def __init__(self) -> None: + self.found = False + + def visit_return_stmt(self, o: ReturnStmt) -> None: + if o.expr is None or isinstance(o.expr, NameExpr) and o.expr.name == "None": + return + self.found = True + + +def has_return_statement(fdef: FuncBase) -> bool: + """Find if a function has a non-trivial return statement. + + Plain 'return' and 'return None' don't count. + """ + seeker = ReturnSeeker() + fdef.accept(seeker) + return seeker.found + + +class NameAndMemberCollector(TraverserVisitor): + def __init__(self) -> None: + super().__init__() + self.name_exprs: list[NameExpr] = [] + self.member_exprs: list[MemberExpr] = [] + + def visit_name_expr(self, o: NameExpr, /) -> None: + self.name_exprs.append(o) + super().visit_name_expr(o) + + def visit_member_expr(self, o: MemberExpr, /) -> None: + self.member_exprs.append(o) + super().visit_member_expr(o) + + +def all_name_and_member_expressions(node: Expression) -> tuple[list[NameExpr], list[MemberExpr]]: + v = NameAndMemberCollector() + node.accept(v) + return (v.name_exprs, v.member_exprs) + + +class StringSeeker(TraverserVisitor): + def __init__(self) -> None: + self.found = False + + def visit_str_expr(self, o: StrExpr, /) -> None: + self.found = True + + +def has_str_expression(node: Expression) -> bool: + v = StringSeeker() + node.accept(v) + return v.found + + +class FuncCollectorBase(TraverserVisitor): + def __init__(self) -> None: + self.inside_func = False + + def visit_func_def(self, defn: FuncDef) -> None: + if not self.inside_func: + self.inside_func = True + super().visit_func_def(defn) + self.inside_func = False + + +class YieldSeeker(FuncCollectorBase): + def __init__(self) -> None: + super().__init__() + self.found = False + + def visit_yield_expr(self, o: YieldExpr) -> None: + self.found = True + + +def has_yield_expression(fdef: FuncBase) -> bool: + seeker = YieldSeeker() + fdef.accept(seeker) + return seeker.found + + +class YieldFromSeeker(FuncCollectorBase): + def __init__(self) -> None: + super().__init__() + self.found = False + + def visit_yield_from_expr(self, o: YieldFromExpr) -> None: + self.found = True + + +def has_yield_from_expression(fdef: FuncBase) -> bool: + seeker = YieldFromSeeker() + fdef.accept(seeker) + return seeker.found + + +class AwaitSeeker(TraverserVisitor): + def __init__(self) -> None: + super().__init__() + self.found = False + + def visit_await_expr(self, o: AwaitExpr) -> None: + self.found = True + + +def has_await_expression(expr: Expression) -> bool: + seeker = AwaitSeeker() + expr.accept(seeker) + return seeker.found + + +class ReturnCollector(FuncCollectorBase): + def __init__(self) -> None: + super().__init__() + self.return_statements: list[ReturnStmt] = [] + + def visit_return_stmt(self, stmt: ReturnStmt) -> None: + self.return_statements.append(stmt) + + +def all_return_statements(node: Node) -> list[ReturnStmt]: + v = ReturnCollector() + node.accept(v) + return v.return_statements + + +class YieldCollector(FuncCollectorBase): + def __init__(self) -> None: + super().__init__() + self.in_assignment = False + self.yield_expressions: list[tuple[YieldExpr, bool]] = [] + + def visit_assignment_stmt(self, stmt: AssignmentStmt) -> None: + self.in_assignment = True + super().visit_assignment_stmt(stmt) + self.in_assignment = False + + def visit_yield_expr(self, expr: YieldExpr) -> None: + self.yield_expressions.append((expr, self.in_assignment)) + + +def all_yield_expressions(node: Node) -> list[tuple[YieldExpr, bool]]: + v = YieldCollector() + node.accept(v) + return v.yield_expressions + + +class YieldFromCollector(FuncCollectorBase): + def __init__(self) -> None: + super().__init__() + self.in_assignment = False + self.yield_from_expressions: list[tuple[YieldFromExpr, bool]] = [] + + def visit_assignment_stmt(self, stmt: AssignmentStmt) -> None: + self.in_assignment = True + super().visit_assignment_stmt(stmt) + self.in_assignment = False + + def visit_yield_from_expr(self, expr: YieldFromExpr) -> None: + self.yield_from_expressions.append((expr, self.in_assignment)) diff --git a/micromamba_root/Lib/site-packages/mypy/treetransform.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/treetransform.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..022721d182b9f5bd9a90aabb7adb95842fed94f0 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/treetransform.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/treetransform.py b/micromamba_root/Lib/site-packages/mypy/treetransform.py new file mode 100644 index 0000000000000000000000000000000000000000..25092de66a149d143a96c92fbea58c6ad6664f3b --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/treetransform.py @@ -0,0 +1,820 @@ +"""Base visitor that implements an identity AST transform. + +Subclass TransformVisitor to perform non-trivial transformations. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import cast + +from mypy.nodes import ( + GDEF, + REVEAL_TYPE, + Argument, + AssertStmt, + AssertTypeExpr, + AssignmentExpr, + AssignmentStmt, + AwaitExpr, + Block, + BreakStmt, + BytesExpr, + CallExpr, + CastExpr, + ClassDef, + ComparisonExpr, + ComplexExpr, + ConditionalExpr, + ContinueStmt, + Decorator, + DelStmt, + DictExpr, + DictionaryComprehension, + EllipsisExpr, + EnumCallExpr, + Expression, + ExpressionStmt, + FloatExpr, + ForStmt, + FuncDef, + FuncItem, + GeneratorExpr, + GlobalDecl, + IfStmt, + Import, + ImportAll, + ImportFrom, + IndexExpr, + IntExpr, + LambdaExpr, + ListComprehension, + ListExpr, + MatchStmt, + MemberExpr, + MypyFile, + NamedTupleExpr, + NameExpr, + NewTypeExpr, + Node, + NonlocalDecl, + OperatorAssignmentStmt, + OpExpr, + OverloadedFuncDef, + OverloadPart, + ParamSpecExpr, + PassStmt, + PromoteExpr, + RaiseStmt, + RefExpr, + ReturnStmt, + RevealExpr, + SetComprehension, + SetExpr, + SliceExpr, + StarExpr, + Statement, + StrExpr, + SuperExpr, + SymbolTable, + TemplateStrExpr, + TempNode, + TryStmt, + TupleExpr, + TypeAliasExpr, + TypeApplication, + TypedDictExpr, + TypeFormExpr, + TypeVarExpr, + TypeVarTupleExpr, + UnaryExpr, + Var, + WhileStmt, + WithStmt, + YieldExpr, + YieldFromExpr, +) +from mypy.patterns import ( + AsPattern, + ClassPattern, + MappingPattern, + OrPattern, + Pattern, + SequencePattern, + SingletonPattern, + StarredPattern, + ValuePattern, +) +from mypy.traverser import TraverserVisitor +from mypy.types import FunctionLike, ProperType, Type +from mypy.util import replace_object_state +from mypy.visitor import NodeVisitor + + +class TransformVisitor(NodeVisitor[Node]): + """Transform a semantically analyzed AST (or subtree) to an identical copy. + + Use the node() method to transform an AST node. + + Subclass to perform a non-identity transform. + + Notes: + + * This can only be used to transform functions or classes, not top-level + statements, and/or modules as a whole. + * Do not duplicate TypeInfo nodes. This would generally not be desirable. + * Only update some name binding cross-references, but only those that + refer to Var, Decorator or FuncDef nodes, not those targeting ClassDef or + TypeInfo nodes. + * Types are not transformed, but you can override type() to also perform + type transformation. + + TODO nested classes and functions have not been tested well enough + """ + + def __init__(self) -> None: + # To simplify testing, set this flag to True if you want to transform + # all statements in a file (this is prohibited in normal mode). + self.test_only = False + # There may be multiple references to a Var node. Keep track of + # Var translations using a dictionary. + self.var_map: dict[Var, Var] = {} + # These are uninitialized placeholder nodes used temporarily for nested + # functions while we are transforming a top-level function. This maps an + # untransformed node to a placeholder (which will later become the + # transformed node). + self.func_placeholder_map: dict[FuncDef, FuncDef] = {} + + def visit_mypy_file(self, node: MypyFile) -> MypyFile: + assert self.test_only, "This visitor should not be used for whole files." + # NOTE: The 'names' and 'imports' instance variables will be empty! + ignored_lines = {line: codes.copy() for line, codes in node.ignored_lines.items()} + new = MypyFile(self.statements(node.defs), [], node.is_bom, ignored_lines=ignored_lines) + new._fullname = node._fullname + new.path = node.path + new.names = SymbolTable() + return new + + def visit_import(self, node: Import) -> Import: + return Import(node.ids.copy()) + + def visit_import_from(self, node: ImportFrom) -> ImportFrom: + return ImportFrom(node.id, node.relative, node.names.copy()) + + def visit_import_all(self, node: ImportAll) -> ImportAll: + return ImportAll(node.id, node.relative) + + def copy_argument(self, argument: Argument) -> Argument: + arg = Argument( + self.visit_var(argument.variable), + argument.type_annotation, + argument.initializer, + argument.kind, + ) + + # Refresh lines of the inner things + arg.set_line(argument) + + return arg + + def visit_func_def(self, node: FuncDef) -> FuncDef: + # Note that a FuncDef must be transformed to a FuncDef. + + # These contortions are needed to handle the case of recursive + # references inside the function being transformed. + # Set up placeholder nodes for references within this function + # to other functions defined inside it. + # Don't create an entry for this function itself though, + # since we want self-references to point to the original + # function if this is the top-level node we are transforming. + init = FuncMapInitializer(self) + for stmt in node.body.body: + stmt.accept(init) + + new = FuncDef( + node.name, + [self.copy_argument(arg) for arg in node.arguments], + self.block(node.body), + cast(FunctionLike | None, self.optional_type(node.type)), + ) + + self.copy_function_attributes(new, node) + + new._fullname = node._fullname + new.is_decorated = node.is_decorated + new.is_conditional = node.is_conditional + new.abstract_status = node.abstract_status + new.is_static = node.is_static + new.is_class = node.is_class + new.is_property = node.is_property + new.is_final = node.is_final + new.original_def = node.original_def + + if node in self.func_placeholder_map: + # There is a placeholder definition for this function. Replace + # the attributes of the placeholder with those form the transformed + # function. We know that the classes will be identical (otherwise + # this wouldn't work). + result = self.func_placeholder_map[node] + replace_object_state(result, new) + return result + else: + return new + + def visit_lambda_expr(self, node: LambdaExpr) -> LambdaExpr: + new = LambdaExpr( + [self.copy_argument(arg) for arg in node.arguments], + self.block(node.body), + cast(FunctionLike | None, self.optional_type(node.type)), + ) + self.copy_function_attributes(new, node) + return new + + def copy_function_attributes(self, new: FuncItem, original: FuncItem) -> None: + new.info = original.info + new.min_args = original.min_args + new.max_pos = original.max_pos + new.is_overload = original.is_overload + new.is_generator = original.is_generator + new.is_coroutine = original.is_coroutine + new.is_async_generator = original.is_async_generator + new.is_awaitable_coroutine = original.is_awaitable_coroutine + new.line = original.line + + def visit_overloaded_func_def(self, node: OverloadedFuncDef) -> OverloadedFuncDef: + items = [cast(OverloadPart, item.accept(self)) for item in node.items] + for newitem, olditem in zip(items, node.items): + newitem.line = olditem.line + new = OverloadedFuncDef(items) + new._fullname = node._fullname + new_type = self.optional_type(node.type) + assert isinstance(new_type, ProperType) + new.type = new_type + new.info = node.info + new.is_static = node.is_static + new.is_class = node.is_class + new.is_property = node.is_property + new.is_final = node.is_final + if node.impl: + new.impl = cast(OverloadPart, node.impl.accept(self)) + return new + + def visit_class_def(self, node: ClassDef) -> ClassDef: + keywords = [(key, self.expr(value)) for key, value in node.keywords.items()] + new = ClassDef( + node.name, + self.block(node.defs), + node.type_vars, + self.expressions(node.base_type_exprs), + self.optional_expr(node.metaclass), + keywords, + ) + new.fullname = node.fullname + new.info = node.info + new.decorators = [self.expr(decorator) for decorator in node.decorators] + return new + + def visit_global_decl(self, node: GlobalDecl) -> GlobalDecl: + return GlobalDecl(node.names.copy()) + + def visit_nonlocal_decl(self, node: NonlocalDecl) -> NonlocalDecl: + return NonlocalDecl(node.names.copy()) + + def visit_block(self, node: Block) -> Block: + return Block(self.statements(node.body), is_unreachable=node.is_unreachable) + + def visit_decorator(self, node: Decorator) -> Decorator: + # Note that a Decorator must be transformed to a Decorator. + func = self.visit_func_def(node.func) + func.line = node.func.line + new = Decorator(func, self.expressions(node.decorators), self.visit_var(node.var)) + new.is_overload = node.is_overload + return new + + def visit_var(self, node: Var) -> Var: + # Note that a Var must be transformed to a Var. + if node in self.var_map: + return self.var_map[node] + new = Var(node.name, self.optional_type(node.type)) + new.line = node.line + new._fullname = node._fullname + new.info = node.info + new.is_self = node.is_self + new.is_ready = node.is_ready + new.is_initialized_in_class = node.is_initialized_in_class + new.is_staticmethod = node.is_staticmethod + new.is_classmethod = node.is_classmethod + new.is_property = node.is_property + new.is_final = node.is_final + new.final_value = node.final_value + new.final_unset_in_class = node.final_unset_in_class + new.final_set_in_init = node.final_set_in_init + new.set_line(node) + self.var_map[node] = new + return new + + def visit_expression_stmt(self, node: ExpressionStmt) -> ExpressionStmt: + return ExpressionStmt(self.expr(node.expr)) + + def visit_assignment_stmt(self, node: AssignmentStmt) -> AssignmentStmt: + return self.duplicate_assignment(node) + + def duplicate_assignment(self, node: AssignmentStmt) -> AssignmentStmt: + new = AssignmentStmt( + self.expressions(node.lvalues), + self.expr(node.rvalue), + self.optional_type(node.unanalyzed_type), + ) + new.line = node.line + new.is_final_def = node.is_final_def + new.type = self.optional_type(node.type) + return new + + def visit_operator_assignment_stmt( + self, node: OperatorAssignmentStmt + ) -> OperatorAssignmentStmt: + return OperatorAssignmentStmt(node.op, self.expr(node.lvalue), self.expr(node.rvalue)) + + def visit_while_stmt(self, node: WhileStmt) -> WhileStmt: + return WhileStmt( + self.expr(node.expr), self.block(node.body), self.optional_block(node.else_body) + ) + + def visit_for_stmt(self, node: ForStmt) -> ForStmt: + new = ForStmt( + self.expr(node.index), + self.expr(node.expr), + self.block(node.body), + self.optional_block(node.else_body), + self.optional_type(node.unanalyzed_index_type), + ) + new.is_async = node.is_async + new.index_type = self.optional_type(node.index_type) + return new + + def visit_return_stmt(self, node: ReturnStmt) -> ReturnStmt: + return ReturnStmt(self.optional_expr(node.expr)) + + def visit_assert_stmt(self, node: AssertStmt) -> AssertStmt: + return AssertStmt(self.expr(node.expr), self.optional_expr(node.msg)) + + def visit_del_stmt(self, node: DelStmt) -> DelStmt: + return DelStmt(self.expr(node.expr)) + + def visit_if_stmt(self, node: IfStmt) -> IfStmt: + return IfStmt( + self.expressions(node.expr), + self.blocks(node.body), + self.optional_block(node.else_body), + ) + + def visit_break_stmt(self, node: BreakStmt) -> BreakStmt: + return BreakStmt() + + def visit_continue_stmt(self, node: ContinueStmt) -> ContinueStmt: + return ContinueStmt() + + def visit_pass_stmt(self, node: PassStmt) -> PassStmt: + return PassStmt() + + def visit_raise_stmt(self, node: RaiseStmt) -> RaiseStmt: + return RaiseStmt(self.optional_expr(node.expr), self.optional_expr(node.from_expr)) + + def visit_try_stmt(self, node: TryStmt) -> TryStmt: + new = TryStmt( + self.block(node.body), + self.optional_names(node.vars), + self.optional_expressions(node.types), + self.blocks(node.handlers), + self.optional_block(node.else_body), + self.optional_block(node.finally_body), + ) + new.is_star = node.is_star + return new + + def visit_with_stmt(self, node: WithStmt) -> WithStmt: + new = WithStmt( + self.expressions(node.expr), + self.optional_expressions(node.target), + self.block(node.body), + self.optional_type(node.unanalyzed_type), + ) + new.is_async = node.is_async + new.analyzed_types = [self.type(typ) for typ in node.analyzed_types] + return new + + def visit_as_pattern(self, p: AsPattern) -> AsPattern: + return AsPattern( + pattern=self.pattern(p.pattern) if p.pattern is not None else None, + name=self.duplicate_name(p.name) if p.name is not None else None, + ) + + def visit_or_pattern(self, p: OrPattern) -> OrPattern: + return OrPattern([self.pattern(pat) for pat in p.patterns]) + + def visit_value_pattern(self, p: ValuePattern) -> ValuePattern: + return ValuePattern(self.expr(p.expr)) + + def visit_singleton_pattern(self, p: SingletonPattern) -> SingletonPattern: + return SingletonPattern(p.value) + + def visit_sequence_pattern(self, p: SequencePattern) -> SequencePattern: + return SequencePattern([self.pattern(pat) for pat in p.patterns]) + + def visit_starred_pattern(self, p: StarredPattern) -> StarredPattern: + return StarredPattern(self.duplicate_name(p.capture) if p.capture is not None else None) + + def visit_mapping_pattern(self, p: MappingPattern) -> MappingPattern: + return MappingPattern( + keys=[self.expr(expr) for expr in p.keys], + values=[self.pattern(pat) for pat in p.values], + rest=self.duplicate_name(p.rest) if p.rest is not None else None, + ) + + def visit_class_pattern(self, p: ClassPattern) -> ClassPattern: + class_ref = p.class_ref.accept(self) + assert isinstance(class_ref, RefExpr) + return ClassPattern( + class_ref=class_ref, + positionals=[self.pattern(pat) for pat in p.positionals], + keyword_keys=list(p.keyword_keys), + keyword_values=[self.pattern(pat) for pat in p.keyword_values], + ) + + def visit_match_stmt(self, o: MatchStmt) -> MatchStmt: + return MatchStmt( + subject=self.expr(o.subject), + patterns=[self.pattern(p) for p in o.patterns], + guards=self.optional_expressions(o.guards), + bodies=self.blocks(o.bodies), + ) + + def visit_star_expr(self, node: StarExpr) -> StarExpr: + return StarExpr(node.expr) + + def visit_int_expr(self, node: IntExpr) -> IntExpr: + return IntExpr(node.value) + + def visit_str_expr(self, node: StrExpr) -> StrExpr: + return StrExpr(node.value) + + def visit_bytes_expr(self, node: BytesExpr) -> BytesExpr: + return BytesExpr(node.value) + + def visit_float_expr(self, node: FloatExpr) -> FloatExpr: + return FloatExpr(node.value) + + def visit_complex_expr(self, node: ComplexExpr) -> ComplexExpr: + return ComplexExpr(node.value) + + def visit_ellipsis(self, node: EllipsisExpr) -> EllipsisExpr: + return EllipsisExpr() + + def visit_name_expr(self, node: NameExpr) -> NameExpr: + return self.duplicate_name(node) + + def duplicate_name(self, node: NameExpr) -> NameExpr: + # This method is used when the transform result must be a NameExpr. + # visit_name_expr() is used when there is no such restriction. + new = NameExpr(node.name) + self.copy_ref(new, node) + new.is_special_form = node.is_special_form + return new + + def visit_member_expr(self, node: MemberExpr) -> MemberExpr: + member = MemberExpr(self.expr(node.expr), node.name) + if node.def_var: + # This refers to an attribute and we don't transform attributes by default, + # just normal variables. + member.def_var = node.def_var + self.copy_ref(member, node) + return member + + def copy_ref(self, new: RefExpr, original: RefExpr) -> None: + new.kind = original.kind + new.fullname = original.fullname + target = original.node + if isinstance(target, Var): + # Do not transform references to global variables. See + # testGenericFunctionAliasExpand for an example where this is important. + if original.kind != GDEF: + target = self.visit_var(target) + elif isinstance(target, Decorator): + target = self.visit_var(target.var) + elif isinstance(target, FuncDef): + # Use a placeholder node for the function if it exists. + target = self.func_placeholder_map.get(target, target) + new.node = target + new.is_new_def = original.is_new_def + new.is_inferred_def = original.is_inferred_def + + def visit_yield_from_expr(self, node: YieldFromExpr) -> YieldFromExpr: + return YieldFromExpr(self.expr(node.expr)) + + def visit_yield_expr(self, node: YieldExpr) -> YieldExpr: + return YieldExpr(self.optional_expr(node.expr)) + + def visit_await_expr(self, node: AwaitExpr) -> AwaitExpr: + return AwaitExpr(self.expr(node.expr)) + + def visit_call_expr(self, node: CallExpr) -> CallExpr: + return CallExpr( + self.expr(node.callee), + self.expressions(node.args), + node.arg_kinds.copy(), + node.arg_names.copy(), + self.optional_expr(node.analyzed), + ) + + def visit_op_expr(self, node: OpExpr) -> OpExpr: + new = OpExpr( + node.op, + self.expr(node.left), + self.expr(node.right), + cast(TypeAliasExpr | None, self.optional_expr(node.analyzed)), + ) + new.method_type = self.optional_type(node.method_type) + return new + + def visit_comparison_expr(self, node: ComparisonExpr) -> ComparisonExpr: + new = ComparisonExpr(node.operators, self.expressions(node.operands)) + new.method_types = [self.optional_type(t) for t in node.method_types] + return new + + def visit_cast_expr(self, node: CastExpr) -> CastExpr: + return CastExpr(self.expr(node.expr), self.type(node.type)) + + def visit_type_form_expr(self, node: TypeFormExpr) -> TypeFormExpr: + return TypeFormExpr(self.type(node.type)) + + def visit_assert_type_expr(self, node: AssertTypeExpr) -> AssertTypeExpr: + return AssertTypeExpr(self.expr(node.expr), self.type(node.type)) + + def visit_reveal_expr(self, node: RevealExpr) -> RevealExpr: + if node.kind == REVEAL_TYPE: + assert node.expr is not None + return RevealExpr(kind=REVEAL_TYPE, expr=self.expr(node.expr)) + else: + # Reveal locals expressions don't have any sub expressions + return node + + def visit_super_expr(self, node: SuperExpr) -> SuperExpr: + call = self.expr(node.call) + assert isinstance(call, CallExpr) + new = SuperExpr(node.name, call) + new.info = node.info + return new + + def visit_assignment_expr(self, node: AssignmentExpr) -> AssignmentExpr: + return AssignmentExpr(self.duplicate_name(node.target), self.expr(node.value)) + + def visit_unary_expr(self, node: UnaryExpr) -> UnaryExpr: + new = UnaryExpr(node.op, self.expr(node.expr)) + new.method_type = self.optional_type(node.method_type) + return new + + def visit_list_expr(self, node: ListExpr) -> ListExpr: + return ListExpr(self.expressions(node.items)) + + def visit_dict_expr(self, node: DictExpr) -> DictExpr: + return DictExpr( + [(self.expr(key) if key else None, self.expr(value)) for key, value in node.items] + ) + + def visit_template_str_expr(self, node: TemplateStrExpr) -> TemplateStrExpr: + items: list[Expression | tuple[Expression, str, str | None, Expression | None]] = [] + for item in node.items: + if isinstance(item, tuple): + value, source, conversion, format_spec = item + items.append( + (self.expr(value), source, conversion, self.optional_expr(format_spec)) + ) + else: + items.append(self.expr(item)) + return TemplateStrExpr(items) + + def visit_tuple_expr(self, node: TupleExpr) -> TupleExpr: + return TupleExpr(self.expressions(node.items)) + + def visit_set_expr(self, node: SetExpr) -> SetExpr: + return SetExpr(self.expressions(node.items)) + + def visit_index_expr(self, node: IndexExpr) -> IndexExpr: + new = IndexExpr(self.expr(node.base), self.expr(node.index)) + if node.method_type: + new.method_type = self.type(node.method_type) + if node.analyzed: + if isinstance(node.analyzed, TypeApplication): + new.analyzed = self.visit_type_application(node.analyzed) + else: + new.analyzed = self.visit_type_alias_expr(node.analyzed) + new.analyzed.set_line(node.analyzed) + return new + + def visit_type_application(self, node: TypeApplication) -> TypeApplication: + return TypeApplication(self.expr(node.expr), self.types(node.types)) + + def visit_list_comprehension(self, node: ListComprehension) -> ListComprehension: + generator = self.duplicate_generator(node.generator) + generator.set_line(node.generator) + return ListComprehension(generator) + + def visit_set_comprehension(self, node: SetComprehension) -> SetComprehension: + generator = self.duplicate_generator(node.generator) + generator.set_line(node.generator) + return SetComprehension(generator) + + def visit_dictionary_comprehension( + self, node: DictionaryComprehension + ) -> DictionaryComprehension: + return DictionaryComprehension( + self.expr(node.key), + self.expr(node.value), + [self.expr(index) for index in node.indices], + [self.expr(s) for s in node.sequences], + [[self.expr(cond) for cond in conditions] for conditions in node.condlists], + node.is_async, + ) + + def visit_generator_expr(self, node: GeneratorExpr) -> GeneratorExpr: + return self.duplicate_generator(node) + + def duplicate_generator(self, node: GeneratorExpr) -> GeneratorExpr: + return GeneratorExpr( + self.expr(node.left_expr), + [self.expr(index) for index in node.indices], + [self.expr(s) for s in node.sequences], + [[self.expr(cond) for cond in conditions] for conditions in node.condlists], + node.is_async, + ) + + def visit_slice_expr(self, node: SliceExpr) -> SliceExpr: + return SliceExpr( + self.optional_expr(node.begin_index), + self.optional_expr(node.end_index), + self.optional_expr(node.stride), + ) + + def visit_conditional_expr(self, node: ConditionalExpr) -> ConditionalExpr: + return ConditionalExpr( + self.expr(node.cond), self.expr(node.if_expr), self.expr(node.else_expr) + ) + + def visit_type_var_expr(self, node: TypeVarExpr) -> TypeVarExpr: + return TypeVarExpr( + node.name, + node.fullname, + self.types(node.values), + self.type(node.upper_bound), + self.type(node.default), + variance=node.variance, + ) + + def visit_paramspec_expr(self, node: ParamSpecExpr) -> ParamSpecExpr: + return ParamSpecExpr( + node.name, + node.fullname, + self.type(node.upper_bound), + self.type(node.default), + variance=node.variance, + ) + + def visit_type_var_tuple_expr(self, node: TypeVarTupleExpr) -> TypeVarTupleExpr: + return TypeVarTupleExpr( + node.name, + node.fullname, + self.type(node.upper_bound), + node.tuple_fallback, + self.type(node.default), + variance=node.variance, + ) + + def visit_type_alias_expr(self, node: TypeAliasExpr) -> TypeAliasExpr: + return TypeAliasExpr(node.node) + + def visit_newtype_expr(self, node: NewTypeExpr) -> NewTypeExpr: + res = NewTypeExpr(node.name, node.old_type, line=node.line, column=node.column) + res.info = node.info + return res + + def visit_namedtuple_expr(self, node: NamedTupleExpr) -> NamedTupleExpr: + return NamedTupleExpr(node.info) + + def visit_enum_call_expr(self, node: EnumCallExpr) -> EnumCallExpr: + return EnumCallExpr(node.info, node.items, node.values) + + def visit_typeddict_expr(self, node: TypedDictExpr) -> Node: + return TypedDictExpr(node.info) + + def visit__promote_expr(self, node: PromoteExpr) -> PromoteExpr: + return PromoteExpr(node.type) + + def visit_temp_node(self, node: TempNode) -> TempNode: + return TempNode(self.type(node.type)) + + def node(self, node: Node) -> Node: + new = node.accept(self) + new.set_line(node) + return new + + def mypyfile(self, node: MypyFile) -> MypyFile: + new = node.accept(self) + assert isinstance(new, MypyFile) + new.set_line(node) + return new + + def expr(self, expr: Expression) -> Expression: + new = expr.accept(self) + assert isinstance(new, Expression) + new.set_line(expr) + return new + + def stmt(self, stmt: Statement) -> Statement: + new = stmt.accept(self) + assert isinstance(new, Statement) + new.set_line(stmt) + return new + + def pattern(self, pattern: Pattern) -> Pattern: + new = pattern.accept(self) + assert isinstance(new, Pattern) + new.set_line(pattern) + return new + + # Helpers + # + # All the node helpers also propagate line numbers. + + def optional_expr(self, expr: Expression | None) -> Expression | None: + if expr: + return self.expr(expr) + else: + return None + + def block(self, block: Block) -> Block: + new = self.visit_block(block) + new.line = block.line + return new + + def optional_block(self, block: Block | None) -> Block | None: + if block: + return self.block(block) + else: + return None + + def statements(self, statements: list[Statement]) -> list[Statement]: + return [self.stmt(stmt) for stmt in statements] + + def expressions(self, expressions: list[Expression]) -> list[Expression]: + return [self.expr(expr) for expr in expressions] + + def optional_expressions( + self, expressions: Iterable[Expression | None] + ) -> list[Expression | None]: + return [self.optional_expr(expr) for expr in expressions] + + def blocks(self, blocks: list[Block]) -> list[Block]: + return [self.block(block) for block in blocks] + + def names(self, names: list[NameExpr]) -> list[NameExpr]: + return [self.duplicate_name(name) for name in names] + + def optional_names(self, names: Iterable[NameExpr | None]) -> list[NameExpr | None]: + result: list[NameExpr | None] = [] + for name in names: + if name: + result.append(self.duplicate_name(name)) + else: + result.append(None) + return result + + def type(self, type: Type) -> Type: + # Override this method to transform types. + return type + + def optional_type(self, type: Type | None) -> Type | None: + if type: + return self.type(type) + else: + return None + + def types(self, types: list[Type]) -> list[Type]: + return [self.type(type) for type in types] + + +class FuncMapInitializer(TraverserVisitor): + """This traverser creates mappings from nested FuncDefs to placeholder FuncDefs. + + The placeholders will later be replaced with transformed nodes. + """ + + def __init__(self, transformer: TransformVisitor) -> None: + self.transformer = transformer + + def visit_func_def(self, node: FuncDef) -> None: + if node not in self.transformer.func_placeholder_map: + # Haven't seen this FuncDef before, so create a placeholder node. + self.transformer.func_placeholder_map[node] = FuncDef( + node.name, node.arguments, node.body, None + ) + super().visit_func_def(node) diff --git a/micromamba_root/Lib/site-packages/mypy/tvar_scope.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/tvar_scope.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..26e321941c70ce617c6725d469e7e9e701f203c1 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/tvar_scope.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/tvar_scope.py b/micromamba_root/Lib/site-packages/mypy/tvar_scope.py new file mode 100644 index 0000000000000000000000000000000000000000..e65f9f5ee3a429b6e4385fc5d2f715114db6bd92 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/tvar_scope.py @@ -0,0 +1,216 @@ +from __future__ import annotations + +from collections.abc import Callable +from typing import TypeAlias as _TypeAlias + +from mypy.nodes import ( + Context, + ParamSpecExpr, + SymbolTableNode, + TypeVarExpr, + TypeVarLikeExpr, + TypeVarTupleExpr, +) +from mypy.types import ( + AnyType, + ParamSpecFlavor, + ParamSpecType, + TrivialSyntheticTypeTranslator, + Type, + TypeAliasType, + TypeOfAny, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, +) + +FailFunc: _TypeAlias = Callable[[str, Context], None] + + +class TypeVarLikeDefaultFixer(TrivialSyntheticTypeTranslator): + """Set namespace for all TypeVarLikeTypes types.""" + + def __init__( + self, + scope: TypeVarLikeScope, + fail_func: FailFunc, + source_tv: TypeVarLikeExpr, + context: Context, + ) -> None: + self.scope = scope + self.fail_func = fail_func + self.source_tv = source_tv + self.context = context + super().__init__() + + def visit_type_var(self, t: TypeVarType) -> Type: + existing = self.scope.get_binding(t.fullname) + if existing is None: + self._report_unbound_tvar(t) + return AnyType(TypeOfAny.from_error) + return existing + + def visit_param_spec(self, t: ParamSpecType) -> Type: + existing = self.scope.get_binding(t.fullname) + if existing is None: + self._report_unbound_tvar(t) + return AnyType(TypeOfAny.from_error) + return existing + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type: + existing = self.scope.get_binding(t.fullname) + if existing is None: + self._report_unbound_tvar(t) + return AnyType(TypeOfAny.from_error) + return existing + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + return t + + def _report_unbound_tvar(self, tvar: TypeVarLikeType) -> None: + self.fail_func( + f"Type variable {tvar.name} referenced in the default" + f" of {self.source_tv.name} is unbound", + self.context, + ) + + +class TypeVarLikeScope: + """Scope that holds bindings for type variables and parameter specifications. + + Node fullname -> TypeVarLikeType. + """ + + def __init__( + self, + parent: TypeVarLikeScope | None = None, + is_class_scope: bool = False, + prohibited: TypeVarLikeScope | None = None, + namespace: str = "", + ) -> None: + """Initializer for TypeVarLikeScope + + Parameters: + parent: the outer scope for this scope + is_class_scope: True if this represents a generic class + prohibited: Type variables that aren't strictly in scope exactly, + but can't be bound because they're part of an outer class's scope. + """ + self.scope: dict[str, TypeVarLikeType] = {} + self.parent = parent + self.func_id = 0 + self.class_id = 0 + self.is_class_scope = is_class_scope + self.prohibited = prohibited + self.namespace = namespace + if parent is not None: + self.func_id = parent.func_id + self.class_id = parent.class_id + + def get_function_scope(self) -> TypeVarLikeScope | None: + """Get the nearest parent that's a function scope, not a class scope""" + it: TypeVarLikeScope | None = self + while it is not None and it.is_class_scope: + it = it.parent + return it + + def allow_binding(self, fullname: str) -> bool: + if fullname in self.scope: + return False + elif self.parent and not self.parent.allow_binding(fullname): + return False + elif self.prohibited and not self.prohibited.allow_binding(fullname): + return False + return True + + def method_frame(self, namespace: str) -> TypeVarLikeScope: + """A new scope frame for binding a method""" + return TypeVarLikeScope(self, False, None, namespace=namespace) + + def class_frame(self, namespace: str) -> TypeVarLikeScope: + """A new scope frame for binding a class. Prohibits *this* class's tvars""" + return TypeVarLikeScope(self.get_function_scope(), True, self, namespace=namespace) + + def new_unique_func_id(self) -> TypeVarId: + """Used by plugin-like code that needs to make synthetic generic functions.""" + self.func_id -= 1 + return TypeVarId(self.func_id) + + def bind_new( + self, name: str, tvar_expr: TypeVarLikeExpr, fail_func: FailFunc, context: Context + ) -> TypeVarLikeType: + if self.is_class_scope: + self.class_id += 1 + i = self.class_id + else: + self.func_id -= 1 + i = self.func_id + namespace = self.namespace + + # Defaults may reference other type variables. That is only valid when the + # referenced variable is already in scope (textually precedes the definition we're + # processing now). + default = tvar_expr.default.accept( + TypeVarLikeDefaultFixer( + self, fail_func=fail_func, source_tv=tvar_expr, context=context + ) + ) + + if isinstance(tvar_expr, TypeVarExpr): + tvar_def: TypeVarLikeType = TypeVarType( + name=name, + fullname=tvar_expr.fullname, + id=TypeVarId(i, namespace=namespace), + values=tvar_expr.values, + upper_bound=tvar_expr.upper_bound, + default=default, + variance=tvar_expr.variance, + line=tvar_expr.line, + column=tvar_expr.column, + ) + elif isinstance(tvar_expr, ParamSpecExpr): + tvar_def = ParamSpecType( + name=name, + fullname=tvar_expr.fullname, + id=TypeVarId(i, namespace=namespace), + flavor=ParamSpecFlavor.BARE, + upper_bound=tvar_expr.upper_bound, + default=default, + line=tvar_expr.line, + column=tvar_expr.column, + ) + elif isinstance(tvar_expr, TypeVarTupleExpr): + tvar_def = TypeVarTupleType( + name=name, + fullname=tvar_expr.fullname, + id=TypeVarId(i, namespace=namespace), + upper_bound=tvar_expr.upper_bound, + tuple_fallback=tvar_expr.tuple_fallback, + default=default, + line=tvar_expr.line, + column=tvar_expr.column, + ) + else: + assert False + self.scope[tvar_expr.fullname] = tvar_def + return tvar_def + + def bind_existing(self, tvar_def: TypeVarLikeType) -> None: + self.scope[tvar_def.fullname] = tvar_def + + def get_binding(self, item: str | SymbolTableNode) -> TypeVarLikeType | None: + fullname = item.fullname if isinstance(item, SymbolTableNode) else item + assert fullname + if fullname in self.scope: + return self.scope[fullname] + elif self.parent is not None: + return self.parent.get_binding(fullname) + else: + return None + + def __str__(self) -> str: + me = ", ".join(f"{k}: {v.name}`{v.id}" for k, v in self.scope.items()) + if self.parent is None: + return me + return f"{self.parent} <- {me}" diff --git a/micromamba_root/Lib/site-packages/mypy/type_visitor.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/type_visitor.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..a7f9ccb07476121945256f55827cd28ac8e74072 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/type_visitor.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/type_visitor.py b/micromamba_root/Lib/site-packages/mypy/type_visitor.py new file mode 100644 index 0000000000000000000000000000000000000000..1b38481ba000479a071973a8e56eeecffceb362c --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/type_visitor.py @@ -0,0 +1,612 @@ +"""Type visitor classes. + +This module defines the type visitors that are intended to be +subclassed by other code. They have been separated out into their own +module to ease converting mypy to run under mypyc, since currently +mypyc-extension classes can extend interpreted classes but not the +other way around. Separating them out, then, allows us to compile +types before we can compile everything that uses a TypeVisitor. + +The visitors are all re-exported from mypy.types and that is how +other modules refer to them. +""" + +from __future__ import annotations + +from abc import abstractmethod +from collections.abc import Iterable, Sequence +from typing import Any, Final, Generic, TypeVar, cast + +from mypy_extensions import mypyc_attr, trait + +from mypy.types import ( + AnyType, + CallableArgument, + CallableType, + DeletedType, + EllipsisType, + ErasedType, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + PlaceholderType, + RawExpressionType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeList, + TypeType, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + get_proper_type, +) + +T = TypeVar("T", covariant=True) + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class TypeVisitor(Generic[T]): + """Visitor class for types (Type subclasses). + + The parameter T is the return type of the visit methods. + """ + + @abstractmethod + def visit_unbound_type(self, t: UnboundType, /) -> T: + pass + + @abstractmethod + def visit_any(self, t: AnyType, /) -> T: + pass + + @abstractmethod + def visit_none_type(self, t: NoneType, /) -> T: + pass + + @abstractmethod + def visit_uninhabited_type(self, t: UninhabitedType, /) -> T: + pass + + @abstractmethod + def visit_erased_type(self, t: ErasedType, /) -> T: + pass + + @abstractmethod + def visit_deleted_type(self, t: DeletedType, /) -> T: + pass + + @abstractmethod + def visit_type_var(self, t: TypeVarType, /) -> T: + pass + + @abstractmethod + def visit_param_spec(self, t: ParamSpecType, /) -> T: + pass + + @abstractmethod + def visit_parameters(self, t: Parameters, /) -> T: + pass + + @abstractmethod + def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> T: + pass + + @abstractmethod + def visit_instance(self, t: Instance, /) -> T: + pass + + @abstractmethod + def visit_callable_type(self, t: CallableType, /) -> T: + pass + + @abstractmethod + def visit_overloaded(self, t: Overloaded, /) -> T: + pass + + @abstractmethod + def visit_tuple_type(self, t: TupleType, /) -> T: + pass + + @abstractmethod + def visit_typeddict_type(self, t: TypedDictType, /) -> T: + pass + + @abstractmethod + def visit_literal_type(self, t: LiteralType, /) -> T: + pass + + @abstractmethod + def visit_union_type(self, t: UnionType, /) -> T: + pass + + @abstractmethod + def visit_partial_type(self, t: PartialType, /) -> T: + pass + + @abstractmethod + def visit_type_type(self, t: TypeType, /) -> T: + pass + + @abstractmethod + def visit_type_alias_type(self, t: TypeAliasType, /) -> T: + pass + + @abstractmethod + def visit_unpack_type(self, t: UnpackType, /) -> T: + pass + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class SyntheticTypeVisitor(TypeVisitor[T]): + """A TypeVisitor that also knows how to visit synthetic AST constructs. + + Not just real types. + """ + + @abstractmethod + def visit_type_list(self, t: TypeList, /) -> T: + pass + + @abstractmethod + def visit_callable_argument(self, t: CallableArgument, /) -> T: + pass + + @abstractmethod + def visit_ellipsis_type(self, t: EllipsisType, /) -> T: + pass + + @abstractmethod + def visit_raw_expression_type(self, t: RawExpressionType, /) -> T: + pass + + @abstractmethod + def visit_placeholder_type(self, t: PlaceholderType, /) -> T: + pass + + +@mypyc_attr(allow_interpreted_subclasses=True) +class TypeTranslator(TypeVisitor[Type]): + """Identity type transformation. + + Subclass this and override some methods to implement a non-trivial + transformation. + + We cache the results of certain translations to avoid + massively expanding the sizes of types. + """ + + def __init__(self, cache: dict[Type, Type] | None = None) -> None: + # For deduplication of results + self.cache = cache + + def get_cached(self, t: Type) -> Type | None: + if self.cache is None: + return None + return self.cache.get(t) + + def set_cached(self, orig: Type, new: Type) -> None: + if self.cache is None: + # Minor optimization: construct lazily + self.cache = {} + self.cache[orig] = new + + def visit_unbound_type(self, t: UnboundType, /) -> Type: + return t + + def visit_any(self, t: AnyType, /) -> Type: + return t + + def visit_none_type(self, t: NoneType, /) -> Type: + return t + + def visit_uninhabited_type(self, t: UninhabitedType, /) -> Type: + return t + + def visit_erased_type(self, t: ErasedType, /) -> Type: + return t + + def visit_deleted_type(self, t: DeletedType, /) -> Type: + return t + + def visit_instance(self, t: Instance, /) -> Type: + last_known_value: LiteralType | None = None + if t.last_known_value is not None: + raw_last_known_value = t.last_known_value.accept(self) + assert isinstance(raw_last_known_value, LiteralType) # type: ignore[misc] + last_known_value = raw_last_known_value + return Instance( + typ=t.type, + args=self.translate_type_tuple(t.args), + line=t.line, + column=t.column, + last_known_value=last_known_value, + extra_attrs=t.extra_attrs, + ) + + def visit_type_var(self, t: TypeVarType, /) -> Type: + return t + + def visit_param_spec(self, t: ParamSpecType, /) -> Type: + return t + + def visit_parameters(self, t: Parameters, /) -> Type: + return t.copy_modified(arg_types=self.translate_type_list(t.arg_types)) + + def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> Type: + return t + + def visit_partial_type(self, t: PartialType, /) -> Type: + return t + + def visit_unpack_type(self, t: UnpackType, /) -> Type: + return UnpackType(t.type.accept(self)) + + def visit_callable_type(self, t: CallableType, /) -> Type: + return t.copy_modified( + arg_types=self.translate_type_list(t.arg_types), + ret_type=t.ret_type.accept(self), + variables=self.translate_variables(t.variables), + ) + + def visit_tuple_type(self, t: TupleType, /) -> Type: + return TupleType( + self.translate_type_list(t.items), + # TODO: This appears to be unsafe. + cast(Any, t.partial_fallback.accept(self)), + t.line, + t.column, + ) + + def visit_typeddict_type(self, t: TypedDictType, /) -> Type: + # Use cache to avoid O(n**2) or worse expansion of types during translation + if cached := self.get_cached(t): + return cached + items = {item_name: item_type.accept(self) for (item_name, item_type) in t.items.items()} + result = TypedDictType( + items, + t.required_keys, + t.readonly_keys, + # TODO: This appears to be unsafe. + cast(Any, t.fallback.accept(self)), + t.line, + t.column, + ) + self.set_cached(t, result) + return result + + def visit_literal_type(self, t: LiteralType, /) -> Type: + fallback = t.fallback.accept(self) + assert isinstance(fallback, Instance) # type: ignore[misc] + return LiteralType(value=t.value, fallback=fallback, line=t.line, column=t.column) + + def visit_union_type(self, t: UnionType, /) -> Type: + # Use cache to avoid O(n**2) or worse expansion of types during translation + # (only for large unions, since caching adds overhead) + use_cache = len(t.items) > 3 + if use_cache and (cached := self.get_cached(t)): + return cached + + result = UnionType( + self.translate_type_list(t.items), + t.line, + t.column, + uses_pep604_syntax=t.uses_pep604_syntax, + ) + if use_cache: + self.set_cached(t, result) + return result + + def translate_type_list(self, types: list[Type]) -> list[Type]: + return [t.accept(self) for t in types] + + def translate_type_tuple(self, types: tuple[Type, ...]) -> tuple[Type, ...]: + return tuple(t.accept(self) for t in types) + + def translate_variables( + self, variables: Sequence[TypeVarLikeType] + ) -> Sequence[TypeVarLikeType]: + return variables + + def visit_overloaded(self, t: Overloaded, /) -> Type: + items: list[CallableType] = [] + for item in t.items: + new = item.accept(self) + assert isinstance(new, CallableType) # type: ignore[misc] + items.append(new) + return Overloaded(items=items) + + def visit_type_type(self, t: TypeType, /) -> Type: + return TypeType.make_normalized( + t.item.accept(self), line=t.line, column=t.column, is_type_form=t.is_type_form + ) + + @abstractmethod + def visit_type_alias_type(self, t: TypeAliasType, /) -> Type: + # This method doesn't have a default implementation for type translators, + # because type aliases are special: some information is contained in the + # TypeAlias node, and we normally don't generate new nodes. Every subclass + # must implement this depending on its semantics. + pass + + +@mypyc_attr(allow_interpreted_subclasses=True) +class TypeQuery(SyntheticTypeVisitor[T]): + """Visitor for performing queries of types. + + strategy is used to combine results for a series of types, + common use cases involve a boolean query using `any` or `all`. + + Note: this visitor keeps an internal state (tracks type aliases to avoid + recursion), so it should *never* be reused for querying different types, + create a new visitor instance instead. + + # TODO: check that we don't have existing violations of this rule. + """ + + def __init__(self) -> None: + # Keep track of the type aliases already visited. This is needed to avoid + # infinite recursion on types like A = Union[int, List[A]]. + self.seen_aliases: set[TypeAliasType] | None = None + # By default, we eagerly expand type aliases, and query also types in the + # alias target. In most cases this is a desired behavior, but we may want + # to skip targets in some cases (e.g. when collecting type variables). + self.skip_alias_target = False + + @abstractmethod + def strategy(self, items: list[T]) -> T: + raise NotImplementedError + + def visit_unbound_type(self, t: UnboundType, /) -> T: + return self.query_types(t.args) + + def visit_type_list(self, t: TypeList, /) -> T: + return self.query_types(t.items) + + def visit_callable_argument(self, t: CallableArgument, /) -> T: + return t.typ.accept(self) + + def visit_any(self, t: AnyType, /) -> T: + return self.strategy([]) + + def visit_uninhabited_type(self, t: UninhabitedType, /) -> T: + return self.strategy([]) + + def visit_none_type(self, t: NoneType, /) -> T: + return self.strategy([]) + + def visit_erased_type(self, t: ErasedType, /) -> T: + return self.strategy([]) + + def visit_deleted_type(self, t: DeletedType, /) -> T: + return self.strategy([]) + + def visit_type_var(self, t: TypeVarType, /) -> T: + return self.query_types([t.upper_bound, t.default] + t.values) + + def visit_param_spec(self, t: ParamSpecType, /) -> T: + return self.query_types([t.upper_bound, t.default, t.prefix]) + + def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> T: + return self.query_types([t.upper_bound, t.default]) + + def visit_unpack_type(self, t: UnpackType, /) -> T: + return self.query_types([t.type]) + + def visit_parameters(self, t: Parameters, /) -> T: + return self.query_types(t.arg_types) + + def visit_partial_type(self, t: PartialType, /) -> T: + return self.strategy([]) + + def visit_instance(self, t: Instance, /) -> T: + return self.query_types(t.args) + + def visit_callable_type(self, t: CallableType, /) -> T: + # FIX generics + return self.query_types(t.arg_types + [t.ret_type]) + + def visit_tuple_type(self, t: TupleType, /) -> T: + return self.query_types([t.partial_fallback] + t.items) + + def visit_typeddict_type(self, t: TypedDictType, /) -> T: + return self.query_types(t.items.values()) + + def visit_raw_expression_type(self, t: RawExpressionType, /) -> T: + return self.strategy([]) + + def visit_literal_type(self, t: LiteralType, /) -> T: + return self.strategy([]) + + def visit_union_type(self, t: UnionType, /) -> T: + return self.query_types(t.items) + + def visit_overloaded(self, t: Overloaded, /) -> T: + return self.query_types(t.items) + + def visit_type_type(self, t: TypeType, /) -> T: + return t.item.accept(self) + + def visit_ellipsis_type(self, t: EllipsisType, /) -> T: + return self.strategy([]) + + def visit_placeholder_type(self, t: PlaceholderType, /) -> T: + return self.query_types(t.args) + + def visit_type_alias_type(self, t: TypeAliasType, /) -> T: + if self.skip_alias_target: + return self.query_types(t.args) + # Skip type aliases already visited types to avoid infinite recursion + # (also use this as a simple-minded cache). + if self.seen_aliases is None: + self.seen_aliases = set() + elif t in self.seen_aliases: + return self.strategy([]) + self.seen_aliases.add(t) + return get_proper_type(t).accept(self) + + def query_types(self, types: Iterable[Type]) -> T: + """Perform a query for a list of types using the strategy to combine the results.""" + return self.strategy([t.accept(self) for t in types]) + + +# Return True if at least one type component returns True +ANY_STRATEGY: Final = 0 +# Return True if no type component returns False +ALL_STRATEGY: Final = 1 + + +class BoolTypeQuery(SyntheticTypeVisitor[bool]): + """Visitor for performing recursive queries of types with a bool result. + + Use TypeQuery if you need non-bool results. + + 'strategy' is used to combine results for a series of types. It must + be ANY_STRATEGY or ALL_STRATEGY. + + Note: This visitor keeps an internal state (tracks type aliases to avoid + recursion), so it should *never* be reused for querying different types + unless you call reset() first. + """ + + def __init__(self, strategy: int) -> None: + self.strategy = strategy + if strategy == ANY_STRATEGY: + self.default = False + else: + assert strategy == ALL_STRATEGY + self.default = True + # Keep track of the type aliases already visited. This is needed to avoid + # infinite recursion on types like A = Union[int, List[A]]. An empty set is + # represented as None as a micro-optimization. + self.seen_aliases: set[TypeAliasType] | None = None + # By default, we eagerly expand type aliases, and query also types in the + # alias target. In most cases this is a desired behavior, but we may want + # to skip targets in some cases (e.g. when collecting type variables). + self.skip_alias_target = False + + def reset(self) -> None: + """Clear mutable state (but preserve strategy). + + This *must* be called if you want to reuse the visitor. + """ + self.seen_aliases = None + + def visit_unbound_type(self, t: UnboundType, /) -> bool: + return self.query_types(t.args) + + def visit_type_list(self, t: TypeList, /) -> bool: + return self.query_types(t.items) + + def visit_callable_argument(self, t: CallableArgument, /) -> bool: + return t.typ.accept(self) + + def visit_any(self, t: AnyType, /) -> bool: + return self.default + + def visit_uninhabited_type(self, t: UninhabitedType, /) -> bool: + return self.default + + def visit_none_type(self, t: NoneType, /) -> bool: + return self.default + + def visit_erased_type(self, t: ErasedType, /) -> bool: + return self.default + + def visit_deleted_type(self, t: DeletedType, /) -> bool: + return self.default + + def visit_type_var(self, t: TypeVarType, /) -> bool: + return self.query_types([t.upper_bound, t.default] + t.values) + + def visit_param_spec(self, t: ParamSpecType, /) -> bool: + return self.query_types([t.upper_bound, t.default, t.prefix]) + + def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> bool: + return self.query_types([t.upper_bound, t.default]) + + def visit_unpack_type(self, t: UnpackType, /) -> bool: + return self.query_types([t.type]) + + def visit_parameters(self, t: Parameters, /) -> bool: + return self.query_types(t.arg_types) + + def visit_partial_type(self, t: PartialType, /) -> bool: + return self.default + + def visit_instance(self, t: Instance, /) -> bool: + return self.query_types(t.args) + + def visit_callable_type(self, t: CallableType, /) -> bool: + # FIX generics + # Avoid allocating any objects here as an optimization. + args = self.query_types(t.arg_types) + ret = t.ret_type.accept(self) + if self.strategy == ANY_STRATEGY: + return args or ret + else: + return args and ret + + def visit_tuple_type(self, t: TupleType, /) -> bool: + return self.query_types([t.partial_fallback] + t.items) + + def visit_typeddict_type(self, t: TypedDictType, /) -> bool: + return self.query_types(list(t.items.values())) + + def visit_raw_expression_type(self, t: RawExpressionType, /) -> bool: + return self.default + + def visit_literal_type(self, t: LiteralType, /) -> bool: + return self.default + + def visit_union_type(self, t: UnionType, /) -> bool: + return self.query_types(t.items) + + def visit_overloaded(self, t: Overloaded, /) -> bool: + return self.query_types(t.items) # type: ignore[arg-type] + + def visit_type_type(self, t: TypeType, /) -> bool: + return t.item.accept(self) + + def visit_ellipsis_type(self, t: EllipsisType, /) -> bool: + return self.default + + def visit_placeholder_type(self, t: PlaceholderType, /) -> bool: + return self.query_types(t.args) + + def visit_type_alias_type(self, t: TypeAliasType, /) -> bool: + if self.skip_alias_target: + return self.query_types(t.args) + # Skip type aliases already visited types to avoid infinite recursion + # (also use this as a simple-minded cache). + if self.seen_aliases is None: + self.seen_aliases = set() + elif t in self.seen_aliases: + return self.default + self.seen_aliases.add(t) + return get_proper_type(t).accept(self) + + def query_types(self, types: list[Type] | tuple[Type, ...]) -> bool: + """Perform a query for a sequence of types using the strategy to combine the results.""" + # Special-case for lists and tuples to allow mypyc to produce better code. + if isinstance(types, list): + if self.strategy == ANY_STRATEGY: + return any(t.accept(self) for t in types) + else: + return all(t.accept(self) for t in types) + else: + if self.strategy == ANY_STRATEGY: + return any(t.accept(self) for t in types) + else: + return all(t.accept(self) for t in types) diff --git a/micromamba_root/Lib/site-packages/mypy/typeanal.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/typeanal.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..27255754a54aee8950fc4883bd19e23bcb420d41 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/typeanal.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/typeanal.py b/micromamba_root/Lib/site-packages/mypy/typeanal.py new file mode 100644 index 0000000000000000000000000000000000000000..941310ae86a34de2beba70a45dcde99d9e61fb31 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/typeanal.py @@ -0,0 +1,2803 @@ +"""Semantic analysis of types""" + +from __future__ import annotations + +import itertools +from collections.abc import Callable, Iterable, Iterator, Sequence +from contextlib import contextmanager +from typing import Final, Protocol, TypeVar + +from mypy import errorcodes as codes, message_registry, nodes +from mypy.errorcodes import ErrorCode +from mypy.errors import ErrorInfo +from mypy.expandtype import expand_type +from mypy.message_registry import ( + INVALID_PARAM_SPEC_LOCATION, + INVALID_PARAM_SPEC_LOCATION_NOTE, + TYPEDDICT_OVERRIDE_MERGE, +) +from mypy.messages import ( + MessageBuilder, + format_type, + format_type_bare, + quote_type_string, + wrong_type_arg_count, +) +from mypy.nodes import ( + ARG_NAMED, + ARG_NAMED_OPT, + ARG_OPT, + ARG_POS, + ARG_STAR, + ARG_STAR2, + MISSING_FALLBACK, + SYMBOL_FUNCBASE_TYPES, + ArgKind, + Context, + Decorator, + ImportFrom, + MypyFile, + ParamSpecExpr, + PlaceholderNode, + SymbolTableNode, + TypeAlias, + TypeInfo, + TypeVarExpr, + TypeVarLikeExpr, + TypeVarTupleExpr, + Var, + check_arg_kinds, + check_param_names, +) +from mypy.options import INLINE_TYPEDDICT, TYPE_FORM, Options +from mypy.plugin import AnalyzeTypeContext, Plugin, TypeAnalyzerPluginInterface +from mypy.semanal_shared import ( + SemanticAnalyzerCoreInterface, + SemanticAnalyzerInterface, + paramspec_args, + paramspec_kwargs, +) +from mypy.state import state +from mypy.tvar_scope import TypeVarLikeScope +from mypy.types import ( + ANNOTATED_TYPE_NAMES, + ANY_STRATEGY, + CONCATENATE_TYPE_NAMES, + FINAL_TYPE_NAMES, + LITERAL_TYPE_NAMES, + MYPYC_NATIVE_INT_NAMES, + NEVER_NAMES, + TUPLE_NAMES, + TYPE_ALIAS_NAMES, + TYPE_NAMES, + UNPACK_TYPE_NAMES, + AnyType, + BoolTypeQuery, + CallableArgument, + CallableType, + DeletedType, + EllipsisType, + ErasedType, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecFlavor, + ParamSpecType, + PartialType, + PlaceholderType, + ProperType, + RawExpressionType, + ReadOnlyType, + RequiredType, + SyntheticTypeVisitor, + TrivialSyntheticTypeTranslator, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeList, + TypeOfAny, + TypeQuery, + TypeType, + TypeVarId, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, + callable_with_ellipsis, + find_unpack_in_list, + flatten_nested_tuples, + get_proper_type, + has_type_vars, +) +from mypy.types_utils import get_bad_type_type_item +from mypy.typevars import fill_typevars + +T = TypeVar("T") + +type_constructors: Final = { + "typing.Callable", + "typing.Optional", + "typing.Tuple", + "typing.Type", + "typing.Union", + *LITERAL_TYPE_NAMES, + *ANNOTATED_TYPE_NAMES, +} + +ARG_KINDS_BY_CONSTRUCTOR: Final = { + "mypy_extensions.Arg": ARG_POS, + "mypy_extensions.DefaultArg": ARG_OPT, + "mypy_extensions.NamedArg": ARG_NAMED, + "mypy_extensions.DefaultNamedArg": ARG_NAMED_OPT, + "mypy_extensions.VarArg": ARG_STAR, + "mypy_extensions.KwArg": ARG_STAR2, +} + +SELF_TYPE_NAMES: Final = {"typing.Self", "typing_extensions.Self"} + + +def analyze_type_alias( + type: Type, + api: SemanticAnalyzerCoreInterface, + tvar_scope: TypeVarLikeScope, + plugin: Plugin, + options: Options, + cur_mod_node: MypyFile, + is_typeshed_stub: bool, + allow_placeholder: bool = False, + in_dynamic_func: bool = False, + global_scope: bool = True, + allowed_alias_tvars: list[TypeVarLikeType] | None = None, + alias_type_params_names: list[str] | None = None, + python_3_12_type_alias: bool = False, +) -> tuple[Type, set[str]]: + """Analyze r.h.s. of a (potential) type alias definition. + + If `node` is valid as a type alias rvalue, return the resulting type and a set of + full names of type aliases it depends on (directly or indirectly). + 'node' must have been semantically analyzed. + """ + analyzer = TypeAnalyser( + api, + tvar_scope, + plugin, + options, + cur_mod_node, + is_typeshed_stub, + defining_alias=True, + allow_placeholder=allow_placeholder, + prohibit_self_type="type alias target", + allowed_alias_tvars=allowed_alias_tvars, + alias_type_params_names=alias_type_params_names, + python_3_12_type_alias=python_3_12_type_alias, + ) + analyzer.in_dynamic_func = in_dynamic_func + analyzer.global_scope = global_scope + res = analyzer.anal_type(type, nested=False) + return res, analyzer.aliases_used + + +class TypeAnalyser(SyntheticTypeVisitor[Type], TypeAnalyzerPluginInterface): + """Semantic analyzer for types. + + Converts unbound types into bound types. This is a no-op for already + bound types. + + If an incomplete reference is encountered, this does a defer. The + caller never needs to defer. + """ + + # Is this called from an untyped function definition? + in_dynamic_func: bool = False + # Is this called from global scope? + global_scope: bool = True + + def __init__( + self, + api: SemanticAnalyzerCoreInterface, + tvar_scope: TypeVarLikeScope, + plugin: Plugin, + options: Options, + cur_mod_node: MypyFile, + is_typeshed_stub: bool, + *, + defining_alias: bool = False, + python_3_12_type_alias: bool = False, + allow_tuple_literal: bool = False, + allow_unbound_tvars: bool = False, + allow_placeholder: bool = False, + allow_typed_dict_special_forms: bool = False, + allow_final: bool = True, + allow_param_spec_literals: bool = False, + allow_unpack: bool = False, + report_invalid_types: bool = True, + prohibit_self_type: str | None = None, + prohibit_special_class_field_types: str | None = None, + allowed_alias_tvars: list[TypeVarLikeType] | None = None, + allow_type_any: bool = False, + alias_type_params_names: list[str] | None = None, + ) -> None: + self.api = api + self.fail_func = api.fail + self.note_func = api.note + self.tvar_scope = tvar_scope + # Are we analysing a type alias definition rvalue? + self.defining_alias = defining_alias + self.python_3_12_type_alias = python_3_12_type_alias + self.allow_tuple_literal = allow_tuple_literal + # Positive if we are analyzing arguments of another (outer) type + self.nesting_level = 0 + # Should we allow new type syntax when targeting older Python versions + # like 'list[int]' or 'X | Y' (allowed in stubs and with `__future__` import)? + self.always_allow_new_syntax = self.api.is_stub_file or self.api.is_future_flag_set( + "annotations" + ) + # Should we accept unbound type variables? This is currently used for class bases, + # and alias right hand sides (before they are analyzed as type aliases). + self.allow_unbound_tvars = allow_unbound_tvars + if allowed_alias_tvars is None: + allowed_alias_tvars = [] + self.allowed_alias_tvars = allowed_alias_tvars + self.alias_type_params_names = alias_type_params_names + # If false, record incomplete ref if we generate PlaceholderType. + self.allow_placeholder = allow_placeholder + # Are we in a context where Required[] is allowed? + self.allow_typed_dict_special_forms = allow_typed_dict_special_forms + # Set True when we analyze ClassVar else False + self.allow_final = allow_final + # Are we in a context where ParamSpec literals are allowed? + self.allow_param_spec_literals = allow_param_spec_literals + # Are we in context where literal "..." specifically is allowed? + self.allow_ellipsis = False + # Should we report an error whenever we encounter a RawExpressionType outside + # of a Literal context: e.g. whenever we encounter an invalid type? Normally, + # we want to report an error, but the caller may want to do more specialized + # error handling. + self.report_invalid_types = report_invalid_types + self.plugin = plugin + self.options = options + self.cur_mod_node = cur_mod_node + self.is_typeshed_stub = is_typeshed_stub + # Names of type aliases encountered while analysing a type will be collected here. + self.aliases_used: set[str] = set() + self.prohibit_self_type = prohibit_self_type + # Set when we analyze TypedDicts or NamedTuples, since they are special: + self.prohibit_special_class_field_types = prohibit_special_class_field_types + # Allow variables typed as Type[Any] and type (useful for base classes). + self.allow_type_any = allow_type_any + self.allow_type_var_tuple = False + self.allow_unpack = allow_unpack + + def lookup_qualified( + self, name: str, ctx: Context, suppress_errors: bool = False + ) -> SymbolTableNode | None: + return self.api.lookup_qualified(name, ctx, suppress_errors) + + def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode: + return self.api.lookup_fully_qualified(fullname) + + def visit_unbound_type(self, t: UnboundType, defining_literal: bool = False) -> Type: + typ = self.visit_unbound_type_nonoptional(t, defining_literal) + if t.optional: + # We don't need to worry about double-wrapping Optionals or + # wrapping Anys: Union simplification will take care of that. + return make_optional_type(typ) + return typ + + def not_declared_in_type_params(self, tvar_name: str) -> bool: + return ( + self.alias_type_params_names is not None + and tvar_name not in self.alias_type_params_names + ) + + def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) -> Type: + sym = self.lookup_qualified(t.name, t) + param_spec_name = None + if t.name.endswith((".args", ".kwargs")): + param_spec_name = t.name.rsplit(".", 1)[0] + maybe_param_spec = self.lookup_qualified(param_spec_name, t) + if maybe_param_spec and isinstance(maybe_param_spec.node, ParamSpecExpr): + sym = maybe_param_spec + else: + param_spec_name = None + + if sym is not None: + node = sym.node + if isinstance(node, PlaceholderNode): + if node.becomes_typeinfo: + # Reference to placeholder type. + if self.api.final_iteration: + self.cannot_resolve_type(t) + return AnyType(TypeOfAny.from_error) + elif self.allow_placeholder: + self.api.defer() + else: + self.api.record_incomplete_ref() + # Always allow ParamSpec for placeholders, if they are actually not valid, + # they will be reported later, after we resolve placeholders. + return PlaceholderType( + node.fullname, + self.anal_array( + t.args, + allow_param_spec=True, + allow_param_spec_literals=True, + allow_unpack=True, + ), + t.line, + ) + else: + if self.api.final_iteration: + self.cannot_resolve_type(t) + return AnyType(TypeOfAny.from_error) + else: + # Reference to an unknown placeholder node. + self.api.record_incomplete_ref() + return AnyType(TypeOfAny.special_form) + if node is None: + self.fail(f"Internal error (node is None, kind={sym.kind})", t) + return AnyType(TypeOfAny.special_form) + fullname = node.fullname + hook = self.plugin.get_type_analyze_hook(fullname) + if hook is not None: + return hook(AnalyzeTypeContext(t, t, self)) + tvar_def = self.tvar_scope.get_binding(sym) + if tvar_def is not None: + # We need to cover special-case explained in get_typevarlike_argument() here, + # since otherwise the deferral will not be triggered if the type variable is + # used in a different module. Using isinstance() should be safe for this purpose. + tvar_params = [tvar_def.upper_bound, tvar_def.default] + if isinstance(tvar_def, TypeVarType): + tvar_params += tvar_def.values + if any(isinstance(tp, PlaceholderType) for tp in tvar_params): + self.api.defer() + if isinstance(sym.node, ParamSpecExpr): + if tvar_def is None: + if self.allow_unbound_tvars: + return t + name = param_spec_name or t.name + if self.defining_alias and self.not_declared_in_type_params(t.name): + msg = f'ParamSpec "{name}" is not included in type_params' + else: + msg = f'ParamSpec "{name}" is unbound' + self.fail(msg, t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + assert isinstance(tvar_def, ParamSpecType) + if len(t.args) > 0: + self.fail( + f'ParamSpec "{t.name}" used with arguments', t, code=codes.VALID_TYPE + ) + if param_spec_name is not None and not self.allow_param_spec_literals: + self.fail( + "ParamSpec components are not allowed here", t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + # Change the line number + return ParamSpecType( + tvar_def.name, + tvar_def.fullname, + tvar_def.id, + tvar_def.flavor, + tvar_def.upper_bound, + tvar_def.default, + line=t.line, + column=t.column, + ) + if ( + isinstance(sym.node, TypeVarExpr) + and self.defining_alias + and not defining_literal + and (tvar_def is None or tvar_def not in self.allowed_alias_tvars) + ): + if self.not_declared_in_type_params(t.name): + if self.python_3_12_type_alias: + msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format( + f'"{t.name}"' + ) + else: + msg = f'Type variable "{t.name}" is not included in type_params' + else: + msg = f'Can\'t use bound type variable "{t.name}" to define generic alias' + self.fail(msg, t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + if isinstance(sym.node, TypeVarExpr) and tvar_def is not None: + assert isinstance(tvar_def, TypeVarType) + if len(t.args) > 0: + self.fail( + f'Type variable "{t.name}" used with arguments', t, code=codes.VALID_TYPE + ) + # Change the line number + return tvar_def.copy_modified(line=t.line, column=t.column) + if isinstance(sym.node, TypeVarTupleExpr) and ( + tvar_def is not None + and self.defining_alias + and tvar_def not in self.allowed_alias_tvars + ): + if self.not_declared_in_type_params(t.name): + msg = f'Type variable "{t.name}" is not included in type_params' + else: + msg = f'Can\'t use bound type variable "{t.name}" to define generic alias' + self.fail(msg, t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + if isinstance(sym.node, TypeVarTupleExpr): + if tvar_def is None: + if self.allow_unbound_tvars: + return t + if self.defining_alias and self.not_declared_in_type_params(t.name): + if self.python_3_12_type_alias: + msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format( + f'"{t.name}"' + ) + else: + msg = f'TypeVarTuple "{t.name}" is not included in type_params' + else: + msg = f'TypeVarTuple "{t.name}" is unbound' + self.fail(msg, t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + assert isinstance(tvar_def, TypeVarTupleType) + if not self.allow_type_var_tuple: + self.fail( + f'TypeVarTuple "{t.name}" is only valid with an unpack', + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + if len(t.args) > 0: + self.fail( + f'Type variable "{t.name}" used with arguments', t, code=codes.VALID_TYPE + ) + + # Change the line number + return TypeVarTupleType( + tvar_def.name, + tvar_def.fullname, + tvar_def.id, + tvar_def.upper_bound, + sym.node.tuple_fallback, + tvar_def.default, + line=t.line, + column=t.column, + ) + special = self.try_analyze_special_unbound_type(t, fullname) + if special is not None: + return special + if isinstance(node, TypeAlias): + self.aliases_used.add(fullname) + an_args = self.anal_array( + t.args, + allow_param_spec=True, + allow_param_spec_literals=node.has_param_spec_type, + allow_unpack=True, # Fixed length unpacks can be used for non-variadic aliases. + ) + if node.has_param_spec_type and len(node.alias_tvars) == 1: + an_args = self.pack_paramspec_args(an_args, t.empty_tuple_index) + + disallow_any = self.options.disallow_any_generics and not self.is_typeshed_stub + res = instantiate_type_alias( + node, + an_args, + self.fail, + node.no_args, + t, + self.options, + unexpanded_type=t, + disallow_any=disallow_any, + empty_tuple_index=t.empty_tuple_index, + ) + # The only case where instantiate_type_alias() can return an incorrect instance is + # when it is top-level instance, so no need to recurse. + if ( + isinstance(res, ProperType) + and isinstance(res, Instance) + and not (self.defining_alias and self.nesting_level == 0) + and not validate_instance(res, self.fail, t.empty_tuple_index) + ): + fix_instance( + res, + self.fail, + self.note, + disallow_any=disallow_any, + options=self.options, + use_generic_error=True, + unexpanded_type=t, + ) + if node.eager: + res = get_proper_type(res) + return res + elif isinstance(node, TypeInfo): + return self.analyze_type_with_type_info(node, t.args, t, t.empty_tuple_index) + elif node.fullname in TYPE_ALIAS_NAMES: + return AnyType(TypeOfAny.special_form) + # Concatenate is an operator, no need for a proper type + elif node.fullname in CONCATENATE_TYPE_NAMES: + # We check the return type further up the stack for valid use locations + return self.apply_concatenate_operator(t) + else: + return self.analyze_unbound_type_without_type_info(t, sym, defining_literal) + else: # sym is None + return AnyType(TypeOfAny.special_form) + + def pack_paramspec_args(self, an_args: Sequence[Type], empty_tuple_index: bool) -> list[Type]: + # "Aesthetic" ParamSpec literals for single ParamSpec: C[int, str] -> C[[int, str]]. + # These do not support mypy_extensions VarArgs, etc. as they were already analyzed + # TODO: should these be re-analyzed to get rid of this inconsistency? + count = len(an_args) + if count == 0 and empty_tuple_index: + return [Parameters([], [], [])] + elif count == 0: + return [] + + if count == 1 and isinstance(get_proper_type(an_args[0]), AnyType): + # Single Any is interpreted as ..., rather that a single argument with Any type. + # I didn't find this in the PEP, but it sounds reasonable. + return list(an_args) + if any(isinstance(a, (Parameters, ParamSpecType)) for a in an_args): + if len(an_args) > 1: + first_wrong = next( + arg for arg in an_args if isinstance(arg, (Parameters, ParamSpecType)) + ) + self.fail( + "Nested parameter specifications are not allowed", + first_wrong, + code=codes.VALID_TYPE, + ) + return [AnyType(TypeOfAny.from_error)] + return list(an_args) + first = an_args[0] + return [ + Parameters( + an_args, [ARG_POS] * count, [None] * count, line=first.line, column=first.column + ) + ] + + def cannot_resolve_type(self, t: UnboundType) -> None: + # TODO: Move error message generation to messages.py. We'd first + # need access to MessageBuilder here. Also move the similar + # message generation logic in semanal.py. + self.api.fail(f'Cannot resolve name "{t.name}" (possible cyclic definition)', t) + if self.api.is_func_scope(): + self.note("Recursive types are not allowed at function scope", t) + + def apply_concatenate_operator(self, t: UnboundType) -> Type: + if len(t.args) == 0: + self.api.fail("Concatenate needs type arguments", t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + + # Last argument has to be ParamSpec or Ellipsis. + ps = self.anal_type(t.args[-1], allow_param_spec=True, allow_ellipsis=True) + if not isinstance(ps, (ParamSpecType, Parameters)): + if isinstance(ps, UnboundType) and self.allow_unbound_tvars: + sym = self.lookup_qualified(ps.name, t) + if sym is not None and isinstance(sym.node, ParamSpecExpr): + return ps + self.api.fail( + "The last parameter to Concatenate needs to be a ParamSpec", + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + elif isinstance(ps, ParamSpecType) and ps.prefix.arg_types: + self.api.fail("Nested Concatenates are invalid", t, code=codes.VALID_TYPE) + + args = self.anal_array(t.args[:-1]) + pre = ps.prefix if isinstance(ps, ParamSpecType) else ps + + # mypy can't infer this :( + names: list[str | None] = [None] * len(args) + + pre = Parameters( + args + pre.arg_types, + [ARG_POS] * len(args) + pre.arg_kinds, + names + pre.arg_names, + line=t.line, + column=t.column, + ) + return ps.copy_modified(prefix=pre) if isinstance(ps, ParamSpecType) else pre + + def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Type | None: + """Bind special type that is recognized through magic name such as 'typing.Any'. + + Return the bound type if successful, and return None if the type is a normal type. + """ + if fullname == "builtins.None": + return NoneType() + elif fullname == "typing.Any": + return AnyType(TypeOfAny.explicit, line=t.line, column=t.column) + elif fullname in FINAL_TYPE_NAMES: + if self.prohibit_special_class_field_types: + self.fail( + f"Final[...] can't be used inside a {self.prohibit_special_class_field_types}", + t, + code=codes.VALID_TYPE, + ) + else: + if not self.allow_final: + self.fail( + "Final can be only used as an outermost qualifier in a variable annotation", + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + elif fullname in TUPLE_NAMES: + # Tuple is special because it is involved in builtin import cycle + # and may be not ready when used. + sym = self.api.lookup_fully_qualified_or_none("builtins.tuple") + if not sym or isinstance(sym.node, PlaceholderNode): + if self.api.is_incomplete_namespace("builtins"): + self.api.record_incomplete_ref() + else: + self.fail('Name "tuple" is not defined', t) + return AnyType(TypeOfAny.special_form) + if len(t.args) == 0 and not t.empty_tuple_index: + # Bare 'Tuple' is same as 'tuple' + any_type = self.get_omitted_any(t) + return self.named_type("builtins.tuple", [any_type], line=t.line, column=t.column) + if len(t.args) == 2 and isinstance(t.args[1], EllipsisType): + # Tuple[T, ...] (uniform, variable-length tuple) + instance = self.named_type("builtins.tuple", [self.anal_type(t.args[0])]) + instance.line = t.line + return instance + return self.tuple_type( + self.anal_array(t.args, allow_unpack=True), line=t.line, column=t.column + ) + elif fullname == "typing.Union": + items = self.anal_array(t.args) + return UnionType.make_union(items, line=t.line, column=t.column) + elif fullname == "typing.Optional": + if len(t.args) != 1: + self.fail( + "Optional[...] must have exactly one type argument", t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + item = self.anal_type(t.args[0]) + return make_optional_type(item) + elif fullname == "typing.Callable": + return self.analyze_callable_type(t) + elif fullname in TYPE_NAMES: + if len(t.args) == 0: + if fullname == "typing.Type": + any_type = self.get_omitted_any(t) + return TypeType(any_type, line=t.line, column=t.column) + else: + # To prevent assignment of 'builtins.type' inferred as 'builtins.object' + # See https://github.com/python/mypy/issues/9476 for more information + return None + type_str = "Type[...]" if fullname == "typing.Type" else "type[...]" + if len(t.args) != 1: + self.fail( + f"{type_str} must have exactly one type argument", t, code=codes.VALID_TYPE + ) + item = self.anal_type(t.args[0]) + bad_item_name = get_bad_type_type_item(item) + if bad_item_name: + self.fail(f'{type_str} can\'t contain "{bad_item_name}"', t, code=codes.VALID_TYPE) + item = AnyType(TypeOfAny.from_error) + return TypeType.make_normalized(item, line=t.line, column=t.column) + elif fullname in ("typing_extensions.TypeForm", "typing.TypeForm"): + if TYPE_FORM not in self.options.enable_incomplete_feature: + self.fail( + "TypeForm is experimental," + " must be enabled with --enable-incomplete-feature=TypeForm", + t, + ) + if len(t.args) == 0: + any_type = self.get_omitted_any(t) + return TypeType(any_type, line=t.line, column=t.column, is_type_form=True) + if len(t.args) != 1: + type_str = "TypeForm[...]" + self.fail( + type_str + " must have exactly one type argument", t, code=codes.VALID_TYPE + ) + item = self.anal_type(t.args[0]) + return TypeType.make_normalized(item, line=t.line, column=t.column, is_type_form=True) + elif fullname == "typing.ClassVar": + if self.nesting_level > 0: + self.fail( + "Invalid type: ClassVar nested inside other type", t, code=codes.VALID_TYPE + ) + if self.prohibit_special_class_field_types: + self.fail( + f"ClassVar[...] can't be used inside a {self.prohibit_special_class_field_types}", + t, + code=codes.VALID_TYPE, + ) + if self.defining_alias: + self.fail( + "ClassVar[...] can't be used inside a type alias", t, code=codes.VALID_TYPE + ) + if len(t.args) == 0: + return AnyType(TypeOfAny.from_omitted_generics, line=t.line, column=t.column) + if len(t.args) != 1: + self.fail( + "ClassVar[...] must have at most one type argument", t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + return self.anal_type(t.args[0], allow_final=self.options.python_version >= (3, 13)) + elif fullname in NEVER_NAMES: + return UninhabitedType() + elif fullname in LITERAL_TYPE_NAMES: + return self.analyze_literal_type(t) + elif fullname in ANNOTATED_TYPE_NAMES: + if len(t.args) < 2: + self.fail( + "Annotated[...] must have exactly one type argument" + " and at least one annotation", + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + return self.anal_type( + t.args[0], allow_typed_dict_special_forms=self.allow_typed_dict_special_forms + ) + elif fullname in ("typing_extensions.Required", "typing.Required"): + if not self.allow_typed_dict_special_forms: + self.fail( + "Required[] can be only used in a TypedDict definition", + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + if len(t.args) != 1: + self.fail( + "Required[] must have exactly one type argument", t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + return RequiredType( + self.anal_type(t.args[0], allow_typed_dict_special_forms=True), required=True + ) + elif fullname in ("typing_extensions.NotRequired", "typing.NotRequired"): + if not self.allow_typed_dict_special_forms: + self.fail( + "NotRequired[] can be only used in a TypedDict definition", + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + if len(t.args) != 1: + self.fail( + "NotRequired[] must have exactly one type argument", t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + return RequiredType( + self.anal_type(t.args[0], allow_typed_dict_special_forms=True), required=False + ) + elif fullname in ("typing_extensions.ReadOnly", "typing.ReadOnly"): + if not self.allow_typed_dict_special_forms: + self.fail( + "ReadOnly[] can be only used in a TypedDict definition", + t, + code=codes.VALID_TYPE, + ) + return AnyType(TypeOfAny.from_error) + if len(t.args) != 1: + self.fail( + '"ReadOnly[]" must have exactly one type argument', t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + return ReadOnlyType(self.anal_type(t.args[0], allow_typed_dict_special_forms=True)) + elif ( + self.anal_type_guard_arg(t, fullname) is not None + or self.anal_type_is_arg(t, fullname) is not None + ): + # In most contexts, TypeGuard[...] acts as an alias for bool (ignoring its args) + return self.named_type("builtins.bool") + elif fullname in UNPACK_TYPE_NAMES: + if len(t.args) != 1: + self.fail("Unpack[...] requires exactly one type argument", t) + return AnyType(TypeOfAny.from_error) + if not self.allow_unpack: + self.fail(message_registry.INVALID_UNPACK_POSITION, t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + self.allow_type_var_tuple = True + result = UnpackType(self.anal_type(t.args[0]), line=t.line, column=t.column) + self.allow_type_var_tuple = False + return result + elif fullname in SELF_TYPE_NAMES: + if t.args: + self.fail("Self type cannot have type arguments", t) + if self.prohibit_self_type is not None: + self.fail(f"Self type cannot be used in {self.prohibit_self_type}", t) + return AnyType(TypeOfAny.from_error) + if self.api.type is None: + self.fail("Self type is only allowed in annotations within class definition", t) + return AnyType(TypeOfAny.from_error) + if self.api.type.has_base("builtins.type"): + self.fail("Self type cannot be used in a metaclass", t) + if self.api.type.self_type is not None: + if self.api.type.is_final or self.api.type.is_enum and self.api.type.enum_members: + return fill_typevars(self.api.type) + return self.api.type.self_type.copy_modified(line=t.line, column=t.column) + # TODO: verify this is unreachable and replace with an assert? + self.fail("Unexpected Self type", t) + return AnyType(TypeOfAny.from_error) + return None + + def get_omitted_any(self, typ: Type, fullname: str | None = None) -> AnyType: + disallow_any = not self.is_typeshed_stub and self.options.disallow_any_generics + return get_omitted_any(disallow_any, self.fail, self.note, typ, self.options, fullname) + + def check_and_warn_deprecated(self, info: TypeInfo, ctx: Context) -> None: + """Similar logic to `TypeChecker.check_deprecated` and `TypeChecker.warn_deprecated.""" + + if ( + (deprecated := info.deprecated) + and not self.is_typeshed_stub + and not (self.api.type and (self.api.type.fullname == info.fullname)) + and not any( + info.fullname == p or info.fullname.startswith(f"{p}.") + for p in self.options.deprecated_calls_exclude + ) + ): + for imp in self.cur_mod_node.imports: + if isinstance(imp, ImportFrom) and any(info.name == n[0] for n in imp.names): + break + else: + warn = self.note if self.options.report_deprecated_as_note else self.fail + warn(deprecated, ctx, code=codes.DEPRECATED) + + def analyze_type_with_type_info( + self, info: TypeInfo, args: Sequence[Type], ctx: Context, empty_tuple_index: bool + ) -> Type: + """Bind unbound type when were able to find target TypeInfo. + + This handles simple cases like 'int', 'modname.UserClass[str]', etc. + """ + + self.check_and_warn_deprecated(info, ctx) + + if len(args) > 0 and info.fullname == "builtins.tuple": + fallback = Instance(info, [AnyType(TypeOfAny.special_form)], ctx.line) + return TupleType(self.anal_array(args, allow_unpack=True), fallback, ctx.line) + + # Analyze arguments and (usually) construct Instance type. The + # number of type arguments and their values are + # checked only later, since we do not always know the + # valid count at this point. Thus we may construct an + # Instance with an invalid number of type arguments. + # + # We allow ParamSpec literals based on a heuristic: it will be + # checked later anyways but the error message may be worse. + instance = Instance( + info, + self.anal_array( + args, + allow_param_spec=True, + allow_param_spec_literals=info.has_param_spec_type, + allow_unpack=True, # Fixed length tuples can be used for non-variadic types. + ), + ctx.line, + ctx.column, + ) + instance.end_line = ctx.end_line + instance.end_column = ctx.end_column + if len(info.type_vars) == 1 and info.has_param_spec_type: + instance.args = tuple(self.pack_paramspec_args(instance.args, empty_tuple_index)) + + if info.fullname == "librt.vecs.vec" and not check_vec_type_args( + instance.args, ctx, self.api + ): + return AnyType(TypeOfAny.from_error) + + # Check type argument count. + instance.args = tuple(flatten_nested_tuples(instance.args)) + if not (self.defining_alias and self.nesting_level == 0) and not validate_instance( + instance, self.fail, empty_tuple_index + ): + fix_instance( + instance, + self.fail, + self.note, + disallow_any=self.options.disallow_any_generics and not self.is_typeshed_stub, + options=self.options, + ) + + tup = info.tuple_type + if tup is not None: + # The class has a Tuple[...] base class so it will be + # represented as a tuple type. + if info.special_alias: + return instantiate_type_alias( + info.special_alias, + # TODO: should we allow NamedTuples generic in ParamSpec? + self.anal_array(args, allow_unpack=True), + self.fail, + False, + ctx, + self.options, + use_standard_error=True, + ) + return tup.copy_modified( + items=self.anal_array(tup.items, allow_unpack=True), fallback=instance + ) + td = info.typeddict_type + if td is not None: + # The class has a TypedDict[...] base class so it will be + # represented as a typeddict type. + if info.special_alias: + return instantiate_type_alias( + info.special_alias, + # TODO: should we allow TypedDicts generic in ParamSpec? + self.anal_array(args, allow_unpack=True), + self.fail, + False, + ctx, + self.options, + use_standard_error=True, + ) + # Create a named TypedDictType + return td.copy_modified( + item_types=self.anal_array(list(td.items.values())), fallback=instance + ) + + if info.fullname == "types.NoneType": + self.fail( + "NoneType should not be used as a type, please use None instead", + ctx, + code=codes.NONETYPE_TYPE, + ) + return NoneType(ctx.line, ctx.column) + + return instance + + def analyze_unbound_type_without_type_info( + self, t: UnboundType, sym: SymbolTableNode, defining_literal: bool + ) -> Type: + """Figure out what an unbound type that doesn't refer to a TypeInfo node means. + + This is something unusual. We try our best to find out what it is. + """ + name = sym.fullname + if name is None: + assert sym.node is not None + name = sym.node.name + # Option 1: + # Something with an Any type -- make it an alias for Any in a type + # context. This is slightly problematic as it allows using the type 'Any' + # as a base class -- however, this will fail soon at runtime so the problem + # is pretty minor. + if isinstance(sym.node, Var): + typ = get_proper_type(sym.node.type) + if isinstance(typ, AnyType): + return AnyType( + TypeOfAny.from_unimported_type, missing_import_name=typ.missing_import_name + ) + elif self.allow_type_any: + if isinstance(typ, Instance) and typ.type.fullname == "builtins.type": + return AnyType(TypeOfAny.special_form) + if isinstance(typ, TypeType) and isinstance(typ.item, AnyType): + return AnyType(TypeOfAny.from_another_any, source_any=typ.item) + # Option 2: + # Unbound type variable. Currently these may be still valid, + # for example when defining a generic type alias. + unbound_tvar = ( + isinstance(sym.node, (TypeVarExpr, TypeVarTupleExpr)) + and self.tvar_scope.get_binding(sym) is None + ) + if self.allow_unbound_tvars and unbound_tvar: + return t + + # Option 3: + # Enum value. Note: we only want to return a LiteralType when + # we're using this enum value specifically within context of + # a "Literal[...]" type. So, if `defining_literal` is not set, + # we bail out early with an error. + # + # If, in the distant future, we decide to permit things like + # `def foo(x: Color.RED) -> None: ...`, we can remove that + # check entirely. + if ( + isinstance(sym.node, Var) + and sym.node.info + and sym.node.info.is_enum + and sym.node.name in sym.node.info.enum_members + ): + value = sym.node.name + base_enum_short_name = sym.node.info.name + if not defining_literal: + msg = message_registry.INVALID_TYPE_RAW_ENUM_VALUE.format( + base_enum_short_name, value + ) + self.fail(msg.value, t, code=msg.code) + return AnyType(TypeOfAny.from_error) + return LiteralType( + value=value, + fallback=Instance(sym.node.info, [], line=t.line, column=t.column), + line=t.line, + column=t.column, + ) + + # None of the above options worked. We parse the args (if there are any) + # to make sure there are no remaining semanal-only types, then give up. + t = t.copy_modified(args=self.anal_array(t.args)) + # TODO: Move this message building logic to messages.py. + notes: list[str] = [] + error_code = codes.VALID_TYPE + if isinstance(sym.node, Var): + notes.append( + "See https://mypy.readthedocs.io/en/" + "stable/common_issues.html#variables-vs-type-aliases" + ) + message = 'Variable "{}" is not valid as a type' + elif isinstance(sym.node, (SYMBOL_FUNCBASE_TYPES, Decorator)): + message = 'Function "{}" is not valid as a type' + if name == "builtins.any": + notes.append('Perhaps you meant "typing.Any" instead of "any"?') + elif name == "builtins.callable": + notes.append('Perhaps you meant "typing.Callable" instead of "callable"?') + else: + notes.append('Perhaps you need "Callable[...]" or a callback protocol?') + elif isinstance(sym.node, MypyFile): + message = 'Module "{}" is not valid as a type' + notes.append("Perhaps you meant to use a protocol matching the module structure?") + elif unbound_tvar: + assert isinstance(sym.node, TypeVarLikeExpr) + if sym.node.is_new_style: + # PEP 695 type parameters are never considered unbound -- they are undefined + # in contexts where they aren't valid, such as in argument default values. + message = 'Name "{}" is not defined' + name = name.split(".")[-1] + error_code = codes.NAME_DEFINED + else: + message = 'Type variable "{}" is unbound' + short = name.split(".")[-1] + notes.append( + f'(Hint: Use "Generic[{short}]" or "Protocol[{short}]" base class' + f' to bind "{short}" inside a class)' + ) + notes.append( + f'(Hint: Use "{short}" in function signature ' + f'to bind "{short}" inside a function)' + ) + else: + message = 'Cannot interpret reference "{}" as a type' + if not defining_literal: + # Literal check already gives a custom error. Avoid duplicating errors. + self.fail(message.format(name), t, code=error_code) + for note in notes: + self.note(note, t, code=error_code) + + # TODO: Would it be better to always return Any instead of UnboundType + # in case of an error? On one hand, UnboundType has a name so error messages + # are more detailed, on the other hand, some of them may be bogus, + # see https://github.com/python/mypy/issues/4987. + return t + + def visit_any(self, t: AnyType) -> Type: + return t + + def visit_none_type(self, t: NoneType) -> Type: + return t + + def visit_uninhabited_type(self, t: UninhabitedType) -> Type: + return t + + def visit_erased_type(self, t: ErasedType) -> Type: + # This type should exist only temporarily during type inference + assert False, "Internal error: Unexpected erased type" + + def visit_deleted_type(self, t: DeletedType) -> Type: + return t + + def visit_type_list(self, t: TypeList) -> Type: + # Parameters literal (Z[[int, str, Whatever]]) + if self.allow_param_spec_literals: + params = self.analyze_callable_args(t) + if params: + ts, kinds, names = params + # bind these types + return Parameters(self.anal_array(ts), kinds, names, line=t.line, column=t.column) + else: + return AnyType(TypeOfAny.from_error) + else: + self.fail( + 'Bracketed expression "[...]" is not valid as a type', t, code=codes.VALID_TYPE + ) + if len(t.items) == 1: + self.note('Did you mean "List[...]"?', t) + return AnyType(TypeOfAny.from_error) + + def visit_callable_argument(self, t: CallableArgument) -> Type: + self.fail("Invalid type", t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + + def visit_instance(self, t: Instance) -> Type: + return t + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + # TODO: should we do something here? + return t + + def visit_type_var(self, t: TypeVarType) -> Type: + return t + + def visit_param_spec(self, t: ParamSpecType) -> Type: + return t + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type: + return t + + def visit_unpack_type(self, t: UnpackType) -> Type: + if not self.allow_unpack: + self.fail(message_registry.INVALID_UNPACK_POSITION, t.type, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + self.allow_type_var_tuple = True + result = UnpackType(self.anal_type(t.type), from_star_syntax=t.from_star_syntax) + self.allow_type_var_tuple = False + return result + + def visit_parameters(self, t: Parameters) -> Type: + raise NotImplementedError("ParamSpec literals cannot have unbound TypeVars") + + def visit_callable_type( + self, t: CallableType, nested: bool = True, namespace: str = "" + ) -> Type: + # Every Callable can bind its own type variables, if they're not in the outer scope + # TODO: attach namespace for nested free type variables (these appear in return type only). + with self.tvar_scope_frame(namespace=namespace): + unpacked_kwargs = t.unpack_kwargs + if self.defining_alias: + variables = t.variables + else: + variables, _ = self.bind_function_type_variables(t, t) + type_guard = self.anal_type_guard(t.ret_type) if t.type_guard is None else t.type_guard + type_is = self.anal_type_is(t.ret_type) if t.type_is is None else t.type_is + + arg_kinds = t.arg_kinds + arg_types = [] + param_spec_with_args = param_spec_with_kwargs = None + param_spec_invalid = False + for kind, ut in zip(arg_kinds, t.arg_types): + if kind == ARG_STAR: + param_spec_with_args, at = self.anal_star_arg_type(ut, kind, nested=nested) + elif kind == ARG_STAR2: + param_spec_with_kwargs, at = self.anal_star_arg_type(ut, kind, nested=nested) + else: + if param_spec_with_args: + param_spec_invalid = True + self.fail( + "Arguments not allowed after ParamSpec.args", t, code=codes.VALID_TYPE + ) + at = self.anal_type(ut, nested=nested, allow_unpack=False) + arg_types.append(at) + + if nested and arg_types: + # If we've got a Callable[[Unpack[SomeTypedDict]], None], make sure + # Unpack is interpreted as `**` and not as `*`. + last = arg_types[-1] + if isinstance(last, UnpackType): + # TODO: it would be better to avoid this get_proper_type() call. + p_at = get_proper_type(last.type) + if isinstance(p_at, TypedDictType) and not last.from_star_syntax: + # Automatically detect Unpack[Foo] in Callable as backwards + # compatible syntax for **Foo, if Foo is a TypedDict. + arg_kinds[-1] = ARG_STAR2 + arg_types[-1] = p_at + unpacked_kwargs = True + arg_types = self.check_unpacks_in_list(arg_types) + + if not param_spec_invalid and param_spec_with_args != param_spec_with_kwargs: + # If already invalid, do not report more errors - definition has + # to be fixed anyway + name = param_spec_with_args or param_spec_with_kwargs + self.fail( + f'ParamSpec must have "*args" typed as "{name}.args" and "**kwargs" typed as "{name}.kwargs"', + t, + code=codes.VALID_TYPE, + ) + param_spec_invalid = True + + if param_spec_invalid: + if ARG_STAR in arg_kinds: + arg_types[arg_kinds.index(ARG_STAR)] = AnyType(TypeOfAny.from_error) + if ARG_STAR2 in arg_kinds: + arg_types[arg_kinds.index(ARG_STAR2)] = AnyType(TypeOfAny.from_error) + + # If there were multiple (invalid) unpacks, the arg types list will become shorter, + # we need to trim the kinds/names as well to avoid crashes. + arg_kinds = t.arg_kinds[: len(arg_types)] + arg_names = t.arg_names[: len(arg_types)] + + ret = t.copy_modified( + arg_types=arg_types, + arg_kinds=arg_kinds, + arg_names=arg_names, + ret_type=self.anal_type(t.ret_type, nested=nested), + # If the fallback isn't filled in yet, + # its type will be the falsey FakeInfo + fallback=(t.fallback if t.fallback.type else self.named_type("builtins.function")), + variables=self.anal_var_defs(variables), + type_guard=type_guard, + type_is=type_is, + unpack_kwargs=unpacked_kwargs, + ) + return ret + + def anal_type_guard(self, t: Type) -> Type | None: + if isinstance(t, UnboundType): + sym = self.lookup_qualified(t.name, t) + if sym is not None and sym.node is not None: + return self.anal_type_guard_arg(t, sym.node.fullname) + # TODO: What if it's an Instance? Then use t.type.fullname? + return None + + def anal_type_guard_arg(self, t: UnboundType, fullname: str) -> Type | None: + if fullname in ("typing_extensions.TypeGuard", "typing.TypeGuard"): + if len(t.args) != 1: + self.fail( + "TypeGuard must have exactly one type argument", t, code=codes.VALID_TYPE + ) + return AnyType(TypeOfAny.from_error) + return self.anal_type(t.args[0]) + return None + + def anal_type_is(self, t: Type) -> Type | None: + if isinstance(t, UnboundType): + sym = self.lookup_qualified(t.name, t) + if sym is not None and sym.node is not None: + return self.anal_type_is_arg(t, sym.node.fullname) + # TODO: What if it's an Instance? Then use t.type.fullname? + return None + + def anal_type_is_arg(self, t: UnboundType, fullname: str) -> Type | None: + if fullname in ("typing_extensions.TypeIs", "typing.TypeIs"): + if len(t.args) != 1: + self.fail("TypeIs must have exactly one type argument", t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + return self.anal_type(t.args[0]) + return None + + def anal_star_arg_type(self, t: Type, kind: ArgKind, nested: bool) -> tuple[str | None, Type]: + """Analyze signature argument type for *args and **kwargs argument.""" + if isinstance(t, UnboundType) and t.name and "." in t.name and not t.args: + components = t.name.split(".") + tvar_name = ".".join(components[:-1]) + sym = self.lookup_qualified(tvar_name, t) + if sym is not None and isinstance(sym.node, ParamSpecExpr): + tvar_def = self.tvar_scope.get_binding(sym) + if isinstance(tvar_def, ParamSpecType): + if kind == ARG_STAR: + make_paramspec = paramspec_args + if components[-1] != "args": + self.fail( + f'Use "{tvar_name}.args" for variadic "*" parameter', + t, + code=codes.VALID_TYPE, + ) + elif kind == ARG_STAR2: + make_paramspec = paramspec_kwargs + if components[-1] != "kwargs": + self.fail( + f'Use "{tvar_name}.kwargs" for variadic "**" parameter', + t, + code=codes.VALID_TYPE, + ) + else: + assert False, kind + return tvar_name, make_paramspec( + tvar_def.name, + tvar_def.fullname, + tvar_def.id, + named_type_func=self.named_type, + line=t.line, + column=t.column, + ) + return None, self.anal_type(t, nested=nested, allow_unpack=True) + + def visit_overloaded(self, t: Overloaded) -> Type: + # Overloaded types are manually constructed in semanal.py by analyzing the + # AST and combining together the Callable types this visitor converts. + # + # So if we're ever asked to reanalyze an Overloaded type, we know it's + # fine to just return it as-is. + return t + + def visit_tuple_type(self, t: TupleType) -> Type: + # Types such as (t1, t2, ...) only allowed in assignment statements. They'll + # generate errors elsewhere, and Tuple[t1, t2, ...] must be used instead. + if t.implicit and not self.allow_tuple_literal: + self.fail("Syntax error in type annotation", t, code=codes.SYNTAX) + if len(t.items) == 0: + self.note( + "Suggestion: Use Tuple[()] instead of () for an empty tuple, or " + "None for a function without a return value", + t, + code=codes.SYNTAX, + ) + elif len(t.items) == 1: + self.note("Suggestion: Is there a spurious trailing comma?", t, code=codes.SYNTAX) + else: + self.note( + "Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)", + t, + code=codes.SYNTAX, + ) + return AnyType(TypeOfAny.from_error) + + any_type = AnyType(TypeOfAny.special_form) + # If the fallback isn't filled in yet, its type will be the falsey FakeInfo + fallback = ( + t.partial_fallback + if t.partial_fallback.type + else self.named_type("builtins.tuple", [any_type]) + ) + return TupleType(self.anal_array(t.items, allow_unpack=True), fallback, t.line) + + def visit_typeddict_type(self, t: TypedDictType) -> Type: + req_keys = set() + readonly_keys = set() + items = {} + for item_name, item_type in t.items.items(): + # TODO: rework + analyzed = self.anal_type(item_type, allow_typed_dict_special_forms=True) + if isinstance(analyzed, RequiredType): + if analyzed.required: + req_keys.add(item_name) + analyzed = analyzed.item + else: + # Keys are required by default. + req_keys.add(item_name) + if isinstance(analyzed, ReadOnlyType): + readonly_keys.add(item_name) + analyzed = analyzed.item + items[item_name] = analyzed + if t.fallback.type is MISSING_FALLBACK: # anonymous/inline TypedDict + if INLINE_TYPEDDICT not in self.options.enable_incomplete_feature: + self.fail( + "Inline TypedDict is experimental," + " must be enabled with --enable-incomplete-feature=InlineTypedDict", + t, + ) + required_keys = req_keys + fallback = self.named_type("typing._TypedDict") + for typ in t.extra_items_from: + analyzed = self.analyze_type(typ) + p_analyzed = get_proper_type(analyzed) + if not isinstance(p_analyzed, TypedDictType): + if not isinstance(p_analyzed, (AnyType, PlaceholderType)): + self.fail("Can only merge-in other TypedDict", t, code=codes.VALID_TYPE) + continue + for sub_item_name, sub_item_type in p_analyzed.items.items(): + if sub_item_name in items: + self.fail(TYPEDDICT_OVERRIDE_MERGE.format(sub_item_name), t) + continue + items[sub_item_name] = sub_item_type + if sub_item_name in p_analyzed.required_keys: + req_keys.add(sub_item_name) + if sub_item_name in p_analyzed.readonly_keys: + readonly_keys.add(sub_item_name) + else: + required_keys = t.required_keys + fallback = t.fallback + return TypedDictType(items, required_keys, readonly_keys, fallback, t.line, t.column) + + def visit_raw_expression_type(self, t: RawExpressionType) -> Type: + # We should never see a bare Literal. We synthesize these raw literals + # in the earlier stages of semantic analysis, but those + # "fake literals" should always be wrapped in an UnboundType + # corresponding to 'Literal'. + # + # Note: if at some point in the distant future, we decide to + # make signatures like "foo(x: 20) -> None" legal, we can change + # this method so it generates and returns an actual LiteralType + # instead. + + if self.report_invalid_types: + if t.base_type_name in ("builtins.int", "builtins.bool"): + # The only time it makes sense to use an int or bool is inside of + # a literal type. + msg = f"Invalid type: try using Literal[{repr(t.literal_value)}] instead?" + elif t.base_type_name in ("builtins.float", "builtins.complex"): + # We special-case warnings for floats and complex numbers. + msg = f"Invalid type: {t.simple_name()} literals cannot be used as a type" + else: + # And in all other cases, we default to a generic error message. + # Note: the reason why we use a generic error message for strings + # but not ints or bools is because whenever we see an out-of-place + # string, it's unclear if the user meant to construct a literal type + # or just misspelled a regular type. So we avoid guessing. + msg = "Invalid type comment or annotation" + + self.fail(msg, t, code=codes.VALID_TYPE) + if t.note is not None: + self.note(t.note, t, code=codes.VALID_TYPE) + + return AnyType(TypeOfAny.from_error, line=t.line, column=t.column) + + def visit_literal_type(self, t: LiteralType) -> Type: + return t + + def visit_union_type(self, t: UnionType) -> Type: + if ( + t.uses_pep604_syntax is True + and t.is_evaluated is True + and not self.always_allow_new_syntax + and not self.options.python_version >= (3, 10) + ): + self.fail("X | Y syntax for unions requires Python 3.10", t, code=codes.SYNTAX) + return UnionType(self.anal_array(t.items), t.line, uses_pep604_syntax=t.uses_pep604_syntax) + + def visit_partial_type(self, t: PartialType) -> Type: + assert False, "Internal error: Unexpected partial type" + + def visit_ellipsis_type(self, t: EllipsisType) -> Type: + if self.allow_ellipsis or self.allow_param_spec_literals: + any_type = AnyType(TypeOfAny.explicit) + return Parameters( + [any_type, any_type], [ARG_STAR, ARG_STAR2], [None, None], is_ellipsis_args=True + ) + else: + self.fail('Unexpected "..."', t) + return AnyType(TypeOfAny.from_error) + + def visit_type_type(self, t: TypeType) -> Type: + return TypeType.make_normalized( + self.anal_type(t.item), line=t.line, is_type_form=t.is_type_form + ) + + def visit_placeholder_type(self, t: PlaceholderType) -> Type: + n = ( + None + # No dot in fullname indicates we are at function scope, and recursive + # types are not supported there anyway, so we just give up. + if not t.fullname or "." not in t.fullname + else self.api.lookup_fully_qualified(t.fullname) + ) + if not n or isinstance(n.node, PlaceholderNode): + self.api.defer() # Still incomplete + return t + else: + # TODO: Handle non-TypeInfo + assert isinstance(n.node, TypeInfo) + return self.analyze_type_with_type_info(n.node, t.args, t, False) + + def analyze_callable_args_for_paramspec( + self, callable_args: Type, ret_type: Type, fallback: Instance + ) -> CallableType | None: + """Construct a 'Callable[P, RET]', where P is ParamSpec, return None if we cannot.""" + if not isinstance(callable_args, UnboundType): + return None + sym = self.lookup_qualified(callable_args.name, callable_args) + if sym is None: + return None + tvar_def = self.tvar_scope.get_binding(sym) + if not isinstance(tvar_def, ParamSpecType): + if ( + tvar_def is None + and self.allow_unbound_tvars + and isinstance(sym.node, ParamSpecExpr) + ): + # We are analyzing this type in runtime context (e.g. as type application). + # If it is not valid as a type in this position an error will be given later. + return callable_with_ellipsis( + AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback + ) + return None + elif ( + self.defining_alias + and self.not_declared_in_type_params(tvar_def.name) + and tvar_def not in self.allowed_alias_tvars + ): + if self.python_3_12_type_alias: + msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format( + f'"{tvar_def.name}"' + ) + else: + msg = f'ParamSpec "{tvar_def.name}" is not included in type_params' + self.fail(msg, callable_args, code=codes.VALID_TYPE) + return callable_with_ellipsis( + AnyType(TypeOfAny.special_form), ret_type=ret_type, fallback=fallback + ) + + return CallableType( + [ + paramspec_args( + tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type + ), + paramspec_kwargs( + tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type + ), + ], + [nodes.ARG_STAR, nodes.ARG_STAR2], + [None, None], + ret_type=ret_type, + fallback=fallback, + ) + + def analyze_callable_args_for_concatenate( + self, callable_args: Type, ret_type: Type, fallback: Instance + ) -> CallableType | AnyType | None: + """Construct a 'Callable[C, RET]', where C is Concatenate[..., P], returning None if we + cannot. + """ + if not isinstance(callable_args, UnboundType): + return None + sym = self.lookup_qualified(callable_args.name, callable_args) + if sym is None: + return None + if sym.node is None: + return None + if sym.node.fullname not in CONCATENATE_TYPE_NAMES: + return None + + tvar_def = self.anal_type(callable_args, allow_param_spec=True) + if not isinstance(tvar_def, (ParamSpecType, Parameters)): + if self.allow_unbound_tvars and isinstance(tvar_def, UnboundType): + sym = self.lookup_qualified(tvar_def.name, callable_args) + if sym is not None and isinstance(sym.node, ParamSpecExpr): + # We are analyzing this type in runtime context (e.g. as type application). + # If it is not valid as a type in this position an error will be given later. + return callable_with_ellipsis( + AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback + ) + # Error was already given, so prevent further errors. + return AnyType(TypeOfAny.from_error) + if isinstance(tvar_def, Parameters): + # This comes from Concatenate[int, ...] + return CallableType( + arg_types=tvar_def.arg_types, + arg_names=tvar_def.arg_names, + arg_kinds=tvar_def.arg_kinds, + ret_type=ret_type, + fallback=fallback, + from_concatenate=True, + ) + + # ick, CallableType should take ParamSpecType + prefix = tvar_def.prefix + # we don't set the prefix here as generic arguments will get updated at some point + # in the future. CallableType.param_spec() accounts for this. + return CallableType( + [ + *prefix.arg_types, + paramspec_args( + tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type + ), + paramspec_kwargs( + tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type + ), + ], + [*prefix.arg_kinds, nodes.ARG_STAR, nodes.ARG_STAR2], + [*prefix.arg_names, None, None], + ret_type=ret_type, + fallback=fallback, + from_concatenate=True, + ) + + def analyze_callable_type(self, t: UnboundType) -> Type: + fallback = self.named_type("builtins.function") + if len(t.args) == 0: + # Callable (bare). Treat as Callable[..., Any]. + any_type = self.get_omitted_any(t) + ret = callable_with_ellipsis(any_type, any_type, fallback) + elif len(t.args) == 2: + callable_args = t.args[0] + ret_type = t.args[1] + if isinstance(callable_args, TypeList): + # Callable[[ARG, ...], RET] (ordinary callable type) + analyzed_args = self.analyze_callable_args(callable_args) + if analyzed_args is None: + return AnyType(TypeOfAny.from_error) + args, kinds, names = analyzed_args + ret = CallableType(args, kinds, names, ret_type=ret_type, fallback=fallback) + elif isinstance(callable_args, EllipsisType): + # Callable[..., RET] (with literal ellipsis; accept arbitrary arguments) + ret = callable_with_ellipsis( + AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback + ) + else: + # Callable[P, RET] (where P is ParamSpec) + with self.tvar_scope_frame(namespace=""): + # Temporarily bind ParamSpecs to allow code like this: + # my_fun: Callable[Q, Foo[Q]] + # We usually do this later in visit_callable_type(), but the analysis + # below happens at very early stage. + variables = [] + for name, tvar_expr in self.find_type_var_likes(callable_args): + variables.append( + self.tvar_scope.bind_new(name, tvar_expr, self.fail_func, t) + ) + maybe_ret = self.analyze_callable_args_for_paramspec( + callable_args, ret_type, fallback + ) or self.analyze_callable_args_for_concatenate( + callable_args, ret_type, fallback + ) + if isinstance(maybe_ret, CallableType): + maybe_ret = maybe_ret.copy_modified(variables=variables) + if maybe_ret is None: + # Callable[?, RET] (where ? is something invalid) + self.fail( + "The first argument to Callable must be a " + 'list of types, parameter specification, or "..."', + t, + code=codes.VALID_TYPE, + ) + self.note( + "See https://mypy.readthedocs.io/en/stable/kinds_of_types.html#callable-types-and-lambdas", + t, + ) + return AnyType(TypeOfAny.from_error) + elif isinstance(maybe_ret, AnyType): + return maybe_ret + ret = maybe_ret + else: + if self.options.disallow_any_generics: + self.fail('Please use "Callable[[], ]"', t) + else: + self.fail('Please use "Callable[[], ]" or "Callable"', t) + return AnyType(TypeOfAny.from_error) + assert isinstance(ret, CallableType) + return ret.accept(self) + + def refers_to_full_names(self, arg: UnboundType, names: Sequence[str]) -> bool: + sym = self.lookup_qualified(arg.name, arg) + if sym is not None: + if sym.fullname in names: + return True + return False + + def analyze_callable_args( + self, arglist: TypeList + ) -> tuple[list[Type], list[ArgKind], list[str | None]] | None: + args: list[Type] = [] + kinds: list[ArgKind] = [] + names: list[str | None] = [] + seen_unpack = False + unpack_types: list[Type] = [] + invalid_unpacks: list[Type] = [] + second_unpack_last = False + for i, arg in enumerate(arglist.items): + if isinstance(arg, CallableArgument): + args.append(arg.typ) + names.append(arg.name) + if arg.constructor is None: + return None + found = self.lookup_qualified(arg.constructor, arg) + if found is None: + # Looking it up already put an error message in + return None + elif found.fullname not in ARG_KINDS_BY_CONSTRUCTOR: + self.fail(f'Invalid argument constructor "{found.fullname}"', arg) + return None + else: + assert found.fullname is not None + kind = ARG_KINDS_BY_CONSTRUCTOR[found.fullname] + kinds.append(kind) + if arg.name is not None and kind.is_star(): + self.fail(f"{arg.constructor} arguments should not have names", arg) + return None + elif ( + isinstance(arg, UnboundType) + and self.refers_to_full_names(arg, UNPACK_TYPE_NAMES) + or isinstance(arg, UnpackType) + ): + if seen_unpack: + # Multiple unpacks, preserve them, so we can give an error later. + if i == len(arglist.items) - 1 and not invalid_unpacks: + # Special case: if there are just two unpacks, and the second one appears + # as last type argument, it can be still valid, if the second unpacked type + # is a TypedDict. This should be checked by the caller. + second_unpack_last = True + invalid_unpacks.append(arg) + continue + seen_unpack = True + unpack_types.append(arg) + else: + if seen_unpack: + unpack_types.append(arg) + else: + args.append(arg) + kinds.append(ARG_POS) + names.append(None) + if seen_unpack: + if len(unpack_types) == 1: + args.append(unpack_types[0]) + else: + first = unpack_types[0] + if isinstance(first, UnpackType): + # UnpackType doesn't have its own line/column numbers, + # so use the unpacked type for error messages. + first = first.type + args.append( + UnpackType(self.tuple_type(unpack_types, line=first.line, column=first.column)) + ) + kinds.append(ARG_STAR) + names.append(None) + for arg in invalid_unpacks: + args.append(arg) + kinds.append(ARG_STAR2 if second_unpack_last else ARG_STAR) + names.append(None) + # Note that arglist below is only used for error context. + check_param_names(names, [arglist] * len(args), self.fail, "Callable") + check_arg_kinds(kinds, [arglist] * len(args), self.fail) + return args, kinds, names + + def analyze_literal_type(self, t: UnboundType) -> Type: + if len(t.args) == 0: + self.fail("Literal[...] must have at least one parameter", t, code=codes.VALID_TYPE) + return AnyType(TypeOfAny.from_error) + + output: list[Type] = [] + for i, arg in enumerate(t.args): + analyzed_types = self.analyze_literal_param(i + 1, arg, t) + if analyzed_types is None: + return AnyType(TypeOfAny.from_error) + else: + output.extend(analyzed_types) + return UnionType.make_union(output, line=t.line) + + def analyze_literal_param(self, idx: int, arg: Type, ctx: Context) -> list[Type] | None: + # This UnboundType was originally defined as a string. + if ( + isinstance(arg, ProperType) + and isinstance(arg, (UnboundType, UnionType)) + and arg.original_str_expr is not None + ): + assert arg.original_str_fallback is not None + return [ + LiteralType( + value=arg.original_str_expr, + fallback=self.named_type(arg.original_str_fallback), + line=arg.line, + column=arg.column, + ) + ] + + # If arg is an UnboundType that was *not* originally defined as + # a string, try expanding it in case it's a type alias or something. + if isinstance(arg, UnboundType): + self.nesting_level += 1 + try: + arg = self.visit_unbound_type(arg, defining_literal=True) + finally: + self.nesting_level -= 1 + + # Literal[...] cannot contain Any. Give up and add an error message + # (if we haven't already). + arg = get_proper_type(arg) + if isinstance(arg, AnyType): + # Note: We can encounter Literals containing 'Any' under three circumstances: + # + # 1. If the user attempts use an explicit Any as a parameter + # 2. If the user is trying to use an enum value imported from a module with + # no type hints, giving it an implicit type of 'Any' + # 3. If there's some other underlying problem with the parameter. + # + # We report an error in only the first two cases. In the third case, we assume + # some other region of the code has already reported a more relevant error. + # + # TODO: Once we start adding support for enums, make sure we report a custom + # error for case 2 as well. + if arg.type_of_any not in (TypeOfAny.from_error, TypeOfAny.special_form): + self.fail( + f'Parameter {idx} of Literal[...] cannot be of type "Any"', + ctx, + code=codes.VALID_TYPE, + ) + return None + elif isinstance(arg, RawExpressionType): + # A raw literal. Convert it directly into a literal if we can. + if arg.literal_value is None: + name = arg.simple_name() + if name in ("float", "complex"): + msg = f'Parameter {idx} of Literal[...] cannot be of type "{name}"' + else: + msg = "Invalid type: Literal[...] cannot contain arbitrary expressions" + self.fail(msg, ctx, code=codes.VALID_TYPE) + # Note: we deliberately ignore arg.note here: the extra info might normally be + # helpful, but it generally won't make sense in the context of a Literal[...]. + return None + + # Remap bytes and unicode into the appropriate type for the correct Python version + fallback = self.named_type(arg.base_type_name) + assert isinstance(fallback, Instance) + return [LiteralType(arg.literal_value, fallback, line=arg.line, column=arg.column)] + elif isinstance(arg, (NoneType, LiteralType)): + # Types that we can just add directly to the literal/potential union of literals. + return [arg] + elif isinstance(arg, Instance) and arg.last_known_value is not None: + # Types generated from declarations like "var: Final = 4". + return [arg.last_known_value] + elif isinstance(arg, UnionType): + out = [] + for union_arg in arg.items: + union_result = self.analyze_literal_param(idx, union_arg, ctx) + if union_result is None: + return None + out.extend(union_result) + return out + else: + self.fail(f"Parameter {idx} of Literal[...] is invalid", ctx, code=codes.VALID_TYPE) + return None + + def analyze_type(self, typ: Type) -> Type: + return typ.accept(self) + + def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + self.fail_func(msg, ctx, code=code) + + def note(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None: + self.note_func(msg, ctx, code=code) + + @contextmanager + def tvar_scope_frame(self, namespace: str) -> Iterator[None]: + old_scope = self.tvar_scope + self.tvar_scope = self.tvar_scope.method_frame(namespace) + yield + self.tvar_scope = old_scope + + def find_type_var_likes(self, t: Type) -> TypeVarLikeList: + visitor = FindTypeVarVisitor(self.api, self.tvar_scope) + t.accept(visitor) + return visitor.type_var_likes + + def infer_type_variables( + self, type: CallableType + ) -> tuple[list[tuple[str, TypeVarLikeExpr]], bool]: + """Infer type variables from a callable. + + Return tuple with these items: + - list of unique type variables referred to in a callable + - whether there is a reference to the Self type + """ + visitor = FindTypeVarVisitor(self.api, self.tvar_scope) + for arg in type.arg_types: + arg.accept(visitor) + + # When finding type variables in the return type of a function, don't + # look inside Callable types. Type variables only appearing in + # functions in the return type belong to those functions, not the + # function we're currently analyzing. + visitor.include_callables = False + type.ret_type.accept(visitor) + + return visitor.type_var_likes, visitor.has_self_type + + def bind_function_type_variables( + self, fun_type: CallableType, defn: Context + ) -> tuple[tuple[TypeVarLikeType, ...], bool]: + """Find the type variables of the function type and bind them in our tvar_scope""" + has_self_type = False + if fun_type.variables: + defs = [] + for var in fun_type.variables: + if self.api.type and self.api.type.self_type and var == self.api.type.self_type: + has_self_type = True + continue + var_node = self.lookup_qualified(var.name, defn) + assert var_node, "Binding for function type variable not found within function" + var_expr = var_node.node + assert isinstance(var_expr, TypeVarLikeExpr) + binding = self.tvar_scope.bind_new(var.name, var_expr, self.fail_func, fun_type) + defs.append(binding) + return tuple(defs), has_self_type + typevars, has_self_type = self.infer_type_variables(fun_type) + # Do not define a new type variable if already defined in scope. + typevars = [ + (name, tvar) for name, tvar in typevars if not self.is_defined_type_var(name, defn) + ] + defs = [] + for name, tvar in typevars: + if not self.tvar_scope.allow_binding(tvar.fullname): + err_msg = message_registry.TYPE_VAR_REDECLARED_IN_NESTED_CLASS.format(name) + self.fail(err_msg.value, defn, code=err_msg.code) + binding = self.tvar_scope.bind_new(name, tvar, self.fail_func, fun_type) + defs.append(binding) + + return tuple(defs), has_self_type + + def is_defined_type_var(self, tvar: str, context: Context) -> bool: + tvar_node = self.lookup_qualified(tvar, context) + if not tvar_node: + return False + return self.tvar_scope.get_binding(tvar_node) is not None + + def anal_array( + self, + a: Iterable[Type], + nested: bool = True, + *, + allow_param_spec: bool = False, + allow_param_spec_literals: bool = False, + allow_unpack: bool = False, + ) -> list[Type]: + old_allow_param_spec_literals = self.allow_param_spec_literals + self.allow_param_spec_literals = allow_param_spec_literals + res: list[Type] = [] + for t in a: + res.append( + self.anal_type( + t, nested, allow_param_spec=allow_param_spec, allow_unpack=allow_unpack + ) + ) + self.allow_param_spec_literals = old_allow_param_spec_literals + return self.check_unpacks_in_list(res) + + def anal_type( + self, + t: Type, + nested: bool = True, + *, + allow_param_spec: bool = False, + allow_unpack: bool = False, + allow_ellipsis: bool = False, + allow_typed_dict_special_forms: bool = False, + allow_final: bool = False, + ) -> Type: + if nested: + self.nesting_level += 1 + old_allow_typed_dict_special_forms = self.allow_typed_dict_special_forms + self.allow_typed_dict_special_forms = allow_typed_dict_special_forms + self.allow_final = allow_final + old_allow_ellipsis = self.allow_ellipsis + self.allow_ellipsis = allow_ellipsis + old_allow_unpack = self.allow_unpack + self.allow_unpack = allow_unpack + try: + analyzed = t.accept(self) + finally: + if nested: + self.nesting_level -= 1 + self.allow_typed_dict_special_forms = old_allow_typed_dict_special_forms + self.allow_ellipsis = old_allow_ellipsis + self.allow_unpack = old_allow_unpack + if ( + not allow_param_spec + and isinstance(analyzed, ParamSpecType) + and analyzed.flavor == ParamSpecFlavor.BARE + ): + if analyzed.prefix.arg_types: + self.fail("Invalid location for Concatenate", t, code=codes.VALID_TYPE) + self.note("You can use Concatenate as the first argument to Callable", t) + analyzed = AnyType(TypeOfAny.from_error) + else: + self.fail( + INVALID_PARAM_SPEC_LOCATION.format(format_type(analyzed, self.options)), + t, + code=codes.VALID_TYPE, + ) + self.note( + INVALID_PARAM_SPEC_LOCATION_NOTE.format(analyzed.name), + t, + code=codes.VALID_TYPE, + ) + analyzed = AnyType(TypeOfAny.from_error) + return analyzed + + def anal_var_def(self, var_def: TypeVarLikeType) -> TypeVarLikeType: + if isinstance(var_def, TypeVarType): + return TypeVarType( + name=var_def.name, + fullname=var_def.fullname, + id=var_def.id, + values=self.anal_array(var_def.values), + upper_bound=var_def.upper_bound.accept(self), + default=var_def.default.accept(self), + variance=var_def.variance, + line=var_def.line, + column=var_def.column, + ) + else: + return var_def + + def anal_var_defs(self, var_defs: Sequence[TypeVarLikeType]) -> list[TypeVarLikeType]: + return [self.anal_var_def(vd) for vd in var_defs] + + def named_type( + self, fullname: str, args: list[Type] | None = None, line: int = -1, column: int = -1 + ) -> Instance: + node = self.lookup_fully_qualified(fullname) + assert isinstance(node.node, TypeInfo) + any_type = AnyType(TypeOfAny.special_form) + if args is not None: + args = self.check_unpacks_in_list(args) + return Instance( + node.node, args or [any_type] * len(node.node.defn.type_vars), line=line, column=column + ) + + def check_unpacks_in_list(self, items: list[Type]) -> list[Type]: + new_items: list[Type] = [] + num_unpacks = 0 + final_unpack = None + for item in items: + # TODO: handle forward references here, they appear as Unpack[Any]. + if isinstance(item, UnpackType) and not isinstance( + get_proper_type(item.type), TupleType + ): + if not num_unpacks: + new_items.append(item) + num_unpacks += 1 + final_unpack = item + else: + new_items.append(item) + + if num_unpacks > 1: + assert final_unpack is not None + self.fail("More than one variadic Unpack in a type is not allowed", final_unpack.type) + return new_items + + def tuple_type(self, items: list[Type], line: int, column: int) -> TupleType: + any_type = AnyType(TypeOfAny.special_form) + return TupleType( + items, fallback=self.named_type("builtins.tuple", [any_type]), line=line, column=column + ) + + +TypeVarLikeList = list[tuple[str, TypeVarLikeExpr]] + + +class MsgCallback(Protocol): + def __call__( + self, __msg: str, __ctx: Context, *, code: ErrorCode | None = None + ) -> ErrorInfo | None: ... + + +def get_omitted_any( + disallow_any: bool, + fail: MsgCallback, + note: MsgCallback, + orig_type: Type, + options: Options, + fullname: str | None = None, + unexpanded_type: Type | None = None, +) -> AnyType: + if disallow_any: + typ = unexpanded_type or orig_type + type_str = typ.name if isinstance(typ, UnboundType) else format_type_bare(typ, options) + + fail( + message_registry.BARE_GENERIC.format(quote_type_string(type_str)), + typ, + code=codes.TYPE_ARG, + ) + + any_type = AnyType(TypeOfAny.from_error, line=typ.line, column=typ.column) + else: + any_type = AnyType( + TypeOfAny.from_omitted_generics, line=orig_type.line, column=orig_type.column + ) + return any_type + + +def fix_type_var_tuple_argument(t: Instance) -> None: + if t.type.has_type_var_tuple_type: + args = list(t.args) + assert t.type.type_var_tuple_prefix is not None + tvt = t.type.defn.type_vars[t.type.type_var_tuple_prefix] + assert isinstance(tvt, TypeVarTupleType) + args[t.type.type_var_tuple_prefix] = UnpackType( + Instance(tvt.tuple_fallback.type, [args[t.type.type_var_tuple_prefix]]) + ) + t.args = tuple(args) + + +def fix_instance( + t: Instance, + fail: MsgCallback, + note: MsgCallback, + disallow_any: bool, + options: Options, + use_generic_error: bool = False, + unexpanded_type: Type | None = None, +) -> None: + """Fix a malformed instance by replacing all type arguments with TypeVar default or Any. + + Also emit a suitable error if this is not due to implicit Any's. + """ + arg_count = len(t.args) + min_tv_count = sum(not tv.has_default() for tv in t.type.defn.type_vars) + max_tv_count = len(t.type.type_vars) + if arg_count < min_tv_count or arg_count > max_tv_count: + # Don't use existing args if arg_count doesn't match + if arg_count > max_tv_count: + # Already wrong arg count error, don't emit missing type parameters error as well. + disallow_any = False + t.args = () + + args: list[Type] = [*(t.args[:max_tv_count])] + any_type: AnyType | None = None + env: dict[TypeVarId, Type] = {} + + for tv, arg in itertools.zip_longest(t.type.defn.type_vars, t.args, fillvalue=None): + if tv is None: + continue + if arg is None: + if tv.has_default(): + arg = tv.default + else: + if any_type is None: + fullname = None if use_generic_error else t.type.fullname + any_type = get_omitted_any( + disallow_any, fail, note, t, options, fullname, unexpanded_type + ) + arg = any_type + args.append(arg) + env[tv.id] = arg + t.args = tuple(args) + fix_type_var_tuple_argument(t) + if not t.type.has_type_var_tuple_type: + with state.strict_optional_set(True): + fixed = expand_type(t, env) + assert isinstance(fixed, Instance) + t.args = fixed.args + + +def instantiate_type_alias( + node: TypeAlias, + args: list[Type], + fail: MsgCallback, + no_args: bool, + ctx: Context, + options: Options, + *, + unexpanded_type: Type | None = None, + disallow_any: bool = False, + use_standard_error: bool = False, + empty_tuple_index: bool = False, +) -> Type: + """Create an instance of a (generic) type alias from alias node and type arguments. + + We are following the rules outlined in TypeAlias docstring. + Here: + node: type alias node (definition) + args: type arguments (types to be substituted in place of type variables + when expanding the alias) + fail: error reporter callback + no_args: whether original definition used a bare generic `A = List` + ctx: context where expansion happens + unexpanded_type, disallow_any, use_standard_error: used to customize error messages + """ + # Type aliases are special, since they can be expanded during semantic analysis, + # so we need to normalize them as soon as possible. + # TODO: can this cause an infinite recursion? + args = flatten_nested_tuples(args) + if any(unknown_unpack(a) for a in args): + # This type is not ready to be validated, because of unknown total count. + # Note that we keep the kind of Any for consistency. + return set_any_tvars(node, [], ctx.line, ctx.column, options, special_form=True) + + if ( + no_args + and isinstance(node.target, ProperType) + and isinstance(node.target, Instance) + and node.target.type.fullname == "builtins.tuple" + and len(args) + ): + no_args = False + + max_tv_count = len(node.alias_tvars) + act_len = len(args) + if ( + max_tv_count > 0 + and act_len == 0 + and not (empty_tuple_index and node.tvar_tuple_index is not None) + ): + # Interpret bare Alias same as normal generic, i.e., Alias[Any, Any, ...] + return set_any_tvars( + node, + args, + ctx.line, + ctx.column, + options, + disallow_any=disallow_any, + fail=fail, + unexpanded_type=unexpanded_type, + ) + if max_tv_count == 0 and act_len == 0: + if no_args: + assert isinstance(node.target, Instance) # type: ignore[misc] + # Note: this is the only case where we use an eager expansion. See more info about + # no_args aliases like L = List in the docstring for TypeAlias class. + return Instance(node.target.type, [], line=ctx.line, column=ctx.column) + return TypeAliasType(node, [], line=ctx.line, column=ctx.column) + if ( + max_tv_count == 0 + and act_len > 0 + and isinstance(node.target, Instance) # type: ignore[misc] + and no_args + ): + tp = Instance(node.target.type, args) + tp.line = ctx.line + tp.column = ctx.column + tp.end_line = ctx.end_line + tp.end_column = ctx.end_column + return tp + if node.tvar_tuple_index is None: + if any(isinstance(a, UnpackType) for a in args): + # A variadic unpack in fixed size alias (fixed unpacks must be flattened by the caller) + fail(message_registry.INVALID_UNPACK_POSITION, ctx, code=codes.VALID_TYPE) + return set_any_tvars(node, [], ctx.line, ctx.column, options, from_error=True) + min_tv_count = sum(not tv.has_default() for tv in node.alias_tvars) + fill_typevars = act_len != max_tv_count + correct = min_tv_count <= act_len <= max_tv_count + else: + min_tv_count = sum( + not tv.has_default() and not isinstance(tv, TypeVarTupleType) + for tv in node.alias_tvars + ) + correct = act_len >= min_tv_count + for a in args: + if isinstance(a, UnpackType): + unpacked = get_proper_type(a.type) + if isinstance(unpacked, Instance) and unpacked.type.fullname == "builtins.tuple": + # Variadic tuple is always correct. + correct = True + fill_typevars = not correct + if fill_typevars: + if not correct: + if use_standard_error: + # This is used if type alias is an internal representation of another type, + # for example a generic TypedDict or NamedTuple. + msg = wrong_type_arg_count(max_tv_count, max_tv_count, str(act_len), node.name) + else: + if node.tvar_tuple_index is not None: + msg = ( + "Bad number of arguments for type alias," + f" expected at least {min_tv_count}, given {act_len}" + ) + elif min_tv_count != max_tv_count: + msg = ( + "Bad number of arguments for type alias," + f" expected between {min_tv_count} and {max_tv_count}, given {act_len}" + ) + else: + msg = ( + "Bad number of arguments for type alias," + f" expected {min_tv_count}, given {act_len}" + ) + fail(msg, ctx, code=codes.TYPE_ARG) + args = [] + return set_any_tvars(node, args, ctx.line, ctx.column, options, from_error=True) + elif node.tvar_tuple_index is not None: + # We also need to check if we are not performing a type variable tuple split. + unpack = find_unpack_in_list(args) + if unpack is not None: + unpack_arg = args[unpack] + assert isinstance(unpack_arg, UnpackType) + if isinstance(unpack_arg.type, TypeVarTupleType): + exp_prefix = node.tvar_tuple_index + act_prefix = unpack + exp_suffix = len(node.alias_tvars) - node.tvar_tuple_index - 1 + act_suffix = len(args) - unpack - 1 + if act_prefix < exp_prefix or act_suffix < exp_suffix: + fail("TypeVarTuple cannot be split", ctx, code=codes.TYPE_ARG) + return set_any_tvars(node, [], ctx.line, ctx.column, options, from_error=True) + # TODO: we need to check args validity w.r.t alias.alias_tvars. + # Otherwise invalid instantiations will be allowed in runtime context. + # Note: in type context, these will be still caught by semanal_typeargs. + typ = TypeAliasType(node, args, ctx.line, ctx.column) + assert typ.alias is not None + # HACK: Implement FlexibleAlias[T, typ] by expanding it to typ here. + if ( + isinstance(typ.alias.target, Instance) # type: ignore[misc] + and typ.alias.target.type.fullname == "mypy_extensions.FlexibleAlias" + ): + exp = get_proper_type(typ) + assert isinstance(exp, Instance) + return exp.args[-1] + return typ + + +def set_any_tvars( + node: TypeAlias, + args: list[Type], + newline: int, + newcolumn: int, + options: Options, + *, + from_error: bool = False, + disallow_any: bool = False, + special_form: bool = False, + fail: MsgCallback | None = None, + unexpanded_type: Type | None = None, +) -> TypeAliasType: + if from_error or disallow_any: + type_of_any = TypeOfAny.from_error + elif special_form: + type_of_any = TypeOfAny.special_form + else: + type_of_any = TypeOfAny.from_omitted_generics + any_type = AnyType(type_of_any, line=newline, column=newcolumn) + + env: dict[TypeVarId, Type] = {} + used_any_type = False + has_type_var_tuple_type = False + for tv, arg in itertools.zip_longest(node.alias_tvars, args, fillvalue=None): + if tv is None: + continue + if arg is None: + if tv.has_default(): + arg = tv.default + else: + arg = any_type + used_any_type = True + if isinstance(tv, TypeVarTupleType): + # TODO Handle TypeVarTuple defaults + has_type_var_tuple_type = True + arg = UnpackType(Instance(tv.tuple_fallback.type, [any_type])) + args.append(arg) + env[tv.id] = arg + t = TypeAliasType(node, args, newline, newcolumn) + if not has_type_var_tuple_type: + with state.strict_optional_set(options.strict_optional): + fixed = expand_type(t, env) + assert isinstance(fixed, TypeAliasType) + t.args = fixed.args + + if used_any_type and disallow_any and node.alias_tvars: + assert fail is not None + if unexpanded_type: + type_str = ( + unexpanded_type.name + if isinstance(unexpanded_type, UnboundType) + else format_type_bare(unexpanded_type, options) + ) + else: + type_str = node.name + + fail( + message_registry.BARE_GENERIC.format(quote_type_string(type_str)), + Context(newline, newcolumn), + code=codes.TYPE_ARG, + ) + return t + + +class DivergingAliasDetector(TrivialSyntheticTypeTranslator): + """See docstring of detect_diverging_alias() for details.""" + + # TODO: this doesn't really need to be a translator, but we don't have a trivial visitor. + def __init__( + self, + seen_nodes: set[TypeAlias], + lookup: Callable[[str, Context], SymbolTableNode | None], + scope: TypeVarLikeScope, + ) -> None: + super().__init__() + self.seen_nodes = seen_nodes + self.lookup = lookup + self.scope = scope + self.diverging = False + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + assert t.alias is not None, f"Unfixed type alias {t.type_ref}" + if t.alias in self.seen_nodes: + for arg in t.args: + if not ( + isinstance(arg, TypeVarLikeType) + or isinstance(arg, UnpackType) + and isinstance(arg.type, TypeVarLikeType) + ) and has_type_vars(arg): + self.diverging = True + return t + # All clear for this expansion chain. + return t + new_nodes = self.seen_nodes | {t.alias} + visitor = DivergingAliasDetector(new_nodes, self.lookup, self.scope) + _ = get_proper_type(t).accept(visitor) + if visitor.diverging: + self.diverging = True + return t + + +def detect_diverging_alias( + node: TypeAlias, + target: Type, + lookup: Callable[[str, Context], SymbolTableNode | None], + scope: TypeVarLikeScope, +) -> bool: + """This detects type aliases that will diverge during type checking. + + For example F = Something[..., F[List[T]]]. At each expansion step this will produce + *new* type aliases: e.g. F[List[int]], F[List[List[int]]], etc. So we can't detect + recursion. It is a known problem in the literature, recursive aliases and generic types + don't always go well together. It looks like there is no known systematic solution yet. + + # TODO: should we handle such aliases using type_recursion counter and some large limit? + They may be handy in rare cases, e.g. to express a union of non-mixed nested lists: + Nested = Union[T, Nested[List[T]]] ~> Union[T, List[T], List[List[T]], ...] + """ + visitor = DivergingAliasDetector({node}, lookup, scope) + _ = target.accept(visitor) + return visitor.diverging + + +def check_for_explicit_any( + typ: Type | None, + options: Options, + is_typeshed_stub: bool, + msg: MessageBuilder, + context: Context, +) -> None: + if options.disallow_any_explicit and not is_typeshed_stub and typ and has_explicit_any(typ): + msg.explicit_any(context) + + +def has_explicit_any(t: Type) -> bool: + """ + Whether this type is or type it contains is an Any coming from explicit type annotation + """ + return t.accept(HasExplicitAny()) + + +class HasExplicitAny(BoolTypeQuery): + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_any(self, t: AnyType) -> bool: + return t.type_of_any == TypeOfAny.explicit + + def visit_typeddict_type(self, t: TypedDictType) -> bool: + # typeddict is checked during TypedDict declaration, so don't typecheck it here. + return False + + +def has_any_from_unimported_type(t: Type) -> bool: + """Return true if this type is Any because an import was not followed. + + If type t is such Any type or has type arguments that contain such Any type + this function will return true. + """ + return t.accept(HasAnyFromUnimportedType()) + + +class HasAnyFromUnimportedType(BoolTypeQuery): + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_any(self, t: AnyType) -> bool: + return t.type_of_any == TypeOfAny.from_unimported_type + + def visit_typeddict_type(self, t: TypedDictType) -> bool: + # typeddict is checked during TypedDict declaration, so don't typecheck it here + return False + + +def collect_all_inner_types(t: Type) -> list[Type]: + """ + Return all types that `t` contains + """ + return t.accept(CollectAllInnerTypesQuery()) + + +class CollectAllInnerTypesQuery(TypeQuery[list[Type]]): + def query_types(self, types: Iterable[Type]) -> list[Type]: + return self.strategy([t.accept(self) for t in types]) + list(types) + + def strategy(self, items: Iterable[list[Type]]) -> list[Type]: + return list(itertools.chain.from_iterable(items)) + + +def make_optional_type(t: Type) -> Type: + """Return the type corresponding to Optional[t]. + + Note that we can't use normal union simplification, since this function + is called during semantic analysis and simplification only works during + type checking. + """ + if isinstance(t, ProperType) and isinstance(t, NoneType): + return t + elif isinstance(t, ProperType) and isinstance(t, UnionType): + # Eagerly expanding aliases is not safe during semantic analysis. + items = [item for item in t.items if not isinstance(get_proper_type(item), NoneType)] + return UnionType(items + [NoneType()], t.line, t.column) + else: + return UnionType([t, NoneType()], t.line, t.column) + + +def validate_instance(t: Instance, fail: MsgCallback, indexed: bool) -> bool: + """Check if this is a well-formed instance with respect to argument count/positions.""" + # TODO: combine logic with instantiate_type_alias(). + if any(unknown_unpack(a) for a in t.args): + # This type is not ready to be validated, because of unknown total count. + # TODO: is it OK to fill with TypeOfAny.from_error instead of special form? + return False + empty_tuple_index = indexed and not t.args + if t.type.has_type_var_tuple_type: + min_tv_count = sum( + not tv.has_default() and not isinstance(tv, TypeVarTupleType) + for tv in t.type.defn.type_vars + ) + correct = len(t.args) >= min_tv_count + if any( + isinstance(a, UnpackType) and isinstance(get_proper_type(a.type), Instance) + for a in t.args + ): + correct = True + if not t.args: + if not (empty_tuple_index and len(t.type.type_vars) == 1): + # The Any arguments should be set by the caller. + if empty_tuple_index and min_tv_count: + fail( + f"At least {min_tv_count} type argument(s) expected, none given", + t, + code=codes.TYPE_ARG, + ) + return False + elif not correct: + fail( + f"Bad number of arguments, expected: at least {min_tv_count}, given: {len(t.args)}", + t, + code=codes.TYPE_ARG, + ) + return False + else: + # We also need to check if we are not performing a type variable tuple split. + unpack = find_unpack_in_list(t.args) + if unpack is not None: + unpack_arg = t.args[unpack] + assert isinstance(unpack_arg, UnpackType) + if isinstance(unpack_arg.type, TypeVarTupleType): + assert t.type.type_var_tuple_prefix is not None + assert t.type.type_var_tuple_suffix is not None + exp_prefix = t.type.type_var_tuple_prefix + act_prefix = unpack + exp_suffix = t.type.type_var_tuple_suffix + act_suffix = len(t.args) - unpack - 1 + if act_prefix < exp_prefix or act_suffix < exp_suffix: + fail("TypeVarTuple cannot be split", t, code=codes.TYPE_ARG) + return False + elif any(isinstance(a, UnpackType) for a in t.args): + # A variadic unpack in fixed size instance (fixed unpacks must be flattened by the caller) + fail(message_registry.INVALID_UNPACK_POSITION, t, code=codes.VALID_TYPE) + t.args = () + return False + elif len(t.args) != len(t.type.type_vars): + # Invalid number of type parameters. + arg_count = len(t.args) + min_tv_count = sum(not tv.has_default() for tv in t.type.defn.type_vars) + max_tv_count = len(t.type.type_vars) + if (arg_count or empty_tuple_index) and ( + arg_count < min_tv_count or arg_count > max_tv_count + ): + fail( + wrong_type_arg_count(min_tv_count, max_tv_count, str(arg_count), t.type.name), + t, + code=codes.TYPE_ARG, + ) + return False + return True + + +def find_self_type(typ: Type, lookup: Callable[[str], SymbolTableNode | None]) -> bool: + return typ.accept(HasSelfType(lookup)) + + +class HasSelfType(BoolTypeQuery): + def __init__(self, lookup: Callable[[str], SymbolTableNode | None]) -> None: + self.lookup = lookup + super().__init__(ANY_STRATEGY) + + def visit_unbound_type(self, t: UnboundType) -> bool: + sym = self.lookup(t.name) + if sym and sym.fullname in SELF_TYPE_NAMES: + return True + return super().visit_unbound_type(t) + + +def unknown_unpack(t: Type) -> bool: + """Check if a given type is an unpack of an unknown type. + + Unfortunately, there is no robust way to distinguish forward references from + genuine undefined names here. But this worked well so far, although it looks + quite fragile. + """ + if isinstance(t, UnpackType): + unpacked = get_proper_type(t.type) + if isinstance(unpacked, AnyType) and unpacked.type_of_any == TypeOfAny.special_form: + return True + return False + + +class FindTypeVarVisitor(SyntheticTypeVisitor[None]): + """Type visitor that looks for type variable types and self types.""" + + def __init__(self, api: SemanticAnalyzerCoreInterface, scope: TypeVarLikeScope) -> None: + self.api = api + self.scope = scope + self.type_var_likes: list[tuple[str, TypeVarLikeExpr]] = [] + self.has_self_type = False + self.include_callables = True + + def _seems_like_callable(self, type: UnboundType) -> bool: + if not type.args: + return False + return isinstance(type.args[0], (EllipsisType, TypeList, ParamSpecType)) + + def visit_unbound_type(self, t: UnboundType) -> None: + name = t.name + node = self.api.lookup_qualified(name, t) + if node and node.fullname in SELF_TYPE_NAMES: + self.has_self_type = True + if ( + node + and isinstance(node.node, TypeVarLikeExpr) + and self.scope.get_binding(node) is None + ): + if (name, node.node) not in self.type_var_likes: + self.type_var_likes.append((name, node.node)) + elif not self.include_callables and self._seems_like_callable(t): + if find_self_type( + t, lambda name: self.api.lookup_qualified(name, t, suppress_errors=True) + ): + self.has_self_type = True + return + elif node and node.fullname in LITERAL_TYPE_NAMES: + return + elif node and node.fullname in ANNOTATED_TYPE_NAMES and t.args: + # Don't query the second argument to Annotated for TypeVars + self.process_types([t.args[0]]) + elif t.args: + self.process_types(t.args) + + def visit_type_list(self, t: TypeList) -> None: + self.process_types(t.items) + + def visit_callable_argument(self, t: CallableArgument) -> None: + t.typ.accept(self) + + def visit_any(self, t: AnyType) -> None: + pass + + def visit_uninhabited_type(self, t: UninhabitedType) -> None: + pass + + def visit_none_type(self, t: NoneType) -> None: + pass + + def visit_erased_type(self, t: ErasedType) -> None: + pass + + def visit_deleted_type(self, t: DeletedType) -> None: + pass + + def visit_type_var(self, t: TypeVarType) -> None: + self.process_types([t.upper_bound, t.default] + t.values) + + def visit_param_spec(self, t: ParamSpecType) -> None: + self.process_types([t.upper_bound, t.default, t.prefix]) + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> None: + self.process_types([t.upper_bound, t.default]) + + def visit_unpack_type(self, t: UnpackType) -> None: + self.process_types([t.type]) + + def visit_parameters(self, t: Parameters) -> None: + self.process_types(t.arg_types) + + def visit_partial_type(self, t: PartialType) -> None: + pass + + def visit_instance(self, t: Instance) -> None: + self.process_types(t.args) + + def visit_callable_type(self, t: CallableType) -> None: + # FIX generics + self.process_types(t.arg_types) + t.ret_type.accept(self) + + def visit_tuple_type(self, t: TupleType) -> None: + self.process_types(t.items) + + def visit_typeddict_type(self, t: TypedDictType) -> None: + self.process_types(list(t.items.values())) + + def visit_raw_expression_type(self, t: RawExpressionType) -> None: + pass + + def visit_literal_type(self, t: LiteralType) -> None: + pass + + def visit_union_type(self, t: UnionType) -> None: + self.process_types(t.items) + + def visit_overloaded(self, t: Overloaded) -> None: + for it in t.items: + it.accept(self) + + def visit_type_type(self, t: TypeType) -> None: + t.item.accept(self) + + def visit_ellipsis_type(self, t: EllipsisType) -> None: + pass + + def visit_placeholder_type(self, t: PlaceholderType) -> None: + return self.process_types(t.args) + + def visit_type_alias_type(self, t: TypeAliasType) -> None: + self.process_types(t.args) + + def process_types(self, types: list[Type] | tuple[Type, ...]) -> None: + # Redundant type check helps mypyc. + if isinstance(types, list): + for t in types: + t.accept(self) + else: + for t in types: + t.accept(self) + + +class TypeVarDefaultTranslator(TrivialSyntheticTypeTranslator): + """Type translate visitor that replaces UnboundTypes with in-scope TypeVars.""" + + def __init__( + self, api: SemanticAnalyzerInterface, tvar_expr_name: str, context: Context + ) -> None: + super().__init__() + self.api = api + self.tvar_expr_name = tvar_expr_name + self.context = context + + def visit_unbound_type(self, t: UnboundType) -> Type: + sym = self.api.lookup_qualified(t.name, t, suppress_errors=True) + if sym is not None: + if type_var := self.api.tvar_scope.get_binding(sym): + return type_var + if isinstance(sym.node, TypeVarLikeExpr): + self.api.fail( + f'Type parameter "{self.tvar_expr_name}" has a default type ' + "that refers to one or more type variables that are out of scope", + self.context, + ) + return AnyType(TypeOfAny.from_error) + return super().visit_unbound_type(t) + + def visit_type_alias_type(self, t: TypeAliasType) -> Type: + # TypeAliasTypes are analyzed separately already, just return it + return t + + +def check_vec_type_args( + args: tuple[Type, ...] | list[Type], ctx: Context, api: SemanticAnalyzerCoreInterface +) -> bool: + """Report an error if type args for 'vec' are invalid. + + Return False on error. + """ + ok = True + if len(args) != 1: + ok = False + else: + arg = get_proper_type(args[0]) + if isinstance(arg, Instance): + if arg.type.fullname == "builtins.int": + # A fixed-width integer such as 'i64' must be used instead of plain 'int' + ok = False + elif isinstance(arg, UnionType): + non_optional = None + items = [get_proper_type(item) for item in arg.items] + if len(items) != 2: + ok = False + elif isinstance(items[0], NoneType): + if not check_vec_type_args([items[1]], ctx, api): + # Error has already been reported so it's fine to return + return False + non_optional = items[1] + elif isinstance(items[1], NoneType): + if not check_vec_type_args([items[0]], ctx, api): + # Error has already been reported so it's fine to return + return False + non_optional = items[0] + else: + ok = False + if isinstance(non_optional, Instance) and ( + non_optional.type.fullname in MYPYC_NATIVE_INT_NAMES + or non_optional.type.fullname + in ("builtins.int", "builtins.float", "builtins.bool", "librt.vecs.vec") + ): + ok = False + elif isinstance(arg, TypeVarType): + # Generic vec types aren't supported in type checked Python code, but + # they can be provided in libraries implemented in C (e.g. append). + if not api.is_stub_file: + ok = False + else: + ok = False + if not ok: + api.fail('Invalid item type for "vec"', ctx) + return ok diff --git a/micromamba_root/Lib/site-packages/mypy/typeops.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/typeops.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..fd89739c9987751be1cec36848220b0d96fe20df Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/typeops.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/typeops.py b/micromamba_root/Lib/site-packages/mypy/typeops.py new file mode 100644 index 0000000000000000000000000000000000000000..839c6454ca28fcda460efe1d76d832895e295bb6 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/typeops.py @@ -0,0 +1,1344 @@ +"""Miscellaneous type operations and helpers for use during type checking. + +NOTE: These must not be accessed from mypy.nodes or mypy.types to avoid import + cycles. These must not be called from the semantic analysis main pass + since these may assume that MROs are ready. +""" + +from __future__ import annotations + +import itertools +from collections.abc import Callable, Iterable, Sequence +from typing import Any, TypeVar, cast + +from mypy.checker_state import checker_state +from mypy.copytype import copy_type +from mypy.expandtype import expand_type, expand_type_by_instance +from mypy.maptype import map_instance_to_supertype +from mypy.nodes import ( + ARG_POS, + ARG_STAR, + ARG_STAR2, + SYMBOL_FUNCBASE_TYPES, + Decorator, + Expression, + FuncBase, + FuncDef, + FuncItem, + OverloadedFuncDef, + StrExpr, + SymbolNode, + TypeInfo, + Var, +) +from mypy.state import state +from mypy.types import ( + ELLIPSIS_TYPE_NAMES, + NOT_IMPLEMENTED_TYPE_NAMES, + AnyType, + CallableType, + ExtraAttrs, + FormalArgument, + FunctionLike, + Instance, + LiteralType, + NoneType, + NormalizedCallableType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeOfAny, + TypeQuery, + TypeType, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UninhabitedType, + UnionType, + UnpackType, + flatten_nested_unions, + get_proper_type, + get_proper_types, + remove_dups, +) +from mypy.typetraverser import TypeTraverserVisitor +from mypy.typevars import fill_typevars + + +def is_recursive_pair(s: Type, t: Type) -> bool: + """Is this a pair of recursive types? + + There may be more cases, and we may be forced to use e.g. has_recursive_types() + here, but this function is called in very hot code, so we try to keep it simple + and return True only in cases we know may have problems. + """ + if isinstance(s, TypeAliasType) and s.is_recursive: + return ( + isinstance(get_proper_type(t), (Instance, UnionType)) + or isinstance(t, TypeAliasType) + and t.is_recursive + # Tuple types are special, they can cause an infinite recursion even if + # the other type is not recursive, because of the tuple fallback that is + # calculated "on the fly". + or isinstance(get_proper_type(s), TupleType) + ) + if isinstance(t, TypeAliasType) and t.is_recursive: + return ( + isinstance(get_proper_type(s), (Instance, UnionType)) + or isinstance(s, TypeAliasType) + and s.is_recursive + # Same as above. + or isinstance(get_proper_type(t), TupleType) + ) + return False + + +def tuple_fallback(typ: TupleType) -> Instance: + """Return fallback type for a tuple.""" + info = typ.partial_fallback.type + if info.fullname != "builtins.tuple": + return typ.partial_fallback + items = [] + for item in typ.items: + if isinstance(item, UnpackType): + unpacked_type = get_proper_type(item.type) + if isinstance(unpacked_type, TypeVarTupleType): + unpacked_type = get_proper_type(unpacked_type.upper_bound) + if ( + isinstance(unpacked_type, Instance) + and unpacked_type.type.fullname == "builtins.tuple" + ): + items.append(unpacked_type.args[0]) + else: + raise NotImplementedError + else: + items.append(item) + return Instance( + info, + # Note: flattening recursive unions is dangerous, since it can fool recursive + # types optimization in subtypes.py and go into infinite recursion. + [make_simplified_union(items, handle_recursive=False)], + extra_attrs=typ.partial_fallback.extra_attrs, + ) + + +def get_self_type(func: CallableType, def_info: TypeInfo) -> Type | None: + default_self = fill_typevars(def_info) + if isinstance(get_proper_type(func.ret_type), UninhabitedType): + return func.ret_type + elif func.arg_types and func.arg_types[0] != default_self and func.arg_kinds[0] == ARG_POS: + return func.arg_types[0] + else: + return None + + +def type_object_type(info: TypeInfo, named_type: Callable[[str], Instance]) -> ProperType: + """Return the type of a type object. + + For a generic type G with type variables T and S the type is generally of form + + Callable[..., G[T, S]] + + where ... are argument types for the __init__/__new__ method (without the self + argument). Also, the fallback type will be 'type' instead of 'function'. + """ + allow_cache = ( + checker_state.type_checker is not None + and checker_state.type_checker.allow_constructor_cache + ) + + if info.type_object_type is not None: + if allow_cache: + return info.type_object_type + info.type_object_type = None + + # We take the type from whichever of __init__ and __new__ is first + # in the MRO, preferring __init__ if there is a tie. + init_method = info.get("__init__") + new_method = info.get("__new__") + if not init_method or not is_valid_constructor(init_method.node): + # Must be an invalid class definition. + return AnyType(TypeOfAny.from_error) + # There *should* always be a __new__ method except the test stubs + # lack it, so just copy init_method in that situation + new_method = new_method or init_method + if not is_valid_constructor(new_method.node): + # Must be an invalid class definition. + return AnyType(TypeOfAny.from_error) + + # The two is_valid_constructor() checks ensure this. + assert isinstance(new_method.node, (SYMBOL_FUNCBASE_TYPES, Decorator)) + assert isinstance(init_method.node, (SYMBOL_FUNCBASE_TYPES, Decorator)) + + init_index = info.mro.index(init_method.node.info) + new_index = info.mro.index(new_method.node.info) + + if info.metaclass_type is not None: + fallback = info.metaclass_type + elif checker_state.type_checker: + # Prefer direct call when it is available. It is faster, and, + # unfortunately, some callers provide bogus callback. + fallback = checker_state.type_checker.named_type("builtins.type") + else: + fallback = named_type("builtins.type") + + if init_index < new_index: + method: FuncBase | Decorator = init_method.node + is_new = False + elif init_index > new_index: + method = new_method.node + is_new = True + else: + if init_method.node.info.fullname == "builtins.object": + # Both are defined by object. But if we've got a bogus + # base class, we can't know for sure, so check for that. + if info.fallback_to_any: + # Construct a universal callable as the prototype. + any_type = AnyType(TypeOfAny.special_form) + sig = CallableType( + arg_types=[any_type, any_type], + arg_kinds=[ARG_STAR, ARG_STAR2], + arg_names=["_args", "_kwds"], + ret_type=any_type, + is_bound=True, + fallback=named_type("builtins.function"), + ) + result: FunctionLike = class_callable(sig, info, fallback, None, is_new=False) + if allow_cache and state.strict_optional: + info.type_object_type = result + return result + + # Otherwise prefer __init__ in a tie. It isn't clear that this + # is the right thing, but __new__ caused problems with + # typeshed (#5647). + method = init_method.node + is_new = False + # Construct callable type based on signature of __init__. Adjust + # return type and insert type arguments. + if isinstance(method, FuncBase): + if isinstance(method, OverloadedFuncDef) and not method.type: + # Do not cache if the type is not ready. Same logic for decorators is + # achieved in early return above because is_valid_constructor() is False. + allow_cache = False + t = function_type(method, fallback) + else: + assert isinstance(method.type, ProperType) + assert isinstance(method.type, FunctionLike) # is_valid_constructor() ensures this + t = method.type + result = type_object_type_from_function(t, info, method.info, fallback, is_new) + # Only write cached result is strict_optional=True, otherwise we may get + # inconsistent behaviour because of union simplification. + if allow_cache and state.strict_optional: + info.type_object_type = result + return result + + +def is_valid_constructor(n: SymbolNode | None) -> bool: + """Does this node represents a valid constructor method? + + This includes normal functions, overloaded functions, and decorators + that return a callable type. + """ + if isinstance(n, SYMBOL_FUNCBASE_TYPES): + return True + if isinstance(n, Decorator): + return isinstance(get_proper_type(n.type), FunctionLike) + return False + + +def type_object_type_from_function( + signature: FunctionLike, info: TypeInfo, def_info: TypeInfo, fallback: Instance, is_new: bool +) -> FunctionLike: + # We first need to record all non-trivial (explicit) self types in __init__, + # since they will not be available after we bind them. Note, we use explicit + # self-types only in the defining class, similar to __new__ (but not exactly the same, + # see comment in class_callable below). This is mostly useful for annotating library + # classes such as subprocess.Popen. + if not is_new and not info.is_newtype: + orig_self_types = [get_self_type(it, def_info) for it in signature.items] + else: + orig_self_types = [None] * len(signature.items) + + # The __init__ method might come from a generic superclass 'def_info' + # with type variables that do not map identically to the type variables of + # the class 'info' being constructed. For example: + # + # class A(Generic[T]): + # def __init__(self, x: T) -> None: ... + # class B(A[List[T]]): + # ... + # + # We need to map B's __init__ to the type (List[T]) -> None. + signature = bind_self( + signature, + original_type=fill_typevars(info), + is_classmethod=is_new, + # Explicit instance self annotations have special handling in class_callable(), + # we don't need to bind any type variables in them if they are generic. + ignore_instances=True, + ) + signature = cast(FunctionLike, map_type_from_supertype(signature, info, def_info)) + + special_sig: str | None = None + if def_info.fullname == "builtins.dict": + # Special signature! + special_sig = "dict" + + if isinstance(signature, CallableType): + return class_callable(signature, info, fallback, special_sig, is_new, orig_self_types[0]) + else: + # Overloaded __init__/__new__. + assert isinstance(signature, Overloaded) + items: list[CallableType] = [] + for item, orig_self in zip(signature.items, orig_self_types): + items.append(class_callable(item, info, fallback, special_sig, is_new, orig_self)) + return Overloaded(items) + + +def class_callable( + init_type: CallableType, + info: TypeInfo, + type_type: Instance, + special_sig: str | None, + is_new: bool, + orig_self_type: Type | None = None, +) -> CallableType: + """Create a type object type based on the signature of __init__.""" + variables: list[TypeVarLikeType] = [] + variables.extend(info.defn.type_vars) + variables.extend(init_type.variables) + + from mypy.subtypes import is_subtype + + init_ret_type = get_proper_type(init_type.ret_type) + orig_self_type = get_proper_type(orig_self_type) + default_ret_type = fill_typevars(info) + explicit_type = init_ret_type if is_new else orig_self_type + if ( + isinstance(explicit_type, (Instance, TupleType, UninhabitedType, LiteralType)) + # We have to skip protocols, because it can be a subtype of a return type + # by accident. Like `Hashable` is a subtype of `object`. See #11799 + and isinstance(default_ret_type, Instance) + and not default_ret_type.type.is_protocol + # Only use the declared return type from __new__ or declared self in __init__ + # if it is actually returning a subtype of what we would return otherwise. + and is_subtype(explicit_type, default_ret_type, ignore_type_params=True) + ): + ret_type: Type = explicit_type + else: + ret_type = default_ret_type + + callable_type = init_type.copy_modified( + ret_type=ret_type, + fallback=type_type, + name=None, + variables=variables, + special_sig=special_sig, + ) + c = callable_type.with_name(info.name) + return c + + +def map_type_from_supertype(typ: Type, sub_info: TypeInfo, super_info: TypeInfo) -> Type: + """Map type variables in a type defined in a supertype context to be valid + in the subtype context. Assume that the result is unique; if more than + one type is possible, return one of the alternatives. + + For example, assume + + class D(Generic[S]): ... + class C(D[E[T]], Generic[T]): ... + + Now S in the context of D would be mapped to E[T] in the context of C. + """ + # Create the type of self in subtype, of form t[a1, ...]. + inst_type = fill_typevars(sub_info) + if isinstance(inst_type, TupleType): + inst_type = tuple_fallback(inst_type) + # Map the type of self to supertype. This gets us a description of the + # supertype type variables in terms of subtype variables, i.e. t[t1, ...] + # so that any type variables in tN are to be interpreted in subtype + # context. + inst_type = map_instance_to_supertype(inst_type, super_info) + # Finally expand the type variables in type with those in the previously + # constructed type. Note that both type and inst_type may have type + # variables, but in type they are interpreted in supertype context while + # in inst_type they are interpreted in subtype context. This works even if + # the names of type variables in supertype and subtype overlap. + return expand_type_by_instance(typ, inst_type) + + +def supported_self_type( + typ: ProperType, allow_callable: bool = True, allow_instances: bool = True +) -> bool: + """Is this a supported kind of explicit self-types? + + Currently, this means an X or Type[X], where X is an instance or + a type variable with an instance upper bound. + """ + if isinstance(typ, TypeType): + return supported_self_type(typ.item) + if allow_callable and isinstance(typ, CallableType): + # Special case: allow class callable instead of Type[...] as cls annotation, + # as well as callable self for callback protocols. + return True + return isinstance(typ, TypeVarType) or ( + allow_instances and isinstance(typ, Instance) and typ != fill_typevars(typ.type) + ) + + +F = TypeVar("F", bound=FunctionLike) + + +def bind_self( + method: F, + original_type: Type | None = None, + is_classmethod: bool = False, + ignore_instances: bool = False, +) -> F: + """Return a copy of `method`, with the type of its first parameter (usually + self or cls) bound to original_type. + + If the type of `self` is a generic type (T, or Type[T] for classmethods), + instantiate every occurrence of type with original_type in the rest of the + signature and in the return type. + + original_type is the type of E in the expression E.copy(). It is None in + compatibility checks. In this case we treat it as the erasure of the + declared type of self. + + This way we can express "the type of self". For example: + + T = TypeVar('T', bound='A') + class A: + def copy(self: T) -> T: ... + + class B(A): pass + + b = B().copy() # type: B + + """ + if isinstance(method, Overloaded): + items = [ + bind_self(c, original_type, is_classmethod, ignore_instances) for c in method.items + ] + return cast(F, Overloaded(items)) + assert isinstance(method, CallableType) + func: CallableType = method + if not func.arg_types: + # Invalid method, return something. + return method + if func.arg_kinds[0] in (ARG_STAR, ARG_STAR2): + # The signature is of the form 'def foo(*args, ...)'. + # In this case we shouldn't drop the first arg, + # since func will be absorbed by the *args. + # TODO: infer bounds on the type of *args? + + # In the case of **kwargs we should probably emit an error, but + # for now we simply skip it, to avoid crashes down the line. + return method + self_param_type = get_proper_type(func.arg_types[0]) + + variables: Sequence[TypeVarLikeType] + # Having a def __call__(self: Callable[...], ...) can cause infinite recursion. Although + # this special-casing looks not very principled, there is nothing meaningful we can infer + # from such definition, since it is inherently indefinitely recursive. + allow_callable = func.name is None or not func.name.startswith("__call__ of") + if func.variables and supported_self_type( + self_param_type, allow_callable=allow_callable, allow_instances=not ignore_instances + ): + from mypy.infer import infer_type_arguments + + if original_type is None: + # TODO: type check method override (see #7861). + original_type = erase_to_bound(self_param_type) + original_type = get_proper_type(original_type) + + # Find which of method type variables appear in the type of "self". + self_ids = {tv.id for tv in get_all_type_vars(self_param_type)} + self_vars = [tv for tv in func.variables if tv.id in self_ids] + + # Solve for these type arguments using the actual class or instance type. + typeargs = infer_type_arguments( + self_vars, self_param_type, original_type, is_supertype=True + ) + if ( + is_classmethod + and any(isinstance(get_proper_type(t), UninhabitedType) for t in typeargs) + and isinstance(original_type, (Instance, TypeVarType, TupleType)) + ): + # In case we call a classmethod through an instance x, fallback to type(x). + typeargs = infer_type_arguments( + self_vars, self_param_type, TypeType(original_type), is_supertype=True + ) + + # Update the method signature with the solutions found. + # Technically, some constraints might be unsolvable, make them Never. + to_apply = [t if t is not None else UninhabitedType() for t in typeargs] + func = expand_type(func, {tv.id: arg for tv, arg in zip(self_vars, to_apply)}) + variables = [v for v in func.variables if v not in self_vars] + else: + variables = func.variables + + res = func.copy_modified( + arg_types=func.arg_types[1:], + arg_kinds=func.arg_kinds[1:], + arg_names=func.arg_names[1:], + variables=variables, + is_bound=True, + ) + return cast(F, res) + + +def erase_to_bound(t: Type) -> Type: + # TODO: use value restrictions to produce a union? + t = get_proper_type(t) + if isinstance(t, TypeVarType): + return t.upper_bound + if isinstance(t, TypeType): + if isinstance(t.item, TypeVarType): + return TypeType.make_normalized(t.item.upper_bound, is_type_form=t.is_type_form) + return t + + +def callable_corresponding_argument( + typ: NormalizedCallableType | Parameters, model: FormalArgument +) -> FormalArgument | None: + """Return the argument of a function that corresponds to `model`""" + + by_name = typ.argument_by_name(model.name) + by_pos = typ.argument_by_position(model.pos) + if by_name is None and by_pos is None: + return None + if by_name is not None and by_pos is not None: + if by_name == by_pos: + return by_name + # If we're dealing with an optional pos-only and an optional + # name-only arg, merge them. This is the case for all functions + # taking both *args and **args, or a pair of functions like so: + + # def right(a: int = ...) -> None: ... + # def left(x: int = ..., /, *, a: int = ...) -> None: ... + from mypy.meet import meet_types + + if ( + not (by_name.required or by_pos.required) + and by_pos.name is None + and by_name.pos is None + # This is not principled, but prevents a crash. It's weird to have a FormalArgument + # that has an UnpackType. + and not isinstance(by_name.typ, UnpackType) + and not isinstance(by_pos.typ, UnpackType) + ): + return FormalArgument( + by_name.name, by_pos.pos, meet_types(by_name.typ, by_pos.typ), False + ) + return by_name + + return by_name if by_name is not None else by_pos + + +def simple_literal_type(t: ProperType | None) -> Instance | None: + """Extract the underlying fallback Instance type for a simple Literal""" + if isinstance(t, Instance) and t.last_known_value is not None: + t = t.last_known_value + if isinstance(t, LiteralType): + return t.fallback + return None + + +def is_simple_literal(t: ProperType) -> bool: + if isinstance(t, LiteralType): + return t.fallback.type.is_enum or t.fallback.type.fullname == "builtins.str" + if isinstance(t, Instance): + return t.last_known_value is not None and isinstance(t.last_known_value.value, str) + return False + + +def make_simplified_union( + items: Sequence[Type], + line: int = -1, + column: int = -1, + *, + keep_erased: bool = False, + contract_literals: bool = True, + handle_recursive: bool = True, +) -> ProperType: + """Build union type with redundant union items removed. + + If only a single item remains, this may return a non-union type. + + Examples: + + * [int, str] -> Union[int, str] + * [int, object] -> object + * [int, int] -> int + * [int, Any] -> Union[int, Any] (Any types are not simplified away!) + * [Any, Any] -> Any + * [int, Union[bytes, str]] -> Union[int, bytes, str] + + Note: This must NOT be used during semantic analysis, since TypeInfos may not + be fully initialized. + + The keep_erased flag is used for type inference against union types + containing type variables. If set to True, keep all ErasedType items. + + The contract_literals flag indicates whether we need to contract literal types + back into a sum type. Set it to False when called by try_expanding_sum_type_ + to_union(). + """ + # Step 1: expand all nested unions + items = flatten_nested_unions(items, handle_recursive=handle_recursive) + + # Step 2: fast path for single item + if len(items) == 1: + return get_proper_type(items[0]) + + # Step 3: remove redundant unions + simplified_set: Sequence[Type] = _remove_redundant_union_items(items, keep_erased) + + # Step 4: If more than one literal exists in the union, try to simplify + if ( + contract_literals + and sum(isinstance(get_proper_type(item), LiteralType) for item in simplified_set) > 1 + ): + simplified_set = try_contracting_literals_in_union(simplified_set) + + result = get_proper_type(UnionType.make_union(simplified_set, line, column)) + + nitems = len(items) + if nitems > 1 and ( + nitems > 2 or not (type(items[0]) is NoneType or type(items[1]) is NoneType) + ): + # Step 5: At last, we erase any (inconsistent) extra attributes on instances. + + # Initialize with None instead of an empty set as a micro-optimization. The set + # is needed very rarely, so we try to avoid constructing it. + extra_attrs_set: set[ExtraAttrs] | None = None + for item in items: + instance = try_getting_instance_fallback(item) + if instance and instance.extra_attrs: + if extra_attrs_set is None: + extra_attrs_set = {instance.extra_attrs} + else: + extra_attrs_set.add(instance.extra_attrs) + + # Code below is awkward, because we don't want the extra checks to affect + # performance in the common case. + erase_extra = False + if extra_attrs_set is not None: + fallback = try_getting_instance_fallback(result) + if fallback is None: + return result + if len(extra_attrs_set) > 1: # This case is too tricky to handle. + erase_extra = True + else: + # Check that all relevant items have the extra attributes. + for item in items: + instance = try_getting_instance_fallback(item) + if instance and instance.type == fallback.type and not instance.extra_attrs: + erase_extra = True + break + if erase_extra: + fallback.extra_attrs = None + + return result + + +def _remove_redundant_union_items(items: list[Type], keep_erased: bool) -> list[Type]: + from mypy.subtypes import is_proper_subtype + + # The first pass through this loop, we check if later items are subtypes of earlier items. + # The second pass through this loop, we check if earlier items are subtypes of later items + # (by reversing the remaining items) + for _direction in range(2): + new_items: list[Type] = [] + # seen is a map from a type to its index in new_items + seen: dict[ProperType, int] = {} + unduplicated_literal_fallbacks: set[Instance] | None = None + for ti in items: + proper_ti = get_proper_type(ti) + + # UninhabitedType is always redundant + if isinstance(proper_ti, UninhabitedType): + continue + + duplicate_index = -1 + # Quickly check if we've seen this type + if proper_ti in seen: + duplicate_index = seen[proper_ti] + elif ( + isinstance(proper_ti, LiteralType) + and unduplicated_literal_fallbacks is not None + and proper_ti.fallback in unduplicated_literal_fallbacks + ): + # This is an optimisation for unions with many LiteralType + # We've already checked for exact duplicates. This means that any super type of + # the LiteralType must be a super type of its fallback. If we've gone through + # the expensive loop below and found no super type for a previous LiteralType + # with the same fallback, we can skip doing that work again and just add the type + # to new_items + pass + else: + # If not, check if we've seen a supertype of this type + for j, tj in enumerate(new_items): + proper_tj = get_proper_type(tj) + # If tj is an Instance with a last_known_value, do not remove proper_ti + # (unless it's an instance with the same last_known_value) + if ( + isinstance(proper_tj, Instance) + and proper_tj.last_known_value is not None + and not ( + isinstance(proper_ti, Instance) + and proper_tj.last_known_value == proper_ti.last_known_value + ) + ): + continue + + if is_proper_subtype( + ti, tj, keep_erased_types=keep_erased, ignore_promotions=True + ): + duplicate_index = j + break + if duplicate_index != -1: + # If deleted subtypes had more general truthiness, use that + orig_item = new_items[duplicate_index] + if not orig_item.can_be_true and ti.can_be_true: + new_items[duplicate_index] = true_or_false(orig_item) + elif not orig_item.can_be_false and ti.can_be_false: + new_items[duplicate_index] = true_or_false(orig_item) + else: + # We have a non-duplicate item, add it to new_items + seen[proper_ti] = len(new_items) + new_items.append(ti) + if isinstance(proper_ti, LiteralType): + if unduplicated_literal_fallbacks is None: + unduplicated_literal_fallbacks = set() + unduplicated_literal_fallbacks.add(proper_ti.fallback) + + items = new_items + if len(items) <= 1: + break + items.reverse() + + return items + + +def _get_type_method_ret_type(t: ProperType, *, name: str) -> Type | None: + # For Enum literals the ret_type can change based on the Enum + # we need to check the type of the enum rather than the literal + if isinstance(t, LiteralType) and t.is_enum_literal(): + t = t.fallback + + if isinstance(t, Instance): + sym = t.type.get(name) + if sym: + sym_type = get_proper_type(sym.type) + if isinstance(sym_type, CallableType): + return sym_type.ret_type + + return None + + +def true_only(t: Type) -> ProperType: + """ + Restricted version of t with only True-ish values + """ + t = get_proper_type(t) + + if not t.can_be_true: + # All values of t are False-ish, so there are no true values in it + return UninhabitedType(line=t.line, column=t.column) + elif not t.can_be_false: + # All values of t are already True-ish, so true_only is idempotent in this case + return t + elif isinstance(t, UnionType): + # The true version of a union type is the union of the true versions of its components + new_items = [true_only(item) for item in t.items] + can_be_true_items = [item for item in new_items if item.can_be_true] + return make_simplified_union(can_be_true_items, line=t.line, column=t.column) + else: + ret_type = _get_type_method_ret_type(t, name="__bool__") or _get_type_method_ret_type( + t, name="__len__" + ) + + if ret_type and not ret_type.can_be_true: + return UninhabitedType(line=t.line, column=t.column) + + new_t = copy_type(t) + new_t.can_be_false = False + return new_t + + +def false_only(t: Type) -> ProperType: + """ + Restricted version of t with only False-ish values + """ + t = get_proper_type(t) + + if not t.can_be_false: + if state.strict_optional: + # All values of t are True-ish, so there are no false values in it + return UninhabitedType(line=t.line) + else: + # When strict optional checking is disabled, everything can be + # False-ish since anything can be None + return NoneType(line=t.line) + elif not t.can_be_true: + # All values of t are already False-ish, so false_only is idempotent in this case + return t + elif isinstance(t, UnionType): + # The false version of a union type is the union of the false versions of its components + new_items = [false_only(item) for item in t.items] + can_be_false_items = [item for item in new_items if item.can_be_false] + return make_simplified_union(can_be_false_items, line=t.line, column=t.column) + elif isinstance(t, Instance) and t.type.fullname in ("builtins.str", "builtins.bytes"): + return LiteralType("", fallback=t) + elif isinstance(t, Instance) and t.type.fullname == "builtins.int": + return LiteralType(0, fallback=t) + else: + ret_type = _get_type_method_ret_type(t, name="__bool__") or _get_type_method_ret_type( + t, name="__len__" + ) + + if ret_type: + if not ret_type.can_be_false: + return UninhabitedType(line=t.line) + elif isinstance(t, Instance): + if (t.type.is_final or t.type.is_enum) and state.strict_optional: + return UninhabitedType(line=t.line) + elif isinstance(t, LiteralType) and t.is_enum_literal() and state.strict_optional: + return UninhabitedType(line=t.line) + + new_t = copy_type(t) + new_t.can_be_true = False + return new_t + + +def true_or_false(t: Type) -> ProperType: + """ + Unrestricted version of t with both True-ish and False-ish values + """ + t = get_proper_type(t) + + if isinstance(t, UnionType): + new_items = [true_or_false(item) for item in t.items] + return make_simplified_union(new_items, line=t.line, column=t.column) + + new_t = copy_type(t) + new_t.can_be_true = new_t.can_be_true_default() + new_t.can_be_false = new_t.can_be_false_default() + return new_t + + +def erase_def_to_union_or_bound(tdef: TypeVarLikeType) -> Type: + # TODO(PEP612): fix for ParamSpecType + if isinstance(tdef, ParamSpecType): + return AnyType(TypeOfAny.from_error) + if isinstance(tdef, TypeVarType) and tdef.values: + return make_simplified_union(tdef.values) + else: + return tdef.upper_bound + + +def erase_to_union_or_bound(typ: TypeVarType) -> ProperType: + if typ.values: + return make_simplified_union(typ.values) + else: + return get_proper_type(typ.upper_bound) + + +def function_type(func: FuncBase, fallback: Instance) -> FunctionLike: + if func.type: + assert isinstance(func.type, FunctionLike) + return func.type + else: + # Implicit type signature with dynamic types. + if isinstance(func, FuncItem): + return callable_type(func, fallback) + else: + # Either a broken overload, or decorated overload type is not ready. + # TODO: make sure the caller defers if possible. + assert isinstance(func, OverloadedFuncDef) + any_type = AnyType(TypeOfAny.from_error) + dummy = CallableType( + [any_type, any_type], + [ARG_STAR, ARG_STAR2], + [None, None], + any_type, + fallback, + line=func.line, + is_ellipsis_args=True, + ) + # Return an Overloaded, because some callers may expect that + # an OverloadedFuncDef has an Overloaded type. + return Overloaded([dummy]) + + +def callable_type( + fdef: FuncItem, fallback: Instance, ret_type: Type | None = None +) -> CallableType: + # TODO: somewhat unfortunate duplication with prepare_method_signature in semanal + if fdef.info and fdef.has_self_or_cls_argument and fdef.arg_names: + self_type: Type = fill_typevars(fdef.info) + if fdef.is_class or fdef.name == "__new__": + self_type = TypeType.make_normalized(self_type) + args = [self_type] + [AnyType(TypeOfAny.unannotated)] * (len(fdef.arg_names) - 1) + else: + args = [AnyType(TypeOfAny.unannotated)] * len(fdef.arg_names) + + return CallableType( + args, + fdef.arg_kinds, + fdef.arg_names, + ret_type or AnyType(TypeOfAny.unannotated), + fallback, + name=fdef.name, + line=fdef.line, + column=fdef.column, + implicit=True, + # We need this for better error messages, like missing `self` note: + definition=fdef if isinstance(fdef, FuncDef) else None, + ) + + +def try_getting_str_literals(expr: Expression, typ: Type) -> list[str] | None: + """If the given expression or type corresponds to a string literal + or a union of string literals, returns a list of the underlying strings. + Otherwise, returns None. + + Specifically, this function is guaranteed to return a list with + one or more strings if one of the following is true: + + 1. 'expr' is a StrExpr + 2. 'typ' is a LiteralType containing a string + 3. 'typ' is a UnionType containing only LiteralType of strings + """ + if isinstance(expr, StrExpr): + return [expr.value] + + # TODO: See if we can eliminate this function and call the below one directly + return try_getting_str_literals_from_type(typ) + + +def try_getting_str_literals_from_type(typ: Type) -> list[str] | None: + """If the given expression or type corresponds to a string Literal + or a union of string Literals, returns a list of the underlying strings. + Otherwise, returns None. + + For example, if we had the type 'Literal["foo", "bar"]' as input, this function + would return a list of strings ["foo", "bar"]. + """ + return try_getting_literals_from_type(typ, str, "builtins.str") + + +def try_getting_int_literals_from_type(typ: Type) -> list[int] | None: + """If the given expression or type corresponds to an int Literal + or a union of int Literals, returns a list of the underlying ints. + Otherwise, returns None. + + For example, if we had the type 'Literal[1, 2, 3]' as input, this function + would return a list of ints [1, 2, 3]. + """ + return try_getting_literals_from_type(typ, int, "builtins.int") + + +T = TypeVar("T") + + +def try_getting_literals_from_type( + typ: Type, target_literal_type: type[T], target_fullname: str +) -> list[T] | None: + """If the given expression or type corresponds to a Literal or + union of Literals where the underlying values correspond to the given + target type, returns a list of those underlying values. Otherwise, + returns None. + """ + typ = get_proper_type(typ) + + if isinstance(typ, Instance) and typ.last_known_value is not None: + possible_literals: list[Type] = [typ.last_known_value] + elif isinstance(typ, UnionType): + possible_literals = list(typ.items) + else: + possible_literals = [typ] + + literals: list[T] = [] + for lit in get_proper_types(possible_literals): + if isinstance(lit, LiteralType) and lit.fallback.type.fullname == target_fullname: + val = lit.value + if isinstance(val, target_literal_type): + literals.append(val) + else: + return None + else: + return None + return literals + + +def is_literal_type_like(t: Type | None) -> bool: + """Returns 'true' if the given type context is potentially either a LiteralType, + a Union of LiteralType, or something similar. + """ + t = get_proper_type(t) + if t is None: + return False + elif isinstance(t, LiteralType): + return True + elif isinstance(t, UnionType): + return any(is_literal_type_like(item) for item in t.items) + elif isinstance(t, TypeVarType): + return is_literal_type_like(t.upper_bound) or any( + is_literal_type_like(item) for item in t.values + ) + else: + return False + + +def is_singleton_identity_type(typ: ProperType) -> bool: + """ + Returns True if every value of this type is identical to every other value of this type, + as judged by the `is` operator. + + Note that this is not true of certain LiteralType, such as Literal[100001] or Literal["string"] + """ + if isinstance(typ, NoneType): + return True + if isinstance(typ, Instance): + return ( + (typ.type.is_enum and len(typ.type.enum_members) == 1) + or (typ.type.fullname in ELLIPSIS_TYPE_NAMES) + or (typ.type.fullname in NOT_IMPLEMENTED_TYPE_NAMES) + ) + if isinstance(typ, LiteralType): + return typ.is_enum_literal() or isinstance(typ.value, bool) + if isinstance(typ, TypeType) and isinstance(typ.item, Instance) and typ.item.type.is_final: + return True + if isinstance(typ, FunctionLike) and typ.is_type_obj() and typ.type_object().is_final: + return True + return False + + +def is_singleton_equality_type(typ: ProperType) -> bool: + """ + Returns True if every value of this type compares equal to every other value of this type, + as judged by the `==` operator. + """ + return isinstance(typ, LiteralType) or is_singleton_identity_type(typ) + + +def try_expanding_sum_type_to_union(typ: Type, target_fullname: str | None) -> Type: + """Attempts to recursively expand any enum Instances with the given target_fullname + into a Union of all of its component LiteralTypes. + + For example, if we have: + + class Color(Enum): + RED = 1 + BLUE = 2 + YELLOW = 3 + + class Status(Enum): + SUCCESS = 1 + FAILURE = 2 + UNKNOWN = 3 + + ...and if we call `try_expanding_sum_type_to_union(Union[Color, Status], 'module.Color')`, + this function will return Literal[Color.RED, Color.BLUE, Color.YELLOW, Status]. + """ + typ = get_proper_type(typ) + + if isinstance(typ, UnionType): + # Non-empty enums cannot subclass each other so simply removing duplicates is enough. + items = [ + try_expanding_sum_type_to_union(item, target_fullname) + for item in remove_dups(flatten_nested_unions(typ.relevant_items())) + ] + return UnionType.make_union(items) + + if isinstance(typ, Instance) and ( + target_fullname is None or typ.type.fullname == target_fullname + ): + if typ.type.fullname == "builtins.bool": + return UnionType([LiteralType(True, typ), LiteralType(False, typ)]) + + if typ.type.is_enum: + items = [LiteralType(name, typ) for name in typ.type.enum_members] + if not items: + return typ + return UnionType.make_union(items) + + return typ + + +def try_contracting_literals_in_union(types: Sequence[Type]) -> list[ProperType]: + """Contracts any literal types back into a sum type if possible. + + Requires a flattened union and does not descend into children. + + Will replace the first instance of the literal with the sum type and + remove all others. + + If we call `try_contracting_union(Literal[Color.RED, Color.BLUE, Color.YELLOW])`, + this function will return Color. + + We also treat `Literal[True, False]` as `bool`. + """ + proper_types = [get_proper_type(typ) for typ in types] + sum_types: dict[str, tuple[set[Any], list[int]]] = {} + marked_for_deletion = set() + for idx, typ in enumerate(proper_types): + if isinstance(typ, LiteralType): + fullname = typ.fallback.type.fullname + if typ.fallback.type.is_enum or isinstance(typ.value, bool): + if fullname not in sum_types: + sum_types[fullname] = ( + ( + set(typ.fallback.type.enum_members) + if typ.fallback.type.is_enum + else {True, False} + ), + [], + ) + literals, indexes = sum_types[fullname] + literals.discard(typ.value) + indexes.append(idx) + if not literals: + first, *rest = indexes + proper_types[first] = typ.fallback + marked_for_deletion |= set(rest) + return list( + itertools.compress( + proper_types, [(i not in marked_for_deletion) for i in range(len(proper_types))] + ) + ) + + +def coerce_to_literal(typ: Type) -> Type: + """Recursively converts any Instances that have a last_known_value or are + instances of enum types with a single value into the corresponding LiteralType. + """ + original_type = typ + typ = get_proper_type(typ) + if isinstance(typ, UnionType): + new_items = [coerce_to_literal(item) for item in typ.items] + return UnionType.make_union(new_items) + elif isinstance(typ, Instance): + if typ.last_known_value: + return typ.last_known_value + elif typ.type.is_enum: + enum_values = typ.type.enum_members + if len(enum_values) == 1: + return LiteralType(value=enum_values[0], fallback=typ) + return original_type + + +def get_type_vars(tp: Type) -> list[TypeVarType]: + return cast("list[TypeVarType]", tp.accept(TypeVarExtractor())) + + +def get_all_type_vars(tp: Type) -> list[TypeVarLikeType]: + # TODO: should we always use this function instead of get_type_vars() above? + return tp.accept(TypeVarExtractor(include_all=True)) + + +class TypeVarExtractor(TypeQuery[list[TypeVarLikeType]]): + def __init__(self, include_all: bool = False) -> None: + super().__init__() + self.include_all = include_all + + def strategy(self, items: Iterable[list[TypeVarLikeType]]) -> list[TypeVarLikeType]: + out = [] + for item in items: + out.extend(item) + return out + + def visit_type_var(self, t: TypeVarType) -> list[TypeVarLikeType]: + return [t] + + def visit_param_spec(self, t: ParamSpecType) -> list[TypeVarLikeType]: + return [t] if self.include_all else [] + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> list[TypeVarLikeType]: + return [t] if self.include_all else [] + + +def freeze_all_type_vars(member_type: Type) -> None: + member_type.accept(FreezeTypeVarsVisitor()) + + +class FreezeTypeVarsVisitor(TypeTraverserVisitor): + def visit_callable_type(self, t: CallableType) -> None: + for v in t.variables: + v.id.meta_level = 0 + super().visit_callable_type(t) + + +def custom_special_method(typ: Type, name: str, check_all: bool = False) -> bool: + """Does this type have a custom special method such as __format__() or __eq__()? + + If check_all is True ensure all items of a union have a custom method, not just some. + """ + typ = get_proper_type(typ) + if isinstance(typ, Instance): + method = typ.type.get(name) + if method and isinstance(method.node, (SYMBOL_FUNCBASE_TYPES, Decorator, Var)): + if method.node.info: + return not method.node.info.fullname.startswith(("builtins.", "typing.")) + return False + if isinstance(typ, UnionType): + if check_all: + return all(custom_special_method(t, name, check_all) for t in typ.items) + return any(custom_special_method(t, name) for t in typ.items) + if isinstance(typ, TupleType): + return custom_special_method(tuple_fallback(typ), name, check_all) + if isinstance(typ, FunctionLike) and typ.is_type_obj(): + # Look up __method__ on the metaclass for class objects. + return custom_special_method(typ.fallback, name, check_all) + if isinstance(typ, TypeType) and isinstance(typ.item, Instance): + if typ.item.type.metaclass_type: + # Look up __method__ on the metaclass for class objects. + return custom_special_method(typ.item.type.metaclass_type, name, check_all) + if isinstance(typ, AnyType): + # Avoid false positives in uncertain cases. + return True + # TODO: support other types (see ExpressionChecker.has_member())? + return False + + +def separate_union_literals(t: UnionType) -> tuple[Sequence[LiteralType], Sequence[Type]]: + """Separate literals from other members in a union type.""" + literal_items = [] + union_items = [] + + for item in t.items: + proper = get_proper_type(item) + if isinstance(proper, LiteralType): + literal_items.append(proper) + else: + union_items.append(item) + + return literal_items, union_items + + +def try_getting_instance_fallback(typ: Type) -> Instance | None: + """Returns the Instance fallback for this type if one exists or None.""" + typ = get_proper_type(typ) + if isinstance(typ, Instance): + return typ + elif isinstance(typ, LiteralType): + return typ.fallback + elif isinstance(typ, (NoneType, AnyType)): + return None # Fast path for None, which is common + elif isinstance(typ, FunctionLike): + return typ.fallback + elif isinstance(typ, TypeVarType): + return try_getting_instance_fallback(typ.upper_bound) + elif isinstance(typ, TupleType): + return typ.partial_fallback + elif isinstance(typ, TypedDictType): + return typ.fallback + return None + + +def fixup_partial_type(typ: Type) -> Type: + """Convert a partial type that we couldn't resolve into something concrete. + + This means, for None we make it Optional[Any], and for anything else we + fill in all of the type arguments with Any. + """ + if not isinstance(typ, PartialType): + return typ + if typ.type is None: + return UnionType.make_union([AnyType(TypeOfAny.unannotated), NoneType()]) + else: + return Instance(typ.type, [AnyType(TypeOfAny.unannotated)] * len(typ.type.type_vars)) + + +def get_protocol_member( + left: Instance, member: str, class_obj: bool, is_lvalue: bool = False +) -> Type | None: + if member == "__call__" and class_obj: + # Special case: class objects always have __call__ that is just the constructor. + + # TODO: this is wrong, it creates callables that are not recognized as type objects. + # Long-term, we should probably get rid of this callback argument altogether. + def named_type(fullname: str) -> Instance: + return Instance(left.type.mro[-1], []) + + return type_object_type(left.type, named_type) + + if member == "__call__" and left.type.is_metaclass(precise=True): + # Special case: we want to avoid falling back to metaclass __call__ + # if constructor signature didn't match, this can cause many false negatives. + return None + + from mypy.subtypes import find_member + + subtype = find_member(member, left, left, class_obj=class_obj, is_lvalue=is_lvalue) + if isinstance(subtype, PartialType): + subtype = ( + NoneType() + if subtype.type is None + else Instance( + subtype.type, [AnyType(TypeOfAny.unannotated)] * len(subtype.type.type_vars) + ) + ) + return subtype + + +def _is_disjoint_base(info: TypeInfo) -> bool: + # It either has the @disjoint_base decorator or defines nonempty __slots__. + if info.is_disjoint_base: + return True + if not info.slots: + return False + own_slots = { + slot + for slot in info.slots + if not any( + base_info.type.slots is not None and slot in base_info.type.slots + for base_info in info.bases + ) + } + return bool(own_slots) + + +def _get_disjoint_base_of(instance: Instance) -> TypeInfo | None: + """Returns the disjoint base of the given instance, if it exists.""" + if _is_disjoint_base(instance.type): + return instance.type + for base in instance.type.mro: + if _is_disjoint_base(base): + return base + return None + + +def can_have_shared_disjoint_base(instances: list[Instance]) -> bool: + """Returns whether the given instances can share a disjoint base. + + This means that a child class of these classes can exist at runtime. + """ + # Ignore None disjoint bases (which are `object`). + disjoint_bases = [ + base for instance in instances if (base := _get_disjoint_base_of(instance)) is not None + ] + if not disjoint_bases: + # All are `object`. + return True + + candidate = disjoint_bases[0] + for base in disjoint_bases[1:]: + if candidate.has_base(base.fullname): + continue + elif base.has_base(candidate.fullname): + candidate = base + else: + return False + return True diff --git a/micromamba_root/Lib/site-packages/mypy/types.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/types.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..df9441387f88343653062427a235eb2c2e89d032 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/types.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/types.py b/micromamba_root/Lib/site-packages/mypy/types.py new file mode 100644 index 0000000000000000000000000000000000000000..d4ed728f4c9b8d003743dde0b1880232c28b2b8b --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/types.py @@ -0,0 +1,4452 @@ +"""Classes for representing mypy types.""" + +from __future__ import annotations + +import sys +from abc import abstractmethod +from collections.abc import Iterable, Sequence +from typing import ( + Any, + ClassVar, + Final, + NewType, + TypeAlias as _TypeAlias, + TypeGuard, + TypeVar, + cast, + overload, +) +from typing_extensions import Self + +from librt.internal import ( + read_int as read_int_bare, + read_str as read_str_bare, + write_int as write_int_bare, + write_str as write_str_bare, +) + +import mypy.nodes +from mypy.bogus_type import Bogus +from mypy.cache import ( + DICT_STR_GEN, + END_TAG, + EXTRA_ATTRS, + LIST_GEN, + LITERAL_NONE, + ReadBuffer, + Tag, + WriteBuffer, + read_bool, + read_int, + read_int_list, + read_literal, + read_str, + read_str_list, + read_str_opt, + read_str_opt_list, + read_tag, + write_bool, + write_int, + write_int_list, + write_literal, + write_str, + write_str_list, + write_str_opt, + write_str_opt_list, + write_tag, +) +from mypy.nodes import ARG_KINDS, ARG_POS, ARG_STAR, ARG_STAR2, INVARIANT, ArgKind, SymbolNode +from mypy.options import Options +from mypy.state import state +from mypy.util import IdMapper + +T = TypeVar("T") + +JsonDict: _TypeAlias = dict[str, Any] + +# The set of all valid expressions that can currently be contained +# inside of a Literal[...]. +# +# Literals can contain bytes and enum-values: we special-case both of these +# and store the value as a string. We rely on the fallback type that's also +# stored with the Literal to determine how a string is being used. +# +# TODO: confirm that we're happy with representing enums (and the +# other types) in the manner described above. +# +# Note: if we change the set of types included below, we must also +# make sure to audit the following methods: +# +# 1. types.LiteralType's serialize and deserialize methods: this method +# needs to make sure it can convert the below types into JSON and back. +# +# 2. types.LiteralType's 'value_repr` method: this method is ultimately used +# by TypeStrVisitor's visit_literal_type to generate a reasonable +# repr-able output. +# +# 3. server.astdiff.SnapshotTypeVisitor's visit_literal_type_method: this +# method assumes that the following types supports equality checks and +# hashability. +# +# Note: Although "Literal[None]" is a valid type, we internally always convert +# such a type directly into "None". So, "None" is not a valid parameter of +# LiteralType and is omitted from this list. +# +# Note: Float values are only used internally. They are not accepted within +# Literal[...]. +LiteralValue: _TypeAlias = int | str | bool | float + + +TUPLE_NAMES: Final = ("builtins.tuple", "typing.Tuple") +TYPE_NAMES: Final = ("builtins.type", "typing.Type") + +TYPE_VAR_LIKE_NAMES: Final = ( + "typing.TypeVar", + "typing_extensions.TypeVar", + "typing.ParamSpec", + "typing_extensions.ParamSpec", + "typing.TypeVarTuple", + "typing_extensions.TypeVarTuple", +) + +TYPED_NAMEDTUPLE_NAMES: Final = ("typing.NamedTuple", "typing_extensions.NamedTuple") + +# Supported names of TypedDict type constructors. +TPDICT_NAMES: Final = ( + "typing.TypedDict", + "typing_extensions.TypedDict", + "mypy_extensions.TypedDict", +) + +# Supported fallback instance type names for TypedDict types. +TPDICT_FB_NAMES: Final = ( + "typing._TypedDict", + "typing_extensions._TypedDict", + "mypy_extensions._TypedDict", +) + +# Supported names of Protocol base class. +PROTOCOL_NAMES: Final = ("typing.Protocol", "typing_extensions.Protocol") + +# Supported TypeAlias names. +TYPE_ALIAS_NAMES: Final = ("typing.TypeAlias", "typing_extensions.TypeAlias") + +# Supported Final type names. +FINAL_TYPE_NAMES: Final = ("typing.Final", "typing_extensions.Final") + +# Supported @final decorator names. +FINAL_DECORATOR_NAMES: Final = ("typing.final", "typing_extensions.final") + +# Supported @type_check_only names. +TYPE_CHECK_ONLY_NAMES: Final = ("typing.type_check_only", "typing_extensions.type_check_only") + +# Supported Literal type names. +LITERAL_TYPE_NAMES: Final = ("typing.Literal", "typing_extensions.Literal") + +# Supported Annotated type names. +ANNOTATED_TYPE_NAMES: Final = ("typing.Annotated", "typing_extensions.Annotated") + +# Supported Concatenate type names. +CONCATENATE_TYPE_NAMES: Final = ("typing.Concatenate", "typing_extensions.Concatenate") + +# Supported Unpack type names. +UNPACK_TYPE_NAMES: Final = ("typing.Unpack", "typing_extensions.Unpack") + +# Supported @deprecated decorator names +DEPRECATED_TYPE_NAMES: Final = ("warnings.deprecated", "typing_extensions.deprecated") + +# Supported @disjoint_base decorator names +DISJOINT_BASE_DECORATOR_NAMES: Final = ("typing.disjoint_base", "typing_extensions.disjoint_base") + +# We use this constant in various places when checking `tuple` subtyping: +TUPLE_LIKE_INSTANCE_NAMES: Final = ( + "builtins.tuple", + "typing.Iterable", + "typing.Container", + "typing.Sequence", + "typing.Reversible", +) + +IMPORTED_REVEAL_TYPE_NAMES: Final = ("typing.reveal_type", "typing_extensions.reveal_type") +REVEAL_TYPE_NAMES: Final = ("builtins.reveal_type", *IMPORTED_REVEAL_TYPE_NAMES) + +ASSERT_TYPE_NAMES: Final = ("typing.assert_type", "typing_extensions.assert_type") + +OVERLOAD_NAMES: Final = ("typing.overload", "typing_extensions.overload") + +NEVER_NAMES: Final = ( + "typing.NoReturn", + "typing_extensions.NoReturn", + "mypy_extensions.NoReturn", + "typing.Never", + "typing_extensions.Never", +) + +# Mypyc fixed-width native int types (compatible with builtins.int) +MYPYC_NATIVE_INT_NAMES: Final = ( + "mypy_extensions.i64", + "mypy_extensions.i32", + "mypy_extensions.i16", + "mypy_extensions.u8", +) + +DATACLASS_TRANSFORM_NAMES: Final = ( + "typing.dataclass_transform", + "typing_extensions.dataclass_transform", +) +# Supported @override decorator names. +OVERRIDE_DECORATOR_NAMES: Final = ("typing.override", "typing_extensions.override") + +ELLIPSIS_TYPE_NAMES: Final = ("builtins.ellipsis", "types.EllipsisType") + +NOT_IMPLEMENTED_TYPE_NAMES: Final = ("builtins._NotImplementedType", "types.NotImplementedType") + +# A placeholder used for Bogus[...] parameters +_dummy: Final[Any] = object() + +# A placeholder for int parameters +_dummy_int: Final = -999999 + + +class TypeOfAny: + """ + This class describes different types of Any. Each 'Any' can be of only one type at a time. + """ + + __slots__ = () + + # Was this Any type inferred without a type annotation? + unannotated: Final = 1 + # Does this Any come from an explicit type annotation? + explicit: Final = 2 + # Does this come from an unfollowed import? See --disallow-any-unimported option + from_unimported_type: Final = 3 + # Does this Any type come from omitted generics? + from_omitted_generics: Final = 4 + # Does this Any come from an error? + from_error: Final = 5 + # Is this a type that can't be represented in mypy's type system? For instance, type of + # call to NewType(...). Even though these types aren't real Anys, we treat them as such. + # Also used for variables named '_'. + special_form: Final = 6 + # Does this Any come from interaction with another Any? + from_another_any: Final = 7 + # Does this Any come from an implementation limitation/bug? + implementation_artifact: Final = 8 + # Does this Any come from use in the suggestion engine? This is + # used to ignore Anys inserted by the suggestion engine when + # generating constraints. + suggestion_engine: Final = 9 + + +def deserialize_type(data: JsonDict | str) -> Type: + if isinstance(data, str): + return Instance.deserialize(data) + classname = data[".class"] + method = deserialize_map.get(classname) + if method is not None: + return method(data) + raise NotImplementedError(f"unexpected .class {classname}") + + +class Type(mypy.nodes.Context): + """Abstract base class for all types.""" + + __slots__ = ("_can_be_true", "_can_be_false") + # 'can_be_true' and 'can_be_false' mean whether the value of the + # expression can be true or false in a boolean context. They are useful + # when inferring the type of logic expressions like `x and y`. + # + # For example: + # * the literal `False` can't be true while `True` can. + # * a value with type `bool` can be true or false. + # * `None` can't be true + # * ... + + def __init__(self, line: int = -1, column: int = -1) -> None: + super().__init__(line, column) + # Value of these can be -1 (use the default, lazy init), 0 (false) or 1 (true) + self._can_be_true = -1 + self._can_be_false = -1 + + @property + def can_be_true(self) -> bool: + if self._can_be_true == -1: # Lazy init helps mypyc + self._can_be_true = self.can_be_true_default() + return bool(self._can_be_true) + + @can_be_true.setter + def can_be_true(self, v: bool) -> None: + self._can_be_true = v + + @property + def can_be_false(self) -> bool: + if self._can_be_false == -1: # Lazy init helps mypyc + self._can_be_false = self.can_be_false_default() + return bool(self._can_be_false) + + @can_be_false.setter + def can_be_false(self, v: bool) -> None: + self._can_be_false = v + + def can_be_true_default(self) -> bool: + return True + + def can_be_false_default(self) -> bool: + return True + + def accept(self, visitor: TypeVisitor[T]) -> T: + raise RuntimeError("Not implemented", type(self)) + + def __repr__(self) -> str: + return self.accept(TypeStrVisitor(options=Options())) + + def str_with_options(self, options: Options) -> str: + return self.accept(TypeStrVisitor(options=options)) + + def serialize(self) -> JsonDict | str: + raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance") + + @classmethod + def deserialize(cls, data: JsonDict) -> Type: + raise NotImplementedError(f"Cannot deserialize {cls.__name__} instance") + + def write(self, data: WriteBuffer) -> None: + raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance") + + @classmethod + def read(cls, data: ReadBuffer) -> Type: + raise NotImplementedError(f"Cannot deserialize {cls.__name__} instance") + + +class TypeAliasType(Type): + """A type alias to another type. + + To support recursive type aliases we don't immediately expand a type alias + during semantic analysis, but create an instance of this type that records the target alias + definition node (mypy.nodes.TypeAlias) and type arguments (for generic aliases). + + This is very similar to how TypeInfo vs Instance interact, where a recursive class-based + structure like + class Node: + value: int + children: List[Node] + can be represented in a tree-like manner. + """ + + __slots__ = ("alias", "args", "type_ref") + + def __init__( + self, + alias: mypy.nodes.TypeAlias | None, + args: list[Type], + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(line, column) + self.alias = alias + self.args = args + self.type_ref: str | None = None + + def _expand_once(self) -> Type: + """Expand to the target type exactly once. + + This doesn't do full expansion, i.e. the result can contain another + (or even this same) type alias. Use this internal helper only when really needed, + its public wrapper mypy.types.get_proper_type() is preferred. + """ + assert self.alias is not None + if self.alias.no_args: + # We know that no_args=True aliases like L = List must have an instance + # as their target. + assert isinstance(self.alias.target, Instance) # type: ignore[misc] + return self.alias.target.copy_modified(args=self.args) + + # TODO: this logic duplicates the one in expand_type_by_instance(). + if self.alias.tvar_tuple_index is None: + mapping: dict[TypeVarId, Type] = { + v.id: s for (v, s) in zip(self.alias.alias_tvars, self.args) + } + else: + prefix = self.alias.tvar_tuple_index + suffix = len(self.alias.alias_tvars) - self.alias.tvar_tuple_index - 1 + start, middle, end = split_with_prefix_and_suffix(tuple(self.args), prefix, suffix) + tvar = self.alias.alias_tvars[prefix] + assert isinstance(tvar, TypeVarTupleType) + mapping = {tvar.id: TupleType(list(middle), tvar.tuple_fallback)} + for tvar, sub in zip( + self.alias.alias_tvars[:prefix] + self.alias.alias_tvars[prefix + 1 :], start + end + ): + mapping[tvar.id] = sub + + return self.alias.target.accept(InstantiateAliasVisitor(mapping)) + + @property + def is_recursive(self) -> bool: + """Whether this type alias is recursive. + + Note this doesn't check generic alias arguments, but only if this alias + *definition* is recursive. The property value thus can be cached on the + underlying TypeAlias node. If you want to include all nested types, use + has_recursive_types() function. + """ + assert self.alias is not None, "Unfixed type alias" + is_recursive = self.alias._is_recursive + if is_recursive is None: + is_recursive = self.alias in self.alias.target.accept(CollectAliasesVisitor()) + # We cache the value on the underlying TypeAlias node as an optimization, + # since the value is the same for all instances of the same alias. + self.alias._is_recursive = is_recursive + return is_recursive + + def can_be_true_default(self) -> bool: + if self.alias is not None: + return self.alias.target.can_be_true + return super().can_be_true_default() + + def can_be_false_default(self) -> bool: + if self.alias is not None: + return self.alias.target.can_be_false + return super().can_be_false_default() + + def copy_modified(self, *, args: list[Type] | None = None) -> TypeAliasType: + return TypeAliasType( + self.alias, args if args is not None else self.args.copy(), self.line, self.column + ) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_type_alias_type(self) + + def __hash__(self) -> int: + return hash((self.alias, tuple(self.args))) + + def __eq__(self, other: object) -> bool: + # Note: never use this to determine subtype relationships, use is_subtype(). + if not isinstance(other, TypeAliasType): + return NotImplemented + return self.alias == other.alias and self.args == other.args + + def serialize(self) -> JsonDict: + assert self.alias is not None + data: JsonDict = { + ".class": "TypeAliasType", + "type_ref": self.alias.fullname, + "args": [arg.serialize() for arg in self.args], + } + return data + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeAliasType: + assert data[".class"] == "TypeAliasType" + args: list[Type] = [] + if "args" in data: + args_list = data["args"] + assert isinstance(args_list, list) + args = [deserialize_type(arg) for arg in args_list] + alias = TypeAliasType(None, args) + alias.type_ref = data["type_ref"] + return alias + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_ALIAS_TYPE) + write_type_list(data, self.args) + assert self.alias is not None + write_str(data, self.alias.fullname) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeAliasType: + alias = TypeAliasType(None, read_type_list(data)) + alias.type_ref = read_str(data) + assert read_tag(data) == END_TAG + return alias + + +class TypeGuardedType(Type): + """Only used by find_isinstance_check() etc.""" + + __slots__ = ("type_guard",) + + def __init__(self, type_guard: Type) -> None: + super().__init__(line=type_guard.line, column=type_guard.column) + self.type_guard = type_guard + + def __repr__(self) -> str: + return f"TypeGuard({self.type_guard})" + + # This may hide some real bugs, but it is convenient for various "synthetic" + # visitors, similar to RequiredType and ReadOnlyType below. + def accept(self, visitor: TypeVisitor[T]) -> T: + return self.type_guard.accept(visitor) + + +class RequiredType(Type): + """Required[T] or NotRequired[T]. Only usable at top-level of a TypedDict definition.""" + + def __init__(self, item: Type, *, required: bool) -> None: + super().__init__(line=item.line, column=item.column) + self.item = item + self.required = required + + def __repr__(self) -> str: + if self.required: + return f"Required[{self.item}]" + else: + return f"NotRequired[{self.item}]" + + def accept(self, visitor: TypeVisitor[T]) -> T: + return self.item.accept(visitor) + + +class ReadOnlyType(Type): + """ReadOnly[T] Only usable at top-level of a TypedDict definition.""" + + def __init__(self, item: Type) -> None: + super().__init__(line=item.line, column=item.column) + self.item = item + + def __repr__(self) -> str: + return f"ReadOnly[{self.item}]" + + def accept(self, visitor: TypeVisitor[T]) -> T: + return self.item.accept(visitor) + + +class ProperType(Type): + """Not a type alias. + + Every type except TypeAliasType must inherit from this type. + """ + + __slots__ = () + + +class TypeVarId: + # A type variable is uniquely identified by its raw id and meta level. + + # For plain variables (type parameters of generic classes and + # functions) raw ids are allocated by semantic analysis, using + # positive ids 1, 2, ... for generic class parameters and negative + # ids -1, ... for generic function type arguments. A special value 0 + # is reserved for Self type variable (autogenerated). This convention + # is only used to keep type variable ids distinct when allocating + # them; the type checker makes no distinction between class and + # function type variables. + + # Metavariables are allocated unique ids starting from 1. + raw_id: Final[int] + + # Level of the variable in type inference. Currently either 0 for + # declared types, or 1 for type inference metavariables. + meta_level: int = 0 + + # Class variable used for allocating fresh ids for metavariables. + next_raw_id: ClassVar[int] = 1 + + # Fullname of class or function/method which declares this type + # variable (not the fullname of the TypeVar definition!), or '' + namespace: str + + def __init__(self, raw_id: int, meta_level: int = 0, *, namespace: str = "") -> None: + self.raw_id = raw_id + self.meta_level = meta_level + self.namespace = namespace + + @staticmethod + def new(meta_level: int) -> TypeVarId: + raw_id = TypeVarId.next_raw_id + TypeVarId.next_raw_id += 1 + return TypeVarId(raw_id, meta_level) + + def __repr__(self) -> str: + return self.raw_id.__repr__() + + def __eq__(self, other: object) -> bool: + # Although this call is not expensive (like UnionType or TypedDictType), + # most of the time we get the same object here, so add a fast path. + if self is other: + return True + return ( + isinstance(other, TypeVarId) + and self.raw_id == other.raw_id + and self.meta_level == other.meta_level + and self.namespace == other.namespace + ) + + def __ne__(self, other: object) -> bool: + return not (self == other) + + def __hash__(self) -> int: + return self.raw_id ^ (self.meta_level << 8) ^ hash(self.namespace) + + def is_meta_var(self) -> bool: + return self.meta_level > 0 + + def is_self(self) -> bool: + # This is a special value indicating typing.Self variable. + return self.raw_id == 0 + + +class TypeVarLikeType(ProperType): + __slots__ = ("name", "fullname", "id", "upper_bound", "default") + + name: str # Name (may be qualified) + fullname: str # Fully qualified name + id: TypeVarId + upper_bound: Type + default: Type + + def __init__( + self, + name: str, + fullname: str, + id: TypeVarId, + upper_bound: Type, + default: Type, + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(line, column) + self.name = name + self.fullname = fullname + self.id = id + self.upper_bound = upper_bound + self.default = default + + def serialize(self) -> JsonDict: + raise NotImplementedError + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeVarLikeType: + raise NotImplementedError + + def copy_modified(self, *, id: TypeVarId, **kwargs: Any) -> Self: + raise NotImplementedError + + @classmethod + def new_unification_variable(cls, old: Self) -> Self: + new_id = TypeVarId.new(meta_level=1) + return old.copy_modified(id=new_id) + + def has_default(self) -> bool: + t = get_proper_type(self.default) + return not (isinstance(t, AnyType) and t.type_of_any == TypeOfAny.from_omitted_generics) + + def values_or_bound(self) -> ProperType: + if isinstance(self, TypeVarType) and self.values: + return UnionType(self.values) + return get_proper_type(self.upper_bound) + + +class TypeVarType(TypeVarLikeType): + """Type that refers to a type variable.""" + + __slots__ = ("values", "variance") + + values: list[Type] # Value restriction, empty list if no restriction + variance: int + + def __init__( + self, + name: str, + fullname: str, + id: TypeVarId, + values: list[Type], + upper_bound: Type, + default: Type, + variance: int = INVARIANT, + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(name, fullname, id, upper_bound, default, line, column) + assert values is not None, "No restrictions must be represented by empty list" + self.values = values + self.variance = variance + + def copy_modified( + self, + *, + values: Bogus[list[Type]] = _dummy, + upper_bound: Bogus[Type] = _dummy, + default: Bogus[Type] = _dummy, + id: Bogus[TypeVarId] = _dummy, + line: int = _dummy_int, + column: int = _dummy_int, + **kwargs: Any, + ) -> TypeVarType: + return TypeVarType( + name=self.name, + fullname=self.fullname, + id=self.id if id is _dummy else id, + values=self.values if values is _dummy else values, + upper_bound=self.upper_bound if upper_bound is _dummy else upper_bound, + default=self.default if default is _dummy else default, + variance=self.variance, + line=self.line if line == _dummy_int else line, + column=self.column if column == _dummy_int else column, + ) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_type_var(self) + + def __hash__(self) -> int: + return hash((self.id, self.upper_bound, tuple(self.values))) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TypeVarType): + return NotImplemented + return ( + self.id == other.id + and self.upper_bound == other.upper_bound + and self.values == other.values + ) + + def serialize(self) -> JsonDict: + assert not self.id.is_meta_var() + return { + ".class": "TypeVarType", + "name": self.name, + "fullname": self.fullname, + "id": self.id.raw_id, + "namespace": self.id.namespace, + "values": [v.serialize() for v in self.values], + "upper_bound": self.upper_bound.serialize(), + "default": self.default.serialize(), + "variance": self.variance, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeVarType: + assert data[".class"] == "TypeVarType" + return TypeVarType( + name=data["name"], + fullname=data["fullname"], + id=TypeVarId(data["id"], namespace=data["namespace"]), + values=[deserialize_type(v) for v in data["values"]], + upper_bound=deserialize_type(data["upper_bound"]), + default=deserialize_type(data["default"]), + variance=data["variance"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_VAR_TYPE) + write_str(data, self.name) + write_str(data, self.fullname) + write_int(data, self.id.raw_id) + write_str(data, self.id.namespace) + write_type_list(data, self.values) + self.upper_bound.write(data) + self.default.write(data) + write_int(data, self.variance) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeVarType: + ret = TypeVarType( + read_str(data), + read_str(data), + TypeVarId(read_int(data), namespace=read_str(data)), + read_type_list(data), + read_type(data), + read_type(data), + read_int(data), + ) + assert read_tag(data) == END_TAG + return ret + + +class ParamSpecFlavor: + # Simple ParamSpec reference such as "P" + BARE: Final = 0 + # P.args + ARGS: Final = 1 + # P.kwargs + KWARGS: Final = 2 + + +class ParamSpecType(TypeVarLikeType): + """Type that refers to a ParamSpec. + + A ParamSpec is a type variable that represents the parameter + types, names and kinds of a callable (i.e., the signature without + the return type). + + This can be one of these forms + * P (ParamSpecFlavor.BARE) + * P.args (ParamSpecFlavor.ARGS) + * P.kwargs (ParamSpecFLavor.KWARGS) + + The upper_bound is really used as a fallback type -- it's shared + with TypeVarType for simplicity. It can't be specified by the user + and the value is directly derived from the flavor (currently + always just 'object'). + """ + + __slots__ = ("flavor", "prefix") + + flavor: int + prefix: Parameters + + def __init__( + self, + name: str, + fullname: str, + id: TypeVarId, + flavor: int, + upper_bound: Type, + default: Type, + *, + line: int = -1, + column: int = -1, + prefix: Parameters | None = None, + ) -> None: + super().__init__(name, fullname, id, upper_bound, default, line=line, column=column) + self.flavor = flavor + self.prefix = prefix or Parameters([], [], []) + + def with_flavor(self, flavor: int) -> ParamSpecType: + return ParamSpecType( + self.name, + self.fullname, + self.id, + flavor, + upper_bound=self.upper_bound, + default=self.default, + prefix=self.prefix, + ) + + def copy_modified( + self, + *, + id: Bogus[TypeVarId] = _dummy, + flavor: int = _dummy_int, + prefix: Bogus[Parameters] = _dummy, + default: Bogus[Type] = _dummy, + **kwargs: Any, + ) -> ParamSpecType: + return ParamSpecType( + self.name, + self.fullname, + id if id is not _dummy else self.id, + flavor if flavor != _dummy_int else self.flavor, + self.upper_bound, + default=default if default is not _dummy else self.default, + line=self.line, + column=self.column, + prefix=prefix if prefix is not _dummy else self.prefix, + ) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_param_spec(self) + + def name_with_suffix(self) -> str: + n = self.name + if self.flavor == ParamSpecFlavor.ARGS: + return f"{n}.args" + elif self.flavor == ParamSpecFlavor.KWARGS: + return f"{n}.kwargs" + return n + + def __hash__(self) -> int: + return hash((self.id, self.flavor, self.prefix)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ParamSpecType): + return NotImplemented + # Upper bound can be ignored, since it's determined by flavor. + return self.id == other.id and self.flavor == other.flavor and self.prefix == other.prefix + + def serialize(self) -> JsonDict: + assert not self.id.is_meta_var() + return { + ".class": "ParamSpecType", + "name": self.name, + "fullname": self.fullname, + "id": self.id.raw_id, + "namespace": self.id.namespace, + "flavor": self.flavor, + "upper_bound": self.upper_bound.serialize(), + "default": self.default.serialize(), + "prefix": self.prefix.serialize(), + } + + @classmethod + def deserialize(cls, data: JsonDict) -> ParamSpecType: + assert data[".class"] == "ParamSpecType" + return ParamSpecType( + data["name"], + data["fullname"], + TypeVarId(data["id"], namespace=data["namespace"]), + data["flavor"], + deserialize_type(data["upper_bound"]), + deserialize_type(data["default"]), + prefix=Parameters.deserialize(data["prefix"]), + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, PARAM_SPEC_TYPE) + self.prefix.write(data) + write_str(data, self.name) + write_str(data, self.fullname) + write_int(data, self.id.raw_id) + write_str(data, self.id.namespace) + write_int(data, self.flavor) + self.upper_bound.write(data) + self.default.write(data) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> ParamSpecType: + assert read_tag(data) == PARAMETERS + prefix = Parameters.read(data) + ret = ParamSpecType( + read_str(data), + read_str(data), + TypeVarId(read_int(data), namespace=read_str(data)), + read_int(data), + read_type(data), + read_type(data), + prefix=prefix, + ) + assert read_tag(data) == END_TAG + return ret + + +class TypeVarTupleType(TypeVarLikeType): + """Type that refers to a TypeVarTuple. + + See PEP646 for more information. + """ + + __slots__ = ("tuple_fallback", "min_len") + + def __init__( + self, + name: str, + fullname: str, + id: TypeVarId, + upper_bound: Type, + tuple_fallback: Instance, + default: Type, + *, + line: int = -1, + column: int = -1, + min_len: int = 0, + ) -> None: + super().__init__(name, fullname, id, upper_bound, default, line=line, column=column) + self.tuple_fallback = tuple_fallback + # This value is not settable by a user. It is an internal-only thing to support + # len()-narrowing of variadic tuples. + self.min_len = min_len + + def serialize(self) -> JsonDict: + assert not self.id.is_meta_var() + return { + ".class": "TypeVarTupleType", + "name": self.name, + "fullname": self.fullname, + "id": self.id.raw_id, + "namespace": self.id.namespace, + "upper_bound": self.upper_bound.serialize(), + "tuple_fallback": self.tuple_fallback.serialize(), + "default": self.default.serialize(), + "min_len": self.min_len, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> TypeVarTupleType: + assert data[".class"] == "TypeVarTupleType" + return TypeVarTupleType( + data["name"], + data["fullname"], + TypeVarId(data["id"], namespace=data["namespace"]), + deserialize_type(data["upper_bound"]), + Instance.deserialize(data["tuple_fallback"]), + deserialize_type(data["default"]), + min_len=data["min_len"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_VAR_TUPLE_TYPE) + self.tuple_fallback.write(data) + write_str(data, self.name) + write_str(data, self.fullname) + write_int(data, self.id.raw_id) + write_str(data, self.id.namespace) + self.upper_bound.write(data) + self.default.write(data) + write_int(data, self.min_len) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypeVarTupleType: + assert read_tag(data) == INSTANCE + fallback = Instance.read(data) + ret = TypeVarTupleType( + read_str(data), + read_str(data), + TypeVarId(read_int(data), namespace=read_str(data)), + read_type(data), + fallback, + read_type(data), + min_len=read_int(data), + ) + assert read_tag(data) == END_TAG + return ret + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_type_var_tuple(self) + + def __hash__(self) -> int: + return hash((self.id, self.min_len)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TypeVarTupleType): + return NotImplemented + return self.id == other.id and self.min_len == other.min_len + + def copy_modified( + self, + *, + id: Bogus[TypeVarId] = _dummy, + upper_bound: Bogus[Type] = _dummy, + default: Bogus[Type] = _dummy, + min_len: Bogus[int] = _dummy, + **kwargs: Any, + ) -> TypeVarTupleType: + return TypeVarTupleType( + self.name, + self.fullname, + self.id if id is _dummy else id, + self.upper_bound if upper_bound is _dummy else upper_bound, + self.tuple_fallback, + self.default if default is _dummy else default, + line=self.line, + column=self.column, + min_len=self.min_len if min_len is _dummy else min_len, + ) + + +class UnboundType(ProperType): + """Instance type that has not been bound during semantic analysis.""" + + __slots__ = ( + "name", + "args", + "optional", + "empty_tuple_index", + "original_str_expr", + "original_str_fallback", + ) + + def __init__( + self, + name: str, + args: Sequence[Type] | None = None, + *, + line: int = -1, + column: int = -1, + optional: bool = False, + empty_tuple_index: bool = False, + original_str_expr: str | None = None, + original_str_fallback: str | None = None, + ) -> None: + super().__init__(line, column) + if not args: + args = [] + self.name = name + self.args = tuple(args) + # Should this type be wrapped in an Optional? + self.optional = optional + # Special case for X[()] + self.empty_tuple_index = empty_tuple_index + # If this UnboundType was originally defined as a str or bytes, keep track of + # the original contents of that string-like thing. This way, if this UnboundExpr + # ever shows up inside of a LiteralType, we can determine whether that + # Literal[...] is valid or not. E.g. Literal[foo] is most likely invalid + # (unless 'foo' is an alias for another literal or something) and + # Literal["foo"] most likely is. + # + # We keep track of the entire string instead of just using a boolean flag + # so we can distinguish between things like Literal["foo"] vs + # Literal[" foo "]. + # + # We also keep track of what the original base fallback type was supposed to be + # so we don't have to try and recompute it later + self.original_str_expr = original_str_expr + self.original_str_fallback = original_str_fallback + + def copy_modified(self, args: Bogus[Sequence[Type] | None] = _dummy) -> UnboundType: + if args is _dummy: + args = self.args + return UnboundType( + name=self.name, + args=args, + line=self.line, + column=self.column, + optional=self.optional, + empty_tuple_index=self.empty_tuple_index, + original_str_expr=self.original_str_expr, + original_str_fallback=self.original_str_fallback, + ) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_unbound_type(self) + + def __hash__(self) -> int: + return hash((self.name, self.optional, tuple(self.args), self.original_str_expr)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UnboundType): + return NotImplemented + return ( + self.name == other.name + and self.optional == other.optional + and self.args == other.args + and self.original_str_expr == other.original_str_expr + and self.original_str_fallback == other.original_str_fallback + ) + + def serialize(self) -> JsonDict: + return { + ".class": "UnboundType", + "name": self.name, + "args": [a.serialize() for a in self.args], + "expr": self.original_str_expr, + "expr_fallback": self.original_str_fallback, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> UnboundType: + assert data[".class"] == "UnboundType" + return UnboundType( + data["name"], + [deserialize_type(a) for a in data["args"]], + original_str_expr=data["expr"], + original_str_fallback=data["expr_fallback"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, UNBOUND_TYPE) + write_str(data, self.name) + write_type_list(data, self.args) + write_str_opt(data, self.original_str_expr) + write_str_opt(data, self.original_str_fallback) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> UnboundType: + ret = UnboundType( + read_str(data), + read_type_list(data), + original_str_expr=read_str_opt(data), + original_str_fallback=read_str_opt(data), + ) + assert read_tag(data) == END_TAG + return ret + + +class CallableArgument(ProperType): + """Represents a Arg(type, 'name') inside a Callable's type list. + + Note that this is a synthetic type for helping parse ASTs, not a real type. + """ + + __slots__ = ("typ", "name", "constructor") + + typ: Type + name: str | None + constructor: str | None + + def __init__( + self, + typ: Type, + name: str | None, + constructor: str | None, + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(line, column) + self.typ = typ + self.name = name + self.constructor = constructor + + def accept(self, visitor: TypeVisitor[T]) -> T: + assert isinstance(visitor, SyntheticTypeVisitor) + ret: T = visitor.visit_callable_argument(self) + return ret + + def serialize(self) -> JsonDict: + assert False, "Synthetic types don't serialize" + + +class TypeList(ProperType): + """Information about argument types and names [...]. + + This is used for the arguments of a Callable type, i.e. for + [arg, ...] in Callable[[arg, ...], ret]. This is not a real type + but a syntactic AST construct. UnboundTypes can also have TypeList + types before they are processed into Callable types. + """ + + __slots__ = ("items",) + + items: list[Type] + + def __init__(self, items: list[Type], line: int = -1, column: int = -1) -> None: + super().__init__(line, column) + self.items = items + + def accept(self, visitor: TypeVisitor[T]) -> T: + assert isinstance(visitor, SyntheticTypeVisitor) + ret: T = visitor.visit_type_list(self) + return ret + + def serialize(self) -> JsonDict: + assert False, "Synthetic types don't serialize" + + def __hash__(self) -> int: + return hash(tuple(self.items)) + + def __eq__(self, other: object) -> bool: + return isinstance(other, TypeList) and self.items == other.items + + +class UnpackType(ProperType): + """Type operator Unpack from PEP646. Can be either with Unpack[] + or unpacking * syntax. + + The inner type should be either a TypeVarTuple, or a variable length tuple. + In an exceptional case of callable star argument it can be a fixed length tuple. + + Note: the above restrictions are only guaranteed by normalizations after semantic + analysis, if your code needs to handle UnpackType *during* semantic analysis, it is + wild west, technically anything can be present in the wrapped type. + """ + + __slots__ = ["type", "from_star_syntax"] + + def __init__( + self, typ: Type, line: int = -1, column: int = -1, from_star_syntax: bool = False + ) -> None: + super().__init__(line, column) + self.type = typ + self.from_star_syntax = from_star_syntax + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_unpack_type(self) + + def serialize(self) -> JsonDict: + return {".class": "UnpackType", "type": self.type.serialize()} + + def write(self, data: WriteBuffer) -> None: + write_tag(data, UNPACK_TYPE) + self.type.write(data) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> UnpackType: + ret = UnpackType(read_type(data)) + assert read_tag(data) == END_TAG + return ret + + @classmethod + def deserialize(cls, data: JsonDict) -> UnpackType: + assert data[".class"] == "UnpackType" + typ = data["type"] + return UnpackType(deserialize_type(typ)) + + def __hash__(self) -> int: + return hash(self.type) + + def __eq__(self, other: object) -> bool: + return isinstance(other, UnpackType) and self.type == other.type + + +class AnyType(ProperType): + """The type 'Any'.""" + + __slots__ = ("type_of_any", "source_any", "missing_import_name") + + def __init__( + self, + type_of_any: int, + source_any: AnyType | None = None, + missing_import_name: str | None = None, + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(line, column) + self.type_of_any = type_of_any + # If this Any was created as a result of interacting with another 'Any', record the source + # and use it in reports. + self.source_any = source_any + if source_any and source_any.source_any: + self.source_any = source_any.source_any + + if source_any is None: + self.missing_import_name = missing_import_name + else: + self.missing_import_name = source_any.missing_import_name + + # Only unimported type anys and anys from other anys should have an import name + assert missing_import_name is None or type_of_any in ( + TypeOfAny.from_unimported_type, + TypeOfAny.from_another_any, + ) + # Only Anys that come from another Any can have source_any. + assert type_of_any != TypeOfAny.from_another_any or source_any is not None + # We should not have chains of Anys. + assert not self.source_any or self.source_any.type_of_any != TypeOfAny.from_another_any + + @property + def is_from_error(self) -> bool: + return self.type_of_any == TypeOfAny.from_error + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_any(self) + + def copy_modified( + self, + # Mark with Bogus because _dummy is just an object (with type Any) + type_of_any: int = _dummy_int, + original_any: Bogus[AnyType | None] = _dummy, + missing_import_name: Bogus[str | None] = _dummy, + ) -> AnyType: + if type_of_any == _dummy_int: + type_of_any = self.type_of_any + if original_any is _dummy: + original_any = self.source_any + if missing_import_name is _dummy: + missing_import_name = self.missing_import_name + return AnyType( + type_of_any=type_of_any, + source_any=original_any, + missing_import_name=missing_import_name, + line=self.line, + column=self.column, + ) + + def __hash__(self) -> int: + return hash(AnyType) + + def __eq__(self, other: object) -> bool: + return isinstance(other, AnyType) + + def serialize(self) -> JsonDict: + return { + ".class": "AnyType", + "type_of_any": self.type_of_any, + "source_any": self.source_any.serialize() if self.source_any is not None else None, + "missing_import_name": self.missing_import_name, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> AnyType: + assert data[".class"] == "AnyType" + source = data["source_any"] + return AnyType( + data["type_of_any"], + AnyType.deserialize(source) if source is not None else None, + data["missing_import_name"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, ANY_TYPE) + write_type_opt(data, self.source_any) + write_int(data, self.type_of_any) + write_str_opt(data, self.missing_import_name) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> AnyType: + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == ANY_TYPE + source_any = AnyType.read(data) + else: + source_any = None + ret = AnyType(read_int(data), source_any, read_str_opt(data)) + assert read_tag(data) == END_TAG + return ret + + +class UninhabitedType(ProperType): + """This type has no members. + + This type is the bottom type. + With strict Optional checking, it is the only common subtype between all + other types, which allows `meet` to be well defined. Without strict + Optional checking, NoneType fills this role. + + In general, for any type T: + join(UninhabitedType, T) = T + meet(UninhabitedType, T) = UninhabitedType + is_subtype(UninhabitedType, T) = True + """ + + __slots__ = ("ambiguous",) + + ambiguous: bool # Is this a result of inference for a variable without constraints? + + def __init__(self, line: int = -1, column: int = -1) -> None: + super().__init__(line, column) + self.ambiguous = False + + def can_be_true_default(self) -> bool: + return False + + def can_be_false_default(self) -> bool: + return False + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_uninhabited_type(self) + + def __hash__(self) -> int: + return hash((UninhabitedType, self.ambiguous)) + + def __eq__(self, other: object) -> bool: + return isinstance(other, UninhabitedType) and other.ambiguous == self.ambiguous + + def serialize(self) -> JsonDict: + return {".class": "UninhabitedType"} + + @classmethod + def deserialize(cls, data: JsonDict) -> UninhabitedType: + assert data[".class"] == "UninhabitedType" + return UninhabitedType() + + def write(self, data: WriteBuffer) -> None: + write_tag(data, UNINHABITED_TYPE) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> UninhabitedType: + assert read_tag(data) == END_TAG + return UninhabitedType() + + +class NoneType(ProperType): + """The type of 'None'. + + This type can be written by users as 'None'. + """ + + __slots__ = () + + def __init__(self, line: int = -1, column: int = -1) -> None: + super().__init__(line, column) + + def can_be_true_default(self) -> bool: + return False + + def __hash__(self) -> int: + return hash(NoneType) + + def __eq__(self, other: object) -> bool: + return isinstance(other, NoneType) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_none_type(self) + + def serialize(self) -> JsonDict: + return {".class": "NoneType"} + + @classmethod + def deserialize(cls, data: JsonDict) -> NoneType: + assert data[".class"] == "NoneType" + return NoneType() + + def write(self, data: WriteBuffer) -> None: + write_tag(data, NONE_TYPE) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> NoneType: + assert read_tag(data) == END_TAG + return NoneType() + + +# NoneType used to be called NoneTyp so to avoid needlessly breaking +# external plugins we keep that alias here. +NoneTyp = NoneType + + +class ErasedType(ProperType): + """Placeholder for an erased type. + + This is used during type inference. This has the special property that + it is ignored during type inference. + """ + + __slots__ = () + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_erased_type(self) + + +class DeletedType(ProperType): + """Type of deleted variables. + + These can be used as lvalues but not rvalues. + """ + + __slots__ = ("source",) + + source: str | None # May be None; name that generated this value + + def __init__(self, source: str | None = None, line: int = -1, column: int = -1) -> None: + super().__init__(line, column) + self.source = source + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_deleted_type(self) + + def serialize(self) -> JsonDict: + return {".class": "DeletedType", "source": self.source} + + @classmethod + def deserialize(cls, data: JsonDict) -> DeletedType: + assert data[".class"] == "DeletedType" + return DeletedType(data["source"]) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, DELETED_TYPE) + write_str_opt(data, self.source) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> DeletedType: + ret = DeletedType(read_str_opt(data)) + assert read_tag(data) == END_TAG + return ret + + +# Fake TypeInfo to be used as a placeholder during Instance de-serialization. +NOT_READY: Final = mypy.nodes.FakeInfo("De-serialization failure: TypeInfo not fixed") + + +class ExtraAttrs: + """Summary of module attributes and types. + + This is used for instances of types.ModuleType, because they can have different + attributes per instance, and for type narrowing with hasattr() checks. + """ + + def __init__( + self, + attrs: dict[str, Type], + immutable: set[str] | None = None, + mod_name: str | None = None, + ) -> None: + self.attrs = attrs + if immutable is None: + immutable = set() + self.immutable = immutable + self.mod_name = mod_name + + def __hash__(self) -> int: + return hash((tuple(self.attrs.items()), tuple(sorted(self.immutable)))) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ExtraAttrs): + return NotImplemented + return self.attrs == other.attrs and self.immutable == other.immutable + + def copy(self) -> ExtraAttrs: + return ExtraAttrs(self.attrs.copy(), self.immutable.copy(), self.mod_name) + + def __repr__(self) -> str: + return f"ExtraAttrs({self.attrs!r}, {self.immutable!r}, {self.mod_name!r})" + + def serialize(self) -> JsonDict: + return { + ".class": "ExtraAttrs", + "attrs": {k: v.serialize() for k, v in self.attrs.items()}, + "immutable": sorted(self.immutable), + "mod_name": self.mod_name, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> ExtraAttrs: + assert data[".class"] == "ExtraAttrs" + return ExtraAttrs( + {k: deserialize_type(v) for k, v in data["attrs"].items()}, + set(data["immutable"]), + data["mod_name"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, EXTRA_ATTRS) + write_type_map(data, self.attrs) + write_str_list(data, sorted(self.immutable)) + write_str_opt(data, self.mod_name) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> ExtraAttrs: + ret = ExtraAttrs(read_type_map(data), set(read_str_list(data)), read_str_opt(data)) + assert read_tag(data) == END_TAG + return ret + + +class Instance(ProperType): + """An instance type of form C[T1, ..., Tn]. + + The list of type variables may be empty. + + Several types have fallbacks to `Instance`, because in Python everything is an object + and this concept is impossible to express without intersection types. We therefore use + fallbacks for all "non-special" (like UninhabitedType, ErasedType etc) types. + """ + + __slots__ = ("type", "args", "invalid", "type_ref", "last_known_value", "_hash", "extra_attrs") + + def __init__( + self, + typ: mypy.nodes.TypeInfo, + args: Sequence[Type], + line: int = -1, + column: int = -1, + *, + last_known_value: LiteralType | None = None, + extra_attrs: ExtraAttrs | None = None, + ) -> None: + super().__init__(line, column) + self.type = typ + self.args = tuple(args) + self.type_ref: str | None = None + + # This field keeps track of the underlying Literal[...] value associated with + # this instance, if one is known. + # + # This field is set whenever possible within expressions, but is erased upon + # variable assignment (see erasetype.remove_instance_last_known_values) unless + # the variable is declared to be final. + # + # For example, consider the following program: + # + # a = 1 + # b: Final[int] = 2 + # c: Final = 3 + # print(a + b + c + 4) + # + # The 'Instance' objects associated with the expressions '1', '2', '3', and '4' will + # have last_known_values of type Literal[1], Literal[2], Literal[3], and Literal[4] + # respectively. However, the Instance object assigned to 'a' and 'b' will have their + # last_known_value erased: variable 'a' is mutable; variable 'b' was declared to be + # specifically an int. + # + # Or more broadly, this field lets this Instance "remember" its original declaration + # when applicable. We want this behavior because we want implicit Final declarations + # to act pretty much identically with constants: we should be able to replace any + # places where we use some Final variable with the original value and get the same + # type-checking behavior. For example, we want this program: + # + # def expects_literal(x: Literal[3]) -> None: pass + # var: Final = 3 + # expects_literal(var) + # + # ...to type-check in the exact same way as if we had written the program like this: + # + # def expects_literal(x: Literal[3]) -> None: pass + # expects_literal(3) + # + # In order to make this work (especially with literal types), we need var's type + # (an Instance) to remember the "original" value. + # + # Preserving this value within expressions is useful for similar reasons. + # + # Currently most of mypy will ignore this field and will continue to treat this type like + # a regular Instance. We end up using this field only when we are explicitly within a + # Literal context. + self.last_known_value = last_known_value + + # Cached hash value + self._hash = -1 + + # Additional attributes defined per instance of this type. For example modules + # have different attributes per instance of types.ModuleType. + self.extra_attrs = extra_attrs + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_instance(self) + + def __hash__(self) -> int: + if self._hash == -1: + self._hash = hash((self.type, self.args, self.last_known_value, self.extra_attrs)) + return self._hash + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Instance): + return NotImplemented + return ( + self.type == other.type + and self.args == other.args + and self.last_known_value == other.last_known_value + and self.extra_attrs == other.extra_attrs + ) + + def serialize(self) -> JsonDict | str: + assert self.type is not None + type_ref = self.type.fullname + if not self.args and not self.last_known_value and not self.extra_attrs: + return type_ref + data: JsonDict = { + ".class": "Instance", + "type_ref": type_ref, + "args": [arg.serialize() for arg in self.args], + } + if self.last_known_value is not None: + data["last_known_value"] = self.last_known_value.serialize() + data["extra_attrs"] = self.extra_attrs.serialize() if self.extra_attrs else None + return data + + @classmethod + def deserialize(cls, data: JsonDict | str) -> Instance: + if isinstance(data, str): + inst = Instance(NOT_READY, []) + inst.type_ref = data + return inst + assert data[".class"] == "Instance" + args: list[Type] = [] + if "args" in data: + args_list = data["args"] + assert isinstance(args_list, list) + args = [deserialize_type(arg) for arg in args_list] + inst = Instance(NOT_READY, args) + inst.type_ref = data["type_ref"] # Will be fixed up by fixup.py later. + if "last_known_value" in data: + inst.last_known_value = LiteralType.deserialize(data["last_known_value"]) + if data.get("extra_attrs") is not None: + inst.extra_attrs = ExtraAttrs.deserialize(data["extra_attrs"]) + return inst + + def write(self, data: WriteBuffer) -> None: + write_tag(data, INSTANCE) + if not self.args and not self.last_known_value and not self.extra_attrs: + type_ref = self.type.fullname + if type_ref == "builtins.str": + write_tag(data, INSTANCE_STR) + elif type_ref == "builtins.function": + write_tag(data, INSTANCE_FUNCTION) + elif type_ref == "builtins.int": + write_tag(data, INSTANCE_INT) + elif type_ref == "builtins.bool": + write_tag(data, INSTANCE_BOOL) + elif type_ref == "builtins.object": + write_tag(data, INSTANCE_OBJECT) + else: + write_tag(data, INSTANCE_SIMPLE) + write_str_bare(data, type_ref) + return + write_tag(data, INSTANCE_GENERIC) + write_str(data, self.type.fullname) + write_type_list(data, self.args) + write_type_opt(data, self.last_known_value) + if self.extra_attrs is None: + write_tag(data, LITERAL_NONE) + else: + self.extra_attrs.write(data) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> Instance: + tag = read_tag(data) + # This is quite verbose, but this is very hot code, so we are not + # using dictionary lookups here. + if tag == INSTANCE_STR: + if instance_cache.str_type is None: + instance_cache.str_type = Instance(NOT_READY, []) + instance_cache.str_type.type_ref = "builtins.str" + return instance_cache.str_type + if tag == INSTANCE_FUNCTION: + if instance_cache.function_type is None: + instance_cache.function_type = Instance(NOT_READY, []) + instance_cache.function_type.type_ref = "builtins.function" + return instance_cache.function_type + if tag == INSTANCE_INT: + if instance_cache.int_type is None: + instance_cache.int_type = Instance(NOT_READY, []) + instance_cache.int_type.type_ref = "builtins.int" + return instance_cache.int_type + if tag == INSTANCE_BOOL: + if instance_cache.bool_type is None: + instance_cache.bool_type = Instance(NOT_READY, []) + instance_cache.bool_type.type_ref = "builtins.bool" + return instance_cache.bool_type + if tag == INSTANCE_OBJECT: + if instance_cache.object_type is None: + instance_cache.object_type = Instance(NOT_READY, []) + instance_cache.object_type.type_ref = "builtins.object" + return instance_cache.object_type + if tag == INSTANCE_SIMPLE: + inst = Instance(NOT_READY, []) + inst.type_ref = read_str_bare(data) + return inst + assert tag == INSTANCE_GENERIC + type_ref = read_str(data) + inst = Instance(NOT_READY, read_type_list(data)) + inst.type_ref = type_ref + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == LITERAL_TYPE + inst.last_known_value = LiteralType.read(data) + tag = read_tag(data) + if tag != LITERAL_NONE: + assert tag == EXTRA_ATTRS + inst.extra_attrs = ExtraAttrs.read(data) + assert read_tag(data) == END_TAG + return inst + + def copy_modified( + self, + *, + args: Bogus[list[Type]] = _dummy, + last_known_value: Bogus[LiteralType | None] = _dummy, + ) -> Instance: + new = Instance( + typ=self.type, + args=args if args is not _dummy else self.args, + line=self.line, + column=self.column, + last_known_value=( + last_known_value if last_known_value is not _dummy else self.last_known_value + ), + extra_attrs=self.extra_attrs, + ) + new.can_be_true = self.can_be_true + new.can_be_false = self.can_be_false + return new + + def copy_with_extra_attr(self, name: str, typ: Type) -> Instance: + if self.extra_attrs: + existing_attrs = self.extra_attrs.copy() + else: + existing_attrs = ExtraAttrs({}, set(), None) + existing_attrs.attrs[name] = typ + new = self.copy_modified() + new.extra_attrs = existing_attrs + return new + + +class InstanceCache: + def __init__(self) -> None: + self.str_type: Instance | None = None + self.function_type: Instance | None = None + self.int_type: Instance | None = None + self.bool_type: Instance | None = None + self.object_type: Instance | None = None + + def reset(self) -> None: + self.str_type = None + self.function_type = None + self.int_type = None + self.bool_type = None + self.object_type = None + + +instance_cache: Final = InstanceCache() + + +class FunctionLike(ProperType): + """Abstract base class for function types.""" + + __slots__ = ("fallback",) + + fallback: Instance + + def __init__(self, line: int = -1, column: int = -1) -> None: + super().__init__(line, column) + self._can_be_false = False + + @abstractmethod + def is_type_obj(self) -> bool: + pass + + @abstractmethod + def type_object(self) -> mypy.nodes.TypeInfo: + pass + + @property + @abstractmethod + def items(self) -> list[CallableType]: + pass + + @abstractmethod + def with_name(self, name: str) -> FunctionLike: + pass + + @abstractmethod + def get_name(self) -> str | None: + pass + + def bound(self) -> bool: + return bool(self.items) and self.items[0].is_bound + + +class FormalArgument: + def __init__(self, name: str | None, pos: int | None, typ: Type, required: bool) -> None: + self.name = name + self.pos = pos + self.typ = typ + self.required = required + + def __eq__(self, other: object) -> bool: + if not isinstance(other, FormalArgument): + return NotImplemented + return ( + self.name == other.name + and self.pos == other.pos + and self.typ == other.typ + and self.required == other.required + ) + + def __hash__(self) -> int: + return hash((self.name, self.pos, self.typ, self.required)) + + +class Parameters(ProperType): + """Type that represents the parameters to a function. + + Used for ParamSpec analysis. Note that by convention we handle this + type as a Callable without return type, not as a "tuple with names", + so that it behaves contravariantly, in particular [x: int] <: [int]. + """ + + __slots__ = ( + "arg_types", + "arg_kinds", + "arg_names", + "min_args", + "is_ellipsis_args", + # TODO: variables don't really belong here, but they are used to allow hacky support + # for forall . Foo[[x: T], T] by capturing generic callable with ParamSpec, see #15909 + "variables", + "imprecise_arg_kinds", + ) + + def __init__( + self, + arg_types: Sequence[Type], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None], + *, + variables: Sequence[TypeVarLikeType] | None = None, + is_ellipsis_args: bool = False, + imprecise_arg_kinds: bool = False, + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(line, column) + self.arg_types = list(arg_types) + self.arg_kinds = arg_kinds + self.arg_names = list(arg_names) + assert len(arg_types) == len(arg_kinds) == len(arg_names) + assert not any(isinstance(t, Parameters) for t in arg_types) + self.min_args = arg_kinds.count(ARG_POS) + self.is_ellipsis_args = is_ellipsis_args + self.variables = variables or [] + self.imprecise_arg_kinds = imprecise_arg_kinds + + def copy_modified( + self, + arg_types: Bogus[Sequence[Type]] = _dummy, + arg_kinds: Bogus[list[ArgKind]] = _dummy, + arg_names: Bogus[Sequence[str | None]] = _dummy, + *, + variables: Bogus[Sequence[TypeVarLikeType]] = _dummy, + is_ellipsis_args: Bogus[bool] = _dummy, + imprecise_arg_kinds: Bogus[bool] = _dummy, + ) -> Parameters: + return Parameters( + arg_types=arg_types if arg_types is not _dummy else self.arg_types, + arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds, + arg_names=arg_names if arg_names is not _dummy else self.arg_names, + is_ellipsis_args=( + is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args + ), + variables=variables if variables is not _dummy else self.variables, + imprecise_arg_kinds=( + imprecise_arg_kinds + if imprecise_arg_kinds is not _dummy + else self.imprecise_arg_kinds + ), + ) + + # TODO: here is a lot of code duplication with Callable type, fix this. + def var_arg(self) -> FormalArgument | None: + """The formal argument for *args.""" + for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)): + if kind == ARG_STAR: + return FormalArgument(None, position, type, False) + return None + + def kw_arg(self) -> FormalArgument | None: + """The formal argument for **kwargs.""" + for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)): + if kind == ARG_STAR2: + return FormalArgument(None, position, type, False) + return None + + def formal_arguments(self, include_star_args: bool = False) -> list[FormalArgument]: + """Yields the formal arguments corresponding to this callable, ignoring *arg and **kwargs. + + To handle *args and **kwargs, use the 'callable.var_args' and 'callable.kw_args' fields, + if they are not None. + + If you really want to include star args in the yielded output, set the + 'include_star_args' parameter to 'True'.""" + args = [] + done_with_positional = False + for i in range(len(self.arg_types)): + kind = self.arg_kinds[i] + if kind.is_named() or kind.is_star(): + done_with_positional = True + if not include_star_args and kind.is_star(): + continue + + required = kind.is_required() + pos = None if done_with_positional else i + arg = FormalArgument(self.arg_names[i], pos, self.arg_types[i], required) + args.append(arg) + return args + + def argument_by_name(self, name: str | None) -> FormalArgument | None: + if name is None: + return None + seen_star = False + for i, (arg_name, kind, typ) in enumerate( + zip(self.arg_names, self.arg_kinds, self.arg_types) + ): + # No more positional arguments after these. + if kind.is_named() or kind.is_star(): + seen_star = True + if kind.is_star(): + continue + if arg_name == name: + position = None if seen_star else i + return FormalArgument(name, position, typ, kind.is_required()) + return self.try_synthesizing_arg_from_kwarg(name) + + def argument_by_position(self, position: int | None) -> FormalArgument | None: + if position is None: + return None + if position >= len(self.arg_names): + return self.try_synthesizing_arg_from_vararg(position) + name, kind, typ = ( + self.arg_names[position], + self.arg_kinds[position], + self.arg_types[position], + ) + if kind.is_positional(): + return FormalArgument(name, position, typ, kind == ARG_POS) + else: + return self.try_synthesizing_arg_from_vararg(position) + + def try_synthesizing_arg_from_kwarg(self, name: str | None) -> FormalArgument | None: + kw_arg = self.kw_arg() + if kw_arg is not None: + return FormalArgument(name, None, kw_arg.typ, False) + else: + return None + + def try_synthesizing_arg_from_vararg(self, position: int | None) -> FormalArgument | None: + var_arg = self.var_arg() + if var_arg is not None: + return FormalArgument(None, position, var_arg.typ, False) + else: + return None + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_parameters(self) + + def serialize(self) -> JsonDict: + return { + ".class": "Parameters", + "arg_types": [t.serialize() for t in self.arg_types], + "arg_kinds": [int(x.value) for x in self.arg_kinds], + "arg_names": self.arg_names, + "variables": [tv.serialize() for tv in self.variables], + "imprecise_arg_kinds": self.imprecise_arg_kinds, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> Parameters: + assert data[".class"] == "Parameters" + return Parameters( + [deserialize_type(t) for t in data["arg_types"]], + # This is a micro-optimization until mypyc gets dedicated enum support. Otherwise, + # we would spend ~20% of types deserialization time in Enum.__call__(). + [ARG_KINDS[x] for x in data["arg_kinds"]], + data["arg_names"], + variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data["variables"]], + imprecise_arg_kinds=data["imprecise_arg_kinds"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, PARAMETERS) + write_type_list(data, self.arg_types) + write_int_list(data, [int(x.value) for x in self.arg_kinds]) + write_str_opt_list(data, self.arg_names) + write_type_list(data, self.variables) + write_bool(data, self.imprecise_arg_kinds) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> Parameters: + ret = Parameters( + read_type_list(data), + # This is a micro-optimization until mypyc gets dedicated enum support. Otherwise, + # we would spend ~20% of types deserialization time in Enum.__call__(). + [ARG_KINDS[ak] for ak in read_int_list(data)], + read_str_opt_list(data), + variables=read_type_var_likes(data), + imprecise_arg_kinds=read_bool(data), + ) + assert read_tag(data) == END_TAG + return ret + + def __hash__(self) -> int: + return hash( + ( + self.is_ellipsis_args, + tuple(self.arg_types), + tuple(self.arg_names), + tuple(self.arg_kinds), + ) + ) + + def __eq__(self, other: object) -> bool: + if isinstance(other, Parameters): + return ( + self.arg_types == other.arg_types + and self.arg_names == other.arg_names + and self.arg_kinds == other.arg_kinds + and self.is_ellipsis_args == other.is_ellipsis_args + ) + else: + return NotImplemented + + +CT = TypeVar("CT", bound="CallableType") + + +class CallableType(FunctionLike): + """Type of a non-overloaded callable object (such as function).""" + + __slots__ = ( + "arg_types", # Types of function arguments + "arg_kinds", # ARG_ constants + "arg_names", # Argument names; None if not a keyword argument + "min_args", # Minimum number of arguments; derived from arg_kinds + "ret_type", # Return value type + "name", # Name (may be None; for error messages and plugins) + "definition", # For error messages. May be None. + "variables", # Type variables for a generic function + "is_ellipsis_args", # Is this Callable[..., t] (with literal '...')? + "implicit", # Was this type implicitly generated instead of explicitly + # specified by the user? + "special_sig", # Non-None for signatures that require special handling + # (currently only values are 'dict' for a signature similar to + # 'dict' and 'partial' for a `functools.partial` evaluation) + "from_type_type", # Was this callable generated by analyzing Type[...] + # instantiation? + "is_bound", # Is this a bound method? + "type_guard", # T, if -> TypeGuard[T] (ret_type is bool in this case). + "type_is", # T, if -> TypeIs[T] (ret_type is bool in this case). + "from_concatenate", # whether this callable is from a concatenate object + # (this is used for error messages) + "imprecise_arg_kinds", + "unpack_kwargs", # Was an Unpack[...] with **kwargs used to define this callable? + ) + + def __init__( + self, + # maybe this should be refactored to take a Parameters object + arg_types: Sequence[Type], + arg_kinds: list[ArgKind], + arg_names: Sequence[str | None], + ret_type: Type, + fallback: Instance, + name: str | None = None, + definition: SymbolNode | None = None, + variables: Sequence[TypeVarLikeType] | None = None, + line: int = -1, + column: int = -1, + is_ellipsis_args: bool = False, + implicit: bool = False, + special_sig: str | None = None, + from_type_type: bool = False, + is_bound: bool = False, + type_guard: Type | None = None, + type_is: Type | None = None, + from_concatenate: bool = False, + imprecise_arg_kinds: bool = False, + unpack_kwargs: bool = False, + ) -> None: + super().__init__(line, column) + assert len(arg_types) == len(arg_kinds) == len(arg_names) + self.arg_types = list(arg_types) + for t in self.arg_types: + if isinstance(t, ParamSpecType): + assert not t.prefix.arg_types + # TODO: should we assert that only ARG_STAR contain ParamSpecType? + # See testParamSpecJoin, that relies on passing e.g `P.args` as plain argument. + self.arg_kinds = arg_kinds + self.arg_names = list(arg_names) + self.min_args = arg_kinds.count(ARG_POS) + self.ret_type = ret_type + self.fallback = fallback + assert not name or " CT: + modified = CallableType( + arg_types=arg_types if arg_types is not _dummy else self.arg_types, + arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds, + arg_names=arg_names if arg_names is not _dummy else self.arg_names, + ret_type=ret_type if ret_type is not _dummy else self.ret_type, + fallback=fallback if fallback is not _dummy else self.fallback, + name=name if name is not _dummy else self.name, + definition=definition if definition is not _dummy else self.definition, + variables=variables if variables is not _dummy else self.variables, + line=line if line != _dummy_int else self.line, + column=column if column != _dummy_int else self.column, + is_ellipsis_args=( + is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args + ), + implicit=implicit if implicit is not _dummy else self.implicit, + special_sig=special_sig if special_sig is not _dummy else self.special_sig, + from_type_type=from_type_type if from_type_type is not _dummy else self.from_type_type, + is_bound=is_bound if is_bound is not _dummy else self.is_bound, + type_guard=type_guard if type_guard is not _dummy else self.type_guard, + type_is=type_is if type_is is not _dummy else self.type_is, + from_concatenate=( + from_concatenate if from_concatenate is not _dummy else self.from_concatenate + ), + imprecise_arg_kinds=( + imprecise_arg_kinds + if imprecise_arg_kinds is not _dummy + else self.imprecise_arg_kinds + ), + unpack_kwargs=unpack_kwargs if unpack_kwargs is not _dummy else self.unpack_kwargs, + ) + # Optimization: Only NewTypes are supported as subtypes since + # the class is effectively final, so we can use a cast safely. + return cast(CT, modified) + + def var_arg(self) -> FormalArgument | None: + """The formal argument for *args.""" + for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)): + if kind == ARG_STAR: + return FormalArgument(None, position, type, False) + return None + + def kw_arg(self) -> FormalArgument | None: + """The formal argument for **kwargs.""" + for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)): + if kind == ARG_STAR2: + return FormalArgument(None, position, type, False) + return None + + @property + def is_var_arg(self) -> bool: + """Does this callable have a *args argument?""" + return ARG_STAR in self.arg_kinds + + @property + def is_kw_arg(self) -> bool: + """Does this callable have a **kwargs argument?""" + return ARG_STAR2 in self.arg_kinds + + def is_type_obj(self) -> bool: + return self.fallback.type.is_metaclass() and not isinstance( + get_proper_type(self.ret_type), UninhabitedType + ) + + def type_object(self) -> mypy.nodes.TypeInfo: + assert self.is_type_obj() + ret = get_proper_type(self.ret_type) + if isinstance(ret, TypeVarType): + ret = get_proper_type(ret.upper_bound) + if isinstance(ret, TupleType): + ret = ret.partial_fallback + if isinstance(ret, TypedDictType): + ret = ret.fallback + if isinstance(ret, LiteralType): + ret = ret.fallback + assert isinstance(ret, Instance) + return ret.type + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_callable_type(self) + + def with_name(self, name: str) -> CallableType: + """Return a copy of this type with the specified name.""" + return self.copy_modified(ret_type=self.ret_type, name=name) + + def get_name(self) -> str | None: + return self.name + + def max_possible_positional_args(self) -> int: + """Returns maximum number of positional arguments this method could possibly accept. + + This takes into account *arg and **kwargs but excludes keyword-only args.""" + if self.is_var_arg or self.is_kw_arg: + return sys.maxsize + return sum(kind.is_positional() for kind in self.arg_kinds) + + def formal_arguments(self, include_star_args: bool = False) -> list[FormalArgument]: + """Return a list of the formal arguments of this callable, ignoring *arg and **kwargs. + + To handle *args and **kwargs, use the 'callable.var_args' and 'callable.kw_args' fields, + if they are not None. + + If you really want to include star args in the yielded output, set the + 'include_star_args' parameter to 'True'.""" + args = [] + done_with_positional = False + for i in range(len(self.arg_types)): + kind = self.arg_kinds[i] + if kind.is_named() or kind.is_star(): + done_with_positional = True + if not include_star_args and kind.is_star(): + continue + + required = kind.is_required() + pos = None if done_with_positional else i + arg = FormalArgument(self.arg_names[i], pos, self.arg_types[i], required) + args.append(arg) + return args + + def argument_by_name(self, name: str | None) -> FormalArgument | None: + if name is None: + return None + seen_star = False + for i, (arg_name, kind, typ) in enumerate( + zip(self.arg_names, self.arg_kinds, self.arg_types) + ): + # No more positional arguments after these. + if kind.is_named() or kind.is_star(): + seen_star = True + if kind.is_star(): + continue + if arg_name == name: + position = None if seen_star else i + return FormalArgument(name, position, typ, kind.is_required()) + return self.try_synthesizing_arg_from_kwarg(name) + + def argument_by_position(self, position: int | None) -> FormalArgument | None: + if position is None: + return None + if position >= len(self.arg_names): + return self.try_synthesizing_arg_from_vararg(position) + name, kind, typ = ( + self.arg_names[position], + self.arg_kinds[position], + self.arg_types[position], + ) + if kind.is_positional(): + return FormalArgument(name, position, typ, kind == ARG_POS) + else: + return self.try_synthesizing_arg_from_vararg(position) + + def try_synthesizing_arg_from_kwarg(self, name: str | None) -> FormalArgument | None: + kw_arg = self.kw_arg() + if kw_arg is not None: + return FormalArgument(name, None, kw_arg.typ, False) + else: + return None + + def try_synthesizing_arg_from_vararg(self, position: int | None) -> FormalArgument | None: + var_arg = self.var_arg() + if var_arg is not None: + return FormalArgument(None, position, var_arg.typ, False) + else: + return None + + @property + def items(self) -> list[CallableType]: + return [self] + + def is_generic(self) -> bool: + return bool(self.variables) + + def type_var_ids(self) -> list[TypeVarId]: + a: list[TypeVarId] = [] + for tv in self.variables: + a.append(tv.id) + return a + + def param_spec(self) -> ParamSpecType | None: + """Return ParamSpec if callable can be called with one. + + A Callable accepting ParamSpec P args (*args, **kwargs) must have the + two final parameters like this: *args: P.args, **kwargs: P.kwargs. + """ + if len(self.arg_types) < 2: + return None + if self.arg_kinds[-2] != ARG_STAR or self.arg_kinds[-1] != ARG_STAR2: + return None + arg_type = self.arg_types[-2] + if not isinstance(arg_type, ParamSpecType): + return None + + # Prepend prefix for def f(prefix..., *args: P.args, **kwargs: P.kwargs) -> ... + # TODO: confirm that all arg kinds are positional + prefix = Parameters(self.arg_types[:-2], self.arg_kinds[:-2], self.arg_names[:-2]) + return arg_type.copy_modified(flavor=ParamSpecFlavor.BARE, prefix=prefix) + + def normalize_trivial_unpack(self) -> None: + # Normalize trivial unpack in var args as *args: *tuple[X, ...] -> *args: X in place. + if self.is_var_arg: + star_index = self.arg_kinds.index(ARG_STAR) + star_type = self.arg_types[star_index] + if isinstance(star_type, UnpackType): + p_type = get_proper_type(star_type.type) + if isinstance(p_type, Instance): + assert p_type.type.fullname == "builtins.tuple" + self.arg_types[star_index] = p_type.args[0] + + def with_unpacked_kwargs(self) -> NormalizedCallableType: + if not self.unpack_kwargs: + return cast(NormalizedCallableType, self) + last_type = get_proper_type(self.arg_types[-1]) + assert isinstance(last_type, TypedDictType) + extra_kinds = [ + ArgKind.ARG_NAMED if name in last_type.required_keys else ArgKind.ARG_NAMED_OPT + for name in last_type.items + ] + new_arg_kinds = self.arg_kinds[:-1] + extra_kinds + new_arg_names = self.arg_names[:-1] + list(last_type.items) + new_arg_types = self.arg_types[:-1] + list(last_type.items.values()) + return NormalizedCallableType( + self.copy_modified( + arg_kinds=new_arg_kinds, + arg_names=new_arg_names, + arg_types=new_arg_types, + unpack_kwargs=False, + ) + ) + + def with_normalized_var_args(self) -> Self: + var_arg = self.var_arg() + if not var_arg or not isinstance(var_arg.typ, UnpackType): + return self + unpacked = get_proper_type(var_arg.typ.type) + if not isinstance(unpacked, TupleType): + # Note that we don't normalize *args: *tuple[X, ...] -> *args: X, + # this should be done once in semanal_typeargs.py for user-defined types, + # and we ourselves rarely construct such type. + return self + unpack_index = find_unpack_in_list(unpacked.items) + if unpack_index == 0 and len(unpacked.items) > 1: + # Already normalized. + return self + + # Boilerplate: + var_arg_index = self.arg_kinds.index(ARG_STAR) + types_prefix = self.arg_types[:var_arg_index] + kinds_prefix = self.arg_kinds[:var_arg_index] + names_prefix = self.arg_names[:var_arg_index] + types_suffix = self.arg_types[var_arg_index + 1 :] + kinds_suffix = self.arg_kinds[var_arg_index + 1 :] + names_suffix = self.arg_names[var_arg_index + 1 :] + no_name: str | None = None # to silence mypy + + # Now we have something non-trivial to do. + if unpack_index is None: + # Plain *Tuple[X, Y, Z] -> replace with ARG_POS completely + types_middle = unpacked.items + kinds_middle = [ARG_POS] * len(unpacked.items) + names_middle = [no_name] * len(unpacked.items) + else: + # *Tuple[X, *Ts, Y, Z] or *Tuple[X, *tuple[T, ...], X, Z], here + # we replace the prefix by ARG_POS (this is how some places expect + # Callables to be represented) + nested_unpack = unpacked.items[unpack_index] + assert isinstance(nested_unpack, UnpackType) + nested_unpacked = get_proper_type(nested_unpack.type) + if unpack_index == len(unpacked.items) - 1: + # Normalize also single item tuples like + # *args: *Tuple[*tuple[X, ...]] -> *args: X + # *args: *Tuple[*Ts] -> *args: *Ts + # This may be not strictly necessary, but these are very verbose. + if isinstance(nested_unpacked, Instance): + assert nested_unpacked.type.fullname == "builtins.tuple" + new_unpack = nested_unpacked.args[0] + else: + if not isinstance(nested_unpacked, TypeVarTupleType): + # We found a non-normalized tuple type, this means this method + # is called during semantic analysis (e.g. from get_proper_type()) + # there is no point in normalizing callables at this stage. + return self + new_unpack = nested_unpack + else: + new_unpack = UnpackType( + unpacked.copy_modified(items=unpacked.items[unpack_index:]) + ) + types_middle = unpacked.items[:unpack_index] + [new_unpack] + kinds_middle = [ARG_POS] * unpack_index + [ARG_STAR] + names_middle = [no_name] * unpack_index + [self.arg_names[var_arg_index]] + return self.copy_modified( + arg_types=types_prefix + types_middle + types_suffix, + arg_kinds=kinds_prefix + kinds_middle + kinds_suffix, + arg_names=names_prefix + names_middle + names_suffix, + ) + + def __hash__(self) -> int: + return hash( + ( + self.ret_type, + self.is_ellipsis_args, + self.name, + tuple(self.arg_types), + tuple(self.arg_names), + tuple(self.arg_kinds), + self.fallback, + ) + ) + + def __eq__(self, other: object) -> bool: + if isinstance(other, CallableType): + return ( + self.ret_type == other.ret_type + and self.arg_types == other.arg_types + and self.arg_names == other.arg_names + and self.arg_kinds == other.arg_kinds + and self.name == other.name + and self.is_ellipsis_args == other.is_ellipsis_args + and self.type_guard == other.type_guard + and self.type_is == other.type_is + and self.fallback == other.fallback + ) + else: + return NotImplemented + + def serialize(self) -> JsonDict: + # TODO: As an optimization, leave out everything related to + # generic functions for non-generic functions. + return { + ".class": "CallableType", + "arg_types": [t.serialize() for t in self.arg_types], + "arg_kinds": [int(x.value) for x in self.arg_kinds], + "arg_names": self.arg_names, + "ret_type": self.ret_type.serialize(), + "fallback": self.fallback.serialize(), + "name": self.name, + # We don't serialize the definition (only used for error messages). + "variables": [v.serialize() for v in self.variables], + "is_ellipsis_args": self.is_ellipsis_args, + "implicit": self.implicit, + "is_bound": self.is_bound, + "type_guard": self.type_guard.serialize() if self.type_guard is not None else None, + "type_is": (self.type_is.serialize() if self.type_is is not None else None), + "from_concatenate": self.from_concatenate, + "imprecise_arg_kinds": self.imprecise_arg_kinds, + "unpack_kwargs": self.unpack_kwargs, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> CallableType: + assert data[".class"] == "CallableType" + # The .definition link is set in fixup.py. + return CallableType( + [deserialize_type(t) for t in data["arg_types"]], + [ARG_KINDS[x] for x in data["arg_kinds"]], + data["arg_names"], + deserialize_type(data["ret_type"]), + Instance.deserialize(data["fallback"]), + name=data["name"], + variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data["variables"]], + is_ellipsis_args=data["is_ellipsis_args"], + implicit=data["implicit"], + is_bound=data["is_bound"], + type_guard=( + deserialize_type(data["type_guard"]) if data["type_guard"] is not None else None + ), + type_is=(deserialize_type(data["type_is"]) if data["type_is"] is not None else None), + from_concatenate=data["from_concatenate"], + imprecise_arg_kinds=data["imprecise_arg_kinds"], + unpack_kwargs=data["unpack_kwargs"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, CALLABLE_TYPE) + self.fallback.write(data) + write_type_list(data, self.arg_types) + write_int_list(data, [int(x.value) for x in self.arg_kinds]) + write_str_opt_list(data, self.arg_names) + self.ret_type.write(data) + write_str_opt(data, self.name) + write_type_list(data, self.variables) + write_bool(data, self.is_ellipsis_args) + write_bool(data, self.implicit) + write_bool(data, self.is_bound) + write_type_opt(data, self.type_guard) + write_type_opt(data, self.type_is) + write_bool(data, self.from_concatenate) + write_bool(data, self.imprecise_arg_kinds) + write_bool(data, self.unpack_kwargs) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> CallableType: + assert read_tag(data) == INSTANCE + fallback = Instance.read(data) + ret = CallableType( + read_type_list(data), + [ARG_KINDS[ak] for ak in read_int_list(data)], + read_str_opt_list(data), + read_type(data), + fallback, + name=read_str_opt(data), + variables=read_type_var_likes(data), + is_ellipsis_args=read_bool(data), + implicit=read_bool(data), + is_bound=read_bool(data), + type_guard=read_type_opt(data), + type_is=read_type_opt(data), + from_concatenate=read_bool(data), + imprecise_arg_kinds=read_bool(data), + unpack_kwargs=read_bool(data), + ) + assert read_tag(data) == END_TAG + return ret + + +# This is a little safety net to prevent reckless special-casing of callables +# that can potentially break Unpack[...] with **kwargs. +# TODO: use this in more places in checkexpr.py etc? +NormalizedCallableType = NewType("NormalizedCallableType", CallableType) + + +class Overloaded(FunctionLike): + """Overloaded function type T1, ... Tn, where each Ti is CallableType. + + The variant to call is chosen based on static argument + types. Overloaded function types can only be defined in stub + files, and thus there is no explicit runtime dispatch + implementation. + """ + + __slots__ = ("_items",) + + _items: list[CallableType] # Must not be empty + + def __init__(self, items: list[CallableType]) -> None: + super().__init__(items[0].line, items[0].column) + self._items = items + self.fallback = items[0].fallback + + @property + def items(self) -> list[CallableType]: + return self._items + + def name(self) -> str | None: + return self.get_name() + + def is_type_obj(self) -> bool: + # All the items must have the same type object status, so it's + # sufficient to query only (any) one of them. + return self._items[0].is_type_obj() + + def type_object(self) -> mypy.nodes.TypeInfo: + # All the items must have the same type object, so it's sufficient to + # query only (any) one of them. + return self._items[0].type_object() + + def with_name(self, name: str) -> Overloaded: + ni: list[CallableType] = [] + for it in self._items: + ni.append(it.with_name(name)) + return Overloaded(ni) + + def get_name(self) -> str | None: + return self._items[0].name + + def with_unpacked_kwargs(self) -> Overloaded: + if any(i.unpack_kwargs for i in self.items): + return Overloaded([i.with_unpacked_kwargs() for i in self.items]) + return self + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_overloaded(self) + + def __hash__(self) -> int: + return hash(tuple(self.items)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Overloaded): + return NotImplemented + return self.items == other.items + + def serialize(self) -> JsonDict: + return {".class": "Overloaded", "items": [t.serialize() for t in self.items]} + + @classmethod + def deserialize(cls, data: JsonDict) -> Overloaded: + assert data[".class"] == "Overloaded" + return Overloaded([CallableType.deserialize(t) for t in data["items"]]) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, OVERLOADED) + write_type_list(data, self.items) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> Overloaded: + items = [] + assert read_tag(data) == LIST_GEN + for _ in range(read_int_bare(data)): + assert read_tag(data) == CALLABLE_TYPE + items.append(CallableType.read(data)) + assert read_tag(data) == END_TAG + return Overloaded(items) + + +class TupleType(ProperType): + """The tuple type Tuple[T1, ..., Tn] (at least one type argument). + + Instance variables: + items: Tuple item types + partial_fallback: The (imprecise) underlying instance type that is used + for non-tuple methods. This is generally builtins.tuple[Any, ...] for + regular tuples, but it's different for named tuples and classes with + a tuple base class. Use mypy.typeops.tuple_fallback to calculate the + precise fallback type derived from item types. + implicit: If True, derived from a tuple expression (t,....) instead of Tuple[t, ...] + """ + + __slots__ = ("items", "partial_fallback", "implicit") + + items: list[Type] + partial_fallback: Instance + implicit: bool + + def __init__( + self, + items: list[Type], + fallback: Instance, + line: int = -1, + column: int = -1, + implicit: bool = False, + ) -> None: + super().__init__(line, column) + self.partial_fallback = fallback + self.items = items + self.implicit = implicit + + def can_be_true_default(self) -> bool: + if self.can_be_any_bool(): + # Corner case: it is a `NamedTuple` with `__bool__` method defined. + # It can be anything: both `True` and `False`. + return True + return self.length() > 0 + + def can_be_false_default(self) -> bool: + if self.can_be_any_bool(): + # Corner case: it is a `NamedTuple` with `__bool__` method defined. + # It can be anything: both `True` and `False`. + return True + if self.length() == 0: + return True + if self.length() > 1: + return False + # Special case tuple[*Ts] may or may not be false. + item = self.items[0] + if not isinstance(item, UnpackType): + return False + if not isinstance(item.type, TypeVarTupleType): + # Non-normalized tuple[int, ...] can be false. + return True + return item.type.min_len == 0 + + def can_be_any_bool(self) -> bool: + return bool( + self.partial_fallback.type + and self.partial_fallback.type.fullname != "builtins.tuple" + and self.partial_fallback.type.names.get("__bool__") + ) + + def length(self) -> int: + return len(self.items) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_tuple_type(self) + + def __hash__(self) -> int: + return hash((tuple(self.items), self.partial_fallback)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TupleType): + return NotImplemented + return self.items == other.items and self.partial_fallback == other.partial_fallback + + def serialize(self) -> JsonDict: + return { + ".class": "TupleType", + "items": [t.serialize() for t in self.items], + "partial_fallback": self.partial_fallback.serialize(), + "implicit": self.implicit, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> TupleType: + assert data[".class"] == "TupleType" + return TupleType( + [deserialize_type(t) for t in data["items"]], + Instance.deserialize(data["partial_fallback"]), + implicit=data["implicit"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TUPLE_TYPE) + self.partial_fallback.write(data) + write_type_list(data, self.items) + write_bool(data, self.implicit) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TupleType: + assert read_tag(data) == INSTANCE + fallback = Instance.read(data) + ret = TupleType(read_type_list(data), fallback, implicit=read_bool(data)) + assert read_tag(data) == END_TAG + return ret + + def copy_modified( + self, *, fallback: Instance | None = None, items: list[Type] | None = None + ) -> TupleType: + if fallback is None: + fallback = self.partial_fallback + if items is None: + items = self.items + return TupleType(items, fallback, self.line, self.column) + + def slice( + self, begin: int | None, end: int | None, stride: int | None, *, fallback: Instance | None + ) -> TupleType | None: + if fallback is None: + fallback = self.partial_fallback + + if stride == 0: + return None + + if any(isinstance(t, UnpackType) for t in self.items): + total = len(self.items) + unpack_index = find_unpack_in_list(self.items) + assert unpack_index is not None + if begin is None and end is None: + # We special-case this to support reversing variadic tuples. + # General support for slicing is tricky, so we handle only simple cases. + if stride == -1: + slice_items = self.items[::-1] + elif stride is None or stride == 1: + slice_items = self.items + else: + return None + elif (begin is None or unpack_index >= begin >= 0) and ( + end is not None and unpack_index >= end >= 0 + ): + # Start and end are in the prefix, everything works in this case. + slice_items = self.items[begin:end:stride] + elif (begin is not None and unpack_index - total < begin < 0) and ( + end is None or unpack_index - total < end < 0 + ): + # Start and end are in the suffix, everything works in this case. + slice_items = self.items[begin:end:stride] + elif (begin is None or unpack_index >= begin >= 0) and ( + end is None or unpack_index - total < end < 0 + ): + # Start in the prefix, end in the suffix, we can support only trivial strides. + if stride is None or stride == 1: + slice_items = self.items[begin:end:stride] + else: + return None + elif (begin is not None and unpack_index - total < begin < 0) and ( + end is not None and unpack_index >= end >= 0 + ): + # Start in the suffix, end in the prefix, we can support only trivial strides. + if stride is None or stride == -1: + slice_items = self.items[begin:end:stride] + else: + return None + else: + # TODO: there some additional cases we can support for homogeneous variadic + # items, we can "eat away" finite number of items. + return None + else: + slice_items = self.items[begin:end:stride] + return TupleType(slice_items, fallback, self.line, self.column, self.implicit) + + +class TypedDictType(ProperType): + """Type of TypedDict object {'k1': v1, ..., 'kn': vn}. + + A TypedDict object is a dictionary with specific string (literal) keys. Each + key has a value with a distinct type that depends on the key. TypedDict objects + are normal dict objects at runtime. + + A TypedDictType can be either named or anonymous. If it's anonymous, its + fallback will be typing_extensions._TypedDict (Instance). _TypedDict is a subclass + of Mapping[str, object] and defines all non-mapping dict methods that TypedDict + supports. Some dict methods are unsafe and not supported. _TypedDict isn't defined + at runtime. + + If a TypedDict is named, its fallback will be an Instance of the named type + (ex: "Point") whose TypeInfo has a typeddict_type that is anonymous. This + is similar to how named tuples work. + + TODO: The fallback structure is perhaps overly complicated. + """ + + __slots__ = ( + "items", + "required_keys", + "readonly_keys", + "fallback", + "extra_items_from", + "to_be_mutated", + ) + + items: dict[str, Type] # item_name -> item_type + required_keys: set[str] + readonly_keys: set[str] + fallback: Instance + + extra_items_from: list[ProperType] # only used during semantic analysis + to_be_mutated: bool # only used in a plugin for `.update`, `|=`, etc + + def __init__( + self, + items: dict[str, Type], + required_keys: set[str], + readonly_keys: set[str], + fallback: Instance, + line: int = -1, + column: int = -1, + ) -> None: + super().__init__(line, column) + self.items = items + self.required_keys = required_keys + self.readonly_keys = readonly_keys + self.fallback = fallback + self.can_be_true = len(self.items) > 0 + self.can_be_false = len(self.required_keys) == 0 + self.extra_items_from = [] + self.to_be_mutated = False + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_typeddict_type(self) + + def __hash__(self) -> int: + return hash( + ( + frozenset(self.items.items()), + self.fallback, + frozenset(self.required_keys), + frozenset(self.readonly_keys), + ) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TypedDictType): + return NotImplemented + if self is other: + return True + return ( + frozenset(self.items.keys()) == frozenset(other.items.keys()) + and all( + left_item_type == right_item_type + for (_, left_item_type, right_item_type) in self.zip(other) + ) + and self.fallback == other.fallback + and self.required_keys == other.required_keys + and self.readonly_keys == other.readonly_keys + ) + + def serialize(self) -> JsonDict: + return { + ".class": "TypedDictType", + "items": [[n, t.serialize()] for (n, t) in self.items.items()], + "required_keys": sorted(self.required_keys), + "readonly_keys": sorted(self.readonly_keys), + "fallback": self.fallback.serialize(), + } + + @classmethod + def deserialize(cls, data: JsonDict) -> TypedDictType: + assert data[".class"] == "TypedDictType" + return TypedDictType( + {n: deserialize_type(t) for (n, t) in data["items"]}, + set(data["required_keys"]), + set(data["readonly_keys"]), + Instance.deserialize(data["fallback"]), + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPED_DICT_TYPE) + self.fallback.write(data) + write_type_map(data, self.items) + write_str_list(data, sorted(self.required_keys)) + write_str_list(data, sorted(self.readonly_keys)) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> TypedDictType: + assert read_tag(data) == INSTANCE + fallback = Instance.read(data) + ret = TypedDictType( + read_type_map(data), set(read_str_list(data)), set(read_str_list(data)), fallback + ) + assert read_tag(data) == END_TAG + return ret + + @property + def is_final(self) -> bool: + return self.fallback.type.is_final + + def is_anonymous(self) -> bool: + return self.fallback.type.fullname in TPDICT_FB_NAMES + + def create_anonymous_fallback(self) -> Instance: + if self.is_anonymous(): + return self.fallback + assert self.fallback.type.typeddict_type is not None + return self.fallback.type.typeddict_type.create_anonymous_fallback() + + def copy_modified( + self, + *, + fallback: Instance | None = None, + item_types: list[Type] | None = None, + item_names: list[str] | None = None, + required_keys: set[str] | None = None, + readonly_keys: set[str] | None = None, + ) -> TypedDictType: + if fallback is None: + fallback = self.fallback + if item_types is None: + items = self.items + else: + items = dict(zip(self.items, item_types)) + if required_keys is None: + required_keys = self.required_keys + if readonly_keys is None: + readonly_keys = self.readonly_keys + if item_names is not None: + items = {k: v for (k, v) in items.items() if k in item_names} + required_keys &= set(item_names) + return TypedDictType(items, required_keys, readonly_keys, fallback, self.line, self.column) + + def names_are_wider_than(self, other: TypedDictType) -> bool: + return len(other.items.keys() - self.items.keys()) == 0 + + def zip(self, right: TypedDictType) -> Iterable[tuple[str, Type, Type]]: + left = self + for item_name, left_item_type in left.items.items(): + right_item_type = right.items.get(item_name) + if right_item_type is not None: + yield (item_name, left_item_type, right_item_type) + + def zipall(self, right: TypedDictType) -> Iterable[tuple[str, Type | None, Type | None]]: + left = self + for item_name, left_item_type in left.items.items(): + right_item_type = right.items.get(item_name) + yield (item_name, left_item_type, right_item_type) + for item_name, right_item_type in right.items.items(): + if item_name in left.items: + continue + yield (item_name, None, right_item_type) + + +class RawExpressionType(ProperType): + """A synthetic type representing some arbitrary expression that does not cleanly + translate into a type. + + This synthetic type is only used at the beginning stages of semantic analysis + and should be completely removing during the process for mapping UnboundTypes to + actual types: we either turn it into a LiteralType or an AnyType. + + For example, suppose `Foo[1]` is initially represented as the following: + + UnboundType( + name='Foo', + args=[ + RawExpressionType(value=1, base_type_name='builtins.int'), + ], + ) + + As we perform semantic analysis, this type will transform into one of two + possible forms. + + If 'Foo' was an alias for 'Literal' all along, this type is transformed into: + + LiteralType(value=1, fallback=int_instance_here) + + Alternatively, if 'Foo' is an unrelated class, we report an error and instead + produce something like this: + + Instance(type=typeinfo_for_foo, args=[AnyType(TypeOfAny.from_error)) + + If the "note" field is not None, the provided note will be reported alongside the + error at this point. + + Note: if "literal_value" is None, that means this object is representing some + expression that cannot possibly be a parameter of Literal[...]. For example, + "Foo[3j]" would be represented as: + + UnboundType( + name='Foo', + args=[ + RawExpressionType(value=None, base_type_name='builtins.complex'), + ], + ) + """ + + __slots__ = ("literal_value", "base_type_name", "note") + + def __init__( + self, + literal_value: LiteralValue | None, + base_type_name: str, + line: int = -1, + column: int = -1, + note: str | None = None, + ) -> None: + super().__init__(line, column) + self.literal_value = literal_value + self.base_type_name = base_type_name + self.note = note + + def simple_name(self) -> str: + return self.base_type_name.replace("builtins.", "") + + def accept(self, visitor: TypeVisitor[T]) -> T: + assert isinstance(visitor, SyntheticTypeVisitor) + ret: T = visitor.visit_raw_expression_type(self) + return ret + + def serialize(self) -> JsonDict: + assert False, "Synthetic types don't serialize" + + def __hash__(self) -> int: + return hash((self.literal_value, self.base_type_name)) + + def __eq__(self, other: object) -> bool: + if isinstance(other, RawExpressionType): + return ( + self.base_type_name == other.base_type_name + and self.literal_value == other.literal_value + ) + else: + return NotImplemented + + +class LiteralType(ProperType): + """The type of a Literal instance. Literal[Value] + + A Literal always consists of: + + 1. A native Python object corresponding to the contained inner value + 2. A fallback for this Literal. The fallback also corresponds to the + parent type this Literal subtypes. + + For example, 'Literal[42]' is represented as + 'LiteralType(value=42, fallback=instance_of_int)' + + As another example, `Literal[Color.RED]` (where Color is an enum) is + represented as `LiteralType(value="RED", fallback=instance_of_color)'. + """ + + __slots__ = ("value", "fallback", "_hash") + + def __init__( + self, value: LiteralValue, fallback: Instance, line: int = -1, column: int = -1 + ) -> None: + super().__init__(line, column) + self.value = value + self.fallback = fallback + + # NOTE: Enum types are always truthy by default, but this can be changed + # in subclasses, so we need to get the truthyness from the Enum + # type rather than base it on the value (which is a non-empty + # string for enums, so always truthy) + # TODO: We should consider moving this branch to the `can_be_true` + # `can_be_false` properties instead, so the truthyness only + # needs to be determined once per set of Enum literals. + # However, the same can be said for `TypeAliasType` in some + # cases and we only set the default based on the type it is + # aliasing. So if we decide to change this, we may want to + # change that as well. perf_compare output was inconclusive + # but slightly favored this version, probably because we have + # almost no test cases where we would redundantly compute + # `can_be_false`/`can_be_true`. + def can_be_false_default(self) -> bool: + if self.fallback.type.is_enum: + return self.fallback.can_be_false + return not self.value + + def can_be_true_default(self) -> bool: + if self.fallback.type.is_enum: + return self.fallback.can_be_true + return bool(self.value) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_literal_type(self) + + def __hash__(self) -> int: + # Intentionally a subset of __eq__ for perf + return hash(self.value) + + def __eq__(self, other: object) -> bool: + if isinstance(other, LiteralType): + return self.value == other.value and self.fallback == other.fallback + else: + return NotImplemented + + def is_enum_literal(self) -> bool: + return self.fallback.type.is_enum + + def value_repr(self) -> str: + """Returns the string representation of the underlying type. + + This function is almost equivalent to running `repr(self.value)`, + except it includes some additional logic to correctly handle cases + where the value is a string, byte string, a unicode string, or an enum. + """ + raw = repr(self.value) + fallback_name = self.fallback.type.fullname + + # If this is backed by an enum, + if self.is_enum_literal(): + return f"{fallback_name}.{self.value}" + + if fallback_name == "builtins.bytes": + # Note: 'builtins.bytes' only appears in Python 3, so we want to + # explicitly prefix with a "b" + return "b" + raw + else: + # 'builtins.str' could mean either depending on context, but either way + # we don't prefix: it's the "native" string. And of course, if value is + # some other type, we just return that string repr directly. + return raw + + def serialize(self) -> JsonDict | str: + return { + ".class": "LiteralType", + "value": self.value, + "fallback": self.fallback.serialize(), + } + + @classmethod + def deserialize(cls, data: JsonDict) -> LiteralType: + assert data[".class"] == "LiteralType" + return LiteralType(value=data["value"], fallback=Instance.deserialize(data["fallback"])) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, LITERAL_TYPE) + self.fallback.write(data) + write_literal(data, self.value) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> LiteralType: + assert read_tag(data) == INSTANCE + fallback = Instance.read(data) + tag = read_tag(data) + ret = LiteralType(read_literal(data, tag), fallback) + assert read_tag(data) == END_TAG + return ret + + +class UnionType(ProperType): + """The union type Union[T1, ..., Tn] (at least one type argument).""" + + __slots__ = ( + "items", + "is_evaluated", + "uses_pep604_syntax", + "original_str_expr", + "original_str_fallback", + ) + + def __init__( + self, + items: Sequence[Type], + line: int = -1, + column: int = -1, + *, + is_evaluated: bool = True, + uses_pep604_syntax: bool = False, + ) -> None: + super().__init__(line, column) + # We must keep this false to avoid crashes during semantic analysis. + # TODO: maybe switch this to True during type-checking pass? + self.items = flatten_nested_unions(items, handle_type_alias_type=False) + # is_evaluated should be set to false for type comments and string literals + self.is_evaluated = is_evaluated + # uses_pep604_syntax is True if Union uses OR syntax (X | Y) + self.uses_pep604_syntax = uses_pep604_syntax + # The meaning of these two is the same as for UnboundType. A UnionType can be + # return by type parser from a string "A|B", and we need to be able to fall back + # to plain string, when such a string appears inside a Literal[...]. + self.original_str_expr: str | None = None + self.original_str_fallback: str | None = None + + def can_be_true_default(self) -> bool: + return any(item.can_be_true for item in self.items) + + def can_be_false_default(self) -> bool: + return any(item.can_be_false for item in self.items) + + def __hash__(self) -> int: + return hash(frozenset(self.items)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UnionType): + return NotImplemented + if self is other: + return True + return frozenset(self.items) == frozenset(other.items) + + @overload + @staticmethod + def make_union( + items: Sequence[ProperType], line: int = -1, column: int = -1 + ) -> ProperType: ... + + @overload + @staticmethod + def make_union(items: Sequence[Type], line: int = -1, column: int = -1) -> Type: ... + + @staticmethod + def make_union(items: Sequence[Type], line: int = -1, column: int = -1) -> Type: + if len(items) > 1: + return UnionType(items, line, column) + elif len(items) == 1: + return items[0] + else: + return UninhabitedType() + + def length(self) -> int: + return len(self.items) + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_union_type(self) + + def relevant_items(self) -> list[Type]: + """Removes NoneTypes from Unions when strict Optional checking is off.""" + if state.strict_optional: + return self.items + else: + return [i for i in self.items if not isinstance(get_proper_type(i), NoneType)] + + def serialize(self) -> JsonDict: + return { + ".class": "UnionType", + "items": [t.serialize() for t in self.items], + "uses_pep604_syntax": self.uses_pep604_syntax, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> UnionType: + assert data[".class"] == "UnionType" + return UnionType( + [deserialize_type(t) for t in data["items"]], + uses_pep604_syntax=data["uses_pep604_syntax"], + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, UNION_TYPE) + write_type_list(data, self.items) + write_bool(data, self.uses_pep604_syntax) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> UnionType: + ret = UnionType(read_type_list(data), uses_pep604_syntax=read_bool(data)) + assert read_tag(data) == END_TAG + return ret + + +class PartialType(ProperType): + """Type such as List[?] where type arguments are unknown, or partial None type. + + These are used for inferring types in multiphase initialization such as this: + + x = [] # x gets a partial type List[?], as item type is unknown + x.append(1) # partial type gets replaced with normal type List[int] + + Or with None: + + x = None # x gets a partial type None + if c: + x = 1 # Infer actual type int for x + """ + + __slots__ = ("type", "var", "value_type") + + # None for the 'None' partial type; otherwise a generic class + type: mypy.nodes.TypeInfo | None + var: mypy.nodes.Var + # For partial defaultdict[K, V], the type V (K is unknown). If V is generic, + # the type argument is Any and will be replaced later. + value_type: Instance | None + + def __init__( + self, + type: mypy.nodes.TypeInfo | None, + var: mypy.nodes.Var, + value_type: Instance | None = None, + ) -> None: + super().__init__() + self.type = type + self.var = var + self.value_type = value_type + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_partial_type(self) + + +class EllipsisType(ProperType): + """The type ... (ellipsis). + + This is not a real type but a syntactic AST construct, used in Callable[..., T], for example. + + A semantically analyzed type will never have ellipsis types. + """ + + __slots__ = () + + def accept(self, visitor: TypeVisitor[T]) -> T: + assert isinstance(visitor, SyntheticTypeVisitor) + ret: T = visitor.visit_ellipsis_type(self) + return ret + + def serialize(self) -> JsonDict: + assert False, "Synthetic types don't serialize" + + +class TypeType(ProperType): + """For types like Type[User] or TypeForm[User | None]. + + Type[C] annotates variables that are class objects, constrained by + the type argument. See PEP 484 for more details. + + TypeForm[T] annotates variables that hold the result of evaluating + a type expression. See PEP 747 for more details. + + We may encounter expressions whose values are specific classes; + those are represented as callables (possibly overloaded) + corresponding to the class's constructor's signature and returning + an instance of that class. The difference with Type[C] is that + those callables always represent the exact class given as the + return type; Type[C] represents any class that's a subclass of C, + and C may also be a type variable or a union (or Any). + + Many questions around subtype relationships between Type[C1] and + def(...) -> C2 are answered by looking at the subtype + relationships between C1 and C2, since Type[] is considered + covariant. + + There's an unsolved problem with constructor signatures (also + unsolved in PEP 484): calling a variable whose type is Type[C] + assumes the constructor signature for C, even though a subclass of + C might completely change the constructor signature. For now we + just assume that users of Type[C] are careful not to do that (in + the future we might detect when they are violating that + assumption). + """ + + __slots__ = ("item", "is_type_form") + + # This can't be everything, but it can be a class reference, + # a generic class instance, a union, Any, a type variable... + item: ProperType + + # If True then this TypeType represents a TypeForm[T]. + # If False then this TypeType represents a Type[C]. + is_type_form: bool + + def __init__( + self, + item: Bogus[Instance | AnyType | TypeVarType | TupleType | NoneType | CallableType], + *, + line: int = -1, + column: int = -1, + is_type_form: bool = False, + ) -> None: + """To ensure Type[Union[A, B]] is always represented as Union[Type[A], Type[B]], item of + type UnionType must be handled through make_normalized static method. + """ + super().__init__(line, column) + self.item = item + self.is_type_form = is_type_form + + @staticmethod + def make_normalized( + item: Type, *, line: int = -1, column: int = -1, is_type_form: bool = False + ) -> ProperType: + item = get_proper_type(item) + if is_type_form: + # Don't convert TypeForm[X | Y] to (TypeForm[X] | TypeForm[Y]) + pass + else: + if isinstance(item, UnionType): + return UnionType.make_union( + [TypeType.make_normalized(union_item) for union_item in item.items], + line=line, + column=column, + ) + return TypeType(item, line=line, column=column, is_type_form=is_type_form) # type: ignore[arg-type] + + def accept(self, visitor: TypeVisitor[T]) -> T: + return visitor.visit_type_type(self) + + def __hash__(self) -> int: + return hash(self.item) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TypeType): + return NotImplemented + return self.item == other.item and self.is_type_form == other.is_type_form + + def serialize(self) -> JsonDict: + return { + ".class": "TypeType", + "item": self.item.serialize(), + "is_type_form": self.is_type_form, + } + + @classmethod + def deserialize(cls, data: JsonDict) -> Type: + assert data[".class"] == "TypeType" + return TypeType.make_normalized( + deserialize_type(data["item"]), is_type_form=data["is_type_form"] + ) + + def write(self, data: WriteBuffer) -> None: + write_tag(data, TYPE_TYPE) + self.item.write(data) + write_tag(data, END_TAG) + + @classmethod + def read(cls, data: ReadBuffer) -> Type: + ret = TypeType.make_normalized(read_type(data)) + assert read_tag(data) == END_TAG + return ret + + +class PlaceholderType(ProperType): + """Temporary, yet-unknown type during semantic analysis. + + This is needed when there's a reference to a type before the real symbol + table entry of the target type is available (specifically, we use a + temporary PlaceholderNode symbol node). Consider this example: + + class str(Sequence[str]): ... + + We use a PlaceholderType for the 'str' in 'Sequence[str]' since we can't create + a TypeInfo for 'str' until all base classes have been resolved. We'll soon + perform another analysis iteration which replaces the base class with a complete + type without any placeholders. After semantic analysis, no placeholder types must + exist. + """ + + __slots__ = ("fullname", "args") + + def __init__(self, fullname: str | None, args: list[Type], line: int) -> None: + super().__init__(line) + self.fullname = fullname # Must be a valid full name of an actual node (or None). + self.args = args + + def accept(self, visitor: TypeVisitor[T]) -> T: + assert isinstance(visitor, SyntheticTypeVisitor) + ret: T = visitor.visit_placeholder_type(self) + return ret + + def __hash__(self) -> int: + return hash((self.fullname, tuple(self.args))) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PlaceholderType): + return NotImplemented + return self.fullname == other.fullname and self.args == other.args + + def serialize(self) -> str: + # We should never get here since all placeholders should be replaced + # during semantic analysis. + assert False, f"Internal error: unresolved placeholder type {self.fullname}" + + +@overload +def get_proper_type(typ: None) -> None: ... + + +@overload +def get_proper_type(typ: Type) -> ProperType: ... + + +def get_proper_type(typ: Type | None) -> ProperType | None: + """Get the expansion of a type alias type. + + If the type is already a proper type, this is a no-op. Use this function + wherever a decision is made on a call like e.g. 'if isinstance(typ, UnionType): ...', + because 'typ' in this case may be an alias to union. Note: if after making the decision + on the isinstance() call you pass on the original type (and not one of its components) + it is recommended to *always* pass on the unexpanded alias. + """ + if typ is None: + return None + # TODO: this is an ugly hack, remove. + if isinstance(typ, TypeGuardedType): + typ = typ.type_guard + while isinstance(typ, TypeAliasType): + typ = typ._expand_once() + # TODO: store the name of original type alias on this type, so we can show it in errors. + return cast(ProperType, typ) + + +@overload +def get_proper_types(types: list[Type] | tuple[Type, ...]) -> list[ProperType]: ... + + +@overload +def get_proper_types( + types: list[Type | None] | tuple[Type | None, ...], +) -> list[ProperType | None]: ... + + +def get_proper_types( + types: list[Type] | list[Type | None] | tuple[Type | None, ...], +) -> list[ProperType] | list[ProperType | None]: + if isinstance(types, list): + typelist = types + # Optimize for the common case so that we don't need to allocate anything + if not any(isinstance(t, (TypeAliasType, TypeGuardedType)) for t in typelist): + return cast("list[ProperType]", typelist) + return [get_proper_type(t) for t in typelist] + else: + return [get_proper_type(t) for t in types] + + +# We split off the type visitor base classes to another module +# to make it easier to gradually get modules working with mypyc. +# Import them here, after the types are defined. +# This is intended as a re-export also. +from mypy.type_visitor import ( + ALL_STRATEGY as ALL_STRATEGY, + ANY_STRATEGY as ANY_STRATEGY, + BoolTypeQuery as BoolTypeQuery, + SyntheticTypeVisitor as SyntheticTypeVisitor, + TypeQuery as TypeQuery, + TypeTranslator as TypeTranslator, + TypeVisitor as TypeVisitor, +) + + +class TypeStrVisitor(SyntheticTypeVisitor[str]): + """Visitor for pretty-printing types into strings. + + This is mostly for debugging/testing. + + Do not preserve original formatting. + + Notes: + - Represent unbound types as Foo? or Foo?[...]. + - Represent the NoneType type as None. + - Represent Union[x, y] as x | y + """ + + def __init__(self, id_mapper: IdMapper | None = None, *, options: Options) -> None: + self.id_mapper = id_mapper + self.options = options + self.dotted_aliases: set[TypeAliasType] | None = None + + def visit_unbound_type(self, t: UnboundType, /) -> str: + s = t.name + "?" + if t.args: + s += f"[{self.list_str(t.args)}]" + return s + + def visit_type_list(self, t: TypeList, /) -> str: + return f"" + + def visit_callable_argument(self, t: CallableArgument, /) -> str: + typ = t.typ.accept(self) + if t.name is None: + return f"{t.constructor}({typ})" + else: + return f"{t.constructor}({typ}, {t.name})" + + def visit_any(self, t: AnyType, /) -> str: + return "Any" + + def visit_none_type(self, t: NoneType, /) -> str: + return "None" + + def visit_uninhabited_type(self, t: UninhabitedType, /) -> str: + return "Never" + + def visit_erased_type(self, t: ErasedType, /) -> str: + return "" + + def visit_deleted_type(self, t: DeletedType, /) -> str: + if t.source is None: + return "" + else: + return f"" + + def visit_instance(self, t: Instance, /) -> str: + fullname = t.type.fullname + if not self.options.reveal_verbose_types and fullname.startswith("builtins."): + fullname = t.type.name + if t.last_known_value and not t.args: + # Instances with a literal fallback should never be generic. If they are, + # something went wrong so we fall back to showing the full Instance repr. + s = f"{t.last_known_value.accept(self)}?" + + else: + s = fullname or t.type.name or "" + + if t.args: + if t.type.fullname == "builtins.tuple": + assert len(t.args) == 1 + s += f"[{self.list_str(t.args)}, ...]" + else: + s += f"[{self.list_str(t.args)}]" + elif t.type.has_type_var_tuple_type and len(t.type.type_vars) == 1: + s += "[()]" + if self.id_mapper: + s += f"<{self.id_mapper.id(t.type)}>" + return s + + def visit_type_var(self, t: TypeVarType, /) -> str: + if not self.options.reveal_verbose_types: + s = t.name + else: + s = f"{t.name}`{t.id}" + if self.id_mapper and t.upper_bound: + s += f"(upper_bound={t.upper_bound.accept(self)})" + if t.has_default() and self.options.reveal_verbose_types: + s += f" = {t.default.accept(self)}" + # TODO: disambiguate type variables with same name using namespace. + # We should reuse find_type_overlaps() and scoped_type_var_name(). + return s + + def visit_param_spec(self, t: ParamSpecType, /) -> str: + # prefixes are displayed as Concatenate + s = "" + if t.prefix.arg_types: + s += f"[{self.list_str(t.prefix.arg_types)}, **" + if not self.options.reveal_verbose_types: + s += t.name_with_suffix() + else: + s += f"{t.name_with_suffix()}`{t.id}" + if t.prefix.arg_types: + s += "]" + if t.has_default() and self.options.reveal_verbose_types: + s += f" = {t.default.accept(self)}" + return s + + def visit_parameters(self, t: Parameters, /) -> str: + # This is copied from visit_callable -- is there a way to decrease duplication? + if t.is_ellipsis_args: + return "..." + + s = "" + bare_asterisk = False + for i in range(len(t.arg_types)): + if s != "": + s += ", " + if t.arg_kinds[i].is_named() and not bare_asterisk: + s += "*, " + bare_asterisk = True + if t.arg_kinds[i] == ARG_STAR: + s += "*" + if t.arg_kinds[i] == ARG_STAR2: + s += "**" + name = t.arg_names[i] + if name: + s += f"{name}: " + r = t.arg_types[i].accept(self) + + s += r + + if t.arg_kinds[i].is_optional(): + s += " =" + + return f"[{s}]" + + def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> str: + if not self.options.reveal_verbose_types: + s = t.name + else: + s = f"{t.name}`{t.id}" + if t.has_default() and self.options.reveal_verbose_types: + s += f" = {t.default.accept(self)}" + return s + + def visit_callable_type(self, t: CallableType, /) -> str: + param_spec = t.param_spec() + if param_spec is not None: + num_skip = 2 + else: + num_skip = 0 + + s = "" + asterisk = False + for i in range(len(t.arg_types) - num_skip): + if s != "": + s += ", " + if t.arg_kinds[i].is_named() and not asterisk: + s += "*, " + asterisk = True + if t.arg_kinds[i] == ARG_STAR: + s += "*" + asterisk = True + if t.arg_kinds[i] == ARG_STAR2: + s += "**" + name = t.arg_names[i] + if not name and not self.options.reveal_verbose_types: + # Avoid ambiguous (and weird) formatting for anonymous args/kwargs. + if t.arg_kinds[i] == ARG_STAR and isinstance(t.arg_types[i], UnpackType): + name = "args" + elif t.arg_kinds[i] == ARG_STAR2 and t.unpack_kwargs: + name = "kwargs" + if name: + s += name + ": " + type_str = t.arg_types[i].accept(self) + if t.arg_kinds[i] == ARG_STAR2 and t.unpack_kwargs: + if not self.options.reveal_verbose_types: + type_str = f"**{type_str}" + else: + type_str = f"Unpack[{type_str}]" + s += type_str + if t.arg_kinds[i].is_optional(): + s += " =" + + if param_spec is not None: + n = param_spec.name + if s: + s += ", " + s += f"*{n}.args, **{n}.kwargs" + if param_spec.has_default(): + s += f" = {param_spec.default.accept(self)}" + + s = f"({s})" + + if not isinstance(get_proper_type(t.ret_type), NoneType): + if t.type_guard is not None: + s += f" -> TypeGuard[{t.type_guard.accept(self)}]" + elif t.type_is is not None: + s += f" -> TypeIs[{t.type_is.accept(self)}]" + else: + s += f" -> {t.ret_type.accept(self)}" + + if t.variables: + vs = [] + for var in t.variables: + if isinstance(var, TypeVarType): + if var.values: + vals = f"({', '.join(val.accept(self) for val in var.values)})" + vs.append(f"{var.name} in {vals}") + elif not is_named_instance(var.upper_bound, "builtins.object"): + vs.append( + f"{var.name} <: {var.upper_bound.accept(self)}{f' = {var.default.accept(self)}' if var.has_default() else ''}" + ) + else: + vs.append( + f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}" + ) + else: + # For other TypeVarLikeTypes, use the name and default + vs.append( + f"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}" + ) + s = f"[{', '.join(vs)}] {s}" + + return f"def {s}" + + def visit_overloaded(self, t: Overloaded, /) -> str: + a = [] + for i in t.items: + a.append(i.accept(self)) + return f"Overload({', '.join(a)})" + + def visit_tuple_type(self, t: TupleType, /) -> str: + s = self.list_str(t.items) or "()" + if t.partial_fallback and t.partial_fallback.type: + fallback_name = t.partial_fallback.type.fullname + if fallback_name != "builtins.tuple": + return f"tuple[{s}, fallback={t.partial_fallback.accept(self)}]" + return f"tuple[{s}]" + + def visit_typeddict_type(self, t: TypedDictType, /) -> str: + def item_str(name: str, typ: str) -> str: + modifier = "" + if name not in t.required_keys: + modifier += "?" + if name in t.readonly_keys: + modifier += "=" + return f"{name!r}{modifier}: {typ}" + + s = ( + "{" + + ", ".join(item_str(name, typ.accept(self)) for name, typ in t.items.items()) + + "}" + ) + prefix = "" + if t.fallback and t.fallback.type: + if t.fallback.type.fullname not in TPDICT_FB_NAMES: + if not self.options.reveal_verbose_types: + prefix = t.fallback.type.fullname + ", " + else: + prefix = repr(t.fallback.type.fullname) + ", " + return f"TypedDict({prefix}{s})" + + def visit_raw_expression_type(self, t: RawExpressionType, /) -> str: + # For bytes literals, the value is already escaped, just add quotes and b prefix + if t.base_type_name == "builtins.bytes": + # The value is already escaped (e.g., "foo" or "hello\\nworld") + # Just add quotes and b prefix + return f"b'{t.literal_value}'" + return repr(t.literal_value) + + def visit_literal_type(self, t: LiteralType, /) -> str: + return f"Literal[{t.value_repr()}]" + + def visit_union_type(self, t: UnionType, /) -> str: + return self.list_str(t.items, use_or_syntax=True) + + def visit_partial_type(self, t: PartialType, /) -> str: + if t.type is None: + return "" + else: + return "".format(t.type.name, ", ".join(["?"] * len(t.type.type_vars))) + + def visit_ellipsis_type(self, t: EllipsisType, /) -> str: + return "..." + + def visit_type_type(self, t: TypeType, /) -> str: + if t.is_type_form: + type_name = "TypeForm" + else: + type_name = "type" + return f"{type_name}[{t.item.accept(self)}]" + + def visit_placeholder_type(self, t: PlaceholderType, /) -> str: + return f"" + + def visit_type_alias_type(self, t: TypeAliasType, /) -> str: + if t.alias is None: + return "" + if not t.is_recursive: + return get_proper_type(t).accept(self) + if self.dotted_aliases is None: + self.dotted_aliases = set() + elif t in self.dotted_aliases: + return "..." + self.dotted_aliases.add(t) + type_str = get_proper_type(t).accept(self) + self.dotted_aliases.discard(t) + return type_str + + def visit_unpack_type(self, t: UnpackType, /) -> str: + if not self.options.reveal_verbose_types: + return f"*{t.type.accept(self)}" + return f"Unpack[{t.type.accept(self)}]" + + def list_str(self, a: Iterable[Type], *, use_or_syntax: bool = False) -> str: + """Convert items of an array to strings (pretty-print types) + and join the results with commas. + """ + res = [] + for t in a: + s = t.accept(self) + if use_or_syntax and isinstance(get_proper_type(t), CallableType): + res.append(f"({s})") + else: + res.append(s) + sep = ", " if not use_or_syntax else " | " + return sep.join(res) + + +class TrivialSyntheticTypeTranslator(TypeTranslator, SyntheticTypeVisitor[Type]): + """A base class for type translators that need to be run during semantic analysis.""" + + def visit_placeholder_type(self, t: PlaceholderType, /) -> Type: + return t + + def visit_callable_argument(self, t: CallableArgument, /) -> Type: + return t + + def visit_ellipsis_type(self, t: EllipsisType, /) -> Type: + return t + + def visit_raw_expression_type(self, t: RawExpressionType, /) -> Type: + return t + + def visit_type_list(self, t: TypeList, /) -> Type: + return t + + +class CollectAliasesVisitor(TypeQuery[list[mypy.nodes.TypeAlias]]): + def __init__(self) -> None: + super().__init__() + self.seen_alias_nodes: set[mypy.nodes.TypeAlias] = set() + + def strategy(self, items: list[list[mypy.nodes.TypeAlias]]) -> list[mypy.nodes.TypeAlias]: + out = [] + for item in items: + out.extend(item) + return out + + def visit_type_alias_type(self, t: TypeAliasType, /) -> list[mypy.nodes.TypeAlias]: + assert t.alias is not None + if t.alias not in self.seen_alias_nodes: + self.seen_alias_nodes.add(t.alias) + res = [t.alias] + t.alias.target.accept(self) + else: + res = [] + for arg in t.args: + res.extend(arg.accept(self)) + return res + + +def is_named_instance(t: Type, fullnames: str | tuple[str, ...]) -> TypeGuard[Instance]: + if not isinstance(fullnames, tuple): + fullnames = (fullnames,) + + t = get_proper_type(t) + return isinstance(t, Instance) and t.type.fullname in fullnames + + +class HasTypeVars(BoolTypeQuery): + """Visitor for querying whether a type has a type variable component.""" + + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + self.skip_alias_target = True + + def visit_type_var(self, t: TypeVarType) -> bool: + return True + + def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool: + return True + + def visit_param_spec(self, t: ParamSpecType) -> bool: + return True + + +def has_type_vars(typ: Type) -> bool: + """Check if a type contains any type variables (recursively).""" + return typ.accept(HasTypeVars()) + + +class HasRecursiveType(BoolTypeQuery): + def __init__(self) -> None: + super().__init__(ANY_STRATEGY) + + def visit_type_alias_type(self, t: TypeAliasType) -> bool: + return t.is_recursive or self.query_types(t.args) + + +# Use singleton since this is hot (note: call reset() before using) +_has_recursive_type: Final = HasRecursiveType() + + +def has_recursive_types(typ: Type) -> bool: + """Check if a type contains any recursive aliases (recursively).""" + _has_recursive_type.reset() + return typ.accept(_has_recursive_type) + + +def split_with_prefix_and_suffix( + types: tuple[Type, ...], prefix: int, suffix: int +) -> tuple[tuple[Type, ...], tuple[Type, ...], tuple[Type, ...]]: + if len(types) <= prefix + suffix: + types = extend_args_for_prefix_and_suffix(types, prefix, suffix) + if suffix: + return types[:prefix], types[prefix:-suffix], types[-suffix:] + else: + return types[:prefix], types[prefix:], () + + +def extend_args_for_prefix_and_suffix( + types: tuple[Type, ...], prefix: int, suffix: int +) -> tuple[Type, ...]: + """Extend list of types by eating out from variadic tuple to satisfy prefix and suffix.""" + idx = None + item = None + for i, t in enumerate(types): + if isinstance(t, UnpackType): + p_type = get_proper_type(t.type) + if isinstance(p_type, Instance) and p_type.type.fullname == "builtins.tuple": + item = p_type.args[0] + idx = i + break + + if idx is None: + return types + assert item is not None + if idx < prefix: + start = (item,) * (prefix - idx) + else: + start = () + if len(types) - idx - 1 < suffix: + end = (item,) * (suffix - len(types) + idx + 1) + else: + end = () + return types[:idx] + start + (types[idx],) + end + types[idx + 1 :] + + +def flatten_nested_unions( + types: Sequence[Type], *, handle_type_alias_type: bool = True, handle_recursive: bool = True +) -> list[Type]: + """Flatten nested unions in a type list.""" + if not isinstance(types, list): + typelist = list(types) + else: + typelist = cast("list[Type]", types) + + # Fast path: most of the time there is nothing to flatten + if not any(isinstance(t, (TypeAliasType, UnionType)) for t in typelist): # type: ignore[misc] + return typelist + + flat_items: list[Type] = [] + for t in typelist: + if handle_type_alias_type and isinstance(t, TypeAliasType): + if not handle_recursive and t.is_recursive: + tp: Type = t + else: + tp = get_proper_type(t) + else: + tp = t + if isinstance(tp, ProperType) and isinstance(tp, UnionType): + flat_items.extend( + flatten_nested_unions( + tp.items, + handle_type_alias_type=handle_type_alias_type, + handle_recursive=handle_recursive, + ) + ) + else: + # Must preserve original aliases when possible. + flat_items.append(t) + return flat_items + + +def find_unpack_in_list(items: Sequence[Type]) -> int | None: + unpack_index: int | None = None + for i, item in enumerate(items): + if isinstance(item, UnpackType): + # We cannot fail here, so we must check this in an earlier + # semanal phase. + # Funky code here avoids mypyc narrowing the type of unpack_index. + old_index = unpack_index + assert old_index is None + # Don't return so that we can also sanity check there is only one. + unpack_index = i + return unpack_index + + +def flatten_nested_tuples(types: Iterable[Type]) -> list[Type]: + """Recursively flatten TupleTypes nested with Unpack. + + For example this will transform + Tuple[A, Unpack[Tuple[B, Unpack[Tuple[C, D]]]]] + into + Tuple[A, B, C, D] + """ + res = [] + for typ in types: + if not isinstance(typ, UnpackType): + res.append(typ) + continue + p_type = get_proper_type(typ.type) + if not isinstance(p_type, TupleType): + res.append(typ) + continue + if isinstance(typ.type, TypeAliasType): + items = [] + for item in p_type.items: + if ( + isinstance(item, ProperType) + and isinstance(item, Instance) + or isinstance(item, TypeAliasType) + ): + if len(item.args) == 0: + item = item.copy_modified() + item.set_line(typ) + items.append(item) + else: + items = p_type.items + res.extend(flatten_nested_tuples(items)) + return res + + +def is_literal_type(typ: ProperType, fallback_fullname: str, value: LiteralValue) -> bool: + """Check if this type is a LiteralType with the given fallback type and value.""" + if isinstance(typ, Instance) and typ.last_known_value: + typ = typ.last_known_value + return ( + isinstance(typ, LiteralType) + and typ.fallback.type.fullname == fallback_fullname + and typ.value == value + ) + + +names: Final = globals().copy() +names.pop("NOT_READY", None) +deserialize_map: Final = { + key: obj.deserialize + for key, obj in names.items() + if isinstance(obj, type) and issubclass(obj, Type) and obj is not Type +} + + +def callable_with_ellipsis(any_type: AnyType, ret_type: Type, fallback: Instance) -> CallableType: + """Construct type Callable[..., ret_type].""" + return CallableType( + [any_type, any_type], + [ARG_STAR, ARG_STAR2], + [None, None], + ret_type=ret_type, + fallback=fallback, + is_ellipsis_args=True, + ) + + +def remove_dups(types: list[T]) -> list[T]: + if len(types) <= 1: + return types + # Get unique elements in order of appearance + all_types: set[T] = set() + new_types: list[T] = [] + for t in types: + if t not in all_types: + new_types.append(t) + all_types.add(t) + return new_types + + +def type_vars_as_args(type_vars: Sequence[TypeVarLikeType]) -> tuple[Type, ...]: + """Represent type variables as they would appear in a type argument list.""" + args: list[Type] = [] + for tv in type_vars: + if isinstance(tv, TypeVarTupleType): + args.append(UnpackType(tv)) + else: + args.append(tv) + return tuple(args) + + +# See docstring for mypy/cache.py for reserved tag ranges. +# Instance-related tags. +INSTANCE: Final[Tag] = 80 +INSTANCE_SIMPLE: Final[Tag] = 81 +INSTANCE_GENERIC: Final[Tag] = 82 +INSTANCE_STR: Final[Tag] = 83 +INSTANCE_FUNCTION: Final[Tag] = 84 +INSTANCE_INT: Final[Tag] = 85 +INSTANCE_BOOL: Final[Tag] = 86 +INSTANCE_OBJECT: Final[Tag] = 87 + +# Other type tags. +TYPE_ALIAS_TYPE: Final[Tag] = 100 +TYPE_VAR_TYPE: Final[Tag] = 101 +PARAM_SPEC_TYPE: Final[Tag] = 102 +TYPE_VAR_TUPLE_TYPE: Final[Tag] = 103 +UNBOUND_TYPE: Final[Tag] = 104 +UNPACK_TYPE: Final[Tag] = 105 +ANY_TYPE: Final[Tag] = 106 +UNINHABITED_TYPE: Final[Tag] = 107 +NONE_TYPE: Final[Tag] = 108 +DELETED_TYPE: Final[Tag] = 109 +CALLABLE_TYPE: Final[Tag] = 110 +OVERLOADED: Final[Tag] = 111 +TUPLE_TYPE: Final[Tag] = 112 +TYPED_DICT_TYPE: Final[Tag] = 113 +LITERAL_TYPE: Final[Tag] = 114 +UNION_TYPE: Final[Tag] = 115 +TYPE_TYPE: Final[Tag] = 116 +PARAMETERS: Final[Tag] = 117 +LIST_TYPE: Final[Tag] = 118 # Only valid in serialized ASTs +ELLIPSIS_TYPE: Final[Tag] = 119 # Only valid in serialized ASTs +RAW_EXPRESSION_TYPE: Final[Tag] = 120 # Only valid in serialized ASTs +CALL_TYPE: Final[Tag] = 121 # Only valid in serialized ASTs + + +def read_type(data: ReadBuffer, tag: Tag | None = None) -> Type: + if tag is None: + tag = read_tag(data) + # The branches here are ordered manually by type "popularity". + if tag == INSTANCE: + return Instance.read(data) + if tag == ANY_TYPE: + return AnyType.read(data) + if tag == TYPE_VAR_TYPE: + return TypeVarType.read(data) + if tag == CALLABLE_TYPE: + return CallableType.read(data) + if tag == NONE_TYPE: + return NoneType.read(data) + if tag == UNION_TYPE: + return UnionType.read(data) + if tag == LITERAL_TYPE: + return LiteralType.read(data) + if tag == TYPE_ALIAS_TYPE: + return TypeAliasType.read(data) + if tag == TUPLE_TYPE: + return TupleType.read(data) + if tag == TYPED_DICT_TYPE: + return TypedDictType.read(data) + if tag == TYPE_TYPE: + return TypeType.read(data) + if tag == OVERLOADED: + return Overloaded.read(data) + if tag == PARAM_SPEC_TYPE: + return ParamSpecType.read(data) + if tag == TYPE_VAR_TUPLE_TYPE: + return TypeVarTupleType.read(data) + if tag == UNPACK_TYPE: + return UnpackType.read(data) + if tag == PARAMETERS: + return Parameters.read(data) + if tag == UNINHABITED_TYPE: + return UninhabitedType.read(data) + if tag == UNBOUND_TYPE: + return UnboundType.read(data) + if tag == DELETED_TYPE: + return DeletedType.read(data) + assert False, f"Unknown type tag {tag}" + + +def read_function_like(data: ReadBuffer, tag: Tag) -> FunctionLike: + if tag == CALLABLE_TYPE: + return CallableType.read(data) + if tag == OVERLOADED: + return Overloaded.read(data) + assert False, f"Invalid type tag for FunctionLike {tag}" + + +def read_type_var_likes(data: ReadBuffer) -> list[TypeVarLikeType]: + """Specialized version of read_type_list() for lists of type variables.""" + assert read_tag(data) == LIST_GEN + ret: list[TypeVarLikeType] = [] + for _ in range(read_int_bare(data)): + tag = read_tag(data) + if tag == TYPE_VAR_TYPE: + ret.append(TypeVarType.read(data)) + elif tag == PARAM_SPEC_TYPE: + ret.append(ParamSpecType.read(data)) + elif tag == TYPE_VAR_TUPLE_TYPE: + ret.append(TypeVarTupleType.read(data)) + else: + assert False, f"Invalid type tag for TypeVarLikeType {tag}" + return ret + + +def read_type_opt(data: ReadBuffer) -> Type | None: + tag = read_tag(data) + if tag == LITERAL_NONE: + return None + return read_type(data, tag) + + +def write_type_opt(data: WriteBuffer, value: Type | None) -> None: + if value is not None: + value.write(data) + else: + write_tag(data, LITERAL_NONE) + + +def read_type_list(data: ReadBuffer) -> list[Type]: + assert read_tag(data) == LIST_GEN + size = read_int_bare(data) + return [read_type(data) for _ in range(size)] + + +def write_type_list(data: WriteBuffer, value: Sequence[Type]) -> None: + write_tag(data, LIST_GEN) + write_int_bare(data, len(value)) + for item in value: + item.write(data) + + +def read_type_map(data: ReadBuffer) -> dict[str, Type]: + assert read_tag(data) == DICT_STR_GEN + size = read_int_bare(data) + return {read_str_bare(data): read_type(data) for _ in range(size)} + + +def write_type_map(data: WriteBuffer, value: dict[str, Type]) -> None: + write_tag(data, DICT_STR_GEN) + write_int_bare(data, len(value)) + for key in sorted(value): + write_str_bare(data, key) + value[key].write(data) + + +# This cyclic import is unfortunate, but to avoid it we would need to move away all uses +# of get_proper_type() from types.py. Majority of them have been removed, but few remaining +# are quite tricky to get rid of, but ultimately we want to do it at some point. +from mypy.expandtype import ExpandTypeVisitor + + +class InstantiateAliasVisitor(ExpandTypeVisitor): + def visit_union_type(self, t: UnionType) -> Type: + # Unlike regular expand_type(), we don't do any simplification for unions, + # not even removing strict duplicates. There are three reasons for this: + # * get_proper_type() is a very hot function, even slightest slow down will + # cause a perf regression + # * We want to preserve this historical behaviour, to avoid possible + # regressions + # * Simplifying unions may (indirectly) call get_proper_type(), causing + # infinite recursion. + return TypeTranslator.visit_union_type(self, t) diff --git a/micromamba_root/Lib/site-packages/mypy/types_utils.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/types_utils.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..9fa1b10e106cf699bc7a6d7ba198edd06759902b Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/types_utils.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/types_utils.py b/micromamba_root/Lib/site-packages/mypy/types_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..160f6c0365d63a3c6ab5005d1f4ddbe4d9b9c6a9 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/types_utils.py @@ -0,0 +1,183 @@ +""" +This module is for (more basic) type operations that should not depend on is_subtype(), +meet_types(), join_types() etc. We don't want to keep them in mypy/types.py for two reasons: +* Reduce the size of that module. +* Reduce use of get_proper_type() in types.py to avoid cyclic imports + expand_type <-> types, if we move get_proper_type() to the former. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable +from typing import cast + +from mypy.nodes import ARG_STAR, ARG_STAR2, FuncItem, TypeAlias +from mypy.types import ( + AnyType, + CallableType, + Instance, + LiteralType, + NoneType, + Overloaded, + ParamSpecType, + ProperType, + TupleType, + Type, + TypeAliasType, + TypeType, + TypeVarType, + UninhabitedType, + UnionType, + UnpackType, + flatten_nested_unions, + get_proper_type, + get_proper_types, +) + + +def flatten_types(types: Iterable[Type]) -> Iterable[Type]: + for t in types: + tp = get_proper_type(t) + if isinstance(tp, UnionType): + yield from flatten_types(tp.items) + else: + yield t + + +def strip_type(typ: Type) -> Type: + """Make a copy of type without 'debugging info' (function name).""" + orig_typ = typ + typ = get_proper_type(typ) + if isinstance(typ, CallableType): + return typ.copy_modified(name=None) + elif isinstance(typ, Overloaded): + return Overloaded([cast(CallableType, strip_type(item)) for item in typ.items]) + else: + return orig_typ + + +def is_invalid_recursive_alias(seen_nodes: set[TypeAlias], target: Type) -> bool: + """Flag aliases like A = Union[int, A], T = tuple[int, *T] (and similar mutual aliases). + + Such aliases don't make much sense, and cause problems in later phases. + """ + if isinstance(target, TypeAliasType): + if target.alias in seen_nodes: + return True + assert target.alias, f"Unfixed type alias {target.type_ref}" + return is_invalid_recursive_alias(seen_nodes | {target.alias}, get_proper_type(target)) + assert isinstance(target, ProperType) + if not isinstance(target, (UnionType, TupleType)): + return False + if isinstance(target, UnionType): + return any(is_invalid_recursive_alias(seen_nodes, item) for item in target.items) + for item in target.items: + if isinstance(item, UnpackType): + if is_invalid_recursive_alias(seen_nodes, item.type): + return True + return False + + +def get_bad_type_type_item(item: Type) -> str | None: + """Prohibit types like Type[Type[...]]. + + Such types are explicitly prohibited by PEP 484. Also, they cause problems + with recursive types like T = Type[T], because internal representation of + TypeType item is normalized (i.e. always a proper type). + + Also forbids `Type[Literal[...]]`, because typing spec does not allow it. + """ + # TODO: what else cannot be present in `type[...]`? + item = get_proper_type(item) + if isinstance(item, TypeType): + return "Type[...]" + if isinstance(item, LiteralType): + return "Literal[...]" + if isinstance(item, UnionType): + items = [ + bad_item + for typ in flatten_nested_unions(item.items) + if (bad_item := get_bad_type_type_item(typ)) is not None + ] + if not items: + return None + if len(items) == 1: + return items[0] + return f"Union[{', '.join(items)}]" + return None + + +def is_union_with_any(tp: Type) -> bool: + """Is this a union with Any or a plain Any type?""" + tp = get_proper_type(tp) + if isinstance(tp, AnyType): + return True + if not isinstance(tp, UnionType): + return False + return any(is_union_with_any(t) for t in get_proper_types(tp.items)) + + +def is_generic_instance(tp: Type) -> bool: + tp = get_proper_type(tp) + return isinstance(tp, Instance) and bool(tp.args) + + +def is_overlapping_none(t: Type) -> bool: + t = get_proper_type(t) + return isinstance(t, NoneType) or ( + isinstance(t, UnionType) and any(isinstance(get_proper_type(e), NoneType) for e in t.items) + ) + + +def remove_optional(typ: Type) -> Type: + typ = get_proper_type(typ) + if isinstance(typ, UnionType): + return UnionType.make_union( + [t for t in typ.items if not isinstance(get_proper_type(t), NoneType)] + ) + elif isinstance(typ, NoneType): + return UninhabitedType() + else: + return typ + + +def is_self_type_like(typ: Type, *, is_classmethod: bool) -> bool: + """Does this look like a self-type annotation?""" + typ = get_proper_type(typ) + if not is_classmethod: + return isinstance(typ, TypeVarType) + if not isinstance(typ, TypeType): + return False + return isinstance(typ.item, TypeVarType) + + +def store_argument_type( + defn: FuncItem, i: int, typ: CallableType, named_type: Callable[[str, list[Type]], Instance] +) -> None: + arg_type = typ.arg_types[i] + if typ.arg_kinds[i] == ARG_STAR: + if isinstance(arg_type, ParamSpecType): + pass + elif isinstance(arg_type, UnpackType): + unpacked_type = get_proper_type(arg_type.type) + if isinstance(unpacked_type, TupleType): + # Instead of using Tuple[Unpack[Tuple[...]]], just use Tuple[...] + arg_type = unpacked_type + elif ( + isinstance(unpacked_type, Instance) + and unpacked_type.type.fullname == "builtins.tuple" + ): + arg_type = unpacked_type + else: + # TODO: verify that we can only have a TypeVarTuple here. + arg_type = TupleType( + [arg_type], + fallback=named_type("builtins.tuple", [named_type("builtins.object", [])]), + ) + else: + # builtins.tuple[T] is typing.Tuple[T, ...] + arg_type = named_type("builtins.tuple", [arg_type]) + elif typ.arg_kinds[i] == ARG_STAR2: + if not isinstance(arg_type, ParamSpecType) and not typ.unpack_kwargs: + arg_type = named_type("builtins.dict", [named_type("builtins.str", []), arg_type]) + defn.arguments[i].variable.type = arg_type diff --git a/micromamba_root/Lib/site-packages/mypy/typestate.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/typestate.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..f9846bcf84835f08aadd820870bbc6924204a1db Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/typestate.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/typestate.py b/micromamba_root/Lib/site-packages/mypy/typestate.py new file mode 100644 index 0000000000000000000000000000000000000000..d45837dad645adcea8901fcd5bac3f5d263b3fdf --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/typestate.py @@ -0,0 +1,328 @@ +""" +A shared state for all TypeInfos that holds global cache and dependency information, +and potentially other mutable TypeInfo state. This module contains mutable global state. +""" + +from __future__ import annotations + +from typing import Final, TypeAlias as _TypeAlias + +from mypy.nodes import VARIANCE_NOT_READY, TypeInfo +from mypy.server.trigger import make_trigger +from mypy.types import Instance, Type, TypeVarId, TypeVarType, get_proper_type + +MAX_NEGATIVE_CACHE_TYPES: Final = 1000 +MAX_NEGATIVE_CACHE_ENTRIES: Final = 10000 + +# Represents that the 'left' instance is a subtype of the 'right' instance +SubtypeRelationship: _TypeAlias = tuple[Instance, Instance] + +# A tuple encoding the specific conditions under which we performed the subtype check. +# (e.g. did we want a proper subtype? A regular subtype while ignoring variance?) +SubtypeKind: _TypeAlias = tuple[bool, ...] + +# A cache that keeps track of whether the given TypeInfo is a part of a particular +# subtype relationship +SubtypeCache: _TypeAlias = dict[TypeInfo, dict[SubtypeKind, set[SubtypeRelationship]]] + + +class TypeState: + """This class provides subtype caching to improve performance of subtype checks. + It also holds protocol fine grained dependencies. + + Note: to avoid leaking global state, 'reset_all_subtype_caches()' should be called + after a build has finished and after a daemon shutdown. This subtype cache only exists for + performance reasons, resetting subtype caches for a class has no semantic effect. + The protocol dependencies however are only stored here, and shouldn't be deleted unless + not needed any more (e.g. during daemon shutdown). + """ + + # '_subtype_caches' keeps track of (subtype, supertype) pairs where supertypes are + # instances of the given TypeInfo. The cache also keeps track of whether the check + # was done in strict optional mode and of the specific *kind* of subtyping relationship, + # which we represent as an arbitrary hashable tuple. + # We need the caches, since subtype checks for structural types are very slow. + _subtype_caches: Final[SubtypeCache] + + # Same as above but for negative subtyping results. + _negative_subtype_caches: Final[SubtypeCache] + + # This contains protocol dependencies generated after running a full build, + # or after an update. These dependencies are special because: + # * They are a global property of the program; i.e. some dependencies for imported + # classes can be generated in the importing modules. + # * Because of the above, they are serialized separately, after a full run, + # or a full update. + # `proto_deps` can be None if after deserialization it turns out that they are + # inconsistent with the other cache files (or an error occurred during deserialization). + # A blocking error will be generated in this case, since we can't proceed safely. + # For the description of kinds of protocol dependencies and corresponding examples, + # see _snapshot_protocol_deps. + proto_deps: dict[str, set[str]] | None + + # Protocols (full names) a given class attempted to implement. + # Used to calculate fine grained protocol dependencies and optimize protocol + # subtype cache invalidation in fine grained mode. For example, if we pass a value + # of type a.A to a function expecting something compatible with protocol p.P, + # we'd have 'a.A' -> {'p.P', ...} in the map. This map is flushed after every incremental + # update. + _attempted_protocols: Final[dict[str, set[str]]] + # We also snapshot protocol members of the above protocols. For example, if we pass + # a value of type a.A to a function expecting something compatible with Iterable, we'd have + # 'a.A' -> {'__iter__', ...} in the map. This map is also flushed after every incremental + # update. This map is needed to only generate dependencies like -> + # instead of a wildcard to avoid unnecessarily invalidating classes. + _checked_against_members: Final[dict[str, set[str]]] + # TypeInfos that appeared as a left type (subtype) in a subtype check since latest + # dependency snapshot update. This is an optimisation for fine grained mode; during a full + # run we only take a dependency snapshot at the very end, so this set will contain all + # subtype-checked TypeInfos. After a fine grained update however, we can gather only new + # dependencies generated from (typically) few TypeInfos that were subtype-checked + # (i.e. appeared as r.h.s. in an assignment or an argument in a function call in + # a re-checked target) during the update. + _rechecked_types: Final[set[TypeInfo]] + + # The two attributes below are assumption stacks for subtyping relationships between + # recursive type aliases. Normally, one would pass type assumptions as an additional + # arguments to is_subtype(), but this would mean updating dozens of related functions + # threading this through all callsites (see also comment for TypeInfo.assuming). + _assuming: Final[list[tuple[Type, Type]]] + _assuming_proper: Final[list[tuple[Type, Type]]] + # Ditto for inference of generic constraints against recursive type aliases. + inferring: Final[list[tuple[Type, Type]]] + # Whether to use joins or unions when solving constraints, see checkexpr.py for details. + infer_unions: bool + # Whether to use new type inference algorithm that can infer polymorphic types. + # This is temporary and will be removed soon when new algorithm is more polished. + infer_polymorphic: bool + + # N.B: We do all of the accesses to these properties through + # TypeState, instead of making these classmethods and accessing + # via the cls parameter, since mypyc can optimize accesses to + # Final attributes of a directly referenced type. + + def __init__(self) -> None: + self._subtype_caches = {} + self._negative_subtype_caches = {} + self.proto_deps = {} + self._attempted_protocols = {} + self._checked_against_members = {} + self._rechecked_types = set() + self._assuming = [] + self._assuming_proper = [] + self.inferring = [] + self.infer_unions = False + self.infer_polymorphic = False + + def is_assumed_subtype(self, left: Type, right: Type) -> bool: + for l, r in reversed(self._assuming): + if get_proper_type(l) == get_proper_type(left) and get_proper_type( + r + ) == get_proper_type(right): + return True + return False + + def is_assumed_proper_subtype(self, left: Type, right: Type) -> bool: + for l, r in reversed(self._assuming_proper): + if get_proper_type(l) == get_proper_type(left) and get_proper_type( + r + ) == get_proper_type(right): + return True + return False + + def get_assumptions(self, is_proper: bool) -> list[tuple[Type, Type]]: + if is_proper: + return self._assuming_proper + return self._assuming + + def reset_all_subtype_caches(self) -> None: + """Completely reset all known subtype caches.""" + self._subtype_caches.clear() + self._negative_subtype_caches.clear() + + def reset_subtype_caches_for(self, info: TypeInfo) -> None: + """Reset subtype caches (if any) for a given supertype TypeInfo.""" + if info in self._subtype_caches: + self._subtype_caches[info].clear() + if info in self._negative_subtype_caches: + self._negative_subtype_caches[info].clear() + + def reset_all_subtype_caches_for(self, info: TypeInfo) -> None: + """Reset subtype caches (if any) for a given supertype TypeInfo and its MRO.""" + for item in info.mro: + self.reset_subtype_caches_for(item) + + def is_cached_subtype_check(self, kind: SubtypeKind, left: Instance, right: Instance) -> bool: + if left.last_known_value is not None or right.last_known_value is not None: + # If there is a literal last known value, give up. There + # will be an unbounded number of potential types to cache, + # making caching less effective. + return False + info = right.type + cache = self._subtype_caches.get(info) + if cache is None: + return False + subcache = cache.get(kind) + if subcache is None: + return False + return (left, right) in subcache + + def is_cached_negative_subtype_check( + self, kind: SubtypeKind, left: Instance, right: Instance + ) -> bool: + if left.last_known_value is not None or right.last_known_value is not None: + # If there is a literal last known value, give up. There + # will be an unbounded number of potential types to cache, + # making caching less effective. + return False + info = right.type + cache = self._negative_subtype_caches.get(info) + if cache is None: + return False + subcache = cache.get(kind) + if subcache is None: + return False + return (left, right) in subcache + + def record_subtype_cache_entry( + self, kind: SubtypeKind, left: Instance, right: Instance + ) -> None: + if left.last_known_value is not None or right.last_known_value is not None: + # These are unlikely to match, due to the large space of + # possible values. Avoid uselessly increasing cache sizes. + return + if any( + (isinstance(tv, TypeVarType) and tv.variance == VARIANCE_NOT_READY) + for tv in right.type.defn.type_vars + ): + # Variance indeterminate -- don't know the result + return + cache = self._subtype_caches.setdefault(right.type, {}) + cache.setdefault(kind, set()).add((left, right)) + + def record_negative_subtype_cache_entry( + self, kind: SubtypeKind, left: Instance, right: Instance + ) -> None: + if left.last_known_value is not None or right.last_known_value is not None: + # These are unlikely to match, due to the large space of + # possible values. Avoid uselessly increasing cache sizes. + return + if len(self._negative_subtype_caches) > MAX_NEGATIVE_CACHE_TYPES: + self._negative_subtype_caches.clear() + cache = self._negative_subtype_caches.setdefault(right.type, {}) + subcache = cache.setdefault(kind, set()) + if len(subcache) > MAX_NEGATIVE_CACHE_ENTRIES: + subcache.clear() + cache.setdefault(kind, set()).add((left, right)) + + def reset_protocol_deps(self) -> None: + """Reset dependencies after a full run or before a daemon shutdown.""" + self.proto_deps = {} + self._attempted_protocols.clear() + self._checked_against_members.clear() + self._rechecked_types.clear() + + def record_protocol_subtype_check(self, left_type: TypeInfo, right_type: TypeInfo) -> None: + assert right_type.is_protocol + self._rechecked_types.add(left_type) + self._attempted_protocols.setdefault(left_type.fullname, set()).add(right_type.fullname) + self._checked_against_members.setdefault(left_type.fullname, set()).update( + right_type.protocol_members + ) + + def _snapshot_protocol_deps(self) -> dict[str, set[str]]: + """Collect protocol attribute dependencies found so far from registered subtype checks. + + There are three kinds of protocol dependencies. For example, after a subtype check: + + x: Proto = C() + + the following dependencies will be generated: + 1. ..., , -> + 2. ..., , -> [for every attr in Proto members] + 3. -> Proto # this one to invalidate the subtype cache + + The first kind is generated immediately per-module in deps.py (see also an example there + for motivation why it is needed). While two other kinds are generated here after all + modules are type checked and we have recorded all the subtype checks. To understand these + two kinds, consider a simple example: + + class A: + def __iter__(self) -> Iterator[int]: + ... + + it: Iterable[int] = A() + + We add -> to invalidate the assignment (module target in this case), + whenever the signature of a.A.__iter__ changes. We also add -> typing.Iterable, + to invalidate the subtype caches of the latter. (Note that the same logic applies to + proper subtype checks, and calculating meets and joins, if this involves calling + 'subtypes.is_protocol_implementation'). + """ + deps: dict[str, set[str]] = {} + for info in self._rechecked_types: + for attr in self._checked_against_members[info.fullname]: + # The need for full MRO here is subtle, during an update, base classes of + # a concrete class may not be reprocessed, so not all -> deps + # are added. + for base_info in info.mro[:-1]: + trigger = make_trigger(f"{base_info.fullname}.{attr}") + if "typing" in trigger or "builtins" in trigger: + # TODO: avoid everything from typeshed + continue + deps.setdefault(trigger, set()).add(make_trigger(info.fullname)) + for proto in self._attempted_protocols[info.fullname]: + trigger = make_trigger(info.fullname) + if "typing" in trigger or "builtins" in trigger: + continue + # If any class that was checked against a protocol changes, + # we need to reset the subtype cache for the protocol. + # + # Note: strictly speaking, the protocol doesn't need to be + # re-checked, we only need to reset the cache, and its uses + # elsewhere are still valid (unless invalidated by other deps). + deps.setdefault(trigger, set()).add(proto) + return deps + + def update_protocol_deps(self, second_map: dict[str, set[str]] | None = None) -> None: + """Update global protocol dependency map. + + We update the global map incrementally, using a snapshot only from recently + type checked types. If second_map is given, update it as well. This is currently used + by FineGrainedBuildManager that maintains normal (non-protocol) dependencies. + """ + assert self.proto_deps is not None, "This should not be called after failed cache load" + new_deps = self._snapshot_protocol_deps() + for trigger, targets in new_deps.items(): + self.proto_deps.setdefault(trigger, set()).update(targets) + if second_map is not None: + for trigger, targets in new_deps.items(): + second_map.setdefault(trigger, set()).update(targets) + self._rechecked_types.clear() + self._attempted_protocols.clear() + self._checked_against_members.clear() + + def add_all_protocol_deps(self, deps: dict[str, set[str]]) -> None: + """Add all known protocol dependencies to deps. + + This is used by tests and debug output, and also when collecting + all collected or loaded dependencies as part of build. + """ + self.update_protocol_deps() # just in case + if self.proto_deps is not None: + for trigger, targets in self.proto_deps.items(): + deps.setdefault(trigger, set()).update(targets) + + +type_state: Final = TypeState() + + +def reset_global_state() -> None: + """Reset most existing global state. + + Currently most of it is in this module. Few exceptions are strict optional status + and functools.lru_cache. + """ + type_state.reset_all_subtype_caches() + type_state.reset_protocol_deps() + TypeVarId.next_raw_id = 1 diff --git a/micromamba_root/Lib/site-packages/mypy/typetraverser.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/typetraverser.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..68d39eb3c7d50f1ca36c15f5a25e17674a28efa1 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/typetraverser.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/typetraverser.py b/micromamba_root/Lib/site-packages/mypy/typetraverser.py new file mode 100644 index 0000000000000000000000000000000000000000..abd0f6bf3bdfebf0b35a10e4f36656af2b73cd9d --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/typetraverser.py @@ -0,0 +1,159 @@ +from __future__ import annotations + +from collections.abc import Iterable + +from mypy_extensions import trait + +from mypy.types import ( + AnyType, + CallableArgument, + CallableType, + DeletedType, + EllipsisType, + ErasedType, + Instance, + LiteralType, + NoneType, + Overloaded, + Parameters, + ParamSpecType, + PartialType, + PlaceholderType, + RawExpressionType, + SyntheticTypeVisitor, + TupleType, + Type, + TypeAliasType, + TypedDictType, + TypeList, + TypeType, + TypeVarTupleType, + TypeVarType, + UnboundType, + UninhabitedType, + UnionType, + UnpackType, +) + + +@trait +class TypeTraverserVisitor(SyntheticTypeVisitor[None]): + """Visitor that traverses all components of a type""" + + # Atomic types + + def visit_any(self, t: AnyType, /) -> None: + pass + + def visit_uninhabited_type(self, t: UninhabitedType, /) -> None: + pass + + def visit_none_type(self, t: NoneType, /) -> None: + pass + + def visit_erased_type(self, t: ErasedType, /) -> None: + pass + + def visit_deleted_type(self, t: DeletedType, /) -> None: + pass + + def visit_type_var(self, t: TypeVarType, /) -> None: + # Note that type variable values and upper bound aren't treated as + # components, since they are components of the type variable + # definition. We want to traverse everything just once. + t.default.accept(self) + + def visit_param_spec(self, t: ParamSpecType, /) -> None: + # TODO: do we need to traverse prefix here? + t.default.accept(self) + + def visit_parameters(self, t: Parameters, /) -> None: + self.traverse_type_list(t.arg_types) + + def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> None: + t.default.accept(self) + + def visit_literal_type(self, t: LiteralType, /) -> None: + t.fallback.accept(self) + + # Composite types + + def visit_instance(self, t: Instance, /) -> None: + self.traverse_type_tuple(t.args) + + def visit_callable_type(self, t: CallableType, /) -> None: + # FIX generics + self.traverse_type_list(t.arg_types) + t.ret_type.accept(self) + t.fallback.accept(self) + + if t.type_guard is not None: + t.type_guard.accept(self) + + if t.type_is is not None: + t.type_is.accept(self) + + def visit_tuple_type(self, t: TupleType, /) -> None: + self.traverse_type_list(t.items) + t.partial_fallback.accept(self) + + def visit_typeddict_type(self, t: TypedDictType, /) -> None: + self.traverse_types(t.items.values()) + t.fallback.accept(self) + + def visit_union_type(self, t: UnionType, /) -> None: + self.traverse_type_list(t.items) + + def visit_overloaded(self, t: Overloaded, /) -> None: + self.traverse_types(t.items) + + def visit_type_type(self, t: TypeType, /) -> None: + t.item.accept(self) + + # Special types (not real types) + + def visit_callable_argument(self, t: CallableArgument, /) -> None: + t.typ.accept(self) + + def visit_unbound_type(self, t: UnboundType, /) -> None: + self.traverse_type_tuple(t.args) + + def visit_type_list(self, t: TypeList, /) -> None: + self.traverse_type_list(t.items) + + def visit_ellipsis_type(self, t: EllipsisType, /) -> None: + pass + + def visit_placeholder_type(self, t: PlaceholderType, /) -> None: + self.traverse_type_list(t.args) + + def visit_partial_type(self, t: PartialType, /) -> None: + pass + + def visit_raw_expression_type(self, t: RawExpressionType, /) -> None: + pass + + def visit_type_alias_type(self, t: TypeAliasType, /) -> None: + # TODO: sometimes we want to traverse target as well + # We need to find a way to indicate explicitly the intent, + # maybe make this method abstract (like for TypeTranslator)? + self.traverse_type_list(t.args) + + def visit_unpack_type(self, t: UnpackType, /) -> None: + t.type.accept(self) + + # Helpers + + def traverse_types(self, types: Iterable[Type], /) -> None: + for typ in types: + typ.accept(self) + + def traverse_type_list(self, types: list[Type], /) -> None: + # Micro-optimization: Specialized for lists + for typ in types: + typ.accept(self) + + def traverse_type_tuple(self, types: tuple[Type, ...], /) -> None: + # Micro-optimization: Specialized for tuples + for typ in types: + typ.accept(self) diff --git a/micromamba_root/Lib/site-packages/mypy/typevars.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/typevars.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..bfbae8cd567669aace09007b0d0db44aea551073 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/typevars.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/typevars.py b/micromamba_root/Lib/site-packages/mypy/typevars.py new file mode 100644 index 0000000000000000000000000000000000000000..e871973104a2dd5b32c54d1519fc85ed5d971be1 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/typevars.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +from mypy.erasetype import erase_typevars +from mypy.nodes import TypeInfo +from mypy.types import ( + Instance, + ParamSpecType, + ProperType, + TupleType, + Type, + TypeOfAny, + TypeVarLikeType, + TypeVarTupleType, + TypeVarType, + UnpackType, +) +from mypy.typevartuples import erased_vars + + +def fill_typevars(typ: TypeInfo) -> Instance | TupleType: + """For a non-generic type, return instance type representing the type. + + For a generic G type with parameters T1, .., Tn, return G[T1, ..., Tn]. + """ + tvs: list[Type] = [] + # TODO: why do we need to keep both typ.type_vars and typ.defn.type_vars? + for i in range(len(typ.defn.type_vars)): + tv: TypeVarLikeType | UnpackType = typ.defn.type_vars[i] + # Change the line number + if isinstance(tv, TypeVarType): + tv = tv.copy_modified(line=-1, column=-1) + elif isinstance(tv, TypeVarTupleType): + tv = UnpackType( + TypeVarTupleType( + tv.name, + tv.fullname, + tv.id, + tv.upper_bound, + tv.tuple_fallback, + tv.default, + line=-1, + column=-1, + ) + ) + else: + assert isinstance(tv, ParamSpecType) + tv = ParamSpecType( + tv.name, + tv.fullname, + tv.id, + tv.flavor, + tv.upper_bound, + tv.default, + line=-1, + column=-1, + ) + tvs.append(tv) + inst = Instance(typ, tvs) + # TODO: do we need to also handle typeddict_type here and below? + if typ.tuple_type is None: + return inst + return typ.tuple_type.copy_modified(fallback=inst) + + +def fill_typevars_with_any(typ: TypeInfo) -> Instance | TupleType: + """Apply a correct number of Any's as type arguments to a type.""" + inst = Instance(typ, erased_vars(typ.defn.type_vars, TypeOfAny.special_form)) + if typ.tuple_type is None: + return inst + erased_tuple_type = erase_typevars(typ.tuple_type, {tv.id for tv in typ.defn.type_vars}) + assert isinstance(erased_tuple_type, ProperType) + if isinstance(erased_tuple_type, TupleType): + return typ.tuple_type.copy_modified(fallback=inst) + return inst + + +def has_no_typevars(typ: Type) -> bool: + # We test if a type contains type variables by erasing all type variables + # and comparing the result to the original type. We use comparison by equality that + # in turn uses `__eq__` defined for types. Note: we can't use `is_same_type` because + # it is not safe with unresolved forward references, while this function may be called + # before forward references resolution patch pass. Note also that it is not safe to use + # `is` comparison because `erase_typevars` doesn't preserve type identity. + return typ == erase_typevars(typ) diff --git a/micromamba_root/Lib/site-packages/mypy/typevartuples.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/typevartuples.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..a252342ab43dd40679b27010968633fe195462d0 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/typevartuples.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/typevartuples.py b/micromamba_root/Lib/site-packages/mypy/typevartuples.py new file mode 100644 index 0000000000000000000000000000000000000000..1bf1a59f7d3fb9ca32c7d075795da45b727a0cec --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/typevartuples.py @@ -0,0 +1,36 @@ +"""Helpers for interacting with type var tuples.""" + +from __future__ import annotations + +from collections.abc import Sequence + +from mypy.types import ( + AnyType, + Instance, + Type, + TypeVarLikeType, + TypeVarTupleType, + UnpackType, + split_with_prefix_and_suffix, +) + + +def split_with_instance( + typ: Instance, +) -> tuple[tuple[Type, ...], tuple[Type, ...], tuple[Type, ...]]: + assert typ.type.type_var_tuple_prefix is not None + assert typ.type.type_var_tuple_suffix is not None + return split_with_prefix_and_suffix( + typ.args, typ.type.type_var_tuple_prefix, typ.type.type_var_tuple_suffix + ) + + +def erased_vars(type_vars: Sequence[TypeVarLikeType], type_of_any: int) -> list[Type]: + args: list[Type] = [] + for tv in type_vars: + # Valid erasure for *Ts is *tuple[Any, ...], not just Any. + if isinstance(tv, TypeVarTupleType): + args.append(UnpackType(tv.tuple_fallback.copy_modified(args=[AnyType(type_of_any)]))) + else: + args.append(AnyType(type_of_any)) + return args diff --git a/micromamba_root/Lib/site-packages/mypy/util.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/util.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..ab66a77c3054722c3d8b26f66420bc7449903f5e Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/util.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/util.py b/micromamba_root/Lib/site-packages/mypy/util.py new file mode 100644 index 0000000000000000000000000000000000000000..86998380ff0aa9a2037ccd6f8d065283a2d9ad69 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/util.py @@ -0,0 +1,961 @@ +"""Utility functions with no non-trivial dependencies.""" + +from __future__ import annotations + +import hashlib +import io +import json +import os +import re +import shutil +import sys +import time +from collections.abc import Callable, Container, Iterable, Sequence, Sized +from importlib import resources as importlib_resources +from typing import IO, Any, Final, Literal, TypeVar + +orjson: Any +try: + import orjson # type: ignore[import-not-found, no-redef, unused-ignore] +except ImportError: + orjson = None + +try: + import _curses # noqa: F401 + import curses + + CURSES_ENABLED = True +except ImportError: + CURSES_ENABLED = False + +T = TypeVar("T") + +TYPESHED_DIR: Final = str(importlib_resources.files("mypy") / "typeshed") + +ENCODING_RE: Final = re.compile(rb"([ \t\v]*#.*(\r\n?|\n))??[ \t\v]*#.*coding[:=][ \t]*([-\w.]+)") + +DEFAULT_SOURCE_OFFSET: Final = 4 +CODE_START: Final = " " * DEFAULT_SOURCE_OFFSET +DEFAULT_COLUMNS: Final = 80 + +# At least this number of columns will be shown on each side of +# error location when printing source code snippet. +MINIMUM_WIDTH: Final = 20 + +# VT100 color code processing was added in Windows 10, but only the second major update, +# Threshold 2. Fortunately, everyone (even on LTSB, Long Term Support Branch) should +# have a version of Windows 10 newer than this. Note that Windows 8 and below are not +# supported, but are either going out of support, or make up only a few % of the market. +MINIMUM_WINDOWS_MAJOR_VT100: Final = 10 +MINIMUM_WINDOWS_BUILD_VT100: Final = 10586 + +SPECIAL_DUNDERS: Final = frozenset( + ("__init__", "__new__", "__call__", "__init_subclass__", "__class_getitem__") +) + + +def is_dunder(name: str, exclude_special: bool = False) -> bool: + """Returns whether name is a dunder name. + + Args: + exclude_special: Whether to return False for a couple special dunder methods. + + """ + if exclude_special and name in SPECIAL_DUNDERS: + return False + return name.startswith("__") and name.endswith("__") + + +def is_sunder(name: str) -> bool: + return not is_dunder(name) and name.startswith("_") and name.endswith("_") and name != "_" + + +def split_module_names(mod_name: str) -> list[str]: + """Return the module and all parent module names. + + So, if `mod_name` is 'a.b.c', this function will return + ['a.b.c', 'a.b', and 'a']. + """ + out = [mod_name] + while "." in mod_name: + mod_name = mod_name.rsplit(".", 1)[0] + out.append(mod_name) + return out + + +def module_prefix(modules: Iterable[str], target: str) -> str | None: + result = split_target(modules, target) + if result is None: + return None + return result[0] + + +def split_target(modules: Iterable[str], target: str) -> tuple[str, str] | None: + remaining: list[str] = [] + while True: + if target in modules: + return target, ".".join(remaining) + components = target.rsplit(".", 1) + if len(components) == 1: + return None + target = components[0] + remaining.insert(0, components[1]) + + +def short_type(obj: object) -> str: + """Return the last component of the type name of an object. + + If obj is None, return 'nil'. For example, if obj is 1, return 'int'. + """ + if obj is None: + return "nil" + t = str(type(obj)) + return t.split(".")[-1].rstrip("'>") + + +def find_python_encoding(text: bytes) -> tuple[str, int]: + """PEP-263 for detecting Python file encoding""" + result = ENCODING_RE.match(text) + if result: + line = 2 if result.group(1) else 1 + encoding = result.group(3).decode("ascii") + # Handle some aliases that Python is happy to accept and that are used in the wild. + if encoding.startswith(("iso-latin-1-", "latin-1-")) or encoding == "iso-latin-1": + encoding = "latin-1" + return encoding, line + else: + default_encoding = "utf8" + return default_encoding, -1 + + +def bytes_to_human_readable_repr(b: bytes) -> str: + """Converts bytes into some human-readable representation. Unprintable + bytes such as the nul byte are escaped. For example: + + >>> b = bytes([102, 111, 111, 10, 0]) + >>> s = bytes_to_human_readable_repr(b) + >>> print(s) + foo\n\x00 + >>> print(repr(s)) + 'foo\\n\\x00' + """ + return repr(b)[2:-1] + + +class DecodeError(Exception): + """Exception raised when a file cannot be decoded due to an unknown encoding type. + + Essentially a wrapper for the LookupError raised by `bytearray.decode` + """ + + +def decode_python_encoding(source: bytes) -> str: + """Read the Python file with while obeying PEP-263 encoding detection. + + Returns the source as a string. + """ + # check for BOM UTF-8 encoding and strip it out if present + if source.startswith(b"\xef\xbb\xbf"): + encoding = "utf8" + source = source[3:] + else: + # look at first two lines and check if PEP-263 coding is present + encoding, _ = find_python_encoding(source) + + try: + source_text = source.decode(encoding) + except LookupError as lookuperr: + raise DecodeError(str(lookuperr)) from lookuperr + return source_text + + +def read_py_file(path: str, read: Callable[[str], bytes]) -> list[str] | None: + """Try reading a Python file as list of source lines. + + Return None if something goes wrong. + """ + try: + source = read(path) + except OSError: + return None + else: + try: + source_lines = decode_python_encoding(source).splitlines() + except DecodeError: + return None + return source_lines + + +def trim_source_line(line: str, max_len: int, col: int, min_width: int) -> tuple[str, int]: + """Trim a line of source code to fit into max_len. + + Show 'min_width' characters on each side of 'col' (an error location). If either + start or end is trimmed, this is indicated by adding '...' there. + A typical result looks like this: + ...some_variable = function_to_call(one_arg, other_arg) or... + + Return the trimmed string and the column offset to adjust error location. + """ + if max_len < 2 * min_width + 1: + # In case the window is too tiny it is better to still show something. + max_len = 2 * min_width + 1 + + # Trivial case: line already fits in. + if len(line) <= max_len: + return line, 0 + + # If column is not too large so that there is still min_width after it, + # the line doesn't need to be trimmed at the start. + if col + min_width < max_len: + return line[:max_len] + "...", 0 + + # Otherwise, if the column is not too close to the end, trim both sides. + if col < len(line) - min_width - 1: + offset = col - max_len + min_width + 1 + return "..." + line[offset : col + min_width + 1] + "...", offset - 3 + + # Finally, if the column is near the end, just trim the start. + return "..." + line[-max_len:], len(line) - max_len - 3 + + +def get_mypy_comments(source: str) -> list[tuple[int, str]]: + PREFIX = "# mypy: " + # Don't bother splitting up the lines unless we know it is useful + if PREFIX not in source: + return [] + lines = source.split("\n") + results = [] + for i, line in enumerate(lines): + if line.startswith(PREFIX): + results.append((i + 1, line[len(PREFIX) :])) + + return results + + +JUNIT_HEADER_TEMPLATE: Final = """ + +""" + +JUNIT_TESTCASE_FAIL_TEMPLATE: Final = """ + {text} + +""" + +JUNIT_ERROR_TEMPLATE: Final = """ + {text} + +""" + +JUNIT_TESTCASE_PASS_TEMPLATE: Final = """ + +""" + +JUNIT_FOOTER: Final = """ +""" + + +def _generate_junit_contents( + dt: float, + serious: bool, + messages_by_file: dict[str | None, list[str]], + version: str, + platform: str, +) -> str: + from xml.sax.saxutils import escape + + if serious: + failures = 0 + errors = len(messages_by_file) + else: + failures = len(messages_by_file) + errors = 0 + + xml = JUNIT_HEADER_TEMPLATE.format( + errors=errors, + failures=failures, + time=dt, + # If there are no messages, we still write one "test" indicating success. + tests=len(messages_by_file) or 1, + ) + + if not messages_by_file: + xml += JUNIT_TESTCASE_PASS_TEMPLATE.format(time=dt, ver=version, platform=platform) + else: + for filename, messages in messages_by_file.items(): + if filename is not None: + xml += JUNIT_TESTCASE_FAIL_TEMPLATE.format( + text=escape("\n".join(messages)), + filename=filename, + time=dt, + name="mypy-py{ver}-{platform} {filename}".format( + ver=version, platform=platform, filename=filename + ), + ) + else: + xml += JUNIT_TESTCASE_FAIL_TEMPLATE.format( + text=escape("\n".join(messages)), + filename="mypy", + time=dt, + name=f"mypy-py{version}-{platform}", + ) + + xml += JUNIT_FOOTER + + return xml + + +def write_junit_xml( + dt: float, + serious: bool, + messages_by_file: dict[str | None, list[str]], + path: str, + version: str, + platform: str, +) -> None: + xml = _generate_junit_contents(dt, serious, messages_by_file, version, platform) + + # creates folders if needed + xml_dirs = os.path.dirname(os.path.abspath(path)) + os.makedirs(xml_dirs, exist_ok=True) + + with open(path, "wb") as f: + f.write(xml.encode("utf-8")) + + +class IdMapper: + """Generate integer ids for objects. + + Unlike id(), these start from 0 and increment by 1, and ids won't + get reused across the life-time of IdMapper. + + Assume objects don't redefine __eq__ or __hash__. + """ + + def __init__(self) -> None: + self.id_map: dict[object, int] = {} + self.next_id = 0 + + def id(self, o: object) -> int: + if o not in self.id_map: + self.id_map[o] = self.next_id + self.next_id += 1 + return self.id_map[o] + + +def get_prefix(fullname: str) -> str: + """Drop the final component of a qualified name (e.g. ('x.y' -> 'x').""" + return fullname.rsplit(".", 1)[0] + + +def correct_relative_import( + cur_mod_id: str, relative: int, target: str, is_cur_package_init_file: bool +) -> tuple[str, bool]: + if relative == 0: + return target, True + parts = cur_mod_id.split(".") + rel = relative + if is_cur_package_init_file: + rel -= 1 + ok = len(parts) >= rel + if rel != 0: + cur_mod_id = ".".join(parts[:-rel]) + return cur_mod_id + (("." + target) if target else ""), ok + + +fields_cache: Final[dict[type[object], list[str]]] = {} + + +def get_class_descriptors(cls: type[object]) -> Sequence[str]: + import inspect # Lazy import for minor startup speed win + + # Maintain a cache of type -> attributes defined by descriptors in the class + # (that is, attributes from __slots__ and C extension classes) + if cls not in fields_cache: + members = inspect.getmembers( + cls, lambda o: inspect.isgetsetdescriptor(o) or inspect.ismemberdescriptor(o) + ) + fields_cache[cls] = [x for x, y in members if x != "__weakref__" and x != "__dict__"] + return fields_cache[cls] + + +def replace_object_state( + new: object, old: object, copy_dict: bool = False, skip_slots: tuple[str, ...] = () +) -> None: + """Copy state of old node to the new node. + + This handles cases where there is __dict__ and/or attribute descriptors + (either from slots or because the type is defined in a C extension module). + + Assume that both objects have the same __class__. + """ + if hasattr(old, "__dict__"): + if copy_dict: + new.__dict__ = dict(old.__dict__) + else: + new.__dict__ = old.__dict__ + + for attr in get_class_descriptors(old.__class__): + if attr in skip_slots: + continue + try: + if hasattr(old, attr): + setattr(new, attr, getattr(old, attr)) + elif hasattr(new, attr): + delattr(new, attr) + # There is no way to distinguish getsetdescriptors that allow + # writes from ones that don't (I think?), so we just ignore + # AttributeErrors if we need to. + # TODO: What about getsetdescriptors that act like properties??? + except AttributeError: + pass + + +def is_sub_path_normabs(path: str, dir: str) -> bool: + """Given two paths, return if path is a sub-path of dir. + + Moral equivalent of: Path(dir) in Path(path).parents + + Similar to the pathlib version: + - Treats paths case-sensitively + - Does not fully handle unnormalised paths (e.g. paths with "..") + - Does not handle a mix of absolute and relative paths + Unlike the pathlib version: + - Fast + - On Windows, assumes input has been slash normalised + - Handles even fewer unnormalised paths (e.g. paths with "." and "//") + + As a result, callers should ensure that inputs have had os.path.abspath called on them + (note that os.path.abspath will normalise) + """ + if not dir.endswith(os.sep): + dir += os.sep + return path.startswith(dir) + + +if sys.platform == "linux" or sys.platform == "darwin": + + def os_path_join(path: str, b: str) -> str: + # Based off of os.path.join, but simplified to str-only, 2 args and mypyc can compile it. + if b.startswith("/") or not path: + return b + elif path.endswith("/"): + return path + b + else: + return path + "/" + b + +else: + + def os_path_join(a: str, p: str) -> str: + return os.path.join(a, p) + + +def hard_exit(status: int = 0) -> None: + """Kill the current process without fully cleaning up. + + This can be quite a bit faster than a normal exit() since objects are not freed. + """ + sys.stdout.flush() + sys.stderr.flush() + os._exit(status) + + +def unmangle(name: str) -> str: + """Remove internal suffixes from a short name.""" + return name.rstrip("'") + + +def get_unique_redefinition_name(name: str, existing: Container[str]) -> str: + """Get a simple redefinition name not present among existing. + + For example, for name 'foo' we try 'foo-redefinition', 'foo-redefinition2', + 'foo-redefinition3', etc. until we find one that is not in existing. + """ + r_name = name + "-redefinition" + if r_name not in existing: + return r_name + + i = 2 + while r_name + str(i) in existing: + i += 1 + return r_name + str(i) + + +def check_python_version(program: str) -> None: + """Report issues with the Python used to run mypy, dmypy, or stubgen""" + # Check for known bad Python versions. + if sys.version_info[:2] < (3, 10): # noqa: UP036, RUF100 + sys.exit( + "Running {name} with Python 3.9 or lower is not supported; " + "please upgrade to 3.10 or newer".format(name=program) + ) + + +def count_stats(messages: list[str]) -> tuple[int, int, int]: + """Count total number of errors, notes and error_files in message list.""" + errors = [e for e in messages if ": error:" in e] + error_files = {e.split(":")[0] for e in errors} + notes = [e for e in messages if ": note:" in e] + return len(errors), len(notes), len(error_files) + + +def split_words(msg: str) -> list[str]: + """Split line of text into words (but not within quoted groups).""" + next_word = "" + res: list[str] = [] + allow_break = True + for c in msg: + if c == " " and allow_break: + res.append(next_word) + next_word = "" + continue + if c == '"': + allow_break = not allow_break + next_word += c + res.append(next_word) + return res + + +def get_terminal_width() -> int: + """Get current terminal width if possible, otherwise return the default one.""" + return ( + int(os.getenv("MYPY_FORCE_TERMINAL_WIDTH", "0")) + or shutil.get_terminal_size().columns + or DEFAULT_COLUMNS + ) + + +def soft_wrap(msg: str, max_len: int, first_offset: int, num_indent: int = 0) -> str: + """Wrap a long error message into few lines. + + Breaks will only happen between words, and never inside a quoted group + (to avoid breaking types such as "Union[int, str]"). The 'first_offset' is + the width before the start of first line. + + Pad every next line with 'num_indent' spaces. Every line will be at most 'max_len' + characters, except if it is a single word or quoted group. + + For example: + first_offset + ------------------------ + path/to/file: error: 58: Some very long error message + that needs to be split in separate lines. + "Long[Type, Names]" are never split. + ^^^^-------------------------------------------------- + num_indent max_len + """ + words = split_words(msg) + next_line = words.pop(0) + lines: list[str] = [] + while words: + next_word = words.pop(0) + max_line_len = max_len - num_indent if lines else max_len - first_offset + # Add 1 to account for space between words. + if len(next_line) + len(next_word) + 1 <= max_line_len: + next_line += " " + next_word + else: + lines.append(next_line) + next_line = next_word + lines.append(next_line) + padding = "\n" + " " * num_indent + return padding.join(lines) + + +def hash_digest(data: bytes) -> str: + """Compute a hash digest of some data. + + We use a cryptographic hash because we want a low probability of + accidental collision, but we don't really care about any of the + cryptographic properties. + """ + return hashlib.sha1(data).hexdigest() + + +def hash_digest_bytes(data: bytes) -> bytes: + """Compute a hash digest of some data. + + Similar to above but returns a bytes object. + """ + return hashlib.sha1(data).digest() + + +def parse_gray_color(cup: bytes) -> str: + """Reproduce a gray color in ANSI escape sequence""" + assert sys.platform != "win32", "curses is not available on Windows" + set_color = "".join([cup[:-1].decode(), "m"]) + gray = curses.tparm(set_color.encode("utf-8"), 1, 9).decode() + return gray + + +def should_force_color() -> bool: + env_var = os.getenv("MYPY_FORCE_COLOR", os.getenv("FORCE_COLOR", "0")) + try: + return bool(int(env_var)) + except ValueError: + return bool(env_var) + + +class FancyFormatter: + """Apply color and bold font to terminal output. + + This currently only works on Linux and Mac. + """ + + def __init__( + self, f_out: IO[str], f_err: IO[str], hide_error_codes: bool, hide_success: bool = False + ) -> None: + self.hide_error_codes = hide_error_codes + self.hide_success = hide_success + + # Check if we are in a human-facing terminal on a supported platform. + if sys.platform not in ("linux", "darwin", "win32", "emscripten"): + self.dummy_term = True + return + if not should_force_color() and (not f_out.isatty() or not f_err.isatty()): + self.dummy_term = True + return + if sys.platform == "win32": + self.dummy_term = not self.initialize_win_colors() + elif sys.platform == "emscripten": + self.dummy_term = not self.initialize_vt100_colors() + else: + self.dummy_term = not self.initialize_unix_colors() + if not self.dummy_term: + self.colors = { + "red": self.RED, + "green": self.GREEN, + "blue": self.BLUE, + "yellow": self.YELLOW, + "none": "", + } + + def initialize_vt100_colors(self) -> bool: + """Return True if initialization was successful and we can use colors, False otherwise""" + # Windows and Emscripten can both use ANSI/VT100 escape sequences for color + assert sys.platform in ("win32", "emscripten") + self.BOLD = "\033[1m" + self.UNDER = "\033[4m" + self.BLUE = "\033[94m" + self.GREEN = "\033[92m" + self.RED = "\033[91m" + self.YELLOW = "\033[93m" + self.NORMAL = "\033[0m" + self.DIM = "\033[2m" + return True + + def initialize_win_colors(self) -> bool: + """Return True if initialization was successful and we can use colors, False otherwise""" + # Windows ANSI escape sequences are only supported on Threshold 2 and above. + # we check with an assert at runtime and an if check for mypy, as asserts do not + # yet narrow platform + if sys.platform == "win32": # needed to find win specific sys apis + winver = sys.getwindowsversion() + if ( + winver.major < MINIMUM_WINDOWS_MAJOR_VT100 + or winver.build < MINIMUM_WINDOWS_BUILD_VT100 + ): + return False + import ctypes + + kernel32 = ctypes.windll.kernel32 + ENABLE_PROCESSED_OUTPUT = 0x1 + ENABLE_WRAP_AT_EOL_OUTPUT = 0x2 + ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4 + STD_OUTPUT_HANDLE = -11 + kernel32.SetConsoleMode( + kernel32.GetStdHandle(STD_OUTPUT_HANDLE), + ENABLE_PROCESSED_OUTPUT + | ENABLE_WRAP_AT_EOL_OUTPUT + | ENABLE_VIRTUAL_TERMINAL_PROCESSING, + ) + self.initialize_vt100_colors() + return True + assert False, "Running not on Windows" + + def initialize_unix_colors(self) -> bool: + """Return True if initialization was successful and we can use colors, False otherwise""" + is_win = sys.platform == "win32" + if is_win or not CURSES_ENABLED: + return False + try: + # setupterm wants a fd to potentially write an "initialization sequence". + # We override sys.stdout for the daemon API so if stdout doesn't have an fd, + # just give it /dev/null. + try: + fd = sys.stdout.fileno() + except io.UnsupportedOperation: + with open("/dev/null", "rb") as f: + curses.setupterm(fd=f.fileno()) + else: + curses.setupterm(fd=fd) + except curses.error: + # Most likely terminfo not found. + return False + bold = curses.tigetstr("bold") + under = curses.tigetstr("smul") + set_color = curses.tigetstr("setaf") + set_eseq = curses.tigetstr("cup") + normal = curses.tigetstr("sgr0") + + if not (bold and under and set_color and set_eseq and normal): + return False + + self.NORMAL = normal.decode() + self.BOLD = bold.decode() + self.UNDER = under.decode() + self.DIM = parse_gray_color(set_eseq) + self.BLUE = curses.tparm(set_color, curses.COLOR_BLUE).decode() + self.GREEN = curses.tparm(set_color, curses.COLOR_GREEN).decode() + self.RED = curses.tparm(set_color, curses.COLOR_RED).decode() + self.YELLOW = curses.tparm(set_color, curses.COLOR_YELLOW).decode() + return True + + def style( + self, + text: str, + color: Literal["red", "green", "blue", "yellow", "none"], + bold: bool = False, + underline: bool = False, + dim: bool = False, + ) -> str: + """Apply simple color and style (underlined or bold).""" + if self.dummy_term: + return text + if bold: + start = self.BOLD + else: + start = "" + if underline: + start += self.UNDER + if dim: + start += self.DIM + return start + self.colors[color] + text + self.NORMAL + + def is_marker_line(self, line: str) -> bool: + s_line = line.lstrip() + return ( + line.startswith(CODE_START) + and s_line.startswith("^") + and set(s_line).issubset({"^", "~"}) + ) + + def fit_in_terminal( + self, messages: list[str], fixed_terminal_width: int | None = None + ) -> list[str]: + """Improve readability by wrapping error messages and trimming source code.""" + width = fixed_terminal_width or get_terminal_width() + new_messages = messages.copy() + for i, error in enumerate(messages): + # TODO: detecting source code highlights through an indent can be surprising. + if not error.startswith(CODE_START) and ": error:" in error: + loc, msg = error.split("error:", maxsplit=1) + msg = soft_wrap(msg, width, first_offset=len(loc) + len("error: ")) + new_messages[i] = loc + "error:" + msg + elif error.startswith(CODE_START) and not self.is_marker_line(error): + # Restore original error message and error location. + error = error[DEFAULT_SOURCE_OFFSET:] + marker_line = messages[i + 1] + marker_column = marker_line.index("^") + column = marker_column - DEFAULT_SOURCE_OFFSET + if "~" not in marker_line: + marker = "^" + else: + # +1 because both ends are included + marker = marker_line[marker_column : marker_line.rindex("~") + 1] + + # Let source have some space also on the right side, plus 6 + # to accommodate ... on each side. + max_len = width - DEFAULT_SOURCE_OFFSET - 6 + source_line, offset = trim_source_line(error, max_len, column, MINIMUM_WIDTH) + + new_messages[i] = " " * DEFAULT_SOURCE_OFFSET + source_line + # Also adjust the error marker position and trim error marker is needed. + new_marker_line = " " * (DEFAULT_SOURCE_OFFSET + column - offset) + marker + if len(new_marker_line) > len(new_messages[i]) and len(marker) > 3: + new_marker_line = new_marker_line[: len(new_messages[i]) - 3] + "..." + new_messages[i + 1] = new_marker_line + return new_messages + + def colorize(self, error: str) -> str: + """Colorize an output line by highlighting the status and error code.""" + # TODO: detecting source code highlights through an indent can be surprising. + if error.startswith(CODE_START): + if not self.is_marker_line(error): + return self.style(error, "none", dim=True) + return self.style(error, "red") + elif ": error:" in error: + loc, msg = error.split("error:", maxsplit=1) + if self.hide_error_codes: + return ( + loc + self.style("error:", "red", bold=True) + self.highlight_quote_groups(msg) + ) + codepos = msg.rfind("[") + if codepos != -1: + code = msg[codepos:] + msg = msg[:codepos] + else: + code = "" # no error code specified + return ( + loc + + self.style("error:", "red", bold=True) + + self.highlight_quote_groups(msg) + + self.style(code, "yellow") + ) + elif ": note:" in error: + loc, msg = error.split("note:", maxsplit=1) + formatted = self.highlight_quote_groups(self.underline_link(msg)) + return loc + self.style("note:", "blue") + formatted + else: + return error + + def highlight_quote_groups(self, msg: str) -> str: + """Make groups quoted with double quotes bold (including quotes). + + This is used to highlight types, attribute names etc. + """ + if msg.count('"') % 2: + # Broken error message, don't do any formatting. + return msg + parts = msg.split('"') + out = "" + for i, part in enumerate(parts): + if i % 2 == 0: + out += self.style(part, "none") + else: + out += self.style('"' + part + '"', "none", bold=True) + return out + + def underline_link(self, note: str) -> str: + """Underline a link in a note message (if any). + + This assumes there is at most one link in the message. + """ + match = re.search(r"https?://\S*", note) + if not match: + return note + start = match.start() + end = match.end() + return note[:start] + self.style(note[start:end], "none", underline=True) + note[end:] + + def format_success(self, n_sources: int, use_color: bool = True) -> str: + """Format short summary in case of success. + + n_sources is total number of files passed directly on command line, + i.e. excluding stubs and followed imports. + """ + if self.hide_success: + return "" + + msg = f"Success: no issues found in {n_sources} source file{plural_s(n_sources)}" + if not use_color: + return msg + return self.style(msg, "green", bold=True) + + def format_error( + self, + n_errors: int, + n_files: int, + n_sources: int, + *, + blockers: bool = False, + use_color: bool = True, + ) -> str: + """Format a short summary in case of errors.""" + msg = f"Found {n_errors} error{plural_s(n_errors)} in {n_files} file{plural_s(n_files)}" + if blockers: + msg += " (errors prevented further checking)" + else: + msg += f" (checked {n_sources} source file{plural_s(n_sources)})" + if not use_color: + return msg + return self.style(msg, "red", bold=True) + + +def is_typeshed_file(typeshed_dir: str | None, file: str) -> bool: + typeshed_dir = typeshed_dir if typeshed_dir is not None else TYPESHED_DIR + try: + return os.path.commonpath((typeshed_dir, os.path.abspath(file))) == typeshed_dir + except ValueError: # Different drives on Windows + return False + + +def is_stdlib_file(typeshed_dir: str | None, file: str) -> bool: + if "stdlib" not in file: + # Fast path + return False + typeshed_dir = typeshed_dir if typeshed_dir is not None else TYPESHED_DIR + stdlib_dir = os.path.join(typeshed_dir, "stdlib") + try: + return os.path.commonpath((stdlib_dir, os.path.abspath(file))) == stdlib_dir + except ValueError: # Different drives on Windows + return False + + +def is_stub_package_file(file: str) -> bool: + # Use hacky heuristics to check whether file is part of a PEP 561 stub package. + if not file.endswith(".pyi"): + return False + return any(component.endswith("-stubs") for component in os.path.split(os.path.abspath(file))) + + +def unnamed_function(name: str | None) -> bool: + return name is not None and name == "_" + + +time_ref = time.perf_counter_ns + + +def time_spent_us(t0: int) -> int: + return int((time.perf_counter_ns() - t0) / 1000) + + +def plural_s(s: int | Sized) -> str: + count = s if isinstance(s, int) else len(s) + if count != 1: + return "s" + else: + return "" + + +def quote_docstring(docstr: str) -> str: + """Returns docstring correctly encapsulated in a single or double quoted form.""" + # Uses repr to get hint on the correct quotes and escape everything properly. + # Creating multiline string for prettier output. + docstr_repr = "\n".join(re.split(r"(?<=[^\\])\\n", repr(docstr))) + + if docstr_repr.startswith("'"): + # Enforce double quotes when it's safe to do so. + # That is when double quotes are not in the string + # or when it doesn't end with a single quote. + if '"' not in docstr_repr[1:-1] and docstr_repr[-2] != "'": + return f'"""{docstr_repr[1:-1]}"""' + return f"''{docstr_repr}''" + else: + return f'""{docstr_repr}""' + + +def json_dumps(obj: object, debug: bool = False) -> bytes: + if orjson is not None: + if debug: + dumps_option = orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS + else: + # TODO: If we don't sort keys here, testIncrementalInternalScramble fails + # We should document exactly what is going on there + dumps_option = orjson.OPT_SORT_KEYS + + try: + return orjson.dumps(obj, option=dumps_option) # type: ignore[no-any-return] + except TypeError as e: + if str(e) != "Integer exceeds 64-bit range": + raise + + if debug: + return json.dumps(obj, indent=2, sort_keys=True).encode("utf-8") + else: + # See above for sort_keys comment + return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +def json_loads(data: bytes) -> Any: + if orjson is not None: + return orjson.loads(data) + return json.loads(data) diff --git a/micromamba_root/Lib/site-packages/mypy/version.py b/micromamba_root/Lib/site-packages/mypy/version.py new file mode 100644 index 0000000000000000000000000000000000000000..cd954b0f8e5579119866c434db923837e456e300 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/version.py @@ -0,0 +1 @@ +__version__ = "1.20.2" diff --git a/micromamba_root/Lib/site-packages/mypy/visitor.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypy/visitor.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..5ea2f0e28e84d234cb5e2f1b50657fb6913fcc88 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypy/visitor.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypy/visitor.py b/micromamba_root/Lib/site-packages/mypy/visitor.py new file mode 100644 index 0000000000000000000000000000000000000000..de754c408f97d767ddbdcbf0be44bdac2833f3a5 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy/visitor.py @@ -0,0 +1,639 @@ +"""Generic abstract syntax tree node visitor""" + +from __future__ import annotations + +from abc import abstractmethod +from typing import TYPE_CHECKING, Generic, TypeVar + +from mypy_extensions import mypyc_attr, trait + +if TYPE_CHECKING: + # break import cycle only needed for mypy + import mypy.nodes + import mypy.patterns + + +T = TypeVar("T") + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class ExpressionVisitor(Generic[T]): + @abstractmethod + def visit_int_expr(self, o: mypy.nodes.IntExpr, /) -> T: + pass + + @abstractmethod + def visit_str_expr(self, o: mypy.nodes.StrExpr, /) -> T: + pass + + @abstractmethod + def visit_bytes_expr(self, o: mypy.nodes.BytesExpr, /) -> T: + pass + + @abstractmethod + def visit_float_expr(self, o: mypy.nodes.FloatExpr, /) -> T: + pass + + @abstractmethod + def visit_complex_expr(self, o: mypy.nodes.ComplexExpr, /) -> T: + pass + + @abstractmethod + def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr, /) -> T: + pass + + @abstractmethod + def visit_star_expr(self, o: mypy.nodes.StarExpr, /) -> T: + pass + + @abstractmethod + def visit_name_expr(self, o: mypy.nodes.NameExpr, /) -> T: + pass + + @abstractmethod + def visit_member_expr(self, o: mypy.nodes.MemberExpr, /) -> T: + pass + + @abstractmethod + def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr, /) -> T: + pass + + @abstractmethod + def visit_yield_expr(self, o: mypy.nodes.YieldExpr, /) -> T: + pass + + @abstractmethod + def visit_call_expr(self, o: mypy.nodes.CallExpr, /) -> T: + pass + + @abstractmethod + def visit_op_expr(self, o: mypy.nodes.OpExpr, /) -> T: + pass + + @abstractmethod + def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr, /) -> T: + pass + + @abstractmethod + def visit_cast_expr(self, o: mypy.nodes.CastExpr, /) -> T: + pass + + @abstractmethod + def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr, /) -> T: + pass + + @abstractmethod + def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr, /) -> T: + pass + + @abstractmethod + def visit_reveal_expr(self, o: mypy.nodes.RevealExpr, /) -> T: + pass + + @abstractmethod + def visit_super_expr(self, o: mypy.nodes.SuperExpr, /) -> T: + pass + + @abstractmethod + def visit_unary_expr(self, o: mypy.nodes.UnaryExpr, /) -> T: + pass + + @abstractmethod + def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr, /) -> T: + pass + + @abstractmethod + def visit_list_expr(self, o: mypy.nodes.ListExpr, /) -> T: + pass + + @abstractmethod + def visit_dict_expr(self, o: mypy.nodes.DictExpr, /) -> T: + pass + + @abstractmethod + def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr, /) -> T: + pass + + @abstractmethod + def visit_tuple_expr(self, o: mypy.nodes.TupleExpr, /) -> T: + pass + + @abstractmethod + def visit_set_expr(self, o: mypy.nodes.SetExpr, /) -> T: + pass + + @abstractmethod + def visit_index_expr(self, o: mypy.nodes.IndexExpr, /) -> T: + pass + + @abstractmethod + def visit_type_application(self, o: mypy.nodes.TypeApplication, /) -> T: + pass + + @abstractmethod + def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr, /) -> T: + pass + + @abstractmethod + def visit_list_comprehension(self, o: mypy.nodes.ListComprehension, /) -> T: + pass + + @abstractmethod + def visit_set_comprehension(self, o: mypy.nodes.SetComprehension, /) -> T: + pass + + @abstractmethod + def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension, /) -> T: + pass + + @abstractmethod + def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr, /) -> T: + pass + + @abstractmethod + def visit_slice_expr(self, o: mypy.nodes.SliceExpr, /) -> T: + pass + + @abstractmethod + def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr, /) -> T: + pass + + @abstractmethod + def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr, /) -> T: + pass + + @abstractmethod + def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr, /) -> T: + pass + + @abstractmethod + def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr, /) -> T: + pass + + @abstractmethod + def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr, /) -> T: + pass + + @abstractmethod + def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr, /) -> T: + pass + + @abstractmethod + def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr, /) -> T: + pass + + @abstractmethod + def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr, /) -> T: + pass + + @abstractmethod + def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr, /) -> T: + pass + + @abstractmethod + def visit__promote_expr(self, o: mypy.nodes.PromoteExpr, /) -> T: + pass + + @abstractmethod + def visit_await_expr(self, o: mypy.nodes.AwaitExpr, /) -> T: + pass + + @abstractmethod + def visit_temp_node(self, o: mypy.nodes.TempNode, /) -> T: + pass + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class StatementVisitor(Generic[T]): + # Definitions + + @abstractmethod + def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt, /) -> T: + pass + + @abstractmethod + def visit_for_stmt(self, o: mypy.nodes.ForStmt, /) -> T: + pass + + @abstractmethod + def visit_with_stmt(self, o: mypy.nodes.WithStmt, /) -> T: + pass + + @abstractmethod + def visit_del_stmt(self, o: mypy.nodes.DelStmt, /) -> T: + pass + + @abstractmethod + def visit_func_def(self, o: mypy.nodes.FuncDef, /) -> T: + pass + + @abstractmethod + def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef, /) -> T: + pass + + @abstractmethod + def visit_class_def(self, o: mypy.nodes.ClassDef, /) -> T: + pass + + @abstractmethod + def visit_global_decl(self, o: mypy.nodes.GlobalDecl, /) -> T: + pass + + @abstractmethod + def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl, /) -> T: + pass + + @abstractmethod + def visit_decorator(self, o: mypy.nodes.Decorator, /) -> T: + pass + + # Module structure + + @abstractmethod + def visit_import(self, o: mypy.nodes.Import, /) -> T: + pass + + @abstractmethod + def visit_import_from(self, o: mypy.nodes.ImportFrom, /) -> T: + pass + + @abstractmethod + def visit_import_all(self, o: mypy.nodes.ImportAll, /) -> T: + pass + + # Statements + + @abstractmethod + def visit_block(self, o: mypy.nodes.Block, /) -> T: + pass + + @abstractmethod + def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt, /) -> T: + pass + + @abstractmethod + def visit_operator_assignment_stmt(self, o: mypy.nodes.OperatorAssignmentStmt, /) -> T: + pass + + @abstractmethod + def visit_while_stmt(self, o: mypy.nodes.WhileStmt, /) -> T: + pass + + @abstractmethod + def visit_return_stmt(self, o: mypy.nodes.ReturnStmt, /) -> T: + pass + + @abstractmethod + def visit_assert_stmt(self, o: mypy.nodes.AssertStmt, /) -> T: + pass + + @abstractmethod + def visit_if_stmt(self, o: mypy.nodes.IfStmt, /) -> T: + pass + + @abstractmethod + def visit_break_stmt(self, o: mypy.nodes.BreakStmt, /) -> T: + pass + + @abstractmethod + def visit_continue_stmt(self, o: mypy.nodes.ContinueStmt, /) -> T: + pass + + @abstractmethod + def visit_pass_stmt(self, o: mypy.nodes.PassStmt, /) -> T: + pass + + @abstractmethod + def visit_raise_stmt(self, o: mypy.nodes.RaiseStmt, /) -> T: + pass + + @abstractmethod + def visit_try_stmt(self, o: mypy.nodes.TryStmt, /) -> T: + pass + + @abstractmethod + def visit_match_stmt(self, o: mypy.nodes.MatchStmt, /) -> T: + pass + + @abstractmethod + def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt, /) -> T: + pass + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class PatternVisitor(Generic[T]): + @abstractmethod + def visit_as_pattern(self, o: mypy.patterns.AsPattern, /) -> T: + pass + + @abstractmethod + def visit_or_pattern(self, o: mypy.patterns.OrPattern, /) -> T: + pass + + @abstractmethod + def visit_value_pattern(self, o: mypy.patterns.ValuePattern, /) -> T: + pass + + @abstractmethod + def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern, /) -> T: + pass + + @abstractmethod + def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern, /) -> T: + pass + + @abstractmethod + def visit_starred_pattern(self, o: mypy.patterns.StarredPattern, /) -> T: + pass + + @abstractmethod + def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern, /) -> T: + pass + + @abstractmethod + def visit_class_pattern(self, o: mypy.patterns.ClassPattern, /) -> T: + pass + + +@trait +@mypyc_attr(allow_interpreted_subclasses=True) +class NodeVisitor(Generic[T], ExpressionVisitor[T], StatementVisitor[T], PatternVisitor[T]): + """Empty base class for parse tree node visitors. + + The T type argument specifies the return type of the visit + methods. As all methods defined here raise by default, + subclasses do not always need to override all the methods. + """ + + # Not in superclasses: + + def visit_mypy_file(self, o: mypy.nodes.MypyFile, /) -> T: + raise NotImplementedError() + + # TODO: We have a visit_var method, but no visit_typeinfo or any + # other non-Statement SymbolNode (accepting those will raise a + # runtime error). Maybe this should be resolved in some direction. + def visit_var(self, o: mypy.nodes.Var, /) -> T: + raise NotImplementedError() + + # Module structure + + def visit_import(self, o: mypy.nodes.Import, /) -> T: + raise NotImplementedError() + + def visit_import_from(self, o: mypy.nodes.ImportFrom, /) -> T: + raise NotImplementedError() + + def visit_import_all(self, o: mypy.nodes.ImportAll, /) -> T: + raise NotImplementedError() + + # Definitions + + def visit_func_def(self, o: mypy.nodes.FuncDef, /) -> T: + raise NotImplementedError() + + def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef, /) -> T: + raise NotImplementedError() + + def visit_class_def(self, o: mypy.nodes.ClassDef, /) -> T: + raise NotImplementedError() + + def visit_global_decl(self, o: mypy.nodes.GlobalDecl, /) -> T: + raise NotImplementedError() + + def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl, /) -> T: + raise NotImplementedError() + + def visit_decorator(self, o: mypy.nodes.Decorator, /) -> T: + raise NotImplementedError() + + def visit_type_alias(self, o: mypy.nodes.TypeAlias, /) -> T: + raise NotImplementedError() + + def visit_placeholder_node(self, o: mypy.nodes.PlaceholderNode, /) -> T: + raise NotImplementedError() + + # Statements + + def visit_block(self, o: mypy.nodes.Block, /) -> T: + raise NotImplementedError() + + def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt, /) -> T: + raise NotImplementedError() + + def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt, /) -> T: + raise NotImplementedError() + + def visit_operator_assignment_stmt(self, o: mypy.nodes.OperatorAssignmentStmt, /) -> T: + raise NotImplementedError() + + def visit_while_stmt(self, o: mypy.nodes.WhileStmt, /) -> T: + raise NotImplementedError() + + def visit_for_stmt(self, o: mypy.nodes.ForStmt, /) -> T: + raise NotImplementedError() + + def visit_return_stmt(self, o: mypy.nodes.ReturnStmt, /) -> T: + raise NotImplementedError() + + def visit_assert_stmt(self, o: mypy.nodes.AssertStmt, /) -> T: + raise NotImplementedError() + + def visit_del_stmt(self, o: mypy.nodes.DelStmt, /) -> T: + raise NotImplementedError() + + def visit_if_stmt(self, o: mypy.nodes.IfStmt, /) -> T: + raise NotImplementedError() + + def visit_break_stmt(self, o: mypy.nodes.BreakStmt, /) -> T: + raise NotImplementedError() + + def visit_continue_stmt(self, o: mypy.nodes.ContinueStmt, /) -> T: + raise NotImplementedError() + + def visit_pass_stmt(self, o: mypy.nodes.PassStmt, /) -> T: + raise NotImplementedError() + + def visit_raise_stmt(self, o: mypy.nodes.RaiseStmt, /) -> T: + raise NotImplementedError() + + def visit_try_stmt(self, o: mypy.nodes.TryStmt, /) -> T: + raise NotImplementedError() + + def visit_with_stmt(self, o: mypy.nodes.WithStmt, /) -> T: + raise NotImplementedError() + + def visit_match_stmt(self, o: mypy.nodes.MatchStmt, /) -> T: + raise NotImplementedError() + + def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt, /) -> T: + raise NotImplementedError() + + # Expressions (default no-op implementation) + + def visit_int_expr(self, o: mypy.nodes.IntExpr, /) -> T: + raise NotImplementedError() + + def visit_str_expr(self, o: mypy.nodes.StrExpr, /) -> T: + raise NotImplementedError() + + def visit_bytes_expr(self, o: mypy.nodes.BytesExpr, /) -> T: + raise NotImplementedError() + + def visit_float_expr(self, o: mypy.nodes.FloatExpr, /) -> T: + raise NotImplementedError() + + def visit_complex_expr(self, o: mypy.nodes.ComplexExpr, /) -> T: + raise NotImplementedError() + + def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr, /) -> T: + raise NotImplementedError() + + def visit_star_expr(self, o: mypy.nodes.StarExpr, /) -> T: + raise NotImplementedError() + + def visit_name_expr(self, o: mypy.nodes.NameExpr, /) -> T: + raise NotImplementedError() + + def visit_member_expr(self, o: mypy.nodes.MemberExpr, /) -> T: + raise NotImplementedError() + + def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr, /) -> T: + raise NotImplementedError() + + def visit_yield_expr(self, o: mypy.nodes.YieldExpr, /) -> T: + raise NotImplementedError() + + def visit_call_expr(self, o: mypy.nodes.CallExpr, /) -> T: + raise NotImplementedError() + + def visit_op_expr(self, o: mypy.nodes.OpExpr, /) -> T: + raise NotImplementedError() + + def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr, /) -> T: + raise NotImplementedError() + + def visit_cast_expr(self, o: mypy.nodes.CastExpr, /) -> T: + raise NotImplementedError() + + def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr, /) -> T: + raise NotImplementedError() + + def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr, /) -> T: + raise NotImplementedError() + + def visit_reveal_expr(self, o: mypy.nodes.RevealExpr, /) -> T: + raise NotImplementedError() + + def visit_super_expr(self, o: mypy.nodes.SuperExpr, /) -> T: + raise NotImplementedError() + + def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr, /) -> T: + raise NotImplementedError() + + def visit_unary_expr(self, o: mypy.nodes.UnaryExpr, /) -> T: + raise NotImplementedError() + + def visit_list_expr(self, o: mypy.nodes.ListExpr, /) -> T: + raise NotImplementedError() + + def visit_dict_expr(self, o: mypy.nodes.DictExpr, /) -> T: + raise NotImplementedError() + + def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr, /) -> T: + raise NotImplementedError() + + def visit_tuple_expr(self, o: mypy.nodes.TupleExpr, /) -> T: + raise NotImplementedError() + + def visit_set_expr(self, o: mypy.nodes.SetExpr, /) -> T: + raise NotImplementedError() + + def visit_index_expr(self, o: mypy.nodes.IndexExpr, /) -> T: + raise NotImplementedError() + + def visit_type_application(self, o: mypy.nodes.TypeApplication, /) -> T: + raise NotImplementedError() + + def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr, /) -> T: + raise NotImplementedError() + + def visit_list_comprehension(self, o: mypy.nodes.ListComprehension, /) -> T: + raise NotImplementedError() + + def visit_set_comprehension(self, o: mypy.nodes.SetComprehension, /) -> T: + raise NotImplementedError() + + def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension, /) -> T: + raise NotImplementedError() + + def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr, /) -> T: + raise NotImplementedError() + + def visit_slice_expr(self, o: mypy.nodes.SliceExpr, /) -> T: + raise NotImplementedError() + + def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr, /) -> T: + raise NotImplementedError() + + def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr, /) -> T: + raise NotImplementedError() + + def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr, /) -> T: + raise NotImplementedError() + + def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr, /) -> T: + raise NotImplementedError() + + def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr, /) -> T: + raise NotImplementedError() + + def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr, /) -> T: + raise NotImplementedError() + + def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr, /) -> T: + raise NotImplementedError() + + def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr, /) -> T: + raise NotImplementedError() + + def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr, /) -> T: + raise NotImplementedError() + + def visit__promote_expr(self, o: mypy.nodes.PromoteExpr, /) -> T: + raise NotImplementedError() + + def visit_await_expr(self, o: mypy.nodes.AwaitExpr, /) -> T: + raise NotImplementedError() + + def visit_temp_node(self, o: mypy.nodes.TempNode, /) -> T: + raise NotImplementedError() + + # Patterns + + def visit_as_pattern(self, o: mypy.patterns.AsPattern, /) -> T: + raise NotImplementedError() + + def visit_or_pattern(self, o: mypy.patterns.OrPattern, /) -> T: + raise NotImplementedError() + + def visit_value_pattern(self, o: mypy.patterns.ValuePattern, /) -> T: + raise NotImplementedError() + + def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern, /) -> T: + raise NotImplementedError() + + def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern, /) -> T: + raise NotImplementedError() + + def visit_starred_pattern(self, o: mypy.patterns.StarredPattern, /) -> T: + raise NotImplementedError() + + def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern, /) -> T: + raise NotImplementedError() + + def visit_class_pattern(self, o: mypy.patterns.ClassPattern, /) -> T: + raise NotImplementedError() diff --git a/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/INSTALLER b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/INSTALLER @@ -0,0 +1 @@ +conda \ No newline at end of file diff --git a/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/METADATA b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..abe8c62e817b4c97fa1d7e84d47ea958d5dc451a --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/METADATA @@ -0,0 +1,29 @@ +Metadata-Version: 2.4 +Name: mypy_extensions +Version: 1.1.0 +Summary: Type system extensions for programs checked with the mypy type checker. +Author-email: The mypy developers +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-Expression: MIT +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Software Development +License-File: LICENSE +Project-URL: Homepage, https://github.com/python/mypy_extensions + +Mypy Extensions +=============== + +The `mypy_extensions` module defines extensions to the Python standard +library `typing` module that are supported by the mypy type checker and +the mypyc compiler. + diff --git a/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/RECORD b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..28a74646889072770beb972efd39a8bfb9a7592e --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/RECORD @@ -0,0 +1,9 @@ +__pycache__/mypy_extensions.cpython-39.pyc,, +mypy_extensions-1.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +mypy_extensions-1.1.0.dist-info/METADATA,sha256=LEpEk22IXzBDMYHKQLv2JFc1Hx9rCHGxH4eJVk-HR38,1100 +mypy_extensions-1.1.0.dist-info/RECORD,, +mypy_extensions-1.1.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +mypy_extensions-1.1.0.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +mypy_extensions-1.1.0.dist-info/direct_url.json,sha256=YT4sV3bFjZD9ZNH74WrVBFhn60PBGamgTZODv4VEnl8,111 +mypy_extensions-1.1.0.dist-info/licenses/LICENSE,sha256=pQRQ2h1TzXd7gM7XfFj_lqvgzNh5cGvRQsPsIOJF8LQ,1204 +mypy_extensions.py,sha256=GY7iLl2lPqbLD90PTm2U_SxA4MavvwvzpM8MESYgqRk,7754 diff --git a/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/REQUESTED b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/WHEEL b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/direct_url.json b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..2ea746ef3882b45afedab7446c3c86cc80039ec9 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypy_extensions-1.1.0.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/conda/feedstock_root/build_artifacts/mypy_extensions_1745776566517/work"} \ No newline at end of file diff --git a/micromamba_root/Lib/site-packages/mypyc/__init__.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/__init__.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..f88f94b98530986c66fad1bd0276af380cde0ae3 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/__init__.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/__init__.py b/micromamba_root/Lib/site-packages/mypyc/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/Lib/site-packages/mypyc/__main__.py b/micromamba_root/Lib/site-packages/mypyc/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..9b3973710efac36fbb129f5c0ff7dacc4ff5e5d0 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/__main__.py @@ -0,0 +1,72 @@ +"""Mypyc command-line tool. + +Usage: + + $ mypyc foo.py [...] + $ python3 -c 'import foo' # Uses compiled 'foo' + + +This is just a thin wrapper that generates a setup.py file that uses +mypycify, suitable for prototyping and testing. +""" + +from __future__ import annotations + +import os +import os.path +import subprocess +import sys + +base_path = os.path.join(os.path.dirname(__file__), "..") + +setup_format = """\ +from setuptools import setup +from mypyc.build import mypycify + +setup( + name='mypyc_output', + ext_modules=mypycify( + {}, + opt_level="{}", + debug_level="{}", + strict_dunder_typing={}, + log_trace={}, + ), +) +""" + + +def main() -> None: + build_dir = "build" # can this be overridden?? + try: + os.mkdir(build_dir) + except FileExistsError: + pass + + opt_level = os.getenv("MYPYC_OPT_LEVEL", "3") + debug_level = os.getenv("MYPYC_DEBUG_LEVEL", "1") + strict_dunder_typing = bool(int(os.getenv("MYPYC_STRICT_DUNDER_TYPING", "0"))) + # If enabled, compiled code writes a sampled log of executed ops (or events) to + # mypyc_trace.txt. + log_trace = bool(int(os.getenv("MYPYC_LOG_TRACE", "0"))) + + setup_file = os.path.join(build_dir, "setup.py") + with open(setup_file, "w") as f: + f.write( + setup_format.format( + sys.argv[1:], opt_level, debug_level, strict_dunder_typing, log_trace + ) + ) + + # We don't use run_setup (like we do in the test suite) because it throws + # away the error code from distutils, and we don't care about the slight + # performance loss here. + env = os.environ.copy() + base_path = os.path.join(os.path.dirname(__file__), "..") + env["PYTHONPATH"] = base_path + os.pathsep + env.get("PYTHONPATH", "") + cmd = subprocess.run([sys.executable, setup_file, "build_ext", "--inplace"], env=env) + sys.exit(cmd.returncode) + + +if __name__ == "__main__": + main() diff --git a/micromamba_root/Lib/site-packages/mypyc/annotate.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/annotate.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..76ca0dc71555556689182af4a69639d76ec25b96 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/annotate.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/annotate.py b/micromamba_root/Lib/site-packages/mypyc/annotate.py new file mode 100644 index 0000000000000000000000000000000000000000..bc282fc3ea6c137d5b069fe3b9cdd05a523b99c0 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/annotate.py @@ -0,0 +1,472 @@ +"""Generate source code formatted as HTML, with bottlenecks annotated and highlighted. + +Various heuristics are used to detect common issues that cause slower than +expected performance. +""" + +from __future__ import annotations + +import os.path +import sys +from html import escape +from typing import Final + +from mypy.build import BuildResult +from mypy.nodes import ( + AssignmentStmt, + CallExpr, + ClassDef, + Decorator, + DictionaryComprehension, + Expression, + ForStmt, + FuncDef, + GeneratorExpr, + IndexExpr, + LambdaExpr, + MemberExpr, + MypyFile, + NamedTupleExpr, + NameExpr, + NewTypeExpr, + Node, + OpExpr, + RefExpr, + TupleExpr, + TypedDictExpr, + TypeInfo, + TypeVarExpr, + Var, + WithStmt, +) +from mypy.traverser import TraverserVisitor +from mypy.types import AnyType, Instance, ProperType, Type, TypeOfAny, get_proper_type +from mypy.util import FancyFormatter +from mypyc.ir.func_ir import FuncIR +from mypyc.ir.module_ir import ModuleIR +from mypyc.ir.ops import CallC, LoadLiteral, LoadStatic, Value +from mypyc.irbuild.mapper import Mapper + + +class Annotation: + """HTML annotation for compiled source code""" + + def __init__(self, message: str, priority: int = 1) -> None: + # Message as HTML that describes an issue and/or how to fix it. + # Multiple messages on a line may be concatenated. + self.message = message + # If multiple annotations are generated for a single line, only report + # the highest-priority ones. Some use cases generate multiple annotations, + # and this can be used to reduce verbosity by hiding the lower-priority + # ones. + self.priority = priority + + +op_hints: Final = { + "PyNumber_Add": Annotation('Generic "+" operation.'), + "PyNumber_Subtract": Annotation('Generic "-" operation.'), + "PyNumber_Multiply": Annotation('Generic "*" operation.'), + "PyNumber_TrueDivide": Annotation('Generic "/" operation.'), + "PyNumber_FloorDivide": Annotation('Generic "//" operation.'), + "PyNumber_Positive": Annotation('Generic unary "+" operation.'), + "PyNumber_Negative": Annotation('Generic unary "-" operation.'), + "PyNumber_And": Annotation('Generic "&" operation.'), + "PyNumber_Or": Annotation('Generic "|" operation.'), + "PyNumber_Xor": Annotation('Generic "^" operation.'), + "PyNumber_Lshift": Annotation('Generic "<<" operation.'), + "PyNumber_Rshift": Annotation('Generic ">>" operation.'), + "PyNumber_Invert": Annotation('Generic "~" operation.'), + "PyObject_Call": Annotation("Generic call operation."), + "PyObject_CallObject": Annotation("Generic call operation."), + "PyObject_RichCompare": Annotation("Generic comparison operation."), + "PyObject_GetItem": Annotation("Generic indexing operation."), + "PyObject_SetItem": Annotation("Generic indexed assignment."), +} + +stdlib_hints: Final = { + "functools.partial": Annotation( + '"functools.partial" is inefficient in compiled code.', priority=3 + ), + "itertools.chain": Annotation( + '"itertools.chain" is inefficient in compiled code (hint: replace with for loops).', + priority=3, + ), + "itertools.groupby": Annotation( + '"itertools.groupby" is inefficient in compiled code.', priority=3 + ), + "itertools.islice": Annotation( + '"itertools.islice" is inefficient in compiled code (hint: replace with for loop over index range).', + priority=3, + ), + "copy.deepcopy": Annotation( + '"copy.deepcopy" tends to be slow. Make a shallow copy if possible.', priority=2 + ), +} + +CSS = """\ +.collapsible { + cursor: pointer; +} + +.content { + display: block; + margin-top: 10px; + margin-bottom: 10px; +} + +.hint { + display: inline; + border: 1px solid #ccc; + padding: 5px; +} +""" + +JS = """\ +document.querySelectorAll('.collapsible').forEach(function(collapsible) { + collapsible.addEventListener('click', function() { + const content = this.nextElementSibling; + if (content.style.display === 'none') { + content.style.display = 'block'; + } else { + content.style.display = 'none'; + } + }); +}); +""" + + +class AnnotatedSource: + """Annotations for a single compiled source file.""" + + def __init__(self, path: str, annotations: dict[int, list[Annotation]]) -> None: + self.path = path + self.annotations = annotations + + +def generate_annotated_html( + html_fnam: str, result: BuildResult, modules: dict[str, ModuleIR], mapper: Mapper +) -> None: + annotations = [] + for mod, mod_ir in modules.items(): + path = result.graph[mod].path + tree = result.graph[mod].tree + assert tree is not None + annotations.append( + generate_annotations(path or "", tree, mod_ir, result.types, mapper) + ) + html = generate_html_report(annotations) + with open(html_fnam, "w") as f: + f.write(html) + + formatter = FancyFormatter(sys.stdout, sys.stderr, False) + formatted = formatter.style(os.path.abspath(html_fnam), "none", underline=True, bold=True) + print(f"\nWrote {formatted} -- open in browser to view\n") + + +def generate_annotations( + path: str, tree: MypyFile, ir: ModuleIR, type_map: dict[Expression, Type], mapper: Mapper +) -> AnnotatedSource: + anns = {} + for func_ir in ir.functions: + anns.update(function_annotations(func_ir, tree)) + visitor = ASTAnnotateVisitor(type_map, mapper) + for defn in tree.defs: + defn.accept(visitor) + anns.update(visitor.anns) + for line in visitor.ignored_lines: + if line in anns: + del anns[line] + return AnnotatedSource(path, anns) + + +def function_annotations(func_ir: FuncIR, tree: MypyFile) -> dict[int, list[Annotation]]: + """Generate annotations based on mypyc IR.""" + # TODO: check if func_ir.line is -1 + anns: dict[int, list[Annotation]] = {} + for block in func_ir.blocks: + for op in block.ops: + if isinstance(op, CallC): + name = op.function_name + ann: str | Annotation | None = None + if name == "CPyObject_GetAttr": + attr_name = get_str_literal(op.args[1]) + if attr_name in ("__prepare__", "GeneratorExit", "StopIteration"): + # These attributes are internal to mypyc/CPython, and/or accessed + # implicitly in generated code. The user has little control over + # them. + ann = None + elif attr_name: + ann = f'Get non-native attribute "{attr_name}".' + else: + ann = "Dynamic attribute lookup." + elif name == "PyObject_SetAttr": + attr_name = get_str_literal(op.args[1]) + if attr_name == "__mypyc_attrs__": + # This is set implicitly and can't be avoided. + ann = None + elif attr_name: + ann = f'Set non-native attribute "{attr_name}".' + else: + ann = "Dynamic attribute set." + elif name == "PyObject_VectorcallMethod": + method_name = get_str_literal(op.args[0]) + if method_name: + ann = f'Call non-native method "{method_name}" (it may be defined in a non-native class, or decorated).' + else: + ann = "Dynamic method call." + elif name in op_hints: + ann = op_hints[name] + elif name in ("CPyDict_GetItem", "CPyDict_SetItem"): + if ( + isinstance(op.args[0], LoadStatic) + and isinstance(op.args[1], LoadLiteral) + and func_ir.name != "__top_level__" + ): + load = op.args[0] + name = str(op.args[1].value) + sym = tree.names.get(name) + if ( + sym + and sym.node + and load.namespace == "static" + and load.identifier == "globals" + ): + if sym.node.fullname in stdlib_hints: + ann = stdlib_hints[sym.node.fullname] + elif isinstance(sym.node, Var): + ann = ( + f'Access global "{name}" through namespace ' + + "dictionary (hint: access is faster if you can make it Final)." + ) + else: + ann = f'Access "{name}" through global namespace dictionary.' + if ann: + if isinstance(ann, str): + ann = Annotation(ann) + anns.setdefault(op.line, []).append(ann) + return anns + + +class ASTAnnotateVisitor(TraverserVisitor): + """Generate annotations from mypy AST and inferred types.""" + + def __init__(self, type_map: dict[Expression, Type], mapper: Mapper) -> None: + self.anns: dict[int, list[Annotation]] = {} + self.ignored_lines: set[int] = set() + self.func_depth = 0 + self.type_map = type_map + self.mapper = mapper + + def visit_func_def(self, o: FuncDef, /) -> None: + if self.func_depth > 0: + self.annotate( + o, + "A nested function object is allocated each time statement is executed. " + + "A module-level function would be faster.", + ) + self.func_depth += 1 + super().visit_func_def(o) + self.func_depth -= 1 + + def visit_for_stmt(self, o: ForStmt, /) -> None: + self.check_iteration([o.expr], "For loop") + super().visit_for_stmt(o) + + def visit_dictionary_comprehension(self, o: DictionaryComprehension, /) -> None: + self.check_iteration(o.sequences, "Comprehension") + super().visit_dictionary_comprehension(o) + + def visit_generator_expr(self, o: GeneratorExpr, /) -> None: + self.check_iteration(o.sequences, "Comprehension or generator") + super().visit_generator_expr(o) + + def check_iteration(self, expressions: list[Expression], kind: str) -> None: + for expr in expressions: + typ = self.get_type(expr) + if isinstance(typ, AnyType): + self.annotate(expr, f'{kind} uses generic operations (iterable has type "Any").') + elif isinstance(typ, Instance) and typ.type.fullname in ( + "typing.Iterable", + "typing.Iterator", + "typing.Sequence", + "typing.MutableSequence", + ): + self.annotate( + expr, + f'{kind} uses generic operations (iterable has the abstract type "{typ.type.fullname}").', + ) + + def visit_class_def(self, o: ClassDef, /) -> None: + super().visit_class_def(o) + if self.func_depth == 0: + # Don't complain about base classes at top level + for base in o.base_type_exprs: + self.ignored_lines.add(base.line) + + for s in o.defs.body: + if isinstance(s, AssignmentStmt): + # Don't complain about attribute initializers + self.ignored_lines.add(s.line) + elif isinstance(s, Decorator): + # Don't complain about decorator definitions that generate some + # dynamic operations. This is a bit heavy-handed. + self.ignored_lines.add(s.func.line) + + def visit_with_stmt(self, o: WithStmt, /) -> None: + for expr in o.expr: + if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr): + node = expr.callee.node + if isinstance(node, Decorator): + if any( + isinstance(d, RefExpr) + and d.node + and d.node.fullname == "contextlib.contextmanager" + for d in node.decorators + ): + self.annotate( + expr, + f'"{node.name}" uses @contextmanager, which is slow ' + + "in compiled code. Use a native class with " + + '"__enter__" and "__exit__" methods instead.', + priority=3, + ) + super().visit_with_stmt(o) + + def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None: + special_form = False + if self.func_depth == 0: + analyzed: Expression | None = o.rvalue + if isinstance(o.rvalue, (CallExpr, IndexExpr, OpExpr)): + analyzed = o.rvalue.analyzed + if o.is_alias_def or isinstance( + analyzed, (TypeVarExpr, NamedTupleExpr, TypedDictExpr, NewTypeExpr) + ): + special_form = True + if special_form: + # TODO: Ignore all lines if multi-line + self.ignored_lines.add(o.line) + super().visit_assignment_stmt(o) + + def visit_name_expr(self, o: NameExpr, /) -> None: + if ann := stdlib_hints.get(o.fullname): + self.annotate(o, ann) + + def visit_member_expr(self, o: MemberExpr, /) -> None: + super().visit_member_expr(o) + if ann := stdlib_hints.get(o.fullname): + self.annotate(o, ann) + + def visit_call_expr(self, o: CallExpr, /) -> None: + super().visit_call_expr(o) + if ( + isinstance(o.callee, RefExpr) + and o.callee.fullname == "builtins.isinstance" + and len(o.args) == 2 + ): + arg = o.args[1] + self.check_isinstance_arg(arg) + elif isinstance(o.callee, RefExpr) and isinstance(o.callee.node, TypeInfo): + info = o.callee.node + class_ir = self.mapper.type_to_ir.get(info) + if (class_ir and not class_ir.is_ext_class) or ( + class_ir is None and not info.fullname.startswith("builtins.") + ): + self.annotate( + o, f'Creating an instance of non-native class "{info.name}" ' + "is slow.", 2 + ) + elif class_ir and class_ir.is_augmented: + self.annotate( + o, + f'Class "{info.name}" is only partially native, and ' + + "constructing an instance is slow.", + 2, + ) + elif isinstance(o.callee, RefExpr) and isinstance(o.callee.node, Decorator): + decorator = o.callee.node + if self.mapper.is_native_ref_expr(o.callee): + self.annotate( + o, + f'Calling a decorated function ("{decorator.name}") is inefficient, even if it\'s native.', + 2, + ) + + def check_isinstance_arg(self, arg: Expression) -> None: + if isinstance(arg, RefExpr): + if isinstance(arg.node, TypeInfo) and arg.node.is_protocol: + self.annotate( + arg, f'Expensive isinstance() check against protocol "{arg.node.name}".' + ) + elif isinstance(arg, TupleExpr): + for item in arg.items: + self.check_isinstance_arg(item) + + def visit_lambda_expr(self, o: LambdaExpr, /) -> None: + self.annotate( + o, + "A new object is allocated for lambda each time it is evaluated. " + + "A module-level function would be faster.", + ) + super().visit_lambda_expr(o) + + def annotate(self, o: Node, ann: str | Annotation, priority: int = 1) -> None: + if isinstance(ann, str): + ann = Annotation(ann, priority=priority) + self.anns.setdefault(o.line, []).append(ann) + + def get_type(self, e: Expression) -> ProperType: + t = self.type_map.get(e) + if t: + return get_proper_type(t) + return AnyType(TypeOfAny.unannotated) + + +def get_str_literal(v: Value) -> str | None: + if isinstance(v, LoadLiteral) and isinstance(v.value, str): + return v.value + return None + + +def get_max_prio(anns: list[Annotation]) -> list[Annotation]: + max_prio = max(a.priority for a in anns) + return [a for a in anns if a.priority == max_prio] + + +def generate_html_report(sources: list[AnnotatedSource]) -> str: + html = [] + html.append("\n\n") + html.append(f"") + html.append("\n") + html.append("\n") + for src in sources: + html.append(f"

{src.path}

\n") + html.append("
")
+        src_anns = src.annotations
+        with open(src.path) as f:
+            lines = f.readlines()
+        for i, s in enumerate(lines):
+            s = escape(s)
+            line = i + 1
+            linenum = "%5d" % line
+            if line in src_anns:
+                anns = get_max_prio(src_anns[line])
+                ann_strs = [a.message for a in anns]
+                hint = " ".join(ann_strs)
+                s = colorize_line(linenum, s, hint_html=hint)
+            else:
+                s = linenum + "  " + s
+            html.append(s)
+        html.append("
") + + html.append("") + + html.append("\n") + return "".join(html) + + +def colorize_line(linenum: str, s: str, hint_html: str) -> str: + hint_prefix = " " * len(linenum) + " " + line_span = f'
{linenum} {s}
' + hint_div = f'
{hint_prefix}
{hint_html}
' + return f"{line_span}{hint_div}" diff --git a/micromamba_root/Lib/site-packages/mypyc/build.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/build.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..aedc8dc0e8f494afec7c9ba4903056cf2616d334 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/build.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/build.py b/micromamba_root/Lib/site-packages/mypyc/build.py new file mode 100644 index 0000000000000000000000000000000000000000..f0384bd1a81d6c9aba131353d64b592ffe27d3b6 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/build.py @@ -0,0 +1,842 @@ +"""Support for building extensions using mypyc with distutils or setuptools + +The main entry point is mypycify, which produces a list of extension +modules to be passed to setup. A trivial setup.py for a mypyc built +project, then, looks like: + + from setuptools import setup + from mypyc.build import mypycify + + setup(name='test_module', + ext_modules=mypycify(['foo.py']), + ) + +See the mypycify docs for additional arguments. + +mypycify can integrate with either distutils or setuptools, but needs +to know at import-time whether it is using distutils or setuputils. We +hackily decide based on whether setuptools has been imported already. +""" + +from __future__ import annotations + +import hashlib +import os.path +import re +import sys +import time +from collections.abc import Iterable +from typing import TYPE_CHECKING, Any, NamedTuple, NoReturn, cast + +import mypyc.build_setup # noqa: F401 +from mypy.build import BuildSource +from mypy.errors import CompileError +from mypy.fscache import FileSystemCache +from mypy.main import process_options +from mypy.options import Options +from mypy.util import write_junit_xml +from mypyc.annotate import generate_annotated_html +from mypyc.codegen import emitmodule +from mypyc.common import IS_FREE_THREADED, RUNTIME_C_FILES, shared_lib_name +from mypyc.errors import Errors +from mypyc.ir.deps import SourceDep +from mypyc.ir.pprint import format_modules +from mypyc.namegen import exported_name +from mypyc.options import CompilerOptions + + +class ModDesc(NamedTuple): + module: str + c_files: list[str] + other_files: list[str] + include_dirs: list[str] + + +LIBRT_MODULES = [ + ModDesc("librt.internal", ["internal/librt_internal.c"], [], ["internal"]), + ModDesc("librt.strings", ["strings/librt_strings.c"], [], ["strings"]), + ModDesc( + "librt.base64", + [ + "base64/librt_base64.c", + "base64/lib.c", + "base64/codec_choose.c", + "base64/tables/tables.c", + "base64/arch/generic/codec.c", + "base64/arch/ssse3/codec.c", + "base64/arch/sse41/codec.c", + "base64/arch/sse42/codec.c", + "base64/arch/avx/codec.c", + "base64/arch/avx2/codec.c", + "base64/arch/avx512/codec.c", + "base64/arch/neon32/codec.c", + "base64/arch/neon64/codec.c", + ], + [ + "base64/arch/avx/enc_loop_asm.c", + "base64/arch/avx2/enc_loop.c", + "base64/arch/avx2/enc_loop_asm.c", + "base64/arch/avx2/enc_reshuffle.c", + "base64/arch/avx2/enc_translate.c", + "base64/arch/avx2/dec_loop.c", + "base64/arch/avx2/dec_reshuffle.c", + "base64/arch/generic/32/enc_loop.c", + "base64/arch/generic/64/enc_loop.c", + "base64/arch/generic/32/dec_loop.c", + "base64/arch/generic/enc_head.c", + "base64/arch/generic/enc_tail.c", + "base64/arch/generic/dec_head.c", + "base64/arch/generic/dec_tail.c", + "base64/arch/ssse3/dec_reshuffle.c", + "base64/arch/ssse3/dec_loop.c", + "base64/arch/ssse3/enc_loop_asm.c", + "base64/arch/ssse3/enc_translate.c", + "base64/arch/ssse3/enc_reshuffle.c", + "base64/arch/ssse3/enc_loop.c", + "base64/arch/neon64/dec_loop.c", + "base64/arch/neon64/enc_loop_asm.c", + "base64/codecs.h", + "base64/env.h", + "base64/lib_openmp.c", + "base64/tables/tables.h", + "base64/tables/table_dec_32bit.h", + "base64/tables/table_enc_12bit.h", + ], + ["base64"], + ), + ModDesc( + "librt.vecs", + [ + "vecs/librt_vecs.c", + "vecs/vec_i64.c", + "vecs/vec_i32.c", + "vecs/vec_i16.c", + "vecs/vec_u8.c", + "vecs/vec_float.c", + "vecs/vec_bool.c", + "vecs/vec_t.c", + "vecs/vec_nested.c", + ], + ["vecs/librt_vecs.h", "vecs/vec_template.c"], + ["vecs"], + ), + ModDesc("librt.time", ["time/librt_time.c"], ["time/librt_time.h"], []), +] + +try: + # Import setuptools so that it monkey-patch overrides distutils + import setuptools +except ImportError: + pass + +if TYPE_CHECKING: + if sys.version_info >= (3, 12): + from setuptools import Extension + else: + from distutils.core import Extension as _distutils_Extension + from typing import TypeAlias + + from setuptools import Extension as _setuptools_Extension + + Extension: TypeAlias = _setuptools_Extension | _distutils_Extension + +if sys.version_info >= (3, 12): + # From setuptools' monkeypatch + from distutils import ccompiler, sysconfig # type: ignore[import-not-found] +else: + from distutils import ccompiler, sysconfig + + +def get_extension() -> type[Extension]: + # We can work with either setuptools or distutils, and pick setuptools + # if it has been imported. + use_setuptools = "setuptools" in sys.modules + extension_class: type[Extension] + + if sys.version_info < (3, 12) and not use_setuptools: + import distutils.core + + extension_class = distutils.core.Extension + else: + if not use_setuptools: + sys.exit("error: setuptools not installed") + extension_class = setuptools.Extension + + return extension_class + + +def setup_mypycify_vars() -> None: + """Rewrite a bunch of config vars in pretty dubious ways.""" + # There has to be a better approach to this. + + # The vars can contain ints but we only work with str ones + vars = cast(dict[str, str], sysconfig.get_config_vars()) + if sys.platform == "darwin": + # Disable building 32-bit binaries, since we generate too much code + # for a 32-bit Mach-O object. There has to be a better way to do this. + vars["LDSHARED"] = vars["LDSHARED"].replace("-arch i386", "") + vars["LDFLAGS"] = vars["LDFLAGS"].replace("-arch i386", "") + vars["CFLAGS"] = vars["CFLAGS"].replace("-arch i386", "") + + +def fail(message: str) -> NoReturn: + # TODO: Is there something else we should do to fail? + sys.exit(message) + + +def emit_messages(options: Options, messages: list[str], dt: float, serious: bool = False) -> None: + # ... you know, just in case. + if options.junit_xml: + py_version = f"{options.python_version[0]}_{options.python_version[1]}" + write_junit_xml( + dt, + serious, + {None: messages} if messages else {}, + options.junit_xml, + py_version, + options.platform, + ) + if messages: + print("\n".join(messages)) + + +def get_mypy_config( + mypy_options: list[str], + only_compile_paths: Iterable[str] | None, + compiler_options: CompilerOptions, + fscache: FileSystemCache | None, +) -> tuple[list[BuildSource], list[BuildSource], Options]: + """Construct mypy BuildSources and Options from file and options lists""" + all_sources, options = process_options(mypy_options, fscache=fscache, mypyc=True) + if only_compile_paths is not None: + paths_set = set(only_compile_paths) + mypyc_sources = [s for s in all_sources if s.path in paths_set] + else: + mypyc_sources = all_sources + + if compiler_options.separate: + mypyc_sources = [src for src in mypyc_sources if src.path] + + if not mypyc_sources: + return mypyc_sources, all_sources, options + + # Override whatever python_version is inferred from the .ini file, + # and set the python_version to be the currently used version. + options.python_version = sys.version_info[:2] + + if options.python_version[0] == 2: + fail("Python 2 not supported") + if not options.strict_optional: + fail("Disabling strict optional checking not supported") + options.show_traceback = True + # Needed to get types for all AST nodes + options.export_types = True + # We use mypy incremental mode when doing separate/incremental mypyc compilation + options.incremental = compiler_options.separate + options.preserve_asts = True + + for source in mypyc_sources: + options.per_module_options.setdefault(source.module, {})["mypyc"] = True + + return mypyc_sources, all_sources, options + + +def is_package_source(source: BuildSource) -> bool: + return source.path is not None and os.path.split(source.path)[1] == "__init__.py" + + +def generate_c_extension_shim( + full_module_name: str, module_name: str, dir_name: str, group_name: str +) -> str: + """Create a C extension shim with a passthrough PyInit function. + + Arguments: + full_module_name: the dotted full module name + module_name: the final component of the module name + dir_name: the directory to place source code + group_name: the name of the group + """ + cname = "%s.c" % full_module_name.replace(".", os.sep) + cpath = os.path.join(dir_name, cname) + + if IS_FREE_THREADED: + # We use multi-phase init in free-threaded builds to enable free threading. + shim_name = "module_shim_no_gil_multiphase.tmpl" + else: + shim_name = "module_shim.tmpl" + + # We load the C extension shim template from a file. + # (So that the file could be reused as a bazel template also.) + with open(os.path.join(include_dir(), shim_name)) as f: + shim_template = f.read() + + write_file( + cpath, + shim_template.format( + modname=module_name, + libname=shared_lib_name(group_name), + full_modname=exported_name(full_module_name), + ), + ) + + return cpath + + +def group_name(modules: list[str]) -> str: + """Produce a probably unique name for a group from a list of module names.""" + if len(modules) == 1: + return modules[0] + + h = hashlib.sha1() + h.update(",".join(modules).encode()) + return h.hexdigest()[:20] + + +def include_dir() -> str: + """Find the path of the lib-rt dir that needs to be included""" + return os.path.join(os.path.abspath(os.path.dirname(__file__)), "lib-rt") + + +def generate_c( + sources: list[BuildSource], + options: Options, + groups: emitmodule.Groups, + fscache: FileSystemCache, + compiler_options: CompilerOptions, +) -> tuple[list[list[tuple[str, str]]], str, list[SourceDep]]: + """Drive the actual core compilation step. + + The groups argument describes how modules are assigned to C + extension modules. See the comments on the Groups type in + mypyc.emitmodule for details. + + Returns the C source code, (for debugging) the pretty printed IR, and list of SourceDeps. + """ + t0 = time.time() + + try: + result = emitmodule.parse_and_typecheck( + sources, options, compiler_options, groups, fscache + ) + except CompileError as e: + emit_messages(options, e.messages, time.time() - t0, serious=(not e.use_stdout)) + sys.exit(1) + + t1 = time.time() + if result.errors: + emit_messages(options, result.errors, t1 - t0) + sys.exit(1) + + if compiler_options.verbose: + print(f"Parsed and typechecked in {t1 - t0:.3f}s") + + errors = Errors(options) + modules, ctext, mapper = emitmodule.compile_modules_to_c( + result, compiler_options=compiler_options, errors=errors, groups=groups + ) + t2 = time.time() + emit_messages(options, errors.new_messages(), t2 - t1) + if errors.num_errors: + # No need to stop the build if only warnings were emitted. + sys.exit(1) + + if compiler_options.verbose: + print(f"Compiled to C in {t2 - t1:.3f}s") + + if options.mypyc_annotation_file: + generate_annotated_html(options.mypyc_annotation_file, result, modules, mapper) + + # Collect SourceDep dependencies + source_deps = sorted(emitmodule.collect_source_dependencies(modules), key=lambda d: d.path) + + return ctext, "\n".join(format_modules(modules)), source_deps + + +def build_using_shared_lib( + sources: list[BuildSource], + group_name: str, + cfiles: list[str], + deps: list[str], + build_dir: str, + extra_compile_args: list[str], +) -> list[Extension]: + """Produce the list of extension modules when a shared library is needed. + + This creates one shared library extension module that all the + others import, and one shim extension module for each + module in the build. Each shim simply calls an initialization function + in the shared library. + + The shared library (which lib_name is the name of) is a Python + extension module that exports the real initialization functions in + Capsules stored in module attributes. + """ + extensions = [ + get_extension()( + shared_lib_name(group_name), + sources=cfiles, + include_dirs=[include_dir(), build_dir], + depends=deps, + extra_compile_args=extra_compile_args, + ) + ] + + for source in sources: + module_name = source.module.split(".")[-1] + shim_file = generate_c_extension_shim(source.module, module_name, build_dir, group_name) + + # We include the __init__ in the "module name" we stick in the Extension, + # since this seems to be needed for it to end up in the right place. + full_module_name = source.module + assert source.path + if is_package_source(source): + full_module_name += ".__init__" + extensions.append( + get_extension()( + full_module_name, sources=[shim_file], extra_compile_args=extra_compile_args + ) + ) + + return extensions + + +def build_single_module( + sources: list[BuildSource], cfiles: list[str], extra_compile_args: list[str] +) -> list[Extension]: + """Produce the list of extension modules for a standalone extension. + + This contains just one module, since there is no need for a shared module. + """ + return [ + get_extension()( + sources[0].module, + sources=cfiles, + include_dirs=[include_dir()], + extra_compile_args=extra_compile_args, + ) + ] + + +def write_file(path: str, contents: str) -> None: + """Write data into a file. + + If the file already exists and has the same contents we + want to write, skip writing so as to preserve the mtime + and avoid triggering recompilation. + """ + # We encode it ourselves and open the files as binary to avoid windows + # newline translation + encoded_contents = contents.encode("utf-8") + try: + with open(path, "rb") as f: + old_contents: bytes | None = f.read() + except OSError: + old_contents = None + if old_contents != encoded_contents: + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "wb") as g: + g.write(encoded_contents) + + # Fudge the mtime forward because otherwise when two builds happen close + # together (like in a test) setuptools might not realize the source is newer + # than the new artifact. + # XXX: This is bad though. + new_mtime = os.stat(path).st_mtime + 1 + os.utime(path, times=(new_mtime, new_mtime)) + + +def construct_groups( + sources: list[BuildSource], + separate: bool | list[tuple[list[str], str | None]], + use_shared_lib: bool, + group_name_override: str | None, +) -> emitmodule.Groups: + """Compute Groups given the input source list and separate configs. + + separate is the user-specified configuration for how to assign + modules to compilation groups (see mypycify docstring for details). + + This takes that and expands it into our internal representation of + group configuration, documented in mypyc.emitmodule's definition + of Group. + """ + + if separate is True: + groups: emitmodule.Groups = [([source], None) for source in sources] + elif isinstance(separate, list): + groups = [] + used_sources = set() + for files, name in separate: + normalized_files = {os.path.normpath(f) for f in files} + group_sources = [ + src + for src in sources + if src.path is not None and os.path.normpath(src.path) in normalized_files + ] + groups.append((group_sources, name)) + used_sources.update(group_sources) + unused_sources = [src for src in sources if src not in used_sources] + if unused_sources: + groups.extend([([source], None) for source in unused_sources]) + else: + groups = [(sources, None)] + + # Generate missing names + for i, (group, name) in enumerate(groups): + if use_shared_lib and not name: + if group_name_override is not None: + name = group_name_override + else: + name = group_name([source.module for source in group]) + groups[i] = (group, name) + + return groups + + +def get_header_deps(cfiles: list[tuple[str, str]]) -> list[str]: + """Find all the headers used by a group of cfiles. + + We do this by just regexping the source, which is a bit simpler than + properly plumbing the data through. + + Arguments: + cfiles: A list of (file name, file contents) pairs. + """ + headers: set[str] = set() + for _, contents in cfiles: + headers.update(re.findall(r'#include "(.*)"', contents)) + + return sorted(headers) + + +def mypyc_build( + paths: list[str], + compiler_options: CompilerOptions, + *, + separate: bool | list[tuple[list[str], str | None]] = False, + only_compile_paths: Iterable[str] | None = None, + skip_cgen_input: tuple[list[list[tuple[str, str]]], list[str]] | None = None, + always_use_shared_lib: bool = False, +) -> tuple[emitmodule.Groups, list[tuple[list[str], list[str]]], list[SourceDep]]: + """Do the front and middle end of mypyc building, producing and writing out C source.""" + fscache = FileSystemCache() + mypyc_sources, all_sources, options = get_mypy_config( + paths, only_compile_paths, compiler_options, fscache + ) + + # We generate a shared lib if there are multiple modules or if any + # of the modules are in package. (Because I didn't want to fuss + # around with making the single module code handle packages.) + use_shared_lib = ( + len(mypyc_sources) > 1 + or any("." in x.module for x in mypyc_sources) + or any(is_package_source(x) for x in mypyc_sources) + or always_use_shared_lib + ) + + groups = construct_groups(mypyc_sources, separate, use_shared_lib, compiler_options.group_name) + + if compiler_options.group_name is not None: + assert len(groups) == 1, "If using custom group_name, only one group is expected" + + # We let the test harness just pass in the c file contents instead + # so that it can do a corner-cutting version without full stubs. + source_deps: list[SourceDep] = [] + if not skip_cgen_input: + group_cfiles, ops_text, source_deps = generate_c( + all_sources, options, groups, fscache, compiler_options=compiler_options + ) + # TODO: unique names? + write_file(os.path.join(compiler_options.target_dir, "ops.txt"), ops_text) + else: + group_cfiles = skip_cgen_input[0] + source_deps = [SourceDep(d) for d in skip_cgen_input[1]] + + # Write out the generated C and collect the files for each group + # Should this be here?? + group_cfilenames: list[tuple[list[str], list[str]]] = [] + for cfiles in group_cfiles: + cfilenames = [] + for cfile, ctext in cfiles: + cfile = os.path.join(compiler_options.target_dir, cfile) + if not options.mypyc_skip_c_generation: + write_file(cfile, ctext) + if os.path.splitext(cfile)[1] == ".c": + cfilenames.append(cfile) + + deps = [os.path.join(compiler_options.target_dir, dep) for dep in get_header_deps(cfiles)] + group_cfilenames.append((cfilenames, deps)) + + return groups, group_cfilenames, source_deps + + +def get_cflags( + *, + compiler_type: str | None = None, + opt_level: str = "3", + debug_level: str = "1", + multi_file: bool = False, + experimental_features: bool = False, + log_trace: bool = False, +) -> list[str]: + """Get C compiler flags for the given configuration. + + Args: + compiler_type: Compiler type, e.g. "unix" or "msvc". If None, detected automatically. + opt_level: Optimization level as string ("0", "1", "2", or "3"). + debug_level: Debug level as string ("0", "1", "2", or "3"). + multi_file: Whether multi-file compilation mode is enabled. + experimental_features: Whether experimental features are enabled. + log_trace: Whether trace logging is enabled. + + Returns: + List of compiler flags. + """ + if compiler_type is None: + compiler: Any = ccompiler.new_compiler() + sysconfig.customize_compiler(compiler) + compiler_type = compiler.compiler_type + + cflags: list[str] = [] + if compiler_type == "unix": + cflags += [ + f"-O{opt_level}", + f"-g{debug_level}", + "-Werror", + "-Wno-unused-function", + "-Wno-unused-label", + "-Wno-unreachable-code", + "-Wno-unused-variable", + "-Wno-unused-command-line-argument", + "-Wno-unknown-warning-option", + "-Wno-unused-but-set-variable", + "-Wno-ignored-optimization-argument", + # GCC at -O3 false-positives on struct hack (items[1]) in vec buffers + "-Wno-array-bounds", + "-Wno-stringop-overread", + "-Wno-stringop-overflow", + # Disables C Preprocessor (cpp) warnings + # See https://github.com/mypyc/mypyc/issues/956 + "-Wno-cpp", + ] + if log_trace: + cflags.append("-DMYPYC_LOG_TRACE") + if experimental_features: + cflags.append("-DMYPYC_EXPERIMENTAL") + if opt_level == "0": + cflags.append("-UNDEBUG") + elif compiler_type == "msvc": + # msvc doesn't have levels, '/O2' is full and '/Od' is disable + if opt_level == "0": + opt_level = "d" + cflags.append("/UNDEBUG") + elif opt_level in ("1", "2", "3"): + opt_level = "2" + if debug_level == "0": + debug_level = "NONE" + elif debug_level == "1": + debug_level = "FASTLINK" + elif debug_level in ("2", "3"): + debug_level = "FULL" + cflags += [ + f"/O{opt_level}", + f"/DEBUG:{debug_level}", + "/wd4102", # unreferenced label + "/wd4101", # unreferenced local variable + "/wd4146", # negating unsigned int + ] + if multi_file: + # Disable whole program optimization in multi-file mode so + # that we actually get the compilation speed and memory + # use wins that multi-file mode is intended for. + cflags += ["/GL-", "/wd9025"] # warning about overriding /GL + if log_trace: + cflags.append("/DMYPYC_LOG_TRACE") + if experimental_features: + cflags.append("/DMYPYC_EXPERIMENTAL") + return cflags + + +def mypycify( + paths: list[str], + *, + only_compile_paths: Iterable[str] | None = None, + verbose: bool = False, + opt_level: str = "3", + debug_level: str = "1", + strip_asserts: bool = False, + multi_file: bool = False, + separate: bool | list[tuple[list[str], str | None]] = False, + skip_cgen_input: tuple[list[list[tuple[str, str]]], list[str]] | None = None, + target_dir: str | None = None, + include_runtime_files: bool | None = None, + strict_dunder_typing: bool = False, + group_name: str | None = None, + log_trace: bool = False, + depends_on_librt_internal: bool = False, + install_librt: bool = False, + experimental_features: bool = False, +) -> list[Extension]: + """Main entry point to building using mypyc. + + This produces a list of Extension objects that should be passed as the + ext_modules parameter to setup. + + Arguments: + paths: A list of file paths to build. It may also contain mypy options. + only_compile_paths: If not None, an iterable of paths that are to be + the only modules compiled, even if other modules + appear in the mypy command line given to paths. + (These modules must still be passed to paths.) + + verbose: Should mypyc be more verbose. Defaults to false. + + opt_level: The optimization level, as a string. Defaults to '3' (meaning '-O3'). + debug_level: The debug level, as a string. Defaults to '1' (meaning '-g1'). + strip_asserts: Should asserts be stripped from the generated code. + + multi_file: Should each Python module be compiled into its own C source file. + This can reduce compile time and memory requirements at the likely + cost of runtime performance of compiled code. Defaults to false. + separate: Should compiled modules be placed in separate extension modules. + If False, all modules are placed in a single shared library. + If True, every module is placed in its own library. + Otherwise, separate should be a list of + (file name list, optional shared library name) pairs specifying + groups of files that should be placed in the same shared library + (while all other modules will be placed in its own library). + + Each group can be compiled independently, which can + speed up compilation, but calls between groups can + be slower than calls within a group and can't be + inlined. + target_dir: The directory to write C output files. Defaults to 'build'. + include_runtime_files: If not None, whether the mypyc runtime library + should be directly #include'd instead of linked + separately in order to reduce compiler invocations. + Defaults to False in multi_file mode, True otherwise. + strict_dunder_typing: If True, force dunder methods to have the return type + of the method strictly, which can lead to more + optimization opportunities. Defaults to False. + group_name: If set, override the default group name derived from + the hash of module names. This is used for the names of the + output C files and the shared library. This is only supported + if there is a single group. [Experimental] + log_trace: If True, compiled code writes a trace log of events in + mypyc_trace.txt (derived from executed operations). This is + useful for performance analysis, such as analyzing which + primitive ops are used the most and on which lines. + depends_on_librt_internal: This is True only for mypy itself. + install_librt: If True, also build the librt extension modules. Normally, + those are build and published on PyPI separately, but during + tests, we want to use their development versions (i.e. from + current commit). + experimental_features: Enable experimental features (install_librt=True is + also needed if using experimental librt features). These + have no backward compatibility guarantees! + """ + + # Figure out our configuration + compiler_options = CompilerOptions( + strip_asserts=strip_asserts, + multi_file=multi_file, + verbose=verbose, + separate=separate is not False, + target_dir=target_dir, + include_runtime_files=include_runtime_files, + strict_dunder_typing=strict_dunder_typing, + group_name=group_name, + log_trace=log_trace, + depends_on_librt_internal=depends_on_librt_internal, + experimental_features=experimental_features, + ) + + # Generate all the actual important C code + groups, group_cfilenames, source_deps = mypyc_build( + paths, + only_compile_paths=only_compile_paths, + compiler_options=compiler_options, + separate=separate, + skip_cgen_input=skip_cgen_input, + ) + + # Mess around with setuptools and actually get the thing built + setup_mypycify_vars() + + # Create a compiler object so we can make decisions based on what + # compiler is being used. typeshed is missing some attributes on the + # compiler object so we give it type Any + compiler: Any = ccompiler.new_compiler() + sysconfig.customize_compiler(compiler) + + build_dir = compiler_options.target_dir + + cflags = get_cflags( + compiler_type=compiler.compiler_type, + opt_level=opt_level, + debug_level=debug_level, + multi_file=multi_file, + experimental_features=experimental_features, + log_trace=log_trace, + ) + + # If configured to (defaults to yes in multi-file mode), copy the + # runtime library in. Otherwise it just gets #included to save on + # compiler invocations. + shared_cfilenames = [] + if not compiler_options.include_runtime_files: + # Collect all files to copy: runtime files + conditional source files + files_to_copy = list(RUNTIME_C_FILES) + for source_dep in source_deps: + files_to_copy.append(source_dep.path) + files_to_copy.append(source_dep.get_header()) + + # Copy all files + for name in files_to_copy: + rt_file = os.path.join(build_dir, name) + with open(os.path.join(include_dir(), name), encoding="utf-8") as f: + write_file(rt_file, f.read()) + if name.endswith(".c"): + shared_cfilenames.append(rt_file) + + extensions = [] + for (group_sources, lib_name), (cfilenames, deps) in zip(groups, group_cfilenames): + if lib_name: + extensions.extend( + build_using_shared_lib( + group_sources, + lib_name, + cfilenames + shared_cfilenames, + deps, + build_dir, + cflags, + ) + ) + else: + extensions.extend( + build_single_module(group_sources, cfilenames + shared_cfilenames, cflags) + ) + + if install_librt: + for name in RUNTIME_C_FILES: + rt_file = os.path.join(build_dir, name) + with open(os.path.join(include_dir(), name), encoding="utf-8") as f: + write_file(rt_file, f.read()) + for mod, file_names, addit_files, includes in LIBRT_MODULES: + for file_name in file_names + addit_files: + rt_file = os.path.join(build_dir, file_name) + with open(os.path.join(include_dir(), file_name), encoding="utf-8") as f: + write_file(rt_file, f.read()) + extensions.append( + get_extension()( + mod, + sources=[ + os.path.join(build_dir, file) for file in file_names + RUNTIME_C_FILES + ], + include_dirs=[include_dir()] + + [os.path.join(include_dir(), d) for d in includes], + extra_compile_args=cflags, + ) + ) + + return extensions diff --git a/micromamba_root/Lib/site-packages/mypyc/build_setup.py b/micromamba_root/Lib/site-packages/mypyc/build_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..ec995935990c4d697e4a21f54fa7aff188f5dfa0 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/build_setup.py @@ -0,0 +1,69 @@ +# This file must have the same content for mypyc/build_setup.py and lib-rt/build_setup.py, +# it exists to work around absence of support for per-file compile flags in setuptools. +# The version in mypyc/ is the source of truth, and should be copied to lib-rt if modified. + +import os +import platform +import sys + +try: + # Import setuptools so that it monkey-patch overrides distutils + import setuptools # noqa: F401 +except ImportError: + pass + +if sys.version_info >= (3, 12): + # From setuptools' monkeypatch + from distutils import ccompiler # type: ignore[import-not-found] +else: + from distutils import ccompiler + +EXTRA_FLAGS_PER_COMPILER_TYPE_PER_PATH_COMPONENT = { + "msvc": { + "base64/arch/sse42": ["/arch:SSE4.2"], + "base64/arch/avx2": ["/arch:AVX2"], + "base64/arch/avx": ["/arch:AVX"], + } +} + +ccompiler.CCompiler.__spawn = ccompiler.CCompiler.spawn # type: ignore[attr-defined] +X86_64 = platform.machine() in ("x86_64", "AMD64", "amd64") +PYODIDE = "PYODIDE" in os.environ +NO_EXTRA_FLAGS = "MYPYC_NO_EXTRA_FLAGS" in os.environ + + +def spawn(self, cmd, **kwargs) -> None: # type: ignore[no-untyped-def] + new_cmd = list(cmd) + if PYODIDE: + for argument in reversed(new_cmd): + if not str(argument).endswith(".c"): + continue + if "base64/arch/" in str(argument): + new_cmd.extend(["-msimd128"]) + elif not NO_EXTRA_FLAGS: + compiler_type: str = self.compiler_type + extra_options = EXTRA_FLAGS_PER_COMPILER_TYPE_PER_PATH_COMPONENT.get(compiler_type, None) + if X86_64 and extra_options is not None: + # filenames are closer to the end of command line + for argument in reversed(new_cmd): + # Check if the matching argument contains a source filename. + if not str(argument).endswith(".c"): + continue + + for path in extra_options.keys(): + if path in str(argument): + if compiler_type == "bcpp": + compiler = new_cmd.pop() + # Borland accepts a source file name at the end, + # insert the options before it + new_cmd.extend(extra_options[path]) + new_cmd.append(compiler) + else: + new_cmd.extend(extra_options[path]) + + # path component is found, no need to search any further + break + self.__spawn(new_cmd, **kwargs) + + +ccompiler.CCompiler.spawn = spawn # type: ignore[method-assign] diff --git a/micromamba_root/Lib/site-packages/mypyc/common.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/common.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..4e3d3790b910435575eed295327a789d90ed261e Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/common.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/common.py b/micromamba_root/Lib/site-packages/mypyc/common.py new file mode 100644 index 0000000000000000000000000000000000000000..33c03ac13b273c5457b3cd0a271690d840c9051f --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/common.py @@ -0,0 +1,149 @@ +from __future__ import annotations + +import importlib.machinery +import sys +import sysconfig +from typing import Any, Final + +from mypy.util import unnamed_function + +PREFIX: Final = "CPyPy_" # Python wrappers +NATIVE_PREFIX: Final = "CPyDef_" # Native functions etc. +DUNDER_PREFIX: Final = "CPyDunder_" # Wrappers for exposing dunder methods to the API +REG_PREFIX: Final = "cpy_r_" # Registers +STATIC_PREFIX: Final = "CPyStatic_" # Static variables (for literals etc.) +TYPE_PREFIX: Final = "CPyType_" # Type object struct +MODULE_PREFIX: Final = "CPyModule_" # Cached modules +TYPE_VAR_PREFIX: Final = "CPyTypeVar_" # Type variables when using new-style Python 3.12 syntax +ATTR_PREFIX: Final = "_" # Attributes +FAST_PREFIX: Final = "__mypyc_fast_" # Optimized methods in non-extension classes + +ENV_ATTR_NAME: Final = "__mypyc_env__" +NEXT_LABEL_ATTR_NAME: Final = "__mypyc_next_label__" +TEMP_ATTR_NAME: Final = "__mypyc_temp__" +LAMBDA_NAME: Final = "__mypyc_lambda__" +PROPSET_PREFIX: Final = "__mypyc_setter__" +SELF_NAME: Final = "__mypyc_self__" +GENERATOR_ATTRIBUTE_PREFIX: Final = "__mypyc_generator_attribute__" +CPYFUNCTION_NAME = "__cpyfunction__" + +# Max short int we accept as a literal is based on 32-bit platforms, +# so that we can just always emit the same code. + +TOP_LEVEL_NAME: Final = "__top_level__" # Special function representing module top level + +# Maximal number of subclasses for a class to trigger fast path in isinstance() checks. +FAST_ISINSTANCE_MAX_SUBCLASSES: Final = 2 + +# Size of size_t, if configured. +SIZEOF_SIZE_T_SYSCONFIG: Final = sysconfig.get_config_var("SIZEOF_SIZE_T") + +SIZEOF_SIZE_T: Final = ( + int(SIZEOF_SIZE_T_SYSCONFIG) + if SIZEOF_SIZE_T_SYSCONFIG is not None + else (sys.maxsize + 1).bit_length() // 8 +) + +IS_32_BIT_PLATFORM: Final = int(SIZEOF_SIZE_T) == 4 + +PLATFORM_SIZE = 4 if IS_32_BIT_PLATFORM else 8 + +# Maximum value for a short tagged integer. +MAX_SHORT_INT: Final = 2 ** (8 * int(SIZEOF_SIZE_T) - 2) - 1 + +# Minimum value for a short tagged integer. +MIN_SHORT_INT: Final = -(MAX_SHORT_INT) - 1 + +# Maximum value for a short tagged integer represented as a C integer literal. +# +# Note: Assume that the compiled code uses the same bit width as mypyc +MAX_LITERAL_SHORT_INT: Final = MAX_SHORT_INT +MIN_LITERAL_SHORT_INT: Final = -MAX_LITERAL_SHORT_INT - 1 + +# Description of the C type used to track the definedness of attributes and +# the presence of argument default values that have types with overlapping +# error values. Each tracked attribute/argument has a dedicated bit in the +# relevant bitmap. +BITMAP_TYPE: Final = "uint32_t" +BITMAP_BITS: Final = 32 + +# Runtime C library files that are always included (some ops may bring +# extra dependencies via mypyc.ir.SourceDep) +RUNTIME_C_FILES: Final = [ + "init.c", + "getargs.c", + "getargsfast.c", + "int_ops.c", + "float_ops.c", + "str_ops.c", + "bytes_ops.c", + "list_ops.c", + "dict_ops.c", + "set_ops.c", + "tuple_ops.c", + "exc_ops.c", + "misc_ops.c", + "generic_ops.c", + "pythonsupport.c", + "function_wrapper.c", +] + +# Python 3.12 introduced immortal objects, specified via a special reference count +# value. The reference counts of immortal objects are normally not modified, but it's +# not strictly wrong to modify them. See PEP 683 for more information, but note that +# some details in the PEP are out of date. +HAVE_IMMORTAL: Final = sys.version_info >= (3, 12) + +# Are we running on a free-threaded build (GIL disabled)? This implies that +# we are on Python 3.13 or later. +IS_FREE_THREADED: Final = bool(sysconfig.get_config_var("Py_GIL_DISABLED")) + +# The file extension suffix for C extension modules on the current platform +# (e.g. ".cpython-312-x86_64-linux-gnu.so" or ".pyd"). +_EXT_SUFFIXES: Final = importlib.machinery.EXTENSION_SUFFIXES +EXT_SUFFIX: Final = _EXT_SUFFIXES[0] if _EXT_SUFFIXES else ".so" + + +JsonDict = dict[str, Any] + + +def shared_lib_name(group_name: str) -> str: + """Given a group name, return the actual name of its extension module. + + (This just adds a suffix to the final component.) + """ + return f"{group_name}__mypyc" + + +def short_name(name: str) -> str: + if name.startswith("builtins."): + return name[9:] + return name + + +def get_id_from_name(name: str, fullname: str, line: int) -> str: + """Create a unique id for a function. + + This creates an id that is unique for any given function definition, so that it can be used as + a dictionary key. This is usually the fullname of the function, but this is different in that + it handles the case where the function is named '_', in which case multiple different functions + could have the same name.""" + if unnamed_function(name): + return f"{fullname}.{line}" + else: + return fullname + + +def short_id_from_name(func_name: str, shortname: str, line: int | None) -> str: + if unnamed_function(func_name): + assert line is not None + partial_name = f"{shortname}.{line}" + else: + partial_name = shortname + return partial_name + + +def bitmap_name(index: int) -> str: + if index == 0: + return "__bitmap" + return f"__bitmap{index + 1}" diff --git a/micromamba_root/Lib/site-packages/mypyc/crash.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/crash.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..a746ec878268d8786aa5a9361186cc8fbd0c09fa Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/crash.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/crash.py b/micromamba_root/Lib/site-packages/mypyc/crash.py new file mode 100644 index 0000000000000000000000000000000000000000..1227aa8978af232bb997b0b54ebf73768eb7131a --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/crash.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +import sys +import traceback +from collections.abc import Iterator +from contextlib import contextmanager +from typing import NoReturn + + +@contextmanager +def catch_errors(module_path: str, line: int) -> Iterator[None]: + try: + yield + except Exception: + crash_report(module_path, line) + + +def crash_report(module_path: str, line: int) -> NoReturn: + # Adapted from report_internal_error in mypy + err = sys.exc_info()[1] + tb = traceback.extract_stack()[:-4] + # Excise all the traceback from the test runner + for i, x in enumerate(tb): + if x.name == "pytest_runtest_call": + tb = tb[i + 1 :] + break + tb2 = traceback.extract_tb(sys.exc_info()[2])[1:] + print("Traceback (most recent call last):") + for s in traceback.format_list(tb + tb2): + print(s.rstrip("\n")) + print(f"{module_path}:{line}: {type(err).__name__}: {err}") + raise SystemExit(2) diff --git a/micromamba_root/Lib/site-packages/mypyc/errors.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/errors.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..d6684fbbf8b5eba1afa0acc28eb974abbe86f3d4 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/errors.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/errors.py b/micromamba_root/Lib/site-packages/mypyc/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..a601ada0b218931db64bff1373b19607002cc69d --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/errors.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +import mypy.errors +from mypy.options import Options + + +class Errors: + def __init__(self, options: Options) -> None: + self.num_errors = 0 + self.num_warnings = 0 + self._errors = mypy.errors.Errors(options, hide_error_codes=True) + + def error(self, msg: str, path: str, line: int) -> None: + self._errors.set_file(path, None, self._errors.options) + self._errors.report(line, None, msg, severity="error") + self.num_errors += 1 + + def note(self, msg: str, path: str, line: int) -> None: + self._errors.set_file(path, None, self._errors.options) + self._errors.report(line, None, msg, severity="note") + + def warning(self, msg: str, path: str, line: int) -> None: + self._errors.set_file(path, None, self._errors.options) + self._errors.report(line, None, msg, severity="warning") + self.num_warnings += 1 + + def new_messages(self) -> list[str]: + return self._errors.new_messages() + + def flush_errors(self) -> None: + for error in self.new_messages(): + print(error) diff --git a/micromamba_root/Lib/site-packages/mypyc/namegen.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/namegen.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..70b687689525a1ac831024c12b322adec8ff40f1 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/namegen.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/namegen.py b/micromamba_root/Lib/site-packages/mypyc/namegen.py new file mode 100644 index 0000000000000000000000000000000000000000..1e05531021752709fbc0144d33ddf8377fa1dfed --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/namegen.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +from collections.abc import Iterable + + +class NameGenerator: + """Utility for generating distinct C names from Python names. + + Since C names can't use '.' (or unicode), some care is required to + make C names generated from Python names unique. Also, we want to + avoid generating overly long C names since they make the generated + code harder to read. + + Note that we don't restrict ourselves to a 32-character distinguishing + prefix guaranteed by the C standard since all the compilers we care + about at the moment support longer names without issues. + + For names that are exported in a shared library (not static) use + exported_name() instead. + + Summary of the approach: + + * Generate a unique name prefix from suffix of fully-qualified + module name used for static names. If only compiling a single + module, this can be empty. For example, if the modules are + 'foo.bar' and 'foo.baz', the prefixes can be 'bar_' and 'baz_', + respectively. If the modules are 'bar.foo' and 'baz.foo', the + prefixes will be 'bar_foo_' and 'baz_foo_'. + + * Replace '.' in the Python name with '___' in the C name. (And + replace the unlikely but possible '___' with '___3_'. This + collides '___' with '.3_', but this is OK because names + may not start with a digit.) + + The generated should be internal to a build and thus the mapping is + arbitrary. Just generating names '1', '2', ... would be correct, + though not very usable. The generated names may be visible in CPU + profiles and when debugging using native debuggers. + """ + + def __init__(self, groups: Iterable[list[str]], *, separate: bool = False) -> None: + """Initialize with a list of modules in each compilation group. + + The names of modules are used to shorten names referring to + modules, for convenience. Arbitrary module + names are supported for generated names, but uncompiled modules + will use long names. + + If separate is True, assume separate compilation. This implies + that we don't have knowledge of all sources that will be linked + together. In this case we won't trim module prefixes, since we + don't have enough information to determine common module prefixes. + """ + self.module_map: dict[str, str] = {} + for names in groups: + if not separate: + self.module_map.update(make_module_translation_map(names)) + else: + for name in names: + self.module_map[name] = name + "." + self.translations: dict[tuple[str, str], str] = {} + self.used_names: set[str] = set() + + def private_name(self, module: str, partial_name: str | None = None) -> str: + """Return a C name usable for a static definition. + + Return a distinct result for each (module, partial_name) pair. + + The caller should add a suitable prefix to the name to avoid + conflicts with other C names. Only ensure that the results of + this function are unique, not that they aren't overlapping with + arbitrary names. + + If a name is not specific to any module, the module argument can + be an empty string. + """ + # TODO: Support unicode + if partial_name is None: + return exported_name(self.module_map[module].rstrip(".")) + if (module, partial_name) in self.translations: + return self.translations[module, partial_name] + if module in self.module_map: + module_prefix = self.module_map[module] + elif module: + module_prefix = module + "." + else: + module_prefix = "" + actual = exported_name(f"{module_prefix}{partial_name}") + self.translations[module, partial_name] = actual + return actual + + +def exported_name(fullname: str) -> str: + """Return a C name usable for an exported definition. + + This is like private_name(), but the output only depends on the + 'fullname' argument, so the names are distinct across multiple + builds. + """ + # TODO: Support unicode + return fullname.replace("___", "___3_").replace(".", "___") + + +def make_module_translation_map(names: list[str]) -> dict[str, str]: + num_instances: dict[str, int] = {} + for name in names: + for suffix in candidate_suffixes(name): + num_instances[suffix] = num_instances.get(suffix, 0) + 1 + result = {} + for name in names: + for suffix in candidate_suffixes(name): + if num_instances[suffix] == 1: + break + # Takes the last suffix if none are unique + result[name] = suffix + return result + + +def candidate_suffixes(fullname: str) -> list[str]: + components = fullname.split(".") + result = [""] + for i in range(len(components)): + result.append(".".join(components[-i - 1 :]) + ".") + return result diff --git a/micromamba_root/Lib/site-packages/mypyc/options.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/options.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..4274e3284ede240712d99b9541353ba60058b433 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/options.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/options.py b/micromamba_root/Lib/site-packages/mypyc/options.py new file mode 100644 index 0000000000000000000000000000000000000000..8eb33b2282567c11ec130a4e282cd2ab2def9d60 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/options.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import sys + + +class CompilerOptions: + def __init__( + self, + strip_asserts: bool = False, + multi_file: bool = False, + verbose: bool = False, + separate: bool = False, + target_dir: str | None = None, + include_runtime_files: bool | None = None, + capi_version: tuple[int, int] | None = None, + python_version: tuple[int, int] | None = None, + strict_dunder_typing: bool = False, + group_name: str | None = None, + log_trace: bool = False, + depends_on_librt_internal: bool = False, + experimental_features: bool = False, + strict_traceback_checks: bool = False, + ) -> None: + self.strip_asserts = strip_asserts + self.multi_file = multi_file + self.verbose = verbose + self.separate = separate + self.global_opts = not separate + self.target_dir = target_dir or "build" + self.include_runtime_files = ( + include_runtime_files if include_runtime_files is not None else not multi_file + ) + # The target Python C API version. Overriding this is mostly + # useful in IR tests, since there's no guarantee that + # binaries are backward compatible even if no recent API + # features are used. + self.capi_version = capi_version or sys.version_info[:2] + self.python_version = python_version + # Make possible to inline dunder methods in the generated code. + # Typically, the convention is the dunder methods can return `NotImplemented` + # even when its return type is just `bool`. + # By enabling this option, this convention is no longer valid and the dunder + # will assume the return type of the method strictly, which can lead to + # more optimization opportunities. + self.strict_dunders_typing = strict_dunder_typing + # Override the automatic group name derived from the hash of module names. + # This affects the names of generated .c, .h and shared library files. + # This is only supported when compiling exactly one group, and a shared + # library is generated (with shims). This can be used to make the output + # file names more predictable. + self.group_name = group_name + # If enabled, write a trace log of events based on executed operations to + # mypyc_trace.txt when compiled module is executed. This is useful for + # performance analysis. + self.log_trace = log_trace + # If enabled, add capsule imports of librt.internal API. This should be used + # only for mypy itself, third-party code compiled with mypyc should not use + # librt.internal. + self.depends_on_librt_internal = depends_on_librt_internal + # Some experimental features are only available when building librt in + # experimental mode (e.g. use _experimental suffix in librt run test). + # These can't be used with a librt wheel installed from PyPI. + self.experimental_features = experimental_features + # If enabled, mypyc will assert that every traceback it generates has a + # positive line number. + # Currently each AST node is assigned line number -1 by default to indicate + # that it's unset. If the line number is never set and a traceback is + # generated that points at such node, then the line number will be interpreted + # as None instead of an integer by Python and potentially crash code that + # expects an integer, such as pytest. + # The goal is to prevent the incorrect tracebacks but it will require a lot + # of changes across mypyc. In the meantime, this option should be enabled in + # tests to make sure that no new code which leads to incorrect tracebacks is + # added. + self.strict_traceback_checks = strict_traceback_checks diff --git a/micromamba_root/Lib/site-packages/mypyc/py.typed b/micromamba_root/Lib/site-packages/mypyc/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/Lib/site-packages/mypyc/rt_subtype.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/rt_subtype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..175ea9be88eeaa08a42de5a1f15c629bcf73a249 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/rt_subtype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/rt_subtype.py b/micromamba_root/Lib/site-packages/mypyc/rt_subtype.py new file mode 100644 index 0000000000000000000000000000000000000000..54205a1de6984487d225d4a8e5c59036fd0d6825 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/rt_subtype.py @@ -0,0 +1,84 @@ +"""'Runtime subtype' check for RTypes. + +A type S is a runtime subtype of T if a value of type S can be used at runtime +when a value of type T is expected without requiring any runtime conversions. + +For boxed types, runtime subtyping is the same as regular subtyping. +Unboxed subtypes, on the other hand, are not runtime subtypes of object +(since they require boxing to be used as an object), but short ints +are runtime subtypes of int. + +Subtyping is used to determine whether an object can be in a +particular place and runtime subtyping is used to determine whether a +coercion is necessary first. +""" + +from __future__ import annotations + +from mypyc.ir.rtypes import ( + RArray, + RInstance, + RPrimitive, + RStruct, + RTuple, + RType, + RTypeVisitor, + RUnion, + RVec, + RVoid, + is_bit_rprimitive, + is_bool_rprimitive, + is_int_rprimitive, + is_short_int_rprimitive, +) +from mypyc.subtype import is_subtype + + +def is_runtime_subtype(left: RType, right: RType) -> bool: + if isinstance(right, RUnion) and not isinstance(left, RUnion): + return any(not item.is_unboxed and is_runtime_subtype(left, item) for item in right.items) + return left.accept(RTSubtypeVisitor(right)) + + +class RTSubtypeVisitor(RTypeVisitor[bool]): + """Is left a runtime subtype of right? + + A few special cases such as right being 'object' are handled in + is_runtime_subtype and don't need to be covered here. + """ + + def __init__(self, right: RType) -> None: + self.right = right + + def visit_rinstance(self, left: RInstance) -> bool: + return is_subtype(left, self.right) + + def visit_rvec(self, left: RVec) -> bool: + # TODO: Better implementation + return left == self.right + + def visit_runion(self, left: RUnion) -> bool: + return not self.right.is_unboxed and is_subtype(left, self.right) + + def visit_rprimitive(self, left: RPrimitive) -> bool: + if is_short_int_rprimitive(left) and is_int_rprimitive(self.right): + return True + if is_bit_rprimitive(left) and is_bool_rprimitive(self.right): + return True + return left is self.right + + def visit_rtuple(self, left: RTuple) -> bool: + if isinstance(self.right, RTuple): + return len(self.right.types) == len(left.types) and all( + is_runtime_subtype(t1, t2) for t1, t2 in zip(left.types, self.right.types) + ) + return False + + def visit_rstruct(self, left: RStruct) -> bool: + return isinstance(self.right, RStruct) and self.right.name == left.name + + def visit_rarray(self, left: RArray) -> bool: + return left == self.right + + def visit_rvoid(self, left: RVoid) -> bool: + return isinstance(self.right, RVoid) diff --git a/micromamba_root/Lib/site-packages/mypyc/sametype.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/sametype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..31e27a891440abf906ae83c09ab759a4716d98c4 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/sametype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/sametype.py b/micromamba_root/Lib/site-packages/mypyc/sametype.py new file mode 100644 index 0000000000000000000000000000000000000000..d6e33f81cccdd6efc98c62a65caa88c64f2f1b80 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/sametype.py @@ -0,0 +1,87 @@ +"""Same type check for RTypes.""" + +from __future__ import annotations + +from mypyc.ir.func_ir import FuncSignature +from mypyc.ir.rtypes import ( + RArray, + RInstance, + RPrimitive, + RStruct, + RTuple, + RType, + RTypeVisitor, + RUnion, + RVec, + RVoid, +) + + +def is_same_type(a: RType, b: RType) -> bool: + return a.accept(SameTypeVisitor(b)) + + +def is_same_signature(a: FuncSignature, b: FuncSignature) -> bool: + return ( + len(a.args) == len(b.args) + and is_same_type(a.ret_type, b.ret_type) + and all( + is_same_type(t1.type, t2.type) and t1.name == t2.name for t1, t2 in zip(a.args, b.args) + ) + ) + + +def is_same_method_signature(a: FuncSignature, b: FuncSignature) -> bool: + return ( + len(a.args) == len(b.args) + and is_same_type(a.ret_type, b.ret_type) + and all( + is_same_type(t1.type, t2.type) + and ((t1.pos_only and t2.pos_only) or t1.name == t2.name) + and t1.optional == t2.optional + for t1, t2 in zip(a.args[1:], b.args[1:]) + ) + ) + + +class SameTypeVisitor(RTypeVisitor[bool]): + def __init__(self, right: RType) -> None: + self.right = right + + def visit_rinstance(self, left: RInstance) -> bool: + return isinstance(self.right, RInstance) and left.name == self.right.name + + def visit_rvec(self, left: RVec) -> bool: + return isinstance(self.right, RVec) and left.item_type == self.right.item_type + + def visit_runion(self, left: RUnion) -> bool: + if isinstance(self.right, RUnion): + items = list(self.right.items) + for left_item in left.items: + for j, right_item in enumerate(items): + if is_same_type(left_item, right_item): + del items[j] + break + else: + return False + return not items + return False + + def visit_rprimitive(self, left: RPrimitive) -> bool: + return left is self.right + + def visit_rtuple(self, left: RTuple) -> bool: + return ( + isinstance(self.right, RTuple) + and len(self.right.types) == len(left.types) + and all(is_same_type(t1, t2) for t1, t2 in zip(left.types, self.right.types)) + ) + + def visit_rstruct(self, left: RStruct) -> bool: + return isinstance(self.right, RStruct) and self.right.name == left.name + + def visit_rarray(self, left: RArray) -> bool: + return left == self.right + + def visit_rvoid(self, left: RVoid) -> bool: + return isinstance(self.right, RVoid) diff --git a/micromamba_root/Lib/site-packages/mypyc/subtype.cp314-win_amd64.pyd b/micromamba_root/Lib/site-packages/mypyc/subtype.cp314-win_amd64.pyd new file mode 100644 index 0000000000000000000000000000000000000000..e92b09c3a5a4dbffda930feb0708903e4deadd92 Binary files /dev/null and b/micromamba_root/Lib/site-packages/mypyc/subtype.cp314-win_amd64.pyd differ diff --git a/micromamba_root/Lib/site-packages/mypyc/subtype.py b/micromamba_root/Lib/site-packages/mypyc/subtype.py new file mode 100644 index 0000000000000000000000000000000000000000..085cfc4f60a4b07a929d0871712511646530e1f9 --- /dev/null +++ b/micromamba_root/Lib/site-packages/mypyc/subtype.py @@ -0,0 +1,103 @@ +"""Subtype check for RTypes.""" + +from __future__ import annotations + +from mypyc.ir.rtypes import ( + RArray, + RInstance, + RPrimitive, + RStruct, + RTuple, + RType, + RTypeVisitor, + RUnion, + RVec, + RVoid, + is_bit_rprimitive, + is_bool_rprimitive, + is_fixed_width_rtype, + is_int_rprimitive, + is_object_rprimitive, + is_short_int_rprimitive, + is_tagged, + is_tuple_rprimitive, +) + + +def is_subtype(left: RType, right: RType, *, relaxed: bool = False) -> bool: + if is_object_rprimitive(right): + return True + elif isinstance(right, RUnion): + if isinstance(left, RUnion): + for left_item in left.items: + if not any( + is_subtype(left_item, right_item, relaxed=relaxed) + for right_item in right.items + ): + return False + return True + else: + return any(is_subtype(left, item, relaxed=relaxed) for item in right.items) + return left.accept(SubtypeVisitor(right, relaxed=relaxed)) + + +class SubtypeVisitor(RTypeVisitor[bool]): + """Is left a subtype of right? + + A few special cases such as right being 'object' are handled in + is_subtype and don't need to be covered here. + """ + + def __init__(self, right: RType, *, relaxed: bool = False) -> None: + self.right = right + self.relaxed = relaxed + + def visit_rinstance(self, left: RInstance) -> bool: + return isinstance(self.right, RInstance) and self.right.class_ir in left.class_ir.mro + + def visit_rvec(self, left: RVec) -> bool: + # TODO: Better implementation + return left == self.right + + def visit_runion(self, left: RUnion) -> bool: + return all(is_subtype(item, self.right, relaxed=self.relaxed) for item in left.items) + + def visit_rprimitive(self, left: RPrimitive) -> bool: + right = self.right + if is_bool_rprimitive(left): + if is_tagged(right) or is_fixed_width_rtype(right): + return True + elif is_bit_rprimitive(left): + if is_bool_rprimitive(right) or is_tagged(right) or is_fixed_width_rtype(right): + return True + elif is_short_int_rprimitive(left): + if is_int_rprimitive(right): + return True + if self.relaxed and is_fixed_width_rtype(right): + return True + elif is_int_rprimitive(left): + if self.relaxed and is_fixed_width_rtype(right): + return True + elif is_fixed_width_rtype(left): + if is_int_rprimitive(right): + return True + return left is right + + def visit_rtuple(self, left: RTuple) -> bool: + if is_tuple_rprimitive(self.right): + return True + if isinstance(self.right, RTuple): + return len(self.right.types) == len(left.types) and all( + is_subtype(t1, t2, relaxed=self.relaxed) + for t1, t2 in zip(left.types, self.right.types) + ) + return False + + def visit_rstruct(self, left: RStruct) -> bool: + return isinstance(self.right, RStruct) and self.right.name == left.name + + def visit_rarray(self, left: RArray) -> bool: + return left == self.right + + def visit_rvoid(self, left: RVoid) -> bool: + return isinstance(self.right, RVoid) diff --git a/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/INSTALLER b/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a34a7e56db35cc4c85bfa166244b3d63a6a240d4 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/INSTALLER @@ -0,0 +1 @@ +conda diff --git a/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/METADATA b/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..d7ca45662842ba99c3ecaf0c6771029f4afef966 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/METADATA @@ -0,0 +1,112 @@ +Metadata-Version: 2.4 +Name: packaging +Version: 26.2 +Summary: Core utilities for Python packages +Author-email: Donald Stufft +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-Expression: Apache-2.0 OR BSD-2-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Programming Language :: Python :: Free Threading :: 4 - Resilient +Classifier: Typing :: Typed +License-File: LICENSE +License-File: LICENSE.APACHE +License-File: LICENSE.BSD +Project-URL: Documentation, https://packaging.pypa.io/ +Project-URL: Source, https://github.com/pypa/packaging + +packaging +========= + +.. start-intro + +Reusable core utilities for various Python Packaging +`interoperability specifications `_. + +This library provides utilities that implement the interoperability +specifications which have clearly one correct behaviour (eg: :pep:`440`) +or benefit greatly from having a single shared implementation (eg: :pep:`425`). + +.. end-intro + +The ``packaging`` project includes the following: version handling, specifiers, +markers, requirements, tags, metadata, lockfiles, utilities. + +Documentation +------------- + +The `documentation`_ provides information and the API for the following: + +- Version Handling +- Specifiers +- Markers +- Licenses +- Requirements +- Metadata +- Tags +- Lockfiles (pylock) +- Direct URL helpers +- Dependency groups +- Errors +- Utilities + +Installation +------------ + +Use ``pip`` to install these utilities:: + + pip install packaging + +The ``packaging`` library uses calendar-based versioning (``YY.N``). + +Discussion +---------- + +If you run into bugs, you can file them in our `issue tracker`_. + +You can also join discussions on `GitHub Discussions`_ to ask questions or get involved. + +.. _`documentation`: https://packaging.pypa.io/ +.. _`issue tracker`: https://github.com/pypa/packaging/issues +.. _`GitHub Discussions`: https://github.com/pypa/packaging/discussions + + +Code of Conduct +--------------- + +Everyone interacting in the packaging project's codebases, issue trackers, chat +rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_. + +.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md + +Contributing +------------ + +The ``CONTRIBUTING.rst`` file outlines how to contribute to this project as +well as how to report a potential security issue. The documentation for this +project also covers information about `project development`_ and `security`_. + +.. _`project development`: https://packaging.pypa.io/en/latest/development/ +.. _`security`: https://packaging.pypa.io/en/latest/security/ + +Project History +--------------- + +Please review the ``CHANGELOG.rst`` file or the `Changelog documentation`_ for +recent changes and project history. + +.. _`Changelog documentation`: https://packaging.pypa.io/en/latest/changelog/ + diff --git a/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/RECORD b/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..84e56cf05047194e4283f3b85b36251183bf9f92 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/RECORD @@ -0,0 +1,50 @@ +packaging-26.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +packaging-26.2.dist-info/METADATA,sha256=T5y815M0FaR5P3dnyYoralEsgj_IHIczeBVwXyMOyr8,3543 +packaging-26.2.dist-info/RECORD,, +packaging-26.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +packaging-26.2.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +packaging-26.2.dist-info/direct_url.json,sha256=6Ft2e2b7eqDhCIzLNO8TNE_5d9SaQJl2NRE7og8vGes,120 +packaging-26.2.dist-info/licenses/LICENSE,sha256=ytHvW9NA1z4HS6YU0m996spceUDD2MNIUuZcSQlobEg,197 +packaging-26.2.dist-info/licenses/LICENSE.APACHE,sha256=DVQuDIgE45qn836wDaWnYhSdxoLXgpRRKH4RuTjpRZQ,10174 +packaging-26.2.dist-info/licenses/LICENSE.BSD,sha256=tw5-m3QvHMb5SLNMFqo5_-zpQZY2S8iP8NIYDwAo-sU,1344 +packaging/__init__.py,sha256=QhMEdPu2XogrJzV3S0KWS6t7l0I9k8EeDRJl4fnw87s,494 +packaging/__pycache__/__init__.cpython-38.pyc,, +packaging/__pycache__/_elffile.cpython-38.pyc,, +packaging/__pycache__/_manylinux.cpython-38.pyc,, +packaging/__pycache__/_musllinux.cpython-38.pyc,, +packaging/__pycache__/_parser.cpython-38.pyc,, +packaging/__pycache__/_structures.cpython-38.pyc,, +packaging/__pycache__/_tokenizer.cpython-38.pyc,, +packaging/__pycache__/dependency_groups.cpython-38.pyc,, +packaging/__pycache__/direct_url.cpython-38.pyc,, +packaging/__pycache__/errors.cpython-38.pyc,, +packaging/__pycache__/markers.cpython-38.pyc,, +packaging/__pycache__/metadata.cpython-38.pyc,, +packaging/__pycache__/pylock.cpython-38.pyc,, +packaging/__pycache__/requirements.cpython-38.pyc,, +packaging/__pycache__/specifiers.cpython-38.pyc,, +packaging/__pycache__/tags.cpython-38.pyc,, +packaging/__pycache__/utils.cpython-38.pyc,, +packaging/__pycache__/version.cpython-38.pyc,, +packaging/_elffile.py,sha256=-sKkptYqzYw2-x3QByJa5mB4rfPWu1pxkZHRx1WAFCY,3211 +packaging/_manylinux.py,sha256=Hf6nB0cOrayEs96-p3oIXAgGnFquv20DO5l-o2_Xnv0,9559 +packaging/_musllinux.py,sha256=Z6swjH3MA7XS3qXnmMN7QPhqP3fnoYI0eQ18e9-HgAE,2707 +packaging/_parser.py,sha256=Kf2nsDw4c54X82pY8ba4F02Bve6OygGMAjL-Begqcew,11698 +packaging/_structures.py,sha256=60jRbF78p8z5MKnNd6cAprgOadCJHV0DlmUmRBqFZcs,1109 +packaging/_tokenizer.py,sha256=tFU2Wr-ZZJdAbkXLEJo7qUQDJaIkfft9DqaifiEND7A,5391 +packaging/dependency_groups.py,sha256=XZIAVFK9uHG4RCGprmJn3VInUWMesxha_kytJuMO9eY,10218 +packaging/direct_url.py,sha256=eKmbDiPP1sLV4Mj_kCSZqqknrIyVO9Sr7JpF8KCjp4U,10917 +packaging/errors.py,sha256=6hfEYXAf8v_IF65-lFadJOMIieBP2xIKtyEXjG1nGIs,2680 +packaging/licenses/__init__.py,sha256=_Jx0XRiD_58palsWnyLrLuh59ZpGCPIPXLKdZo9OJvQ,7293 +packaging/licenses/__pycache__/__init__.cpython-38.pyc,, +packaging/licenses/__pycache__/_spdx.cpython-38.pyc,, +packaging/licenses/_spdx.py,sha256=WW7DXiyg68up_YND_wpRYlr1SHhiV4FfJLQffghhMxQ,51122 +packaging/markers.py,sha256=8fDIUhAF6YMnCNB5FSiwh9pEIusiFzAF73J-0OB8bTk,17055 +packaging/metadata.py,sha256=crAh0E3GVGVqPlu6EdRFsaG-Y6UYznTUqjuGKRGPv6c,38770 +packaging/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +packaging/pylock.py,sha256=G_1gncTmDbRLY1jo4VDI9Uw-b5IErh_Q9V_BbVJTmD8,33890 +packaging/requirements.py,sha256=dd1c9aa1gp5NI6btF6UFRQjPn1nxQXnE_T34yDDTEpc,4383 +packaging/specifiers.py,sha256=Mfp8avQg0lVot17to9lVKBtZD1FsWBTItoGwFUZ3wtg,71514 +packaging/tags.py,sha256=NQ1weo69_Sjte3xBZ1I_G63CIgCmaN0C24mz-z3hGYo,34224 +packaging/utils.py,sha256=M7-JMKic2sP1YtV_8aW7eVGB-x3ADuKCiSrsVeCd2Uo,9848 +packaging/version.py,sha256=Y1aTtxe3sn2xOMa5BdI85-AcHuybbanOVkEvvSRRC8I,38369 diff --git a/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/REQUESTED b/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/WHEEL b/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/direct_url.json b/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/direct_url.json new file mode 100644 index 0000000000000000000000000000000000000000..174a6f4ea68b376cf4017ee430d136f92b05ad88 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging-26.2.dist-info/direct_url.json @@ -0,0 +1 @@ +{"dir_info": {}, "url": "file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_packaging_1777103621/work"} \ No newline at end of file diff --git a/micromamba_root/Lib/site-packages/packaging/__init__.py b/micromamba_root/Lib/site-packages/packaging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a6bdf59cd713d41593ba3da47032a831a1be1504 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/__init__.py @@ -0,0 +1,15 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +__title__ = "packaging" +__summary__ = "Core utilities for Python packages" +__uri__ = "https://github.com/pypa/packaging" + +__version__ = "26.2" + +__author__ = "Donald Stufft and individual contributors" +__email__ = "donald@stufft.io" + +__license__ = "BSD-2-Clause or Apache-2.0" +__copyright__ = f"2014 {__author__}" diff --git a/micromamba_root/Lib/site-packages/packaging/_elffile.py b/micromamba_root/Lib/site-packages/packaging/_elffile.py new file mode 100644 index 0000000000000000000000000000000000000000..497b0645217512ae2ba8ff61341fd2bbfa3648cd --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/_elffile.py @@ -0,0 +1,108 @@ +""" +ELF file parser. + +This provides a class ``ELFFile`` that parses an ELF executable in a similar +interface to ``ZipFile``. Only the read interface is implemented. + +ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html +""" + +from __future__ import annotations + +import enum +import os +import struct +from typing import IO + + +class ELFInvalid(ValueError): + pass + + +class EIClass(enum.IntEnum): + C32 = 1 + C64 = 2 + + +class EIData(enum.IntEnum): + Lsb = 1 + Msb = 2 + + +class EMachine(enum.IntEnum): + I386 = 3 + S390 = 22 + Arm = 40 + X8664 = 62 + AArc64 = 183 + + +class ELFFile: + """ + Representation of an ELF executable. + """ + + def __init__(self, f: IO[bytes]) -> None: + self._f = f + + try: + ident = self._read("16B") + except struct.error as e: + raise ELFInvalid("unable to parse identification") from e + magic = bytes(ident[:4]) + if magic != b"\x7fELF": + raise ELFInvalid(f"invalid magic: {magic!r}") + + self.capacity = ident[4] # Format for program header (bitness). + self.encoding = ident[5] # Data structure encoding (endianness). + + try: + # e_fmt: Format for program header. + # p_fmt: Format for section header. + # p_idx: Indexes to find p_type, p_offset, and p_filesz. + e_fmt, self._p_fmt, self._p_idx = { + (1, 1): ("HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB. + (2, 1): ("HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB. + }[(self.capacity, self.encoding)] + except KeyError as e: + raise ELFInvalid( + f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})" + ) from e + + try: + ( + _, + self.machine, # Architecture type. + _, + _, + self._e_phoff, # Offset of program header. + _, + self.flags, # Processor-specific flags. + _, + self._e_phentsize, # Size of section. + self._e_phnum, # Number of sections. + ) = self._read(e_fmt) + except struct.error as e: + raise ELFInvalid("unable to parse machine and section information") from e + + def _read(self, fmt: str) -> tuple[int, ...]: + return struct.unpack(fmt, self._f.read(struct.calcsize(fmt))) + + @property + def interpreter(self) -> str | None: + """ + The path recorded in the ``PT_INTERP`` section header. + """ + for index in range(self._e_phnum): + self._f.seek(self._e_phoff + self._e_phentsize * index) + try: + data = self._read(self._p_fmt) + except struct.error: + continue + if data[self._p_idx[0]] != 3: # Not PT_INTERP. + continue + self._f.seek(data[self._p_idx[1]]) + return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0") + return None diff --git a/micromamba_root/Lib/site-packages/packaging/_manylinux.py b/micromamba_root/Lib/site-packages/packaging/_manylinux.py new file mode 100644 index 0000000000000000000000000000000000000000..0e79e8a882be74fe76c80ccf49a9cd68fb636fd4 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/_manylinux.py @@ -0,0 +1,262 @@ +from __future__ import annotations + +import collections +import contextlib +import functools +import os +import re +import sys +import warnings +from typing import Generator, Iterator, NamedTuple, Sequence + +from ._elffile import EIClass, EIData, ELFFile, EMachine + +EF_ARM_ABIMASK = 0xFF000000 +EF_ARM_ABI_VER5 = 0x05000000 +EF_ARM_ABI_FLOAT_HARD = 0x00000400 + +_ALLOWED_ARCHS = { + "x86_64", + "aarch64", + "ppc64", + "ppc64le", + "s390x", + "loongarch64", + "riscv64", +} + + +# `os.PathLike` not a generic type until Python 3.9, so sticking with `str` +# as the type for `path` until then. +@contextlib.contextmanager +def _parse_elf(path: str) -> Generator[ELFFile | None, None, None]: + try: + with open(path, "rb") as f: + yield ELFFile(f) + except (OSError, TypeError, ValueError): + yield None + + +def _is_linux_armhf(executable: str) -> bool: + # hard-float ABI can be detected from the ELF header of the running + # process + # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf + with _parse_elf(executable) as f: + return ( + f is not None + and f.capacity == EIClass.C32 + and f.encoding == EIData.Lsb + and f.machine == EMachine.Arm + and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5 + and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD + ) + + +def _is_linux_i686(executable: str) -> bool: + with _parse_elf(executable) as f: + return ( + f is not None + and f.capacity == EIClass.C32 + and f.encoding == EIData.Lsb + and f.machine == EMachine.I386 + ) + + +def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool: + if "armv7l" in archs: + return _is_linux_armhf(executable) + if "i686" in archs: + return _is_linux_i686(executable) + return any(arch in _ALLOWED_ARCHS for arch in archs) + + +# If glibc ever changes its major version, we need to know what the last +# minor version was, so we can build the complete list of all versions. +# For now, guess what the highest minor version might be, assume it will +# be 50 for testing. Once this actually happens, update the dictionary +# with the actual value. +_LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50) + + +class _GLibCVersion(NamedTuple): + major: int + minor: int + + +def _glibc_version_string_confstr() -> str | None: + """ + Primary implementation of glibc_version_string using os.confstr. + """ + # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely + # to be broken or missing. This strategy is used in the standard library + # platform module. + # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183 + try: + # Should be a string like "glibc 2.17". + version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION") + assert version_string is not None + _, version = version_string.rsplit() + except (AssertionError, AttributeError, OSError, ValueError): + # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)... + return None + return version + + +def _glibc_version_string_ctypes() -> str | None: + """ + Fallback implementation of glibc_version_string using ctypes. + """ + try: + import ctypes # noqa: PLC0415 + except ImportError: + return None + + # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen + # manpage says, "If filename is NULL, then the returned handle is for the + # main program". This way we can let the linker do the work to figure out + # which libc our process is actually using. + # + # We must also handle the special case where the executable is not a + # dynamically linked executable. This can occur when using musl libc, + # for example. In this situation, dlopen() will error, leading to an + # OSError. Interestingly, at least in the case of musl, there is no + # errno set on the OSError. The single string argument used to construct + # OSError comes from libc itself and is therefore not portable to + # hard code here. In any case, failure to call dlopen() means we + # can proceed, so we bail on our attempt. + try: + process_namespace = ctypes.CDLL(None) + except OSError: + return None + + try: + gnu_get_libc_version = process_namespace.gnu_get_libc_version + except AttributeError: + # Symbol doesn't exist -> therefore, we are not linked to + # glibc. + return None + + # Call gnu_get_libc_version, which returns a string like "2.5" + gnu_get_libc_version.restype = ctypes.c_char_p + version_str: str = gnu_get_libc_version() + # py2 / py3 compatibility: + if not isinstance(version_str, str): + version_str = version_str.decode("ascii") + + return version_str + + +def _glibc_version_string() -> str | None: + """Returns glibc version string, or None if not using glibc.""" + return _glibc_version_string_confstr() or _glibc_version_string_ctypes() + + +def _parse_glibc_version(version_str: str) -> _GLibCVersion: + """Parse glibc version. + + We use a regexp instead of str.split because we want to discard any + random junk that might come after the minor version -- this might happen + in patched/forked versions of glibc (e.g. Linaro's version of glibc + uses version strings like "2.20-2014.11"). See gh-3588. + """ + m = re.match(r"(?P[0-9]+)\.(?P[0-9]+)", version_str) + if not m: + warnings.warn( + f"Expected glibc version with 2 components major.minor, got: {version_str}", + RuntimeWarning, + stacklevel=2, + ) + return _GLibCVersion(-1, -1) + return _GLibCVersion(int(m.group("major")), int(m.group("minor"))) + + +@functools.lru_cache +def _get_glibc_version() -> _GLibCVersion: + version_str = _glibc_version_string() + if version_str is None: + return _GLibCVersion(-1, -1) + return _parse_glibc_version(version_str) + + +# From PEP 513, PEP 600 +def _is_compatible(arch: str, version: _GLibCVersion) -> bool: + sys_glibc = _get_glibc_version() + if sys_glibc < version: + return False + # Check for presence of _manylinux module. + try: + import _manylinux # noqa: PLC0415 + except ImportError: + return True + if hasattr(_manylinux, "manylinux_compatible"): + result = _manylinux.manylinux_compatible(version[0], version[1], arch) + if result is not None: + return bool(result) + return True + if version == _GLibCVersion(2, 5) and hasattr(_manylinux, "manylinux1_compatible"): + return bool(_manylinux.manylinux1_compatible) + if version == _GLibCVersion(2, 12) and hasattr( + _manylinux, "manylinux2010_compatible" + ): + return bool(_manylinux.manylinux2010_compatible) + if version == _GLibCVersion(2, 17) and hasattr( + _manylinux, "manylinux2014_compatible" + ): + return bool(_manylinux.manylinux2014_compatible) + return True + + +_LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = { + # CentOS 7 w/ glibc 2.17 (PEP 599) + _GLibCVersion(2, 17): "manylinux2014", + # CentOS 6 w/ glibc 2.12 (PEP 571) + _GLibCVersion(2, 12): "manylinux2010", + # CentOS 5 w/ glibc 2.5 (PEP 513) + _GLibCVersion(2, 5): "manylinux1", +} + + +def platform_tags(archs: Sequence[str]) -> Iterator[str]: + """Generate manylinux tags compatible to the current platform. + + :param archs: Sequence of compatible architectures. + The first one shall be the closest to the actual architecture and be the part of + platform tag after the ``linux_`` prefix, e.g. ``x86_64``. + The ``linux_`` prefix is assumed as a prerequisite for the current platform to + be manylinux-compatible. + + :returns: An iterator of compatible manylinux tags. + """ + if not _have_compatible_abi(sys.executable, archs): + return + # Oldest glibc to be supported regardless of architecture is (2, 17). + too_old_glibc2 = _GLibCVersion(2, 16) + if set(archs) & {"x86_64", "i686"}: + # On x86/i686 also oldest glibc to be supported is (2, 5). + too_old_glibc2 = _GLibCVersion(2, 4) + current_glibc = _GLibCVersion(*_get_glibc_version()) + glibc_max_list = [current_glibc] + # We can assume compatibility across glibc major versions. + # https://sourceware.org/bugzilla/show_bug.cgi?id=24636 + # + # Build a list of maximum glibc versions so that we can + # output the canonical list of all glibc from current_glibc + # down to too_old_glibc2, including all intermediary versions. + for glibc_major in range(current_glibc.major - 1, 1, -1): + glibc_minor = _LAST_GLIBC_MINOR[glibc_major] + glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor)) + for arch in archs: + for glibc_max in glibc_max_list: + if glibc_max.major == too_old_glibc2.major: + min_minor = too_old_glibc2.minor + else: + # For other glibc major versions oldest supported is (x, 0). + min_minor = -1 + for glibc_minor in range(glibc_max.minor, min_minor, -1): + glibc_version = _GLibCVersion(glibc_max.major, glibc_minor) + if _is_compatible(arch, glibc_version): + yield "manylinux_{}_{}_{}".format(*glibc_version, arch) + + # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags. + if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version): + yield f"{legacy_tag}_{arch}" diff --git a/micromamba_root/Lib/site-packages/packaging/_musllinux.py b/micromamba_root/Lib/site-packages/packaging/_musllinux.py new file mode 100644 index 0000000000000000000000000000000000000000..4e8116a79ca80d60657542a23b4bbcbc3c518eaf --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/_musllinux.py @@ -0,0 +1,85 @@ +"""PEP 656 support. + +This module implements logic to detect if the currently running Python is +linked against musl, and what musl version is used. +""" + +from __future__ import annotations + +import functools +import re +import subprocess +import sys +from typing import Iterator, NamedTuple, Sequence + +from ._elffile import ELFFile + + +class _MuslVersion(NamedTuple): + major: int + minor: int + + +def _parse_musl_version(output: str) -> _MuslVersion | None: + lines = [n for n in (n.strip() for n in output.splitlines()) if n] + if len(lines) < 2 or lines[0][:4] != "musl": + return None + m = re.match(r"Version (\d+)\.(\d+)", lines[1]) + if not m: + return None + return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2))) + + +@functools.lru_cache +def _get_musl_version(executable: str) -> _MuslVersion | None: + """Detect currently-running musl runtime version. + + This is done by checking the specified executable's dynamic linking + information, and invoking the loader to parse its output for a version + string. If the loader is musl, the output would be something like:: + + musl libc (x86_64) + Version 1.2.2 + Dynamic Program Loader + """ + try: + with open(executable, "rb") as f: + ld = ELFFile(f).interpreter + except (OSError, TypeError, ValueError): + return None + if ld is None or "musl" not in ld: + return None + proc = subprocess.run([ld], check=False, stderr=subprocess.PIPE, text=True) + return _parse_musl_version(proc.stderr) + + +def platform_tags(archs: Sequence[str]) -> Iterator[str]: + """Generate musllinux tags compatible to the current platform. + + :param archs: Sequence of compatible architectures. + The first one shall be the closest to the actual architecture and be the part of + platform tag after the ``linux_`` prefix, e.g. ``x86_64``. + The ``linux_`` prefix is assumed as a prerequisite for the current platform to + be musllinux-compatible. + + :returns: An iterator of compatible musllinux tags. + """ + sys_musl = _get_musl_version(sys.executable) + if sys_musl is None: # Python not dynamically linked against musl. + return + for arch in archs: + for minor in range(sys_musl.minor, -1, -1): + yield f"musllinux_{sys_musl.major}_{minor}_{arch}" + + +if __name__ == "__main__": # pragma: no cover + import sysconfig + + plat = sysconfig.get_platform() + assert plat.startswith("linux-"), "not linux" + + print("plat:", plat) + print("musl:", _get_musl_version(sys.executable)) + print("tags:", end=" ") + for t in platform_tags(re.sub(r"[.-]", "_", plat.split("-", 1)[-1])): + print(t, end="\n ") diff --git a/micromamba_root/Lib/site-packages/packaging/_parser.py b/micromamba_root/Lib/site-packages/packaging/_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..d320269e1531d822003bde7a826ba24eecca3bae --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/_parser.py @@ -0,0 +1,393 @@ +"""Handwritten parser of dependency specifiers. + +The docstring for each __parse_* function contains EBNF-inspired grammar representing +the implementation. +""" + +from __future__ import annotations + +import ast +from typing import List, Literal, NamedTuple, Sequence, Tuple, Union + +from ._tokenizer import DEFAULT_RULES, Tokenizer + + +class Node: + __slots__ = ("value",) + + def __init__(self, value: str) -> None: + self.value = value + + def __str__(self) -> str: + return self.value + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}({self.value!r})>" + + def serialize(self) -> str: + raise NotImplementedError + + def __getstate__(self) -> str: + # Return just the value string for compactness and stability. + return self.value + + def _restore_value(self, value: object) -> None: + if not isinstance(value, str): + raise TypeError( + f"Cannot restore {self.__class__.__name__} value from {value!r}" + ) + self.value = value + + def __setstate__(self, state: object) -> None: + if isinstance(state, str): + # New format (26.2+): just the value string. + self._restore_value(state) + return + if isinstance(state, tuple) and len(state) == 2: + # Old format (packaging <= 26.0, __slots__): (None, {slot: value}). + _, slot_dict = state + if isinstance(slot_dict, dict) and "value" in slot_dict: + self._restore_value(slot_dict["value"]) + return + if isinstance(state, dict) and "value" in state: + # Old format (packaging <= 25.0, no __slots__): plain __dict__. + self._restore_value(state["value"]) + return + raise TypeError(f"Cannot restore {self.__class__.__name__} from {state!r}") + + +class Variable(Node): + __slots__ = () + + def serialize(self) -> str: + return str(self) + + +class Value(Node): + __slots__ = () + + def serialize(self) -> str: + return f'"{self}"' + + +class Op(Node): + __slots__ = () + + def serialize(self) -> str: + return str(self) + + +MarkerLogical = Literal["and", "or"] +MarkerVar = Union[Variable, Value] +MarkerItem = Tuple[MarkerVar, Op, MarkerVar] +MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]] +MarkerList = List[Union["MarkerList", MarkerAtom, MarkerLogical]] + + +class ParsedRequirement(NamedTuple): + name: str + url: str + extras: list[str] + specifier: str + marker: MarkerList | None + + +# -------------------------------------------------------------------------------------- +# Recursive descent parser for dependency specifier +# -------------------------------------------------------------------------------------- +def parse_requirement(source: str) -> ParsedRequirement: + return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES)) + + +def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement: + """ + requirement = WS? IDENTIFIER WS? extras WS? requirement_details + """ + tokenizer.consume("WS") + + name_token = tokenizer.expect( + "IDENTIFIER", expected="package name at the start of dependency specifier" + ) + name = name_token.text + tokenizer.consume("WS") + + extras = _parse_extras(tokenizer) + tokenizer.consume("WS") + + url, specifier, marker = _parse_requirement_details(tokenizer) + tokenizer.expect("END", expected="end of dependency specifier") + + return ParsedRequirement(name, url, extras, specifier, marker) + + +def _parse_requirement_details( + tokenizer: Tokenizer, +) -> tuple[str, str, MarkerList | None]: + """ + requirement_details = AT URL (WS requirement_marker?)? + | specifier WS? (requirement_marker)? + """ + + specifier = "" + url = "" + marker = None + + if tokenizer.check("AT"): + tokenizer.read() + tokenizer.consume("WS") + + url_start = tokenizer.position + url = tokenizer.expect("URL", expected="URL after @").text + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + tokenizer.expect("WS", expected="whitespace after URL") + + # The input might end after whitespace. + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + marker = _parse_requirement_marker( + tokenizer, + span_start=url_start, + expected="semicolon (after URL and whitespace)", + ) + else: + specifier_start = tokenizer.position + specifier = _parse_specifier(tokenizer) + tokenizer.consume("WS") + + if tokenizer.check("END", peek=True): + return (url, specifier, marker) + + marker = _parse_requirement_marker( + tokenizer, + span_start=specifier_start, + expected=( + "comma (within version specifier), semicolon (after version specifier)" + if specifier + else "semicolon (after name with no version specifier)" + ), + ) + + return (url, specifier, marker) + + +def _parse_requirement_marker( + tokenizer: Tokenizer, *, span_start: int, expected: str +) -> MarkerList: + """ + requirement_marker = SEMICOLON marker WS? + """ + + if not tokenizer.check("SEMICOLON"): + tokenizer.raise_syntax_error( + f"Expected {expected} or end", + span_start=span_start, + span_end=None, + ) + tokenizer.read() + + marker = _parse_marker(tokenizer) + tokenizer.consume("WS") + + return marker + + +def _parse_extras(tokenizer: Tokenizer) -> list[str]: + """ + extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)? + """ + if not tokenizer.check("LEFT_BRACKET", peek=True): + return [] + + with tokenizer.enclosing_tokens( + "LEFT_BRACKET", + "RIGHT_BRACKET", + around="extras", + ): + tokenizer.consume("WS") + extras = _parse_extras_list(tokenizer) + tokenizer.consume("WS") + + return extras + + +def _parse_extras_list(tokenizer: Tokenizer) -> list[str]: + """ + extras_list = identifier (wsp* ',' wsp* identifier)* + """ + extras: list[str] = [] + + if not tokenizer.check("IDENTIFIER"): + return extras + + extras.append(tokenizer.read().text) + + while True: + tokenizer.consume("WS") + if tokenizer.check("IDENTIFIER", peek=True): + tokenizer.raise_syntax_error("Expected comma between extra names") + elif not tokenizer.check("COMMA"): + break + + tokenizer.read() + tokenizer.consume("WS") + + extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma") + extras.append(extra_token.text) + + return extras + + +def _parse_specifier(tokenizer: Tokenizer) -> str: + """ + specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS + | WS? version_many WS? + """ + with tokenizer.enclosing_tokens( + "LEFT_PARENTHESIS", + "RIGHT_PARENTHESIS", + around="version specifier", + ): + tokenizer.consume("WS") + parsed_specifiers = _parse_version_many(tokenizer) + tokenizer.consume("WS") + + return parsed_specifiers + + +def _parse_version_many(tokenizer: Tokenizer) -> str: + """ + version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)? + """ + parsed_specifiers = "" + while tokenizer.check("SPECIFIER"): + span_start = tokenizer.position + parsed_specifiers += tokenizer.read().text + if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True): + tokenizer.raise_syntax_error( + ".* suffix can only be used with `==` or `!=` operators", + span_start=span_start, + span_end=tokenizer.position + 1, + ) + if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True): + tokenizer.raise_syntax_error( + "Local version label can only be used with `==` or `!=` operators", + span_start=span_start, + span_end=tokenizer.position, + ) + tokenizer.consume("WS") + if not tokenizer.check("COMMA"): + break + parsed_specifiers += tokenizer.read().text + tokenizer.consume("WS") + + return parsed_specifiers + + +# -------------------------------------------------------------------------------------- +# Recursive descent parser for marker expression +# -------------------------------------------------------------------------------------- +def parse_marker(source: str) -> MarkerList: + return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES)) + + +def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList: + retval = _parse_marker(tokenizer) + tokenizer.expect("END", expected="end of marker expression") + return retval + + +def _parse_marker(tokenizer: Tokenizer) -> MarkerList: + """ + marker = marker_atom (BOOLOP marker_atom)+ + """ + expression = [_parse_marker_atom(tokenizer)] + while tokenizer.check("BOOLOP"): + token = tokenizer.read() + expr_right = _parse_marker_atom(tokenizer) + expression.extend((token.text, expr_right)) + return expression + + +def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom: + """ + marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS? + | WS? marker_item WS? + """ + + tokenizer.consume("WS") + if tokenizer.check("LEFT_PARENTHESIS", peek=True): + with tokenizer.enclosing_tokens( + "LEFT_PARENTHESIS", + "RIGHT_PARENTHESIS", + around="marker expression", + ): + tokenizer.consume("WS") + marker: MarkerAtom = _parse_marker(tokenizer) + tokenizer.consume("WS") + else: + marker = _parse_marker_item(tokenizer) + tokenizer.consume("WS") + return marker + + +def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem: + """ + marker_item = WS? marker_var WS? marker_op WS? marker_var WS? + """ + tokenizer.consume("WS") + marker_var_left = _parse_marker_var(tokenizer) + tokenizer.consume("WS") + marker_op = _parse_marker_op(tokenizer) + tokenizer.consume("WS") + marker_var_right = _parse_marker_var(tokenizer) + tokenizer.consume("WS") + return (marker_var_left, marker_op, marker_var_right) + + +def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: # noqa: RET503 + """ + marker_var = VARIABLE | QUOTED_STRING + """ + if tokenizer.check("VARIABLE"): + return process_env_var(tokenizer.read().text.replace(".", "_")) + elif tokenizer.check("QUOTED_STRING"): + return process_python_str(tokenizer.read().text) + else: + tokenizer.raise_syntax_error( + message="Expected a marker variable or quoted string" + ) + + +def process_env_var(env_var: str) -> Variable: + if env_var in ("platform_python_implementation", "python_implementation"): + return Variable("platform_python_implementation") + else: + return Variable(env_var) + + +def process_python_str(python_str: str) -> Value: + value = ast.literal_eval(python_str) + return Value(str(value)) + + +def _parse_marker_op(tokenizer: Tokenizer) -> Op: + """ + marker_op = IN | NOT IN | OP + """ + if tokenizer.check("IN"): + tokenizer.read() + return Op("in") + elif tokenizer.check("NOT"): + tokenizer.read() + tokenizer.expect("WS", expected="whitespace after 'not'") + tokenizer.expect("IN", expected="'in' after 'not'") + return Op("not in") + elif tokenizer.check("OP"): + return Op(tokenizer.read().text) + else: + return tokenizer.raise_syntax_error( + "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in" + ) diff --git a/micromamba_root/Lib/site-packages/packaging/_structures.py b/micromamba_root/Lib/site-packages/packaging/_structures.py new file mode 100644 index 0000000000000000000000000000000000000000..4306784d9a26466aa0a210cb2f262903c67d46ca --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/_structures.py @@ -0,0 +1,33 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +"""Backward-compatibility shim for unpickling Version objects serialized before +packaging 26.1. + +Old pickles reference ``packaging._structures.InfinityType`` and +``packaging._structures.NegativeInfinityType``. This module provides minimal +stand-in classes so that ``pickle.loads()`` can resolve those references. +The deserialized objects are not used for comparisons — ``Version.__setstate__`` +discards the stale ``_key`` cache and recomputes it from the core version fields. +""" + +from __future__ import annotations + + +class InfinityType: + """Stand-in for the removed ``InfinityType`` used in old comparison keys.""" + + def __repr__(self) -> str: + return "Infinity" + + +class NegativeInfinityType: + """Stand-in for the removed ``NegativeInfinityType`` used in old comparison keys.""" + + def __repr__(self) -> str: + return "-Infinity" + + +Infinity = InfinityType() +NegativeInfinity = NegativeInfinityType() diff --git a/micromamba_root/Lib/site-packages/packaging/_tokenizer.py b/micromamba_root/Lib/site-packages/packaging/_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..5ab891ccb8e9048cf64573ca303357efe6afae32 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/_tokenizer.py @@ -0,0 +1,193 @@ +from __future__ import annotations + +import contextlib +import re +from dataclasses import dataclass +from typing import Generator, Mapping, NoReturn + +from .specifiers import Specifier + + +@dataclass +class Token: + name: str + text: str + position: int + + +class ParserSyntaxError(Exception): + """The provided source text could not be parsed correctly.""" + + def __init__( + self, + message: str, + *, + source: str, + span: tuple[int, int], + ) -> None: + self.span = span + self.message = message + self.source = source + + super().__init__() + + def __str__(self) -> str: + marker = " " * self.span[0] + "~" * (self.span[1] - self.span[0]) + "^" + return f"{self.message}\n {self.source}\n {marker}" + + +DEFAULT_RULES: dict[str, re.Pattern[str]] = { + "LEFT_PARENTHESIS": re.compile(r"\("), + "RIGHT_PARENTHESIS": re.compile(r"\)"), + "LEFT_BRACKET": re.compile(r"\["), + "RIGHT_BRACKET": re.compile(r"\]"), + "SEMICOLON": re.compile(r";"), + "COMMA": re.compile(r","), + "QUOTED_STRING": re.compile( + r""" + ( + ('[^']*') + | + ("[^"]*") + ) + """, + re.VERBOSE, + ), + "OP": re.compile(r"(===|==|~=|!=|<=|>=|<|>)"), + "BOOLOP": re.compile(r"\b(or|and)\b"), + "IN": re.compile(r"\bin\b"), + "NOT": re.compile(r"\bnot\b"), + "VARIABLE": re.compile( + r""" + \b( + python_version + |python_full_version + |os[._]name + |sys[._]platform + |platform_(release|system) + |platform[._](version|machine|python_implementation) + |python_implementation + |implementation_(name|version) + |extras? + |dependency_groups + )\b + """, + re.VERBOSE, + ), + "SPECIFIER": re.compile( + Specifier._specifier_regex_str, + re.VERBOSE | re.IGNORECASE, + ), + "AT": re.compile(r"\@"), + "URL": re.compile(r"[^ \t]+"), + "IDENTIFIER": re.compile(r"\b[a-zA-Z0-9][a-zA-Z0-9._-]*\b"), + "VERSION_PREFIX_TRAIL": re.compile(r"\.\*"), + "VERSION_LOCAL_LABEL_TRAIL": re.compile(r"\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*"), + "WS": re.compile(r"[ \t]+"), + "END": re.compile(r"$"), +} + + +class Tokenizer: + """Context-sensitive token parsing. + + Provides methods to examine the input stream to check whether the next token + matches. + """ + + def __init__( + self, + source: str, + *, + rules: Mapping[str, re.Pattern[str]], + ) -> None: + self.source = source + self.rules = rules + self.next_token: Token | None = None + self.position = 0 + + def consume(self, name: str) -> None: + """Move beyond provided token name, if at current position.""" + if self.check(name): + self.read() + + def check(self, name: str, *, peek: bool = False) -> bool: + """Check whether the next token has the provided name. + + By default, if the check succeeds, the token *must* be read before + another check. If `peek` is set to `True`, the token is not loaded and + would need to be checked again. + """ + assert self.next_token is None, ( + f"Cannot check for {name!r}, already have {self.next_token!r}" + ) + assert name in self.rules, f"Unknown token name: {name!r}" + + expression = self.rules[name] + + match = expression.match(self.source, self.position) + if match is None: + return False + if not peek: + self.next_token = Token(name, match[0], self.position) + return True + + def expect(self, name: str, *, expected: str) -> Token: + """Expect a certain token name next, failing with a syntax error otherwise. + + The token is *not* read. + """ + if not self.check(name): + raise self.raise_syntax_error(f"Expected {expected}") + return self.read() + + def read(self) -> Token: + """Consume the next token and return it.""" + token = self.next_token + assert token is not None + + self.position += len(token.text) + self.next_token = None + + return token + + def raise_syntax_error( + self, + message: str, + *, + span_start: int | None = None, + span_end: int | None = None, + ) -> NoReturn: + """Raise ParserSyntaxError at the given position.""" + span = ( + self.position if span_start is None else span_start, + self.position if span_end is None else span_end, + ) + raise ParserSyntaxError( + message, + source=self.source, + span=span, + ) + + @contextlib.contextmanager + def enclosing_tokens( + self, open_token: str, close_token: str, *, around: str + ) -> Generator[None, None, None]: + if self.check(open_token): + open_position = self.position + self.read() + else: + open_position = None + + yield + + if open_position is None: + return + + if not self.check(close_token): + self.raise_syntax_error( + f"Expected matching {close_token} for {open_token}, after {around}", + span_start=open_position, + ) + + self.read() diff --git a/micromamba_root/Lib/site-packages/packaging/dependency_groups.py b/micromamba_root/Lib/site-packages/packaging/dependency_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..413e5cb4b40d734564b99092320bb58a8f3c2c2b --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/dependency_groups.py @@ -0,0 +1,302 @@ +from __future__ import annotations + +import re +from collections.abc import Mapping, Sequence + +from .errors import _ErrorCollector +from .requirements import Requirement + +__all__ = [ + "CyclicDependencyGroup", + "DependencyGroupInclude", + "DependencyGroupResolver", + "DuplicateGroupNames", + "InvalidDependencyGroupObject", + "resolve_dependency_groups", +] + + +def __dir__() -> list[str]: + return __all__ + + +# ----------- +# Error Types +# ----------- + + +class DuplicateGroupNames(ValueError): + """ + The same dependency groups were defined twice, with different non-normalized names. + """ + + +class CyclicDependencyGroup(ValueError): + """ + The dependency group includes form a cycle. + """ + + def __init__(self, requested_group: str, group: str, include_group: str) -> None: + self.requested_group = requested_group + self.group = group + self.include_group = include_group + + if include_group == group: + reason = f"{group} includes itself" + else: + reason = f"{include_group} -> {group}, {group} -> {include_group}" + super().__init__( + "Cyclic dependency group include while resolving " + f"{requested_group}: {reason}" + ) + + +# in the PEP 735 spec, the tables in dependency group lists were described as +# "Dependency Object Specifiers", but the only defined type of object was a +# "Dependency Group Include" -- hence the naming of this error as "Object" +class InvalidDependencyGroupObject(ValueError): + """ + A member of a dependency group was identified as a dict, but was not in a valid + format. + """ + + +# ------------------------ +# Object Model & Interface +# ------------------------ + + +class DependencyGroupInclude: + __slots__ = ("include_group",) + + def __init__(self, include_group: str) -> None: + """ + Initialize a DependencyGroupInclude. + + :param include_group: The name of the group referred to by this include. + """ + self.include_group = include_group + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.include_group!r})" + + +class DependencyGroupResolver: + """ + A resolver for Dependency Group data. + + This class handles caching, name normalization, cycle detection, and other + parsing requirements. There are only two public methods for exploring the data: + ``lookup()`` and ``resolve()``. + + :param dependency_groups: A mapping, as provided via pyproject + ``[dependency-groups]``. + """ + + def __init__( + self, + dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], + ) -> None: + errors = _ErrorCollector() + + self.dependency_groups = _normalize_group_names(dependency_groups, errors) + + # a map of group names to parsed data + self._parsed_groups: dict[ + str, tuple[Requirement | DependencyGroupInclude, ...] + ] = {} + # a map of group names to their ancestors, used for cycle detection + self._include_graph_ancestors: dict[str, tuple[str, ...]] = {} + # a cache of completed resolutions to Requirement lists + self._resolve_cache: dict[str, tuple[Requirement, ...]] = {} + + errors.finalize("[dependency-groups] data was invalid") + + def lookup(self, group: str) -> tuple[Requirement | DependencyGroupInclude, ...]: + """ + Lookup a group name, returning the parsed dependency data for that group. + This will not resolve includes. + + :param group: the name of the group to lookup + """ + group = _normalize_name(group) + + with _ErrorCollector().on_exit( + f"[dependency-groups] data for {group!r} was malformed" + ) as errors: + return self._parse_group(group, errors) + + def resolve(self, group: str) -> tuple[Requirement, ...]: + """ + Resolve a dependency group to a list of requirements. + + :param group: the name of the group to resolve + """ + group = _normalize_name(group) + + with _ErrorCollector().on_exit( + f"[dependency-groups] data for {group!r} was malformed" + ) as errors: + return self._resolve(group, group, errors) + + def _resolve( + self, group: str, requested_group: str, errors: _ErrorCollector + ) -> tuple[Requirement, ...]: + """ + This is a helper for cached resolution to strings. It preserves the name of the + group which the user initially requested in order to present a clearer error in + the event that a cycle is detected. + + :param group: The normalized name of the group to resolve. + :param requested_group: The group which was used in the original, user-facing + request. + """ + if group in self._resolve_cache: + return self._resolve_cache[group] + + parsed = self._parse_group(group, errors) + + resolved_group = [] + + for item in parsed: + if isinstance(item, Requirement): + resolved_group.append(item) + elif isinstance(item, DependencyGroupInclude): + include_group = _normalize_name(item.include_group) + + # if a group is cyclic, record the error + # otherwise, follow the include_group reference + # + # this allows us to examine all includes in a group, even in the + # presence of errors + if include_group in self._include_graph_ancestors.get(group, ()): + errors.error( + CyclicDependencyGroup( + requested_group, group, item.include_group + ) + ) + else: + self._include_graph_ancestors[include_group] = ( + *self._include_graph_ancestors.get(group, ()), + group, + ) + resolved_group.extend( + self._resolve(include_group, requested_group, errors) + ) + else: # pragma: no cover + raise NotImplementedError( + f"Invalid dependency group item after parse: {item}" + ) + + # in the event that errors were detected, present the group as empty and do not + # cache the result + # this ensures that repeated access to a cyclic group will raise multiple errors + if errors.errors: + return () + + self._resolve_cache[group] = tuple(resolved_group) + return self._resolve_cache[group] + + def _parse_group( + self, group: str, errors: _ErrorCollector + ) -> tuple[Requirement | DependencyGroupInclude, ...]: + # short circuit -- never do the work twice + if group in self._parsed_groups: + return self._parsed_groups[group] + + if group not in self.dependency_groups: + errors.error(LookupError(f"Dependency group '{group}' not found")) + return () + + raw_group = self.dependency_groups[group] + if isinstance(raw_group, str): + errors.error( + TypeError( + f"Dependency group {group!r} contained a string rather than a list." + ) + ) + return () + + if not isinstance(raw_group, Sequence): + errors.error( + TypeError(f"Dependency group {group!r} is not a sequence type.") + ) + return () + + elements: list[Requirement | DependencyGroupInclude] = [] + for item in raw_group: + if isinstance(item, str): + # packaging.requirements.Requirement parsing ensures that this is a + # valid PEP 508 Dependency Specifier + # raises InvalidRequirement on failure + elements.append(Requirement(item)) + elif isinstance(item, Mapping): + if tuple(item.keys()) != ("include-group",): + errors.error( + InvalidDependencyGroupObject( + f"Invalid dependency group item: {item!r}" + ) + ) + else: + include_group = item["include-group"] + elements.append(DependencyGroupInclude(include_group=include_group)) + else: + errors.error(TypeError(f"Invalid dependency group item: {item!r}")) + + self._parsed_groups[group] = tuple(elements) + return self._parsed_groups[group] + + +# -------------------- +# Functional Interface +# -------------------- + + +def resolve_dependency_groups( + dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], /, *groups: str +) -> tuple[str, ...]: + """ + Resolve a dependency group to a tuple of requirements, as strings. + + :param dependency_groups: the parsed contents of the ``[dependency-groups]`` table + from ``pyproject.toml`` + :param groups: the name of the group(s) to resolve + """ + resolver = DependencyGroupResolver(dependency_groups) + return tuple(str(r) for group in groups for r in resolver.resolve(group)) + + +# ---------------- +# internal helpers +# ---------------- + + +_NORMALIZE_PATTERN = re.compile(r"[-_.]+") + + +def _normalize_name(name: str) -> str: + return _NORMALIZE_PATTERN.sub("-", name).lower() + + +def _normalize_group_names( + dependency_groups: Mapping[str, Sequence[str | Mapping[str, str]]], + errors: _ErrorCollector, +) -> dict[str, Sequence[str | Mapping[str, str]]]: + original_names: dict[str, list[str]] = {} + normalized_groups: dict[str, Sequence[str | Mapping[str, str]]] = {} + + for group_name, value in dependency_groups.items(): + normed_group_name = _normalize_name(group_name) + original_names.setdefault(normed_group_name, []).append(group_name) + normalized_groups[normed_group_name] = value + + for normed_name, names in original_names.items(): + if len(names) > 1: + errors.error( + DuplicateGroupNames( + "Duplicate dependency group names: " + f"{normed_name} ({', '.join(names)})" + ) + ) + + return normalized_groups diff --git a/micromamba_root/Lib/site-packages/packaging/direct_url.py b/micromamba_root/Lib/site-packages/packaging/direct_url.py new file mode 100644 index 0000000000000000000000000000000000000000..5d1c56ca9d6fcd92111b0a86258853224509abb0 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/direct_url.py @@ -0,0 +1,325 @@ +from __future__ import annotations + +import dataclasses +import re +import urllib.parse +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any, Protocol, TypeVar + +if TYPE_CHECKING: # pragma: no cover + import sys + from collections.abc import Collection + + if sys.version_info >= (3, 11): + from typing import Self + else: + from typing_extensions import Self + +__all__ = [ + "ArchiveInfo", + "DirInfo", + "DirectUrl", + "DirectUrlValidationError", + "VcsInfo", +] + + +def __dir__() -> list[str]: + return __all__ + + +_T = TypeVar("_T") + + +class _FromMappingProtocol(Protocol): # pragma: no cover + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: ... + + +_FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol) + + +def _json_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: + return {key: value for key, value in data if value is not None} + + +def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: + """Get a value from the dictionary and verify it's the expected type.""" + if (value := d.get(key)) is None: + return None + if not isinstance(value, expected_type): + raise DirectUrlValidationError( + f"Unexpected type {type(value).__name__} " + f"(expected {expected_type.__name__})", + context=key, + ) + return value + + +def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: + """Get a required value from the dictionary and verify it's the expected type.""" + if (value := _get(d, expected_type, key)) is None: + raise _DirectUrlRequiredKeyError(key) + return value + + +def _get_object( + d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str +) -> _FromMappingProtocolT | None: + """Get a dictionary value from the dictionary and convert it to a dataclass.""" + if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] + return None + try: + return target_type._from_dict(value) + except Exception as e: + raise DirectUrlValidationError(e, context=key) from e + + +_PEP610_USER_PASS_ENV_VARS_REGEX = re.compile( + r"^\$\{[A-Za-z0-9-_]+\}(:\$\{[A-Za-z0-9-_]+\})?$" +) + + +def _strip_auth_from_netloc(netloc: str, safe_user_passwords: Collection[str]) -> str: + if "@" not in netloc: + return netloc + user_pass, netloc_no_user_pass = netloc.split("@", 1) + if user_pass in safe_user_passwords: + return netloc + if _PEP610_USER_PASS_ENV_VARS_REGEX.match(user_pass): + return netloc + return netloc_no_user_pass + + +def _strip_url(url: str, safe_user_passwords: Collection[str]) -> str: + """url with user:password part removed unless it is formed with + environment variables as specified in PEP 610, or it is a safe user:password + such as `git`. + """ + parsed_url = urllib.parse.urlsplit(url) + netloc = _strip_auth_from_netloc(parsed_url.netloc, safe_user_passwords) + return urllib.parse.urlunsplit( + ( + parsed_url.scheme, + netloc, + parsed_url.path, + parsed_url.query, + parsed_url.fragment, + ) + ) + + +class DirectUrlValidationError(Exception): + """Raised when when input data is not spec-compliant.""" + + context: str | None = None + message: str + + def __init__( + self, + cause: str | Exception, + *, + context: str | None = None, + ) -> None: + if isinstance(cause, DirectUrlValidationError): + if cause.context: + self.context = ( + f"{context}.{cause.context}" if context else cause.context + ) + else: + self.context = context # pragma: no cover + self.message = cause.message + else: + self.context = context + self.message = str(cause) + + def __str__(self) -> str: + if self.context: + return f"{self.message} in {self.context!r}" + return self.message + + +class _DirectUrlRequiredKeyError(DirectUrlValidationError): + def __init__(self, key: str) -> None: + super().__init__("Missing required value", context=key) + + +@dataclasses.dataclass(frozen=True, init=False) +class VcsInfo: + vcs: str + commit_id: str + requested_revision: str | None = None + + def __init__( + self, + *, + vcs: str, + commit_id: str, + requested_revision: str | None = None, + ) -> None: + object.__setattr__(self, "vcs", vcs) + object.__setattr__(self, "commit_id", commit_id) + object.__setattr__(self, "requested_revision", requested_revision) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + # We can't validate vcs value because is not closed. + return cls( + vcs=_get_required(d, str, "vcs"), + requested_revision=_get(d, str, "requested_revision"), + commit_id=_get_required(d, str, "commit_id"), + ) + + +@dataclasses.dataclass(frozen=True, init=False) +class ArchiveInfo: + hashes: Mapping[str, str] | None = None + + def __init__( + self, + *, + hashes: Mapping[str, str] | None = None, + ) -> None: + object.__setattr__(self, "hashes", hashes) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + hashes = _get(d, Mapping, "hashes") # type: ignore[type-abstract] + if hashes is not None and not all(isinstance(h, str) for h in hashes.values()): + raise DirectUrlValidationError( + "Hash values must be strings", context="hashes" + ) + legacy_hash = _get(d, str, "hash") + if legacy_hash is not None: + if "=" not in legacy_hash: + raise DirectUrlValidationError( + "Invalid hash format (expected '=')", + context="hash", + ) + hash_algorithm, hash_value = legacy_hash.split("=", 1) + if hashes is None: + # if `hashes` are not present, we can derive it from the legacy `hash` + hashes = {hash_algorithm: hash_value} + else: + # if `hashes` are present, the legacy `hash` must match one of them + if hash_algorithm not in hashes: + raise DirectUrlValidationError( + f"Algorithm {hash_algorithm!r} used in hash field " + f"is not present in hashes field", + context="hashes", + ) + if hashes[hash_algorithm] != hash_value: + raise DirectUrlValidationError( + f"Algorithm {hash_algorithm!r} used in hash field " + f"has different value in hashes field", + context="hash", + ) + return cls(hashes=hashes) + + +@dataclasses.dataclass(frozen=True, init=False) +class DirInfo: + editable: bool | None = None + + def __init__( + self, + *, + editable: bool | None = None, + ) -> None: + object.__setattr__(self, "editable", editable) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + return cls( + editable=_get(d, bool, "editable"), + ) + + +@dataclasses.dataclass(frozen=True, init=False) +class DirectUrl: + """A class representing a direct URL.""" + + url: str + archive_info: ArchiveInfo | None = None + vcs_info: VcsInfo | None = None + dir_info: DirInfo | None = None + subdirectory: str | None = None # XXX Path or str? + + def __init__( + self, + *, + url: str, + archive_info: ArchiveInfo | None = None, + vcs_info: VcsInfo | None = None, + dir_info: DirInfo | None = None, + subdirectory: str | None = None, + ) -> None: + object.__setattr__(self, "url", url) + object.__setattr__(self, "archive_info", archive_info) + object.__setattr__(self, "vcs_info", vcs_info) + object.__setattr__(self, "dir_info", dir_info) + object.__setattr__(self, "subdirectory", subdirectory) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + direct_url = cls( + url=_get_required(d, str, "url"), + archive_info=_get_object(d, ArchiveInfo, "archive_info"), + vcs_info=_get_object(d, VcsInfo, "vcs_info"), + dir_info=_get_object(d, DirInfo, "dir_info"), + subdirectory=_get(d, str, "subdirectory"), + ) + if ( + bool(direct_url.vcs_info) + + bool(direct_url.archive_info) + + bool(direct_url.dir_info) + ) != 1: + raise DirectUrlValidationError( + "Exactly one of vcs_info, archive_info, dir_info must be present" + ) + if direct_url.dir_info is not None and not direct_url.url.startswith("file://"): + raise DirectUrlValidationError( + "URL scheme must be file:// when dir_info is present", + context="url", + ) + # XXX subdirectory must be relative, can we, should we validate that here? + return direct_url + + @classmethod + def from_dict(cls, d: Mapping[str, Any], /) -> Self: + """Create and validate a DirectUrl instance from a JSON dictionary.""" + return cls._from_dict(d) + + def to_dict( + self, + *, + generate_legacy_hash: bool = False, + strip_user_password: bool = True, + safe_user_passwords: Collection[str] = ("git",), + ) -> Mapping[str, Any]: + """Convert the DirectUrl instance to a JSON dictionary. + + :param generate_legacy_hash: If True, include a legacy `hash` field in + `archive_info` for backward compatibility with tools that don't + support the `hashes` field. + :param strip_user_password: If True, strip user:password from the URL + unless it is formed with environment variables as specified in PEP + 610, or it is a safe user:password such as `git`. + :param safe_user_passwords: A collection of user:password strings that + should not be stripped from the URL even if `strip_user_password` is + True. + """ + res = dataclasses.asdict(self, dict_factory=_json_dict_factory) + if generate_legacy_hash and self.archive_info and self.archive_info.hashes: + hash_algorithm, hash_value = next(iter(self.archive_info.hashes.items())) + res["archive_info"]["hash"] = f"{hash_algorithm}={hash_value}" + if strip_user_password: + res["url"] = _strip_url(self.url, safe_user_passwords) + return res + + def validate(self) -> None: + """Validate the DirectUrl instance against the specification. + + Raises :class:`DirectUrlValidationError` if invalid. + """ + self.from_dict(self.to_dict()) diff --git a/micromamba_root/Lib/site-packages/packaging/errors.py b/micromamba_root/Lib/site-packages/packaging/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..d1d47cf6c3416179750bf5bf170aafe9d0fa6497 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/errors.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import contextlib +import dataclasses +import sys +import typing + +__all__ = ["ExceptionGroup"] + + +def __dir__() -> list[str]: + return __all__ + + +if sys.version_info >= (3, 11): # pragma: no cover + from builtins import ExceptionGroup +else: # pragma: no cover + + class ExceptionGroup(Exception): + """A minimal implementation of :external:exc:`ExceptionGroup` from Python 3.11. + + If :external:exc:`ExceptionGroup` is already defined by Python itself, + that version is used instead. + """ + + message: str + exceptions: list[Exception] + + def __init__(self, message: str, exceptions: list[Exception]) -> None: + self.message = message + self.exceptions = exceptions + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.message!r}, {self.exceptions!r})" + + +@dataclasses.dataclass +class _ErrorCollector: + """ + Collect errors into ExceptionGroups. + + Used like this: + + collector = _ErrorCollector() + # Add a single exception + collector.error(ValueError("one")) + + # Supports nesting, including combining ExceptionGroups + with collector.collect(): + raise ValueError("two") + collector.finalize("Found some errors") + + Since making a collector and then calling finalize later is a common pattern, + a convenience method ``on_exit`` is provided. + """ + + errors: list[Exception] = dataclasses.field(default_factory=list, init=False) + + def finalize(self, msg: str) -> None: + """Raise a group exception if there are any errors.""" + if self.errors: + raise ExceptionGroup(msg, self.errors) + + @contextlib.contextmanager + def on_exit(self, msg: str) -> typing.Generator[_ErrorCollector, None, None]: + """ + Calls finalize if no uncollected errors were present. + + Uncollected errors are raised normally. + """ + yield self + self.finalize(msg) + + @contextlib.contextmanager + def collect(self, *err_cls: type[Exception]) -> typing.Generator[None, None, None]: + """ + Context manager to collect errors into the error list. + + Must be inside loops, as only one error can be collected at a time. + """ + error_classes = err_cls or (Exception,) + try: + yield + except ExceptionGroup as error: + self.errors.extend(error.exceptions) + except error_classes as error: + self.errors.append(error) + + def error( + self, + error: Exception, + ) -> None: + """Add an error to the list.""" + self.errors.append(error) diff --git a/micromamba_root/Lib/site-packages/packaging/markers.py b/micromamba_root/Lib/site-packages/packaging/markers.py new file mode 100644 index 0000000000000000000000000000000000000000..564451f530bad3dbbd95ae7575835967b1ea45df --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/markers.py @@ -0,0 +1,492 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import operator +import os +import platform +import sys +from typing import AbstractSet, Callable, Literal, Mapping, TypedDict, Union, cast + +from ._parser import MarkerAtom, MarkerList, Op, Value, Variable +from ._parser import parse_marker as _parse_marker +from ._tokenizer import ParserSyntaxError +from .specifiers import InvalidSpecifier, Specifier +from .utils import canonicalize_name + +__all__ = [ + "Environment", + "EvaluateContext", + "InvalidMarker", + "Marker", + "UndefinedComparison", + "UndefinedEnvironmentName", + "default_environment", +] + + +def __dir__() -> list[str]: + return __all__ + + +Operator = Callable[[str, Union[str, AbstractSet[str]]], bool] +EvaluateContext = Literal["metadata", "lock_file", "requirement"] +"""A ``typing.Literal`` enumerating valid marker evaluation contexts. + +Valid values for the ``context`` passed to :meth:`Marker.evaluate` are: + +* ``"metadata"`` (for core metadata; default) +* ``"lock_file"`` (for lock files) +* ``"requirement"`` (i.e. all other situations) +""" + +MARKERS_ALLOWING_SET = {"extras", "dependency_groups"} +MARKERS_REQUIRING_VERSION = { + "implementation_version", + "platform_release", + "python_full_version", + "python_version", +} + + +class InvalidMarker(ValueError): + """Raised when attempting to create a :class:`Marker` from invalid input. + + This error indicates that the given marker string does not conform to the + :ref:`specification of dependency specifiers `. + """ + + +class UndefinedComparison(ValueError): + """Raised when evaluating an unsupported marker comparison. + + This can happen when marker values are compared as versions but do not + conform to the :ref:`specification of version specifiers + `. + """ + + +class UndefinedEnvironmentName(ValueError): + """Raised when evaluating a marker that references a missing environment key.""" + + +class Environment(TypedDict): + """ + A dictionary that represents a Python environment as captured by + :func:`default_environment`. All fields are required. + """ + + implementation_name: str + """The implementation's identifier, e.g. ``'cpython'``.""" + + implementation_version: str + """ + The implementation's version, e.g. ``'3.13.0a2'`` for CPython 3.13.0a2, or + ``'7.3.13'`` for PyPy3.10 v7.3.13. + """ + + os_name: str + """ + The value of :py:data:`os.name`. The name of the operating system dependent module + imported, e.g. ``'posix'``. + """ + + platform_machine: str + """ + Returns the machine type, e.g. ``'i386'``. + + An empty string if the value cannot be determined. + """ + + platform_release: str + """ + The system's release, e.g. ``'2.2.0'`` or ``'NT'``. + + An empty string if the value cannot be determined. + """ + + platform_system: str + """ + The system/OS name, e.g. ``'Linux'``, ``'Windows'`` or ``'Java'``. + + An empty string if the value cannot be determined. + """ + + platform_version: str + """ + The system's release version, e.g. ``'#3 on degas'``. + + An empty string if the value cannot be determined. + """ + + python_full_version: str + """ + The Python version as string ``'major.minor.patchlevel'``. + + Note that unlike the Python :py:data:`sys.version`, this value will always include + the patchlevel (it defaults to 0). + """ + + platform_python_implementation: str + """ + A string identifying the Python implementation, e.g. ``'CPython'``. + """ + + python_version: str + """The Python version as string ``'major.minor'``.""" + + sys_platform: str + """ + This string contains a platform identifier that can be used to append + platform-specific components to :py:data:`sys.path`, for instance. + + For Unix systems, except on Linux and AIX, this is the lowercased OS name as + returned by ``uname -s`` with the first part of the version as returned by + ``uname -r`` appended, e.g. ``'sunos5'`` or ``'freebsd8'``, at the time when Python + was built. + """ + + +def _normalize_extras( + result: MarkerList | MarkerAtom | str, +) -> MarkerList | MarkerAtom | str: + if not isinstance(result, tuple): + return result + + lhs, op, rhs = result + if isinstance(lhs, Variable) and lhs.value == "extra": + normalized_extra = canonicalize_name(rhs.value) + rhs = Value(normalized_extra) + elif isinstance(rhs, Variable) and rhs.value == "extra": + normalized_extra = canonicalize_name(lhs.value) + lhs = Value(normalized_extra) + return lhs, op, rhs + + +def _normalize_extra_values(results: MarkerList) -> MarkerList: + """ + Normalize extra values. + """ + + return [_normalize_extras(r) for r in results] + + +def _format_marker( + marker: list[str] | MarkerAtom | str, first: bool | None = True +) -> str: + assert isinstance(marker, (list, tuple, str)) + + # Sometimes we have a structure like [[...]] which is a single item list + # where the single item is itself it's own list. In that case we want skip + # the rest of this function so that we don't get extraneous () on the + # outside. + if ( + isinstance(marker, list) + and len(marker) == 1 + and isinstance(marker[0], (list, tuple)) + ): + return _format_marker(marker[0]) + + if isinstance(marker, list): + inner = (_format_marker(m, first=False) for m in marker) + if first: + return " ".join(inner) + else: + return "(" + " ".join(inner) + ")" + elif isinstance(marker, tuple): + return " ".join([m.serialize() for m in marker]) + else: + return marker + + +_operators: dict[str, Operator] = { + "in": lambda lhs, rhs: lhs in rhs, + "not in": lambda lhs, rhs: lhs not in rhs, + "<": lambda _lhs, _rhs: False, + "<=": operator.eq, + "==": operator.eq, + "!=": operator.ne, + ">=": operator.eq, + ">": lambda _lhs, _rhs: False, +} + + +def _eval_op(lhs: str, op: Op, rhs: str | AbstractSet[str], *, key: str) -> bool: + op_str = op.serialize() + if key in MARKERS_REQUIRING_VERSION: + try: + spec = Specifier(f"{op_str}{rhs}") + except InvalidSpecifier: + pass + else: + return spec.contains(lhs, prereleases=True) + + oper: Operator | None = _operators.get(op_str) + if oper is None: + raise UndefinedComparison(f"Undefined {op!r} on {lhs!r} and {rhs!r}.") + + return oper(lhs, rhs) + + +def _normalize( + lhs: str, rhs: str | AbstractSet[str], key: str +) -> tuple[str, str | AbstractSet[str]]: + # PEP 685 - Comparison of extra names for optional distribution dependencies + # https://peps.python.org/pep-0685/ + # > When comparing extra names, tools MUST normalize the names being + # > compared using the semantics outlined in PEP 503 for names + if key == "extra": + assert isinstance(rhs, str), "extra value must be a string" + # Both sides are normalized at this point already + return (lhs, rhs) + if key in MARKERS_ALLOWING_SET: + if isinstance(rhs, str): # pragma: no cover + return (canonicalize_name(lhs), canonicalize_name(rhs)) + else: + return (canonicalize_name(lhs), {canonicalize_name(v) for v in rhs}) + + # other environment markers don't have such standards + return lhs, rhs + + +def _evaluate_markers( + markers: MarkerList, environment: dict[str, str | AbstractSet[str]] +) -> bool: + groups: list[list[bool]] = [[]] + + for marker in markers: + if isinstance(marker, list): + groups[-1].append(_evaluate_markers(marker, environment)) + elif isinstance(marker, tuple): + lhs, op, rhs = marker + + if isinstance(lhs, Variable): + environment_key = lhs.value + lhs_value = environment[environment_key] + rhs_value = rhs.value + else: + lhs_value = lhs.value + environment_key = rhs.value + rhs_value = environment[environment_key] + + assert isinstance(lhs_value, str), "lhs must be a string" + lhs_value, rhs_value = _normalize(lhs_value, rhs_value, key=environment_key) + groups[-1].append(_eval_op(lhs_value, op, rhs_value, key=environment_key)) + elif marker == "or": + groups.append([]) + elif marker == "and": + pass + else: # pragma: nocover + raise TypeError(f"Unexpected marker {marker!r}") + + return any(all(item) for item in groups) + + +def _format_full_version(info: sys._version_info) -> str: + version = f"{info.major}.{info.minor}.{info.micro}" + kind = info.releaselevel + if kind != "final": + version += kind[0] + str(info.serial) + return version + + +def default_environment() -> Environment: + """Return the default marker environment for the current Python process. + + This is the base environment used by :meth:`Marker.evaluate`. + """ + iver = _format_full_version(sys.implementation.version) + implementation_name = sys.implementation.name + return { + "implementation_name": implementation_name, + "implementation_version": iver, + "os_name": os.name, + "platform_machine": platform.machine(), + "platform_release": platform.release(), + "platform_system": platform.system(), + "platform_version": platform.version(), + "python_full_version": platform.python_version(), + "platform_python_implementation": platform.python_implementation(), + "python_version": ".".join(platform.python_version_tuple()[:2]), + "sys_platform": sys.platform, + } + + +class Marker: + """Represents a parsed dependency marker expression. + + Marker expressions are parsed according to the + :ref:`specification of dependency specifiers `. + + :param marker: The string representation of a marker expression. + :raises InvalidMarker: If ``marker`` cannot be parsed. + + Instances are safe to serialize with :mod:`pickle`. They use a stable + format so the same pickle can be loaded in future packaging releases. + + .. versionchanged:: 26.2 + + Added a stable pickle format. Pickles created with packaging 26.2+ can + be unpickled with future releases. Backward compatibility with pickles + from packaging < 26.2 is supported but may be removed in a future + release. + """ + + __slots__ = ("_markers",) + + def __init__(self, marker: str) -> None: + # Note: We create a Marker object without calling this constructor in + # packaging.requirements.Requirement. If any additional logic is + # added here, make sure to mirror/adapt Requirement. + + # If this fails and throws an error, the repr still expects _markers to + # be defined. + self._markers: MarkerList = [] + + try: + self._markers = _normalize_extra_values(_parse_marker(marker)) + # The attribute `_markers` can be described in terms of a recursive type: + # MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]] + # + # For example, the following expression: + # python_version > "3.6" or (python_version == "3.6" and os_name == "unix") + # + # is parsed into: + # [ + # (, ')>, ), + # 'and', + # [ + # (, , ), + # 'or', + # (, , ) + # ] + # ] + except ParserSyntaxError as e: + raise InvalidMarker(str(e)) from e + + @classmethod + def _from_markers(cls, markers: MarkerList) -> Marker: + """Create a Marker instance from a pre-parsed marker tree. + + This avoids re-parsing serialised marker strings when combining markers. + """ + new = cls.__new__(cls) + new._markers = markers + return new + + def __str__(self) -> str: + return _format_marker(self._markers) + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}({str(self)!r})>" + + def __hash__(self) -> int: + return hash(str(self)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Marker): + return NotImplemented + + return str(self) == str(other) + + def __getstate__(self) -> str: + # Return the marker expression string for compactness and stability. + # Internal Node objects are excluded; the string is re-parsed on load. + return str(self) + + def __setstate__(self, state: object) -> None: + if isinstance(state, str): + # New format (26.2+): just the marker expression string. + try: + self._markers = _normalize_extra_values(_parse_marker(state)) + except ParserSyntaxError as exc: + raise TypeError(f"Cannot restore Marker from {state!r}") from exc + return + if isinstance(state, dict) and "_markers" in state: + # Old format (packaging <= 26.1, no __slots__): plain __dict__. + markers = state["_markers"] + if isinstance(markers, list): + self._markers = markers + return + if isinstance(state, tuple) and len(state) == 2: + # Old format (packaging <= 26.1, __slots__): (None, {slot: value}). + _, slot_dict = state + if isinstance(slot_dict, dict) and "_markers" in slot_dict: + markers = slot_dict["_markers"] + if isinstance(markers, list): + self._markers = markers + return + raise TypeError(f"Cannot restore Marker from {state!r}") + + def __and__(self, other: Marker) -> Marker: + if not isinstance(other, Marker): + return NotImplemented + return self._from_markers([self._markers, "and", other._markers]) + + def __or__(self, other: Marker) -> Marker: + if not isinstance(other, Marker): + return NotImplemented + return self._from_markers([self._markers, "or", other._markers]) + + def evaluate( + self, + environment: Mapping[str, str | AbstractSet[str]] | None = None, + context: EvaluateContext = "metadata", + ) -> bool: + """Evaluate a marker. + + Return the boolean from evaluating this marker against the environment. + The environment is determined from the current Python process unless + passed in explicitly. + + :param environment: Mapping containing keys and values to override the + detected environment. + :param EvaluateContext context: The context in which the marker is + evaluated, which influences what marker names are considered valid. + Accepted values are ``"metadata"`` (for core metadata; default), + ``"lock_file"``, and ``"requirement"`` (i.e. all other situations). + :raises UndefinedComparison: If the marker uses a comparison on values + that are not valid versions per the :ref:`specification of version + specifiers `. + :raises UndefinedEnvironmentName: If the marker references a value that + is missing from the evaluation environment. + :returns: ``True`` if the marker matches, otherwise ``False``. + + """ + current_environment = cast( + "dict[str, str | AbstractSet[str]]", default_environment() + ) + if context == "lock_file": + current_environment.update( + extras=frozenset(), dependency_groups=frozenset() + ) + elif context == "metadata": + current_environment["extra"] = "" + + if environment is not None: + current_environment.update(environment) + if "extra" in current_environment: + # The API used to allow setting extra to None. We need to handle + # this case for backwards compatibility. Also skip running + # normalize name if extra is empty. + extra = cast("str | None", current_environment["extra"]) + current_environment["extra"] = canonicalize_name(extra) if extra else "" + + return _evaluate_markers( + self._markers, _repair_python_full_version(current_environment) + ) + + +def _repair_python_full_version( + env: dict[str, str | AbstractSet[str]], +) -> dict[str, str | AbstractSet[str]]: + """ + Work around platform.python_version() returning something that is not PEP 440 + compliant for non-tagged Python builds. + """ + python_full_version = cast("str", env["python_full_version"]) + if python_full_version.endswith("+"): + env["python_full_version"] = f"{python_full_version}local" + return env diff --git a/micromamba_root/Lib/site-packages/packaging/metadata.py b/micromamba_root/Lib/site-packages/packaging/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..dccb627dea31193b8bb1082223dcdc4305fcfb18 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/metadata.py @@ -0,0 +1,964 @@ +from __future__ import annotations + +import email.header +import email.message +import email.parser +import email.policy +import keyword +import pathlib +import typing +from typing import ( + Any, + Callable, + Generic, + Literal, + TypedDict, + cast, +) + +from . import licenses, requirements, specifiers, utils +from . import version as version_module +from .errors import ExceptionGroup, _ErrorCollector + +if typing.TYPE_CHECKING: + from .licenses import NormalizedLicenseExpression + +T = typing.TypeVar("T") + + +__all__ = [ + "ExceptionGroup", # Keep this for a bit (makes mypy happy w/ 26.0 compat) + "InvalidMetadata", + "Metadata", + "RFC822Message", + "RFC822Policy", + "RawMetadata", + "parse_email", +] + + +def __dir__() -> list[str]: + return __all__ + + +class InvalidMetadata(ValueError): + """A metadata field contains invalid data.""" + + field: str + """The name of the field that contains invalid data.""" + + def __init__(self, field: str, message: str) -> None: + self.field = field + super().__init__(message) + + +# The RawMetadata class attempts to make as few assumptions about the underlying +# serialization formats as possible. The idea is that as long as a serialization +# formats offer some very basic primitives in *some* way then we can support +# serializing to and from that format. +class RawMetadata(TypedDict, total=False): + """A dictionary of raw core metadata. + + Each field in core metadata maps to a key of this dictionary (when data is + provided). The key is lower-case and underscores are used instead of dashes + compared to the equivalent core metadata field. Any core metadata field that + can be specified multiple times or can hold multiple values in a single + field have a key with a plural name. See :class:`Metadata` whose attributes + match the keys of this dictionary. + + Core metadata fields that can be specified multiple times are stored as a + list or dict depending on which is appropriate for the field. Any fields + which hold multiple values in a single field are stored as a list. All fields + are considered optional. + """ + + # Metadata 1.0 - PEP 241 + metadata_version: str + name: str + version: str + platforms: list[str] + summary: str + description: str + keywords: list[str] + home_page: str + author: str + author_email: str + license: str + + # Metadata 1.1 - PEP 314 + supported_platforms: list[str] + download_url: str + classifiers: list[str] + requires: list[str] + provides: list[str] + obsoletes: list[str] + + # Metadata 1.2 - PEP 345 + maintainer: str + maintainer_email: str + requires_dist: list[str] + provides_dist: list[str] + obsoletes_dist: list[str] + requires_python: str + requires_external: list[str] + project_urls: dict[str, str] + + # Metadata 2.0 + # PEP 426 attempted to completely revamp the metadata format + # but got stuck without ever being able to build consensus on + # it and ultimately ended up withdrawn. + # + # However, a number of tools had started emitting METADATA with + # `2.0` Metadata-Version, so for historical reasons, this version + # was skipped. + + # Metadata 2.1 - PEP 566 + description_content_type: str + provides_extra: list[str] + + # Metadata 2.2 - PEP 643 + dynamic: list[str] + + # Metadata 2.3 - PEP 685 + # No new fields were added in PEP 685, just some edge case were + # tightened up to provide better interoperability. + + # Metadata 2.4 - PEP 639 + license_expression: str + license_files: list[str] + + # Metadata 2.5 - PEP 794 + import_names: list[str] + import_namespaces: list[str] + + +# 'keywords' is special as it's a string in the core metadata spec, but we +# represent it as a list. +_STRING_FIELDS = { + "author", + "author_email", + "description", + "description_content_type", + "download_url", + "home_page", + "license", + "license_expression", + "maintainer", + "maintainer_email", + "metadata_version", + "name", + "requires_python", + "summary", + "version", +} + +_LIST_FIELDS = { + "classifiers", + "dynamic", + "license_files", + "obsoletes", + "obsoletes_dist", + "platforms", + "provides", + "provides_dist", + "provides_extra", + "requires", + "requires_dist", + "requires_external", + "supported_platforms", + "import_names", + "import_namespaces", +} + +_DICT_FIELDS = { + "project_urls", +} + + +def _parse_keywords(data: str) -> list[str]: + """Split a string of comma-separated keywords into a list of keywords.""" + return [k.strip() for k in data.split(",")] + + +def _parse_project_urls(data: list[str]) -> dict[str, str]: + """Parse a list of label/URL string pairings separated by a comma.""" + urls = {} + for pair in data: + # Our logic is slightly tricky here as we want to try and do + # *something* reasonable with malformed data. + # + # The main thing that we have to worry about, is data that does + # not have a ',' at all to split the label from the Value. There + # isn't a singular right answer here, and we will fail validation + # later on (if the caller is validating) so it doesn't *really* + # matter, but since the missing value has to be an empty str + # and our return value is dict[str, str], if we let the key + # be the missing value, then they'd have multiple '' values that + # overwrite each other in a accumulating dict. + # + # The other potential issue is that it's possible to have the + # same label multiple times in the metadata, with no solid "right" + # answer with what to do in that case. As such, we'll do the only + # thing we can, which is treat the field as unparsable and add it + # to our list of unparsed fields. + # + # TODO: The spec doesn't say anything about if the keys should be + # considered case sensitive or not... logically they should + # be case-preserving and case-insensitive, but doing that + # would open up more cases where we might have duplicate + # entries. + label, _, url = (s.strip() for s in pair.partition(",")) + + if label in urls: + # The label already exists in our set of urls, so this field + # is unparsable, and we can just add the whole thing to our + # unparsable data and stop processing it. + raise KeyError("duplicate labels in project urls") + urls[label] = url + + return urls + + +def _get_payload(msg: email.message.Message, source: bytes | str) -> str: + """Get the body of the message.""" + # If our source is a str, then our caller has managed encodings for us, + # and we don't need to deal with it. + if isinstance(source, str): + payload = msg.get_payload() + assert isinstance(payload, str) + return payload + # If our source is a bytes, then we're managing the encoding and we need + # to deal with it. + else: + bpayload = msg.get_payload(decode=True) + assert isinstance(bpayload, bytes) + try: + return bpayload.decode("utf8", "strict") + except UnicodeDecodeError as exc: + raise ValueError("payload in an invalid encoding") from exc + + +# The various parse_FORMAT functions here are intended to be as lenient as +# possible in their parsing, while still returning a correctly typed +# RawMetadata. +# +# To aid in this, we also generally want to do as little touching of the +# data as possible, except where there are possibly some historic holdovers +# that make valid data awkward to work with. +# +# While this is a lower level, intermediate format than our ``Metadata`` +# class, some light touch ups can make a massive difference in usability. + +# Map METADATA fields to RawMetadata. +_EMAIL_TO_RAW_MAPPING = { + "author": "author", + "author-email": "author_email", + "classifier": "classifiers", + "description": "description", + "description-content-type": "description_content_type", + "download-url": "download_url", + "dynamic": "dynamic", + "home-page": "home_page", + "import-name": "import_names", + "import-namespace": "import_namespaces", + "keywords": "keywords", + "license": "license", + "license-expression": "license_expression", + "license-file": "license_files", + "maintainer": "maintainer", + "maintainer-email": "maintainer_email", + "metadata-version": "metadata_version", + "name": "name", + "obsoletes": "obsoletes", + "obsoletes-dist": "obsoletes_dist", + "platform": "platforms", + "project-url": "project_urls", + "provides": "provides", + "provides-dist": "provides_dist", + "provides-extra": "provides_extra", + "requires": "requires", + "requires-dist": "requires_dist", + "requires-external": "requires_external", + "requires-python": "requires_python", + "summary": "summary", + "supported-platform": "supported_platforms", + "version": "version", +} +_RAW_TO_EMAIL_MAPPING = {raw: email for email, raw in _EMAIL_TO_RAW_MAPPING.items()} + + +# This class is for writing RFC822 messages +class RFC822Policy(email.policy.EmailPolicy): + """ + This is :class:`email.policy.EmailPolicy`, but with a simple ``header_store_parse`` + implementation that handles multi-line values, and some nice defaults. + """ + + utf8 = True + mangle_from_ = False + max_line_length = 0 + + def header_store_parse(self, name: str, value: str) -> tuple[str, str]: + size = len(name) + 2 + value = value.replace("\n", "\n" + " " * size) + return (name, value) + + +# This class is for writing RFC822 messages +class RFC822Message(email.message.EmailMessage): + """ + This is :class:`email.message.EmailMessage` with two small changes: it defaults to + our `RFC822Policy`, and it correctly writes unicode when being called + with `bytes()`. + """ + + def __init__(self) -> None: + super().__init__(policy=RFC822Policy()) + + def as_bytes( + self, unixfrom: bool = False, policy: email.policy.Policy | None = None + ) -> bytes: + """ + Return the bytes representation of the message. + + This handles unicode encoding. + """ + return self.as_string(unixfrom, policy=policy).encode("utf-8") + + +def parse_email(data: bytes | str) -> tuple[RawMetadata, dict[str, list[str]]]: + """Parse a distribution's metadata stored as email headers (e.g. from ``METADATA``). + + This function returns a two-item tuple of dicts. The first dict is of + recognized fields from the core metadata specification. Fields that can be + parsed and translated into Python's built-in types are converted + appropriately. All other fields are left as-is. Fields that are allowed to + appear multiple times are stored as lists. + + The second dict contains all other fields from the metadata. This includes + any unrecognized fields. It also includes any fields which are expected to + be parsed into a built-in type but were not formatted appropriately. Finally, + any fields that are expected to appear only once but are repeated are + included in this dict. + + """ + raw: dict[str, str | list[str] | dict[str, str]] = {} + unparsed: dict[str, list[str]] = {} + + if isinstance(data, str): + parsed = email.parser.Parser(policy=email.policy.compat32).parsestr(data) + else: + parsed = email.parser.BytesParser(policy=email.policy.compat32).parsebytes(data) + + # We have to wrap parsed.keys() in a set, because in the case of multiple + # values for a key (a list), the key will appear multiple times in the + # list of keys, but we're avoiding that by using get_all(). + for name_with_case in frozenset(parsed.keys()): + # Header names in RFC are case insensitive, so we'll normalize to all + # lower case to make comparisons easier. + name = name_with_case.lower() + + # We use get_all() here, even for fields that aren't multiple use, + # because otherwise someone could have e.g. two Name fields, and we + # would just silently ignore it rather than doing something about it. + headers = parsed.get_all(name) or [] + + # The way the email module works when parsing bytes is that it + # unconditionally decodes the bytes as ascii using the surrogateescape + # handler. When you pull that data back out (such as with get_all() ), + # it looks to see if the str has any surrogate escapes, and if it does + # it wraps it in a Header object instead of returning the string. + # + # As such, we'll look for those Header objects, and fix up the encoding. + value = [] + # Flag if we have run into any issues processing the headers, thus + # signalling that the data belongs in 'unparsed'. + valid_encoding = True + for h in headers: + # It's unclear if this can return more types than just a Header or + # a str, so we'll just assert here to make sure. + assert isinstance(h, (email.header.Header, str)) + + # If it's a header object, we need to do our little dance to get + # the real data out of it. In cases where there is invalid data + # we're going to end up with mojibake, but there's no obvious, good + # way around that without reimplementing parts of the Header object + # ourselves. + # + # That should be fine since, if mojibacked happens, this key is + # going into the unparsed dict anyways. + if isinstance(h, email.header.Header): + # The Header object stores it's data as chunks, and each chunk + # can be independently encoded, so we'll need to check each + # of them. + chunks: list[tuple[bytes, str | None]] = [] + for binary, _encoding in email.header.decode_header(h): + try: + binary.decode("utf8", "strict") + except UnicodeDecodeError: + # Enable mojibake. + encoding = "latin1" + valid_encoding = False + else: + encoding = "utf8" + chunks.append((binary, encoding)) + + # Turn our chunks back into a Header object, then let that + # Header object do the right thing to turn them into a + # string for us. + value.append(str(email.header.make_header(chunks))) + # This is already a string, so just add it. + else: + value.append(h) + + # We've processed all of our values to get them into a list of str, + # but we may have mojibake data, in which case this is an unparsed + # field. + if not valid_encoding: + unparsed[name] = value + continue + + raw_name = _EMAIL_TO_RAW_MAPPING.get(name) + if raw_name is None: + # This is a bit of a weird situation, we've encountered a key that + # we don't know what it means, so we don't know whether it's meant + # to be a list or not. + # + # Since we can't really tell one way or another, we'll just leave it + # as a list, even though it may be a single item list, because that's + # what makes the most sense for email headers. + unparsed[name] = value + continue + + # If this is one of our string fields, then we'll check to see if our + # value is a list of a single item. If it is then we'll assume that + # it was emitted as a single string, and unwrap the str from inside + # the list. + # + # If it's any other kind of data, then we haven't the faintest clue + # what we should parse it as, and we have to just add it to our list + # of unparsed stuff. + if raw_name in _STRING_FIELDS and len(value) == 1: + raw[raw_name] = value[0] + # If this is import_names, we need to special case the empty field + # case, which converts to an empty list instead of None. We can't let + # the empty case slip through, as it will fail validation. + elif raw_name == "import_names" and value == [""]: + raw[raw_name] = [] + # If this is one of our list of string fields, then we can just assign + # the value, since email *only* has strings, and our get_all() call + # above ensures that this is a list. + elif raw_name in _LIST_FIELDS: + raw[raw_name] = value + # Special Case: Keywords + # The keywords field is implemented in the metadata spec as a str, + # but it conceptually is a list of strings, and is serialized using + # ", ".join(keywords), so we'll do some light data massaging to turn + # this into what it logically is. + elif raw_name == "keywords" and len(value) == 1: + raw[raw_name] = _parse_keywords(value[0]) + # Special Case: Project-URL + # The project urls is implemented in the metadata spec as a list of + # specially-formatted strings that represent a key and a value, which + # is fundamentally a mapping, however the email format doesn't support + # mappings in a sane way, so it was crammed into a list of strings + # instead. + # + # We will do a little light data massaging to turn this into a map as + # it logically should be. + elif raw_name == "project_urls": + try: + raw[raw_name] = _parse_project_urls(value) + except KeyError: + unparsed[name] = value + # Nothing that we've done has managed to parse this, so it'll just + # throw it in our unparsable data and move on. + else: + unparsed[name] = value + + # We need to support getting the Description from the message payload in + # addition to getting it from the the headers. This does mean, though, there + # is the possibility of it being set both ways, in which case we put both + # in 'unparsed' since we don't know which is right. + try: + payload = _get_payload(parsed, data) + except ValueError: + unparsed.setdefault("description", []).append( + parsed.get_payload(decode=isinstance(data, bytes)) # type: ignore[call-overload] + ) + else: + if payload: + # Check to see if we've already got a description, if so then both + # it, and this body move to unparsable. + if "description" in raw: + description_header = cast("str", raw.pop("description")) + unparsed.setdefault("description", []).extend( + [description_header, payload] + ) + elif "description" in unparsed: + unparsed["description"].append(payload) + else: + raw["description"] = payload + + # We need to cast our `raw` to a metadata, because a TypedDict only support + # literal key names, but we're computing our key names on purpose, but the + # way this function is implemented, our `TypedDict` can only have valid key + # names. + return cast("RawMetadata", raw), unparsed + + +_NOT_FOUND = object() + + +# Keep the two values in sync. +_VALID_METADATA_VERSIONS = ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"] +_MetadataVersion = Literal["1.0", "1.1", "1.2", "2.1", "2.2", "2.3", "2.4", "2.5"] + +_REQUIRED_ATTRS = frozenset(["metadata_version", "name", "version"]) + + +class _Validator(Generic[T]): + """Validate a metadata field. + + All _process_*() methods correspond to a core metadata field. The method is + called with the field's raw value. If the raw value is valid it is returned + in its "enriched" form (e.g. ``version.Version`` for the ``Version`` field). + If the raw value is invalid, :exc:`InvalidMetadata` is raised (with a cause + as appropriate). + """ + + name: str + raw_name: str + added: _MetadataVersion + + def __init__( + self, + *, + added: _MetadataVersion = "1.0", + ) -> None: + self.added = added + + def __set_name__(self, _owner: Metadata, name: str) -> None: + self.name = name + self.raw_name = _RAW_TO_EMAIL_MAPPING[name] + + def __get__(self, instance: Metadata, _owner: type[Metadata]) -> T: + # With Python 3.8, the caching can be replaced with functools.cached_property(). + # No need to check the cache as attribute lookup will resolve into the + # instance's __dict__ before __get__ is called. + cache = instance.__dict__ + value = instance._raw.get(self.name) + + # To make the _process_* methods easier, we'll check if the value is None + # and if this field is NOT a required attribute, and if both of those + # things are true, we'll skip the the converter. This will mean that the + # converters never have to deal with the None union. + if self.name in _REQUIRED_ATTRS or value is not None: + try: + converter: Callable[[Any], T] = getattr(self, f"_process_{self.name}") + except AttributeError: + pass + else: + value = converter(value) + + cache[self.name] = value + try: + del instance._raw[self.name] # type: ignore[misc] + except KeyError: + pass + + return cast("T", value) + + def _invalid_metadata( + self, msg: str, cause: Exception | None = None + ) -> InvalidMetadata: + exc = InvalidMetadata( + self.raw_name, msg.format_map({"field": repr(self.raw_name)}) + ) + exc.__cause__ = cause + return exc + + def _process_metadata_version(self, value: str) -> _MetadataVersion: + # Implicitly makes Metadata-Version required. + if value not in _VALID_METADATA_VERSIONS: + raise self._invalid_metadata(f"{value!r} is not a valid metadata version") + return cast("_MetadataVersion", value) + + def _process_name(self, value: str) -> str: + if not value: + raise self._invalid_metadata("{field} is a required field") + # Validate the name as a side-effect. + try: + utils.canonicalize_name(value, validate=True) + except utils.InvalidName as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return value + + def _process_version(self, value: str) -> version_module.Version: + if not value: + raise self._invalid_metadata("{field} is a required field") + try: + return version_module.parse(value) + except version_module.InvalidVersion as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_summary(self, value: str) -> str: + """Check the field contains no newlines.""" + if "\n" in value: + raise self._invalid_metadata("{field} must be a single line") + return value + + def _process_description_content_type(self, value: str) -> str: + content_types = {"text/plain", "text/x-rst", "text/markdown"} + message = email.message.EmailMessage() + message["content-type"] = value + + content_type, parameters = ( + # Defaults to `text/plain` if parsing failed. + message.get_content_type().lower(), + message["content-type"].params, + ) + # Check if content-type is valid or defaulted to `text/plain` and thus was + # not parseable. + if content_type not in content_types or content_type not in value.lower(): + raise self._invalid_metadata( + f"{{field}} must be one of {list(content_types)}, not {value!r}" + ) + + charset = parameters.get("charset", "UTF-8") + if charset != "UTF-8": + raise self._invalid_metadata( + f"{{field}} can only specify the UTF-8 charset, not {charset!r}" + ) + + markdown_variants = {"GFM", "CommonMark"} + variant = parameters.get("variant", "GFM") # Use an acceptable default. + if content_type == "text/markdown" and variant not in markdown_variants: + raise self._invalid_metadata( + f"valid Markdown variants for {{field}} are {list(markdown_variants)}, " + f"not {variant!r}", + ) + return value + + def _process_dynamic(self, value: list[str]) -> list[str]: + for dynamic_field in map(str.lower, value): + if dynamic_field in {"name", "version", "metadata-version"}: + raise self._invalid_metadata( + f"{dynamic_field!r} is not allowed as a dynamic field" + ) + elif dynamic_field not in _EMAIL_TO_RAW_MAPPING: + raise self._invalid_metadata( + f"{dynamic_field!r} is not a valid dynamic field" + ) + return list(map(str.lower, value)) + + def _process_provides_extra( + self, + value: list[str], + ) -> list[utils.NormalizedName]: + normalized_names = [] + try: + for name in value: + normalized_names.append(utils.canonicalize_name(name, validate=True)) + except utils.InvalidName as exc: + raise self._invalid_metadata( + f"{name!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return normalized_names + + def _process_requires_python(self, value: str) -> specifiers.SpecifierSet: + try: + return specifiers.SpecifierSet(value) + except specifiers.InvalidSpecifier as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_requires_dist( + self, + value: list[str], + ) -> list[requirements.Requirement]: + reqs = [] + try: + for req in value: + reqs.append(requirements.Requirement(req)) + except requirements.InvalidRequirement as exc: + raise self._invalid_metadata( + f"{req!r} is invalid for {{field}}", cause=exc + ) from exc + else: + return reqs + + def _process_license_expression(self, value: str) -> NormalizedLicenseExpression: + try: + return licenses.canonicalize_license_expression(value) + except ValueError as exc: + raise self._invalid_metadata( + f"{value!r} is invalid for {{field}}", cause=exc + ) from exc + + def _process_license_files(self, value: list[str]) -> list[str]: + paths = [] + for path in value: + if ".." in path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, " + "parent directory indicators are not allowed" + ) + if "*" in path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must be resolved" + ) + if ( + pathlib.PurePosixPath(path).is_absolute() + or pathlib.PureWindowsPath(path).is_absolute() + ): + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must be relative" + ) + if pathlib.PureWindowsPath(path).as_posix() != path: + raise self._invalid_metadata( + f"{path!r} is invalid for {{field}}, paths must use '/' delimiter" + ) + paths.append(path) + return paths + + def _process_import_names(self, value: list[str]) -> list[str]: + for import_name in value: + name, semicolon, private = import_name.partition(";") + name = name.rstrip() + for identifier in name.split("."): + if not identifier.isidentifier(): + raise self._invalid_metadata( + f"{name!r} is invalid for {{field}}; " + f"{identifier!r} is not a valid identifier" + ) + elif keyword.iskeyword(identifier): + raise self._invalid_metadata( + f"{name!r} is invalid for {{field}}; " + f"{identifier!r} is a keyword" + ) + if semicolon and private.lstrip() != "private": + raise self._invalid_metadata( + f"{import_name!r} is invalid for {{field}}; " + "the only valid option is 'private'" + ) + return value + + _process_import_namespaces = _process_import_names + + +class Metadata: + """Representation of distribution metadata. + + Compared to :class:`RawMetadata`, this class provides objects representing + metadata fields instead of only using built-in types. Any invalid metadata + will cause :exc:`InvalidMetadata` to be raised (with a + :py:attr:`~BaseException.__cause__` attribute as appropriate). + """ + + _raw: RawMetadata + + @classmethod + def from_raw(cls, data: RawMetadata, *, validate: bool = True) -> Metadata: + """Create an instance from :class:`RawMetadata`. + + If *validate* is true, all metadata will be validated. All exceptions + related to validation will be gathered and raised as an :class:`ExceptionGroup`. + """ + ins = cls() + ins._raw = data.copy() # Mutations occur due to caching enriched values. + + if validate: + collector = _ErrorCollector() + metadata_version = None + with collector.collect(InvalidMetadata): + metadata_version = ins.metadata_version + metadata_age = _VALID_METADATA_VERSIONS.index(metadata_version) + + # Make sure to check for the fields that are present, the required + # fields (so their absence can be reported). + fields_to_check = frozenset(ins._raw) | _REQUIRED_ATTRS + # Remove fields that have already been checked. + fields_to_check -= {"metadata_version"} + + for key in fields_to_check: + try: + if metadata_version: + # Can't use getattr() as that triggers descriptor protocol which + # will fail due to no value for the instance argument. + try: + field_metadata_version = cls.__dict__[key].added + except KeyError: + exc = InvalidMetadata(key, f"unrecognized field: {key!r}") + collector.error(exc) + continue + field_age = _VALID_METADATA_VERSIONS.index( + field_metadata_version + ) + if field_age > metadata_age: + field = _RAW_TO_EMAIL_MAPPING[key] + exc = InvalidMetadata( + field, + f"{field} introduced in metadata version " + f"{field_metadata_version}, not {metadata_version}", + ) + collector.error(exc) + continue + getattr(ins, key) + except InvalidMetadata as exc: + collector.error(exc) + + collector.finalize("invalid metadata") + + return ins + + @classmethod + def from_email(cls, data: bytes | str, *, validate: bool = True) -> Metadata: + """Parse metadata from email headers. + + If *validate* is true, the metadata will be validated. All exceptions + related to validation will be gathered and raised as an :class:`ExceptionGroup`. + """ + raw, unparsed = parse_email(data) + + if validate: + with _ErrorCollector().on_exit("unparsed") as collector: + for unparsed_key in unparsed: + if unparsed_key in _EMAIL_TO_RAW_MAPPING: + message = f"{unparsed_key!r} has invalid data" + else: + message = f"unrecognized field: {unparsed_key!r}" + collector.error(InvalidMetadata(unparsed_key, message)) + + try: + return cls.from_raw(raw, validate=validate) + except ExceptionGroup as exc_group: + raise ExceptionGroup( + "invalid or unparsed metadata", exc_group.exceptions + ) from None + + metadata_version: _Validator[_MetadataVersion] = _Validator() + """:external:ref:`core-metadata-metadata-version` + (required; validated to be a valid metadata version)""" + # `name` is not normalized/typed to NormalizedName so as to provide access to + # the original/raw name. + name: _Validator[str] = _Validator() + """:external:ref:`core-metadata-name` + (required; validated using :func:`~packaging.utils.canonicalize_name` and its + *validate* parameter)""" + version: _Validator[version_module.Version] = _Validator() + """:external:ref:`core-metadata-version` (required)""" + dynamic: _Validator[list[str] | None] = _Validator( + added="2.2", + ) + """:external:ref:`core-metadata-dynamic` + (validated against core metadata field names and lowercased)""" + platforms: _Validator[list[str] | None] = _Validator() + """:external:ref:`core-metadata-platform`""" + supported_platforms: _Validator[list[str] | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-supported-platform`""" + summary: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-summary` (validated to contain no newlines)""" + description: _Validator[str | None] = _Validator() # TODO 2.1: can be in body + """:external:ref:`core-metadata-description`""" + description_content_type: _Validator[str | None] = _Validator(added="2.1") + """:external:ref:`core-metadata-description-content-type` (validated)""" + keywords: _Validator[list[str] | None] = _Validator() + """:external:ref:`core-metadata-keywords`""" + home_page: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-home-page`""" + download_url: _Validator[str | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-download-url`""" + author: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-author`""" + author_email: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-author-email`""" + maintainer: _Validator[str | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-maintainer`""" + maintainer_email: _Validator[str | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-maintainer-email`""" + license: _Validator[str | None] = _Validator() + """:external:ref:`core-metadata-license`""" + license_expression: _Validator[NormalizedLicenseExpression | None] = _Validator( + added="2.4" + ) + """:external:ref:`core-metadata-license-expression`""" + license_files: _Validator[list[str] | None] = _Validator(added="2.4") + """:external:ref:`core-metadata-license-file`""" + classifiers: _Validator[list[str] | None] = _Validator(added="1.1") + """:external:ref:`core-metadata-classifier`""" + requires_dist: _Validator[list[requirements.Requirement] | None] = _Validator( + added="1.2" + ) + """:external:ref:`core-metadata-requires-dist`""" + requires_python: _Validator[specifiers.SpecifierSet | None] = _Validator( + added="1.2" + ) + """:external:ref:`core-metadata-requires-python`""" + # Because `Requires-External` allows for non-PEP 440 version specifiers, we + # don't do any processing on the values. + requires_external: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-requires-external`""" + project_urls: _Validator[dict[str, str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-project-url`""" + # PEP 685 lets us raise an error if an extra doesn't pass `Name` validation + # regardless of metadata version. + provides_extra: _Validator[list[utils.NormalizedName] | None] = _Validator( + added="2.1", + ) + """:external:ref:`core-metadata-provides-extra`""" + provides_dist: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-provides-dist`""" + obsoletes_dist: _Validator[list[str] | None] = _Validator(added="1.2") + """:external:ref:`core-metadata-obsoletes-dist`""" + import_names: _Validator[list[str] | None] = _Validator(added="2.5") + """:external:ref:`core-metadata-import-name`""" + import_namespaces: _Validator[list[str] | None] = _Validator(added="2.5") + """:external:ref:`core-metadata-import-namespace`""" + requires: _Validator[list[str] | None] = _Validator(added="1.1") + """``Requires`` (deprecated)""" + provides: _Validator[list[str] | None] = _Validator(added="1.1") + """``Provides`` (deprecated)""" + obsoletes: _Validator[list[str] | None] = _Validator(added="1.1") + """``Obsoletes`` (deprecated)""" + + def as_rfc822(self) -> RFC822Message: + """ + Return an RFC822 message with the metadata. + """ + message = RFC822Message() + self._write_metadata(message) + return message + + def _write_metadata(self, message: RFC822Message) -> None: + """ + Return an RFC822 message with the metadata. + """ + for name, validator in self.__class__.__dict__.items(): + if isinstance(validator, _Validator) and name != "description": + value = getattr(self, name) + email_name = _RAW_TO_EMAIL_MAPPING[name] + if value is not None: + if email_name == "project-url": + for label, url in value.items(): + message[email_name] = f"{label}, {url}" + elif email_name == "keywords": + message[email_name] = ",".join(value) + elif email_name == "import-name" and value == []: + message[email_name] = "" + elif isinstance(value, list): + for item in value: + message[email_name] = str(item) + else: + message[email_name] = str(value) + + # The description is a special case because it is in the body of the message. + if self.description is not None: + message.set_payload(self.description) diff --git a/micromamba_root/Lib/site-packages/packaging/py.typed b/micromamba_root/Lib/site-packages/packaging/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/Lib/site-packages/packaging/pylock.py b/micromamba_root/Lib/site-packages/packaging/pylock.py new file mode 100644 index 0000000000000000000000000000000000000000..84e25378fc6fa21d2d637dbcc6cd43c0dd2ad1d4 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/pylock.py @@ -0,0 +1,905 @@ +from __future__ import annotations + +import dataclasses +import logging +import re +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from datetime import datetime +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Protocol, + TypeVar, + cast, +) +from urllib.parse import urlparse + +from .markers import Environment, Marker, default_environment +from .specifiers import SpecifierSet +from .tags import create_compatible_tags_selector, sys_tags +from .utils import ( + NormalizedName, + is_normalized_name, + parse_sdist_filename, + parse_wheel_filename, +) +from .version import Version + +if TYPE_CHECKING: # pragma: no cover + from collections.abc import Collection, Iterator + from pathlib import Path + + from typing_extensions import Self + + from .tags import Tag + +_logger = logging.getLogger(__name__) + +__all__ = [ + "Package", + "PackageArchive", + "PackageDirectory", + "PackageSdist", + "PackageVcs", + "PackageWheel", + "Pylock", + "PylockUnsupportedVersionError", + "PylockValidationError", + "is_valid_pylock_path", +] + + +def __dir__() -> list[str]: + return __all__ + + +_T = TypeVar("_T") +_T2 = TypeVar("_T2") + + +class _FromMappingProtocol(Protocol): # pragma: no cover + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: ... + + +_FromMappingProtocolT = TypeVar("_FromMappingProtocolT", bound=_FromMappingProtocol) + + +_PYLOCK_FILE_NAME_RE = re.compile(r"^pylock\.([^.]+)\.toml$") + + +def is_valid_pylock_path(path: Path) -> bool: + """Check if the given path is a valid pylock file path.""" + return path.name == "pylock.toml" or bool(_PYLOCK_FILE_NAME_RE.match(path.name)) + + +def _toml_key(key: str) -> str: + return key.replace("_", "-") + + +def _toml_value(key: str, value: Any) -> Any: # noqa: ANN401 + if isinstance(value, (Version, Marker, SpecifierSet)): + return str(value) + if isinstance(value, Sequence) and key == "environments": + return [str(v) for v in value] + return value + + +def _toml_dict_factory(data: list[tuple[str, Any]]) -> dict[str, Any]: + return { + _toml_key(key): _toml_value(key, value) + for key, value in data + if value is not None + } + + +def _get(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T | None: + """Get a value from the dictionary and verify it's the expected type.""" + if (value := d.get(key)) is None: + return None + if not isinstance(value, expected_type): + raise PylockValidationError( + f"Unexpected type {type(value).__name__} " + f"(expected {expected_type.__name__})", + context=key, + ) + return value + + +def _get_required(d: Mapping[str, Any], expected_type: type[_T], key: str) -> _T: + """Get a required value from the dictionary and verify it's the expected type.""" + if (value := _get(d, expected_type, key)) is None: + raise _PylockRequiredKeyError(key) + return value + + +def _get_sequence( + d: Mapping[str, Any], expected_item_type: type[_T], key: str +) -> Sequence[_T] | None: + """Get a list value from the dictionary and verify it's the expected items type.""" + if (value := _get(d, Sequence, key)) is None: # type: ignore[type-abstract] + return None + if isinstance(value, (str, bytes)): + # special case: str and bytes are Sequences, but we want to reject it + raise PylockValidationError( + f"Unexpected type {type(value).__name__} (expected Sequence)", + context=key, + ) + for i, item in enumerate(value): + if not isinstance(item, expected_item_type): + raise PylockValidationError( + f"Unexpected type {type(item).__name__} " + f"(expected {expected_item_type.__name__})", + context=f"{key}[{i}]", + ) + return value + + +def _get_as( + d: Mapping[str, Any], + expected_type: type[_T], + target_type: Callable[[_T], _T2], + key: str, +) -> _T2 | None: + """Get a value from the dictionary, verify it's the expected type, + and convert to the target type. + + This assumes the target_type constructor accepts the value. + """ + if (value := _get(d, expected_type, key)) is None: + return None + try: + return target_type(value) + except Exception as e: + raise PylockValidationError(e, context=key) from e + + +def _get_required_as( + d: Mapping[str, Any], + expected_type: type[_T], + target_type: Callable[[_T], _T2], + key: str, +) -> _T2: + """Get a required value from the dict, verify it's the expected type, + and convert to the target type.""" + if (value := _get_as(d, expected_type, target_type, key)) is None: + raise _PylockRequiredKeyError(key) + return value + + +def _get_sequence_as( + d: Mapping[str, Any], + expected_item_type: type[_T], + target_item_type: Callable[[_T], _T2], + key: str, +) -> list[_T2] | None: + """Get list value from dictionary and verify expected items type.""" + if (value := _get_sequence(d, expected_item_type, key)) is None: + return None + result = [] + try: + for item in value: + typed_item = target_item_type(item) + result.append(typed_item) + except Exception as e: + raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e + return result + + +def _get_object( + d: Mapping[str, Any], target_type: type[_FromMappingProtocolT], key: str +) -> _FromMappingProtocolT | None: + """Get a dictionary value from the dictionary and convert it to a dataclass.""" + if (value := _get(d, Mapping, key)) is None: # type: ignore[type-abstract] + return None + try: + return target_type._from_dict(value) + except Exception as e: + raise PylockValidationError(e, context=key) from e + + +def _get_sequence_of_objects( + d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str +) -> list[_FromMappingProtocolT] | None: + """Get a list value from the dictionary and convert its items to a dataclass.""" + if (value := _get_sequence(d, Mapping, key)) is None: # type: ignore[type-abstract] + return None + result: list[_FromMappingProtocolT] = [] + try: + for item in value: + typed_item = target_item_type._from_dict(item) + result.append(typed_item) + except Exception as e: + raise PylockValidationError(e, context=f"{key}[{len(result)}]") from e + return result + + +def _get_required_sequence_of_objects( + d: Mapping[str, Any], target_item_type: type[_FromMappingProtocolT], key: str +) -> Sequence[_FromMappingProtocolT]: + """Get a required list value from the dictionary and convert its items to a + dataclass.""" + if (result := _get_sequence_of_objects(d, target_item_type, key)) is None: + raise _PylockRequiredKeyError(key) + return result + + +def _validate_normalized_name(name: str) -> NormalizedName: + """Validate that a string is a NormalizedName.""" + if not is_normalized_name(name): + raise PylockValidationError(f"Name {name!r} is not normalized") + return NormalizedName(name) + + +def _validate_path_url(path: str | None, url: str | None) -> None: + if not path and not url: + raise PylockValidationError("path or url must be provided") + + +def _path_name(path: str | None) -> str | None: + if not path: + return None + # If the path is relative it MAY use POSIX-style path separators explicitly + # for portability + if "/" in path: + return path.rsplit("/", 1)[-1] + elif "\\" in path: + return path.rsplit("\\", 1)[-1] + else: + return path + + +def _url_name(url: str | None) -> str | None: + if not url: + return None + url_path = urlparse(url).path + return url_path.rsplit("/", 1)[-1] + + +def _validate_hashes(hashes: Mapping[str, Any]) -> Mapping[str, Any]: + if not hashes: + raise PylockValidationError("At least one hash must be provided") + if not all(isinstance(hash_val, str) for hash_val in hashes.values()): + raise PylockValidationError("Hash values must be strings") + return hashes + + +class PylockValidationError(Exception): + """Raised when when input data is not spec-compliant.""" + + context: str | None = None + message: str + + def __init__( + self, + cause: str | Exception, + *, + context: str | None = None, + ) -> None: + if isinstance(cause, PylockValidationError): + if cause.context: + self.context = ( + f"{context}.{cause.context}" if context else cause.context + ) + else: + self.context = context + self.message = cause.message + else: + self.context = context + self.message = str(cause) + + def __str__(self) -> str: + if self.context: + return f"{self.message} in {self.context!r}" + return self.message + + +class _PylockRequiredKeyError(PylockValidationError): + def __init__(self, key: str) -> None: + super().__init__("Missing required value", context=key) + + +class PylockUnsupportedVersionError(PylockValidationError): + """Raised when encountering an unsupported `lock_version`.""" + + +class PylockSelectError(Exception): + """Base exception for errors raised by :meth:`Pylock.select`.""" + + +@dataclass(frozen=True, init=False) +class PackageVcs: + type: str + url: str | None = None + path: str | None = None + requested_revision: str | None = None + commit_id: str # type: ignore[misc] + subdirectory: str | None = None + + def __init__( + self, + *, + type: str, + url: str | None = None, + path: str | None = None, + requested_revision: str | None = None, + commit_id: str, + subdirectory: str | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "type", type) + object.__setattr__(self, "url", url) + object.__setattr__(self, "path", path) + object.__setattr__(self, "requested_revision", requested_revision) + object.__setattr__(self, "commit_id", commit_id) + object.__setattr__(self, "subdirectory", subdirectory) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package_vcs = cls( + type=_get_required(d, str, "type"), + url=_get(d, str, "url"), + path=_get(d, str, "path"), + requested_revision=_get(d, str, "requested-revision"), + commit_id=_get_required(d, str, "commit-id"), + subdirectory=_get(d, str, "subdirectory"), + ) + _validate_path_url(package_vcs.path, package_vcs.url) + return package_vcs + + +@dataclass(frozen=True, init=False) +class PackageDirectory: + path: str + editable: bool | None = None + subdirectory: str | None = None + + def __init__( + self, + *, + path: str, + editable: bool | None = None, + subdirectory: str | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "path", path) + object.__setattr__(self, "editable", editable) + object.__setattr__(self, "subdirectory", subdirectory) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + return cls( + path=_get_required(d, str, "path"), + editable=_get(d, bool, "editable"), + subdirectory=_get(d, str, "subdirectory"), + ) + + +@dataclass(frozen=True, init=False) +class PackageArchive: + url: str | None = None + path: str | None = None + size: int | None = None + upload_time: datetime | None = None + hashes: Mapping[str, str] # type: ignore[misc] + subdirectory: str | None = None + + def __init__( + self, + *, + url: str | None = None, + path: str | None = None, + size: int | None = None, + upload_time: datetime | None = None, + hashes: Mapping[str, str], + subdirectory: str | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "url", url) + object.__setattr__(self, "path", path) + object.__setattr__(self, "size", size) + object.__setattr__(self, "upload_time", upload_time) + object.__setattr__(self, "hashes", hashes) + object.__setattr__(self, "subdirectory", subdirectory) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package_archive = cls( + url=_get(d, str, "url"), + path=_get(d, str, "path"), + size=_get(d, int, "size"), + upload_time=_get(d, datetime, "upload-time"), + hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] + subdirectory=_get(d, str, "subdirectory"), + ) + _validate_path_url(package_archive.path, package_archive.url) + return package_archive + + +@dataclass(frozen=True, init=False) +class PackageSdist: + name: str | None = None + upload_time: datetime | None = None + url: str | None = None + path: str | None = None + size: int | None = None + hashes: Mapping[str, str] # type: ignore[misc] + + def __init__( + self, + *, + name: str | None = None, + upload_time: datetime | None = None, + url: str | None = None, + path: str | None = None, + size: int | None = None, + hashes: Mapping[str, str], + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "name", name) + object.__setattr__(self, "upload_time", upload_time) + object.__setattr__(self, "url", url) + object.__setattr__(self, "path", path) + object.__setattr__(self, "size", size) + object.__setattr__(self, "hashes", hashes) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package_sdist = cls( + name=_get(d, str, "name"), + upload_time=_get(d, datetime, "upload-time"), + url=_get(d, str, "url"), + path=_get(d, str, "path"), + size=_get(d, int, "size"), + hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] + ) + _validate_path_url(package_sdist.path, package_sdist.url) + return package_sdist + + @property + def filename(self) -> str: + """Get the filename of the sdist.""" + filename = self.name or _path_name(self.path) or _url_name(self.url) + if not filename: + raise PylockValidationError("Cannot determine sdist filename") + return filename + + +@dataclass(frozen=True, init=False) +class PackageWheel: + name: str | None = None + upload_time: datetime | None = None + url: str | None = None + path: str | None = None + size: int | None = None + hashes: Mapping[str, str] # type: ignore[misc] + + def __init__( + self, + *, + name: str | None = None, + upload_time: datetime | None = None, + url: str | None = None, + path: str | None = None, + size: int | None = None, + hashes: Mapping[str, str], + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "name", name) + object.__setattr__(self, "upload_time", upload_time) + object.__setattr__(self, "url", url) + object.__setattr__(self, "path", path) + object.__setattr__(self, "size", size) + object.__setattr__(self, "hashes", hashes) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package_wheel = cls( + name=_get(d, str, "name"), + upload_time=_get(d, datetime, "upload-time"), + url=_get(d, str, "url"), + path=_get(d, str, "path"), + size=_get(d, int, "size"), + hashes=_get_required_as(d, Mapping, _validate_hashes, "hashes"), # type: ignore[type-abstract] + ) + _validate_path_url(package_wheel.path, package_wheel.url) + return package_wheel + + @property + def filename(self) -> str: + """Get the filename of the wheel.""" + filename = self.name or _path_name(self.path) or _url_name(self.url) + if not filename: + raise PylockValidationError("Cannot determine wheel filename") + return filename + + +@dataclass(frozen=True, init=False) +class Package: + name: NormalizedName + version: Version | None = None + marker: Marker | None = None + requires_python: SpecifierSet | None = None + dependencies: Sequence[Mapping[str, Any]] | None = None + vcs: PackageVcs | None = None + directory: PackageDirectory | None = None + archive: PackageArchive | None = None + index: str | None = None + sdist: PackageSdist | None = None + wheels: Sequence[PackageWheel] | None = None + attestation_identities: Sequence[Mapping[str, Any]] | None = None + tool: Mapping[str, Any] | None = None + + def __init__( + self, + *, + name: NormalizedName, + version: Version | None = None, + marker: Marker | None = None, + requires_python: SpecifierSet | None = None, + dependencies: Sequence[Mapping[str, Any]] | None = None, + vcs: PackageVcs | None = None, + directory: PackageDirectory | None = None, + archive: PackageArchive | None = None, + index: str | None = None, + sdist: PackageSdist | None = None, + wheels: Sequence[PackageWheel] | None = None, + attestation_identities: Sequence[Mapping[str, Any]] | None = None, + tool: Mapping[str, Any] | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "name", name) + object.__setattr__(self, "version", version) + object.__setattr__(self, "marker", marker) + object.__setattr__(self, "requires_python", requires_python) + object.__setattr__(self, "dependencies", dependencies) + object.__setattr__(self, "vcs", vcs) + object.__setattr__(self, "directory", directory) + object.__setattr__(self, "archive", archive) + object.__setattr__(self, "index", index) + object.__setattr__(self, "sdist", sdist) + object.__setattr__(self, "wheels", wheels) + object.__setattr__(self, "attestation_identities", attestation_identities) + object.__setattr__(self, "tool", tool) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + package = cls( + name=_get_required_as(d, str, _validate_normalized_name, "name"), + version=_get_as(d, str, Version, "version"), + requires_python=_get_as(d, str, SpecifierSet, "requires-python"), + dependencies=_get_sequence(d, Mapping, "dependencies"), # type: ignore[type-abstract] + marker=_get_as(d, str, Marker, "marker"), + vcs=_get_object(d, PackageVcs, "vcs"), + directory=_get_object(d, PackageDirectory, "directory"), + archive=_get_object(d, PackageArchive, "archive"), + index=_get(d, str, "index"), + sdist=_get_object(d, PackageSdist, "sdist"), + wheels=_get_sequence_of_objects(d, PackageWheel, "wheels"), + attestation_identities=_get_sequence(d, Mapping, "attestation-identities"), # type: ignore[type-abstract] + tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] + ) + distributions = bool(package.sdist) + len(package.wheels or []) + direct_urls = ( + bool(package.vcs) + bool(package.directory) + bool(package.archive) + ) + if distributions > 0 and direct_urls > 0: + raise PylockValidationError( + "None of vcs, directory, archive must be set if sdist or wheels are set" + ) + if distributions == 0 and direct_urls != 1: + raise PylockValidationError( + "Exactly one of vcs, directory, archive must be set " + "if sdist and wheels are not set" + ) + for i, wheel in enumerate(package.wheels or []): + try: + (name, version, _, _) = parse_wheel_filename(wheel.filename) + except Exception as e: + raise PylockValidationError( + f"Invalid wheel filename {wheel.filename!r}", + context=f"wheels[{i}]", + ) from e + if name != package.name: + raise PylockValidationError( + f"Name in {wheel.filename!r} is not consistent with " + f"package name {package.name!r}", + context=f"wheels[{i}]", + ) + if package.version and version != package.version: + raise PylockValidationError( + f"Version in {wheel.filename!r} is not consistent with " + f"package version {str(package.version)!r}", + context=f"wheels[{i}]", + ) + if package.sdist: + try: + name, version = parse_sdist_filename(package.sdist.filename) + except Exception as e: + raise PylockValidationError( + f"Invalid sdist filename {package.sdist.filename!r}", + context="sdist", + ) from e + if name != package.name: + raise PylockValidationError( + f"Name in {package.sdist.filename!r} is not consistent with " + f"package name {package.name!r}", + context="sdist", + ) + if package.version and version != package.version: + raise PylockValidationError( + f"Version in {package.sdist.filename!r} is not consistent with " + f"package version {str(package.version)!r}", + context="sdist", + ) + try: + for i, attestation_identity in enumerate( # noqa: B007 + package.attestation_identities or [] + ): + _get_required(attestation_identity, str, "kind") + except Exception as e: + raise PylockValidationError( + e, context=f"attestation-identities[{i}]" + ) from e + return package + + @property + def is_direct(self) -> bool: + return not (self.sdist or self.wheels) + + +@dataclass(frozen=True, init=False) +class Pylock: + """A class representing a pylock file.""" + + lock_version: Version + environments: Sequence[Marker] | None = None + requires_python: SpecifierSet | None = None + extras: Sequence[NormalizedName] | None = None + dependency_groups: Sequence[str] | None = None + default_groups: Sequence[str] | None = None + created_by: str # type: ignore[misc] + packages: Sequence[Package] # type: ignore[misc] + tool: Mapping[str, Any] | None = None + + def __init__( + self, + *, + lock_version: Version, + environments: Sequence[Marker] | None = None, + requires_python: SpecifierSet | None = None, + extras: Sequence[NormalizedName] | None = None, + dependency_groups: Sequence[str] | None = None, + default_groups: Sequence[str] | None = None, + created_by: str, + packages: Sequence[Package], + tool: Mapping[str, Any] | None = None, + ) -> None: + # In Python 3.10+ make dataclass kw_only=True and remove __init__ + object.__setattr__(self, "lock_version", lock_version) + object.__setattr__(self, "environments", environments) + object.__setattr__(self, "requires_python", requires_python) + object.__setattr__(self, "extras", extras) + object.__setattr__(self, "dependency_groups", dependency_groups) + object.__setattr__(self, "default_groups", default_groups) + object.__setattr__(self, "created_by", created_by) + object.__setattr__(self, "packages", packages) + object.__setattr__(self, "tool", tool) + + @classmethod + def _from_dict(cls, d: Mapping[str, Any]) -> Self: + pylock = cls( + lock_version=_get_required_as(d, str, Version, "lock-version"), + environments=_get_sequence_as(d, str, Marker, "environments"), + extras=_get_sequence_as(d, str, _validate_normalized_name, "extras"), + dependency_groups=_get_sequence(d, str, "dependency-groups"), + default_groups=_get_sequence(d, str, "default-groups"), + created_by=_get_required(d, str, "created-by"), + requires_python=_get_as(d, str, SpecifierSet, "requires-python"), + packages=_get_required_sequence_of_objects(d, Package, "packages"), + tool=_get(d, Mapping, "tool"), # type: ignore[type-abstract] + ) + if not Version("1") <= pylock.lock_version < Version("2"): + raise PylockUnsupportedVersionError( + f"pylock version {pylock.lock_version} is not supported" + ) + if pylock.lock_version > Version("1.0"): + _logger.warning( + "pylock minor version %s is not supported", pylock.lock_version + ) + return pylock + + @classmethod + def from_dict(cls, d: Mapping[str, Any], /) -> Self: + """Create and validate a Pylock instance from a TOML dictionary. + + Raises :class:`PylockValidationError` if the input data is not + spec-compliant. + """ + return cls._from_dict(d) + + def to_dict(self) -> Mapping[str, Any]: + """Convert the Pylock instance to a TOML dictionary.""" + return dataclasses.asdict(self, dict_factory=_toml_dict_factory) + + def validate(self) -> None: + """Validate the Pylock instance against the specification. + + Raises :class:`PylockValidationError` otherwise.""" + self.from_dict(self.to_dict()) + + def select( + self, + *, + environment: Environment | None = None, + tags: Sequence[Tag] | None = None, + extras: Collection[str] | None = None, + dependency_groups: Collection[str] | None = None, + ) -> Iterator[ + tuple[ + Package, + PackageVcs + | PackageDirectory + | PackageArchive + | PackageWheel + | PackageSdist, + ] + ]: + """Select what to install from the lock file. + + The *environment* and *tags* parameters represent the environment being + selected for. If unspecified, ``packaging.markers.default_environment()`` and + ``packaging.tags.sys_tags()`` are used. + + The *extras* parameter represents the extras to install. + + The *dependency_groups* parameter represents the groups to install. If + unspecified, the default groups are used. + + This method must be used on valid Pylock instances (i.e. one obtained + from :meth:`Pylock.from_dict` or if constructed manually, after calling + :meth:`Pylock.validate`). + """ + compatible_tags_selector = create_compatible_tags_selector(tags or sys_tags()) + + # #. Gather the extras and dependency groups to install and set ``extras`` and + # ``dependency_groups`` for marker evaluation, respectively. + # + # #. ``extras`` SHOULD be set to the empty set by default. + # #. ``dependency_groups`` SHOULD be the set created from + # :ref:`pylock-default-groups` by default. + env = cast( + "dict[str, str | frozenset[str]]", + dict( + environment or {}, # Marker.evaluate will fill-up + extras=frozenset(extras or []), + dependency_groups=frozenset( + (self.default_groups or []) + if dependency_groups is None # to allow selecting no group + else dependency_groups + ), + ), + ) + env_python_full_version = ( + environment["python_full_version"] + if environment + else default_environment()["python_full_version"] + ) + + # #. Check if the metadata version specified by :ref:`pylock-lock-version` is + # supported; an error or warning MUST be raised as appropriate. + # Covered by lock.validate() which is a precondition for this method. + + # #. If :ref:`pylock-requires-python` is specified, check that the environment + # being installed for meets the requirement; an error MUST be raised if it is + # not met. + if self.requires_python and not self.requires_python.contains( + env_python_full_version, + ): + raise PylockSelectError( + f"python_full_version {env_python_full_version!r} " + f"in provided environment does not satisfy the Python version " + f"requirement {str(self.requires_python)!r}" + ) + + # #. If :ref:`pylock-environments` is specified, check that at least one of the + # environment marker expressions is satisfied; an error MUST be raised if no + # expression is satisfied. + if self.environments: + for env_marker in self.environments: + if env_marker.evaluate( + cast("dict[str, str]", environment or {}), context="requirement" + ): + break + else: + raise PylockSelectError( + "Provided environment does not satisfy any of the " + "environments specified in the lock file" + ) + + # #. For each package listed in :ref:`pylock-packages`: + selected_packages_by_name: dict[str, tuple[int, Package]] = {} + for package_index, package in enumerate(self.packages): + # #. If :ref:`pylock-packages-marker` is specified, check if it is + # satisfied;if it isn't, skip to the next package. + if package.marker and not package.marker.evaluate(env, context="lock_file"): + continue + + # #. If :ref:`pylock-packages-requires-python` is specified, check if it is + # satisfied; an error MUST be raised if it isn't. + if package.requires_python and not package.requires_python.contains( + env_python_full_version, + ): + raise PylockSelectError( + f"python_full_version {env_python_full_version!r} " + f"in provided environment does not satisfy the Python version " + f"requirement {str(package.requires_python)!r} for package " + f"{package.name!r} at packages[{package_index}]" + ) + + # #. Check that no other conflicting instance of the package has been slated + # to be installed; an error about the ambiguity MUST be raised otherwise. + if package.name in selected_packages_by_name: + raise PylockSelectError( + f"Multiple packages with the name {package.name!r} are " + f"selected at packages[{package_index}] and " + f"packages[{selected_packages_by_name[package.name][0]}]" + ) + + # #. Check that the source of the package is specified appropriately (i.e. + # there are no conflicting sources in the package entry); + # an error MUST be raised if any issues are found. + # Covered by lock.validate() which is a precondition for this method. + + # #. Add the package to the set of packages to install. + selected_packages_by_name[package.name] = (package_index, package) + + # #. For each package to be installed: + for package_index, package in selected_packages_by_name.values(): + # - If :ref:`pylock-packages-vcs` is set: + if package.vcs is not None: + yield package, package.vcs + + # - Else if :ref:`pylock-packages-directory` is set: + elif package.directory is not None: + yield package, package.directory + + # - Else if :ref:`pylock-packages-archive` is set: + elif package.archive is not None: + yield package, package.archive + + # - Else if there are entries for :ref:`pylock-packages-wheels`: + elif package.wheels: + # #. Look for the appropriate wheel file based on + # :ref:`pylock-packages-wheels-name`; if one is not found then move + # on to :ref:`pylock-packages-sdist` or an error MUST be raised about + # a lack of source for the project. + best_wheel = next( + compatible_tags_selector( + (wheel, parse_wheel_filename(wheel.filename)[-1]) + for wheel in package.wheels + ), + None, + ) + if best_wheel: + yield package, best_wheel + elif package.sdist is not None: + yield package, package.sdist + else: + raise PylockSelectError( + f"No wheel found matching the provided tags " + f"for package {package.name!r} " + f"at packages[{package_index}], " + f"and no sdist available as a fallback" + ) + + # - Else if no :ref:`pylock-packages-wheels` file is found or + # :ref:`pylock-packages-sdist` is solely set: + elif package.sdist is not None: + yield package, package.sdist + + else: + # Covered by lock.validate() which is a precondition for this method. + raise NotImplementedError # pragma: no cover diff --git a/micromamba_root/Lib/site-packages/packaging/requirements.py b/micromamba_root/Lib/site-packages/packaging/requirements.py new file mode 100644 index 0000000000000000000000000000000000000000..5892aee6ee2e391673a8609eecb5e43be4931a89 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/requirements.py @@ -0,0 +1,129 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +from __future__ import annotations + +from typing import Iterator + +from ._parser import parse_requirement as _parse_requirement +from ._tokenizer import ParserSyntaxError +from .markers import Marker, _normalize_extra_values +from .specifiers import SpecifierSet +from .utils import canonicalize_name + +__all__ = [ + "InvalidRequirement", + "Requirement", +] + + +def __dir__() -> list[str]: + return __all__ + + +class InvalidRequirement(ValueError): + """ + An invalid requirement was found, users should refer to PEP 508. + """ + + +class Requirement: + """Parse a requirement. + + Parse a given requirement string into its parts, such as name, specifier, + URL, and extras. Raises InvalidRequirement on a badly-formed requirement + string. + + Instances are safe to serialize with :mod:`pickle`. They use a stable + format so the same pickle can be loaded in future packaging releases. + + .. versionchanged:: 26.2 + + Added a stable pickle format. Pickles created with packaging 26.2+ can + be unpickled with future releases. Backward compatibility with pickles + from packaging < 26.2 is supported but may be removed in a future + release. + """ + + # TODO: Can we test whether something is contained within a requirement? + # If so how do we do that? Do we need to test against the _name_ of + # the thing as well as the version? What about the markers? + # TODO: Can we normalize the name and extra name? + + def __init__(self, requirement_string: str) -> None: + try: + parsed = _parse_requirement(requirement_string) + except ParserSyntaxError as e: + raise InvalidRequirement(str(e)) from e + + self.name: str = parsed.name + self.url: str | None = parsed.url or None + self.extras: set[str] = set(parsed.extras or []) + self.specifier: SpecifierSet = SpecifierSet(parsed.specifier) + self.marker: Marker | None = None + if parsed.marker is not None: + self.marker = Marker.__new__(Marker) + self.marker._markers = _normalize_extra_values(parsed.marker) + + def _iter_parts(self, name: str) -> Iterator[str]: + yield name + + if self.extras: + formatted_extras = ",".join(sorted(self.extras)) + yield f"[{formatted_extras}]" + + if self.specifier: + yield str(self.specifier) + + if self.url: + yield f" @ {self.url}" + if self.marker: + yield " " + + if self.marker: + yield f"; {self.marker}" + + def __getstate__(self) -> str: + # Return the requirement string for compactness and stability. + # Re-parsed on load to reconstruct all fields. + return str(self) + + def __setstate__(self, state: object) -> None: + if isinstance(state, str): + # New format (26.2+): just the requirement string. + try: + tmp = Requirement(state) + except InvalidRequirement as exc: + raise TypeError(f"Cannot restore Requirement from {state!r}") from exc + self.name = tmp.name + self.url = tmp.url + self.extras = tmp.extras + self.specifier = tmp.specifier + self.marker = tmp.marker + return + if isinstance(state, dict): + # Old format (packaging <= 26.1, no __slots__): plain __dict__. + self.__dict__.update(state) + return + raise TypeError(f"Cannot restore Requirement from {state!r}") + + def __str__(self) -> str: + return "".join(self._iter_parts(self.name)) + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}({str(self)!r})>" + + def __hash__(self) -> int: + return hash(tuple(self._iter_parts(canonicalize_name(self.name)))) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Requirement): + return NotImplemented + + return ( + canonicalize_name(self.name) == canonicalize_name(other.name) + and self.extras == other.extras + and self.specifier == other.specifier + and self.url == other.url + and self.marker == other.marker + ) diff --git a/micromamba_root/Lib/site-packages/packaging/specifiers.py b/micromamba_root/Lib/site-packages/packaging/specifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..b165dc0f7c8201f2291780ce0273af8127105ab0 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/specifiers.py @@ -0,0 +1,1943 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.specifiers import Specifier, SpecifierSet, InvalidSpecifier + from packaging.version import Version +""" + +from __future__ import annotations + +import abc +import enum +import functools +import itertools +import re +import sys +import typing +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Final, + Iterable, + Iterator, + Sequence, + TypeVar, + Union, +) + +from .utils import canonicalize_version +from .version import InvalidVersion, Version + +if sys.version_info >= (3, 10): + from typing import TypeGuard # pragma: no cover +elif TYPE_CHECKING: + from typing_extensions import TypeGuard + +__all__ = [ + "BaseSpecifier", + "InvalidSpecifier", + "Specifier", + "SpecifierSet", +] + + +def __dir__() -> list[str]: + return __all__ + + +def _validate_spec(spec: object, /) -> TypeGuard[tuple[str, str]]: + return ( + isinstance(spec, tuple) + and len(spec) == 2 + and isinstance(spec[0], str) + and isinstance(spec[1], str) + ) + + +def _validate_pre(pre: object, /) -> TypeGuard[bool | None]: + return pre is None or isinstance(pre, bool) + + +T = TypeVar("T") +UnparsedVersion = Union[Version, str] +UnparsedVersionVar = TypeVar("UnparsedVersionVar", bound=UnparsedVersion) +CallableOperator = Callable[[Version, str], bool] + +# The smallest possible PEP 440 version. No valid version is less than this. +_MIN_VERSION: Final[Version] = Version("0.dev0") + + +def _trim_release(release: tuple[int, ...]) -> tuple[int, ...]: + """Strip trailing zeros from a release tuple for normalized comparison.""" + end = len(release) + while end > 1 and release[end - 1] == 0: + end -= 1 + return release if end == len(release) else release[:end] + + +class _BoundaryKind(enum.Enum): + """Where a boundary marker sits in the version ordering.""" + + AFTER_LOCALS = enum.auto() # after V+local, before V.post0 + AFTER_POSTS = enum.auto() # after V.postN, before next release + + +@functools.total_ordering +class _BoundaryVersion: + """A point on the version line between two real PEP 440 versions. + + Some specifier semantics imply boundaries between real versions: + ``<=1.0`` includes ``1.0+local`` and ``>1.0`` excludes + ``1.0.post0``. No real :class:`Version` falls on those boundaries, + so this class creates values that sort between the real versions + on either side. + + Two kinds exist, shown relative to a base version V:: + + V < V+local < AFTER_LOCALS(V) < V.post0 < AFTER_POSTS(V) + + ``AFTER_LOCALS`` sits after V and every V+local, but before + V.post0. Upper bound of ``<=V``, ``==V``, ``!=V``. + + ``AFTER_POSTS`` sits after every V.postN, but before the next + release segment. Lower bound of ``>V`` (final or pre-release V) + to exclude post-releases per PEP 440. + """ + + __slots__ = ("_kind", "_trimmed_release", "version") + + def __init__(self, version: Version, kind: _BoundaryKind) -> None: + self.version = version + self._kind = kind + self._trimmed_release = _trim_release(version.release) + + def _is_family(self, other: Version) -> bool: + """Is ``other`` a version that this boundary sorts above?""" + v = self.version + if not ( + other.epoch == v.epoch + and _trim_release(other.release) == self._trimmed_release + and other.pre == v.pre + ): + return False + if self._kind == _BoundaryKind.AFTER_LOCALS: + # Local family: exact same public version (any local label). + return other.post == v.post and other.dev == v.dev + # Post family: same base + any post-release (or identical). + return other.dev == v.dev or other.post is not None + + def __eq__(self, other: object) -> bool: + if isinstance(other, _BoundaryVersion): + return self.version == other.version and self._kind == other._kind + return NotImplemented + + def __lt__(self, other: _BoundaryVersion | Version) -> bool: + if isinstance(other, _BoundaryVersion): + if self.version != other.version: + return self.version < other.version + return self._kind.value < other._kind.value + return not self._is_family(other) and self.version < other + + def __hash__(self) -> int: + return hash((self.version, self._kind)) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.version!r}, {self._kind.name})" + + +@functools.total_ordering +class _LowerBound: + """Lower bound of a version range. + + A version *v* of ``None`` means unbounded below (-inf). + At equal versions, ``[v`` sorts before ``(v`` because an inclusive + bound starts earlier. + """ + + __slots__ = ("inclusive", "version") + + def __init__(self, version: _VersionOrBoundary, inclusive: bool) -> None: + self.version = version + self.inclusive = inclusive + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _LowerBound): + return NotImplemented # pragma: no cover + return self.version == other.version and self.inclusive == other.inclusive + + def __lt__(self, other: _LowerBound) -> bool: + if not isinstance(other, _LowerBound): # pragma: no cover + return NotImplemented + # -inf < anything (except -inf). + if self.version is None: + return other.version is not None + if other.version is None: + return False + if self.version != other.version: + return self.version < other.version + # [v < (v: inclusive starts earlier. + return self.inclusive and not other.inclusive + + def __hash__(self) -> int: + return hash((self.version, self.inclusive)) + + def __repr__(self) -> str: + bracket = "[" if self.inclusive else "(" + return f"<{self.__class__.__name__} {bracket}{self.version!r}>" + + +@functools.total_ordering +class _UpperBound: + """Upper bound of a version range. + + A version *v* of ``None`` means unbounded above (+inf). + At equal versions, ``v)`` sorts before ``v]`` because an exclusive + bound ends earlier. + """ + + __slots__ = ("inclusive", "version") + + def __init__(self, version: _VersionOrBoundary, inclusive: bool) -> None: + self.version = version + self.inclusive = inclusive + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _UpperBound): + return NotImplemented # pragma: no cover + return self.version == other.version and self.inclusive == other.inclusive + + def __lt__(self, other: _UpperBound) -> bool: + if not isinstance(other, _UpperBound): # pragma: no cover + return NotImplemented + # Nothing < +inf (except +inf itself). + if self.version is None: + return False + if other.version is None: + return True + if self.version != other.version: + return self.version < other.version + # v) < v]: exclusive ends earlier. + return not self.inclusive and other.inclusive + + def __hash__(self) -> int: + return hash((self.version, self.inclusive)) + + def __repr__(self) -> str: + bracket = "]" if self.inclusive else ")" + return f"<{self.__class__.__name__} {self.version!r}{bracket}>" + + +if typing.TYPE_CHECKING: + _VersionOrBoundary = Union[Version, _BoundaryVersion, None] + + #: A single contiguous version range, represented as a + #: (lower bound, upper bound) pair. + _VersionRange = tuple[_LowerBound, _UpperBound] + +_NEG_INF = _LowerBound(None, False) +_POS_INF = _UpperBound(None, False) +_FULL_RANGE: tuple[_VersionRange] = ((_NEG_INF, _POS_INF),) + + +def _range_is_empty(lower: _LowerBound, upper: _UpperBound) -> bool: + """True when the range defined by *lower* and *upper* contains no versions.""" + if lower.version is None or upper.version is None: + return False + if lower.version == upper.version: + return not (lower.inclusive and upper.inclusive) + return lower.version > upper.version + + +def _intersect_ranges( + left: Sequence[_VersionRange], + right: Sequence[_VersionRange], +) -> list[_VersionRange]: + """Intersect two sorted, non-overlapping range lists (two-pointer merge).""" + result: list[_VersionRange] = [] + left_index = right_index = 0 + while left_index < len(left) and right_index < len(right): + left_lower, left_upper = left[left_index] + right_lower, right_upper = right[right_index] + + lower = max(left_lower, right_lower) + upper = min(left_upper, right_upper) + + if not _range_is_empty(lower, upper): + result.append((lower, upper)) + + # Advance whichever side has the smaller upper bound. + if left_upper < right_upper: + left_index += 1 + else: + right_index += 1 + + return result + + +def _next_prefix_dev0(version: Version) -> Version: + """Smallest version in the next prefix: 1.2 -> 1.3.dev0.""" + release = (*version.release[:-1], version.release[-1] + 1) + return Version.from_parts(epoch=version.epoch, release=release, dev=0) + + +def _base_dev0(version: Version) -> Version: + """The .dev0 of a version's base release: 1.2 -> 1.2.dev0.""" + return Version.from_parts(epoch=version.epoch, release=version.release, dev=0) + + +def _coerce_version(version: UnparsedVersion) -> Version | None: + if not isinstance(version, Version): + try: + version = Version(version) + except InvalidVersion: + return None + return version + + +def _public_version(version: Version) -> Version: + if version.local is None: + return version + return version.__replace__(local=None) + + +def _post_base(version: Version) -> Version: + """The version that *version* is a post-release of. + + 1.0.post1 -> 1.0, 1.0a1.post0 -> 1.0a1, 1.0.post0.dev1 -> 1.0. + """ + return version.__replace__(post=None, dev=None, local=None) + + +def _earliest_prerelease(version: Version) -> Version: + """Earliest pre-release of *version*. + + 1.2 -> 1.2.dev0, 1.2.post1 -> 1.2.post1.dev0. + """ + return version.__replace__(dev=0, local=None) + + +def _nearest_non_prerelease( + v: _VersionOrBoundary, +) -> Version | None: + """Smallest non-pre-release version at or above *v*, or None.""" + if v is None: + return None + if isinstance(v, _BoundaryVersion): + inner = v.version + if inner.is_prerelease: + # AFTER_LOCALS(1.0a1) -> nearest non-pre is 1.0 + return inner.__replace__(pre=None, dev=None, local=None) + # AFTER_LOCALS(1.0) -> nearest non-pre is 1.0.post0 + # AFTER_LOCALS(1.0.post0) -> nearest non-pre is 1.0.post1 + k = (inner.post + 1) if inner.post is not None else 0 + return inner.__replace__(post=k, local=None) + if not v.is_prerelease: + return v + # Strip pre/dev to get the final or post-release form. + return v.__replace__(pre=None, dev=None, local=None) + + +class InvalidSpecifier(ValueError): + """ + Raised when attempting to create a :class:`Specifier` with a specifier + string that is invalid. + + >>> Specifier("lolwat") + Traceback (most recent call last): + ... + packaging.specifiers.InvalidSpecifier: Invalid specifier: 'lolwat' + """ + + +class BaseSpecifier(metaclass=abc.ABCMeta): + __slots__ = () + __match_args__ = ("_str",) + + @property + def _str(self) -> str: + """Internal property for match_args""" + return str(self) + + @abc.abstractmethod + def __str__(self) -> str: + """ + Returns the str representation of this Specifier-like object. This + should be representative of the Specifier itself. + """ + + @abc.abstractmethod + def __hash__(self) -> int: + """ + Returns a hash value for this Specifier-like object. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Returns a boolean representing whether or not the two Specifier-like + objects are equal. + + :param other: The other object to check against. + """ + + @property + @abc.abstractmethod + def prereleases(self) -> bool | None: + """Whether or not pre-releases as a whole are allowed. + + This can be set to either ``True`` or ``False`` to explicitly enable or disable + prereleases or it can be set to ``None`` (the default) to use default semantics. + """ + + @prereleases.setter # noqa: B027 + def prereleases(self, value: bool) -> None: + """Setter for :attr:`prereleases`. + + :param value: The value to set. + """ + + @abc.abstractmethod + def contains(self, item: str, prereleases: bool | None = None) -> bool: + """ + Determines if the given item is contained within this specifier. + """ + + @typing.overload + def filter( + self, + iterable: Iterable[UnparsedVersionVar], + prereleases: bool | None = None, + key: None = ..., + ) -> Iterator[UnparsedVersionVar]: ... + + @typing.overload + def filter( + self, + iterable: Iterable[T], + prereleases: bool | None = None, + key: Callable[[T], UnparsedVersion] = ..., + ) -> Iterator[T]: ... + + @abc.abstractmethod + def filter( + self, + iterable: Iterable[Any], + prereleases: bool | None = None, + key: Callable[[Any], UnparsedVersion] | None = None, + ) -> Iterator[Any]: + """ + Takes an iterable of items and filters them so that only items which + are contained within this specifier are allowed in it. + """ + + +class Specifier(BaseSpecifier): + """This class abstracts handling of version specifiers. + + .. tip:: + + It is generally not required to instantiate this manually. You should instead + prefer to work with :class:`SpecifierSet` instead, which can parse + comma-separated version specifiers (which is what package metadata contains). + + Instances are safe to serialize with :mod:`pickle`. They use a stable + format so the same pickle can be loaded in future packaging releases. + + .. versionchanged:: 26.2 + + Added a stable pickle format. Pickles created with packaging 26.2+ can + be unpickled with future releases. Backward compatibility with pickles + from packaging < 26.2 is supported but may be removed in a future + release. + """ + + __slots__ = ( + "_prereleases", + "_ranges", + "_spec", + "_spec_version", + "_wildcard_split", + ) + + _specifier_regex_str = r""" + (?: + (?: + # The identity operators allow for an escape hatch that will + # do an exact string match of the version you wish to install. + # This will not be parsed by PEP 440 and we cannot determine + # any semantic meaning from it. This operator is discouraged + # but included entirely as an escape hatch. + === # Only match for the identity operator + \s* + [^\s;)]* # The arbitrary version can be just about anything, + # we match everything except for whitespace, a + # semi-colon for marker support, and a closing paren + # since versions can be enclosed in them. + ) + | + (?: + # The (non)equality operators allow for wild card and local + # versions to be specified so we have to define these two + # operators separately to enable that. + (?:==|!=) # Only match for equals and not equals + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)* # release + + # You cannot use a wild card and a pre-release, post-release, a dev or + # local version together so group them with a | and make them optional. + (?: + \.\* # Wild card syntax of .* + | + (?a: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?a: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?a:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + (?a:\+[a-z0-9]+(?:[-_\.][a-z0-9]+)*)? # local + )? + ) + | + (?: + # The compatible operator requires at least two digits in the + # release segment. + (?:~=) # Only match for the compatible operator + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)+ # release (We have a + instead of a *) + (?: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + ) + | + (?: + # All other operators only allow a sub set of what the + # (non)equality operators do. Specifically they do not allow + # local versions to be specified nor do they allow the prefix + # matching wild cards. + (?:<=|>=|<|>) + + \s* + v? + (?:[0-9]+!)? # epoch + [0-9]+(?:\.[0-9]+)* # release + (?a: # pre release + [-_\.]? + (alpha|beta|preview|pre|a|b|c|rc) + [-_\.]? + [0-9]* + )? + (?a: # post release + (?:-[0-9]+)|(?:[-_\.]?(post|rev|r)[-_\.]?[0-9]*) + )? + (?a:[-_\.]?dev[-_\.]?[0-9]*)? # dev release + ) + ) + """ + + _regex = re.compile( + r"\s*" + _specifier_regex_str + r"\s*", re.VERBOSE | re.IGNORECASE + ) + + _operators: Final = { + "~=": "compatible", + "==": "equal", + "!=": "not_equal", + "<=": "less_than_equal", + ">=": "greater_than_equal", + "<": "less_than", + ">": "greater_than", + "===": "arbitrary", + } + + def __init__(self, spec: str = "", prereleases: bool | None = None) -> None: + """Initialize a Specifier instance. + + :param spec: + The string representation of a specifier which will be parsed and + normalized before use. + :param prereleases: + This tells the specifier if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + :raises InvalidSpecifier: + If the given specifier is invalid (i.e. bad syntax). + """ + if not self._regex.fullmatch(spec): + raise InvalidSpecifier(f"Invalid specifier: {spec!r}") + + spec = spec.strip() + if spec.startswith("==="): + operator, version = spec[:3], spec[3:].strip() + elif spec.startswith(("~=", "==", "!=", "<=", ">=")): + operator, version = spec[:2], spec[2:].strip() + else: + operator, version = spec[:1], spec[1:].strip() + + self._spec: tuple[str, str] = (operator, version) + + # Store whether or not this Specifier should accept prereleases + self._prereleases = prereleases + + # Specifier version cache + self._spec_version: tuple[str, Version] | None = None + + # Populated on first wildcard (==X.*) comparison + self._wildcard_split: tuple[list[str], int] | None = None + + # Version range cache (populated by _to_ranges) + self._ranges: Sequence[_VersionRange] | None = None + + def _get_spec_version(self, version: str) -> Version | None: + """One element cache, as only one spec Version is needed per Specifier.""" + if self._spec_version is not None and self._spec_version[0] == version: + return self._spec_version[1] + + version_specifier = _coerce_version(version) + if version_specifier is None: + return None + + self._spec_version = (version, version_specifier) + return version_specifier + + def _require_spec_version(self, version: str) -> Version: + """Get spec version, asserting it's valid (not for === operator). + + This method should only be called for operators where version + strings are guaranteed to be valid PEP 440 versions (not ===). + """ + spec_version = self._get_spec_version(version) + assert spec_version is not None + return spec_version + + def _to_ranges(self) -> Sequence[_VersionRange]: + """Convert this specifier to sorted, non-overlapping version ranges. + + Each standard operator maps to one or two ranges. ``===`` is + modeled as full range (actual check done separately). Cached. + """ + if self._ranges is not None: + return self._ranges + + op = self.operator + ver_str = self.version + + if op == "===": + self._ranges = _FULL_RANGE + return _FULL_RANGE + + if ver_str.endswith(".*"): + result = self._wildcard_ranges(op, ver_str) + else: + result = self._standard_ranges(op, ver_str) + + self._ranges = result + return result + + def _wildcard_ranges(self, op: str, ver_str: str) -> list[_VersionRange]: + # ==1.2.* -> [1.2.dev0, 1.3.dev0); !=1.2.* -> complement. + base = self._require_spec_version(ver_str[:-2]) + lower = _base_dev0(base) + upper = _next_prefix_dev0(base) + if op == "==": + return [(_LowerBound(lower, True), _UpperBound(upper, False))] + # != + return [ + (_NEG_INF, _UpperBound(lower, False)), + (_LowerBound(upper, True), _POS_INF), + ] + + def _standard_ranges(self, op: str, ver_str: str) -> list[_VersionRange]: + v = self._require_spec_version(ver_str) + + if op == ">=": + return [(_LowerBound(v, True), _POS_INF)] + + if op == "<=": + return [ + ( + _NEG_INF, + _UpperBound(_BoundaryVersion(v, _BoundaryKind.AFTER_LOCALS), True), + ) + ] + + if op == ">": + if v.dev is not None: + # >V.devN: dev versions have no post-releases, so the + # next real version is V.dev(N+1). + lower_ver = v.__replace__(dev=v.dev + 1, local=None) + return [(_LowerBound(lower_ver, True), _POS_INF)] + if v.post is not None: + # >V.postN: next real version is V.post(N+1).dev0. + lower_ver = v.__replace__(post=v.post + 1, dev=0, local=None) + return [(_LowerBound(lower_ver, True), _POS_INF)] + # >V (final or pre-release): skip V+local and all V.postN. + return [ + ( + _LowerBound(_BoundaryVersion(v, _BoundaryKind.AFTER_POSTS), False), + _POS_INF, + ) + ] + + if op == "<": + # bool | None: + # If there is an explicit prereleases set for this, then we'll just + # blindly use that. + if self._prereleases is not None: + return self._prereleases + + # Only the "!=" operator does not imply prereleases when + # the version in the specifier is a prerelease. + operator, version_str = self._spec + if operator == "!=": + return False + + # The == specifier with trailing .* cannot include prereleases + # e.g. "==1.0a1.*" is not valid. + if operator == "==" and version_str.endswith(".*"): + return False + + # "===" can have arbitrary string versions, so we cannot parse + # those, we take prereleases as unknown (None) for those. + version = self._get_spec_version(version_str) + if version is None: + return None + + # For all other operators, use the check if spec Version + # object implies pre-releases. + return version.is_prerelease + + @prereleases.setter + def prereleases(self, value: bool | None) -> None: + self._prereleases = value + + def __getstate__(self) -> tuple[tuple[str, str], bool | None]: + # Return state as a 2-item tuple for compactness: + # ((operator, version), prereleases) + # Cache members are excluded and will be recomputed on demand. + return (self._spec, self._prereleases) + + def __setstate__(self, state: object) -> None: + # Always discard cached values - they will be recomputed on demand. + self._spec_version = None + self._wildcard_split = None + self._ranges = None + + if isinstance(state, tuple): + if len(state) == 2: + # New format (26.2+): ((operator, version), prereleases) + spec, prereleases = state + if _validate_spec(spec) and _validate_pre(prereleases): + self._spec = spec + self._prereleases = prereleases + return + if len(state) == 2 and isinstance(state[1], dict): + # Format (packaging 26.0-26.1): (None, {slot: value}). + _, slot_dict = state + spec = slot_dict.get("_spec") + prereleases = slot_dict.get("_prereleases", "invalid") + if _validate_spec(spec) and _validate_pre(prereleases): + self._spec = spec + self._prereleases = prereleases + return + if isinstance(state, dict): + # Old format (packaging <= 25.x, no __slots__): state is a plain dict. + spec = state.get("_spec") + prereleases = state.get("_prereleases", "invalid") + if _validate_spec(spec) and _validate_pre(prereleases): + self._spec = spec + self._prereleases = prereleases + return + + raise TypeError(f"Cannot restore Specifier from {state!r}") + + @property + def operator(self) -> str: + """The operator of this specifier. + + >>> Specifier("==1.2.3").operator + '==' + """ + return self._spec[0] + + @property + def version(self) -> str: + """The version of this specifier. + + >>> Specifier("==1.2.3").version + '1.2.3' + """ + return self._spec[1] + + def __repr__(self) -> str: + """A representation of the Specifier that shows all internal state. + + >>> Specifier('>=1.0.0') + =1.0.0')> + >>> Specifier('>=1.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> Specifier('>=1.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"<{self.__class__.__name__}({str(self)!r}{pre})>" + + def __str__(self) -> str: + """A string representation of the Specifier that can be round-tripped. + + >>> str(Specifier('>=1.0.0')) + '>=1.0.0' + >>> str(Specifier('>=1.0.0', prereleases=False)) + '>=1.0.0' + """ + return "{}{}".format(*self._spec) + + @property + def _canonical_spec(self) -> tuple[str, str]: + operator, version = self._spec + if operator == "===" or version.endswith(".*"): + return operator, version + + spec_version = self._require_spec_version(version) + + canonical_version = canonicalize_version( + spec_version, strip_trailing_zero=(operator != "~=") + ) + + return operator, canonical_version + + def __hash__(self) -> int: + return hash(self._canonical_spec) + + def __eq__(self, other: object) -> bool: + """Whether or not the two Specifier-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> Specifier("==1.2.3") == Specifier("== 1.2.3.0") + True + >>> (Specifier("==1.2.3", prereleases=False) == + ... Specifier("==1.2.3", prereleases=True)) + True + >>> Specifier("==1.2.3") == "==1.2.3" + True + >>> Specifier("==1.2.3") == Specifier("==1.2.4") + False + >>> Specifier("==1.2.3") == Specifier("~=1.2.3") + False + """ + if isinstance(other, str): + try: + other = self.__class__(str(other)) + except InvalidSpecifier: + return NotImplemented + elif not isinstance(other, self.__class__): + return NotImplemented + + return self._canonical_spec == other._canonical_spec + + def _get_operator(self, op: str) -> CallableOperator: + operator_callable: CallableOperator = getattr( + self, f"_compare_{self._operators[op]}" + ) + return operator_callable + + def _compare_compatible(self, prospective: Version, spec: str) -> bool: + # Compatible releases have an equivalent combination of >= and ==. That + # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to + # implement this in terms of the other specifiers instead of + # implementing it ourselves. The only thing we need to do is construct + # the other specifiers. + + # We want everything but the last item in the version, but we want to + # ignore suffix segments. + prefix = _version_join( + list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1] + ) + + # Add the prefix notation to the end of our string + prefix += ".*" + + return (self._compare_greater_than_equal(prospective, spec)) and ( + self._compare_equal(prospective, prefix) + ) + + def _get_wildcard_split(self, spec: str) -> tuple[list[str], int]: + """Cached split of a wildcard spec into components and numeric length. + + >>> Specifier("==1.*")._get_wildcard_split("1.*") + (['0', '1'], 2) + >>> Specifier("==3.10.*")._get_wildcard_split("3.10.*") + (['0', '3', '10'], 3) + """ + wildcard_split = self._wildcard_split + if wildcard_split is None: + normalized = canonicalize_version(spec[:-2], strip_trailing_zero=False) + split_spec = _version_split(normalized) + wildcard_split = (split_spec, _numeric_prefix_len(split_spec)) + self._wildcard_split = wildcard_split + return wildcard_split + + def _compare_equal(self, prospective: Version, spec: str) -> bool: + # We need special logic to handle prefix matching + if spec.endswith(".*"): + split_spec, spec_numeric_len = self._get_wildcard_split(spec) + + # In the case of prefix matching we want to ignore local segment. + normalized_prospective = canonicalize_version( + _public_version(prospective), strip_trailing_zero=False + ) + # Split the prospective version out by bangs and dots, and pretend + # that there is an implicit dot in between a release segment and + # a pre-release segment. + split_prospective = _version_split(normalized_prospective) + + # 0-pad the prospective version before shortening it to get the correct + # shortened version. + padded_prospective = _left_pad(split_prospective, spec_numeric_len) + + # Shorten the prospective version to be the same length as the spec + # so that we can determine if the specifier is a prefix of the + # prospective version or not. + shortened_prospective = padded_prospective[: len(split_spec)] + + return shortened_prospective == split_spec + else: + # Convert our spec string into a Version + spec_version = self._require_spec_version(spec) + + # If the specifier does not have a local segment, then we want to + # act as if the prospective version also does not have a local + # segment. + if not spec_version.local: + prospective = _public_version(prospective) + + return prospective == spec_version + + def _compare_not_equal(self, prospective: Version, spec: str) -> bool: + return not self._compare_equal(prospective, spec) + + def _compare_less_than_equal(self, prospective: Version, spec: str) -> bool: + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return _public_version(prospective) <= self._require_spec_version(spec) + + def _compare_greater_than_equal(self, prospective: Version, spec: str) -> bool: + # NB: Local version identifiers are NOT permitted in the version + # specifier, so local version labels can be universally removed from + # the prospective version. + return _public_version(prospective) >= self._require_spec_version(spec) + + def _compare_less_than(self, prospective: Version, spec_str: str) -> bool: + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = self._require_spec_version(spec_str) + + # Check to see if the prospective version is less than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective < spec: + return False + + # The spec says: "= _earliest_prerelease(spec) + ): + return False + + # If we've gotten to here, it means that prospective version is both + # less than the spec version *and* it's not a pre-release of the same + # version in the spec. + return True + + def _compare_greater_than(self, prospective: Version, spec_str: str) -> bool: + # Convert our spec to a Version instance, since we'll want to work with + # it as a version. + spec = self._require_spec_version(spec_str) + + # Check to see if the prospective version is greater than the spec + # version. If it's not we can short circuit and just return False now + # instead of doing extra unneeded work. + if not prospective > spec: + return False + + # The spec says: ">V MUST NOT allow a post-release of the specified + # version unless the specified version is itself a post-release." + if ( + not spec.is_postrelease + and prospective.is_postrelease + and _post_base(prospective) == spec + ): + return False + + # Per the spec: ">V MUST NOT match a local version of the specified + # version". A "local version of V" is any version whose public part + # equals V. So >1.0a1 must not match 1.0a1+local, but must still + # match 1.0a2+local. + if prospective.local is not None and _public_version(prospective) == spec: + return False + + # If we've gotten to here, it means that prospective version is both + # greater than the spec version *and* it's not a pre-release of the + # same version in the spec. + return True + + def _compare_arbitrary(self, prospective: Version | str, spec: str) -> bool: + return str(prospective).lower() == str(spec).lower() + + def __contains__(self, item: str | Version) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in Specifier(">=1.2.3") + True + >>> Version("1.2.3") in Specifier(">=1.2.3") + True + >>> "1.0.0" in Specifier(">=1.2.3") + False + >>> "1.3.0a1" in Specifier(">=1.2.3") + True + >>> "1.3.0a1" in Specifier(">=1.2.3", prereleases=True) + True + """ + return self.contains(item) + + def contains(self, item: UnparsedVersion, prereleases: bool | None = None) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this Specifier. If set to + ``None`` (the default), it will follow the recommendation from + :pep:`440` and match prereleases, as there are no other versions. + + >>> Specifier(">=1.2.3").contains("1.2.3") + True + >>> Specifier(">=1.2.3").contains(Version("1.2.3")) + True + >>> Specifier(">=1.2.3").contains("1.0.0") + False + >>> Specifier(">=1.2.3").contains("1.3.0a1") + True + >>> Specifier(">=1.2.3", prereleases=False).contains("1.3.0a1") + False + >>> Specifier(">=1.2.3").contains("1.3.0a1") + True + """ + + return bool(list(self.filter([item], prereleases=prereleases))) + + @typing.overload + def filter( + self, + iterable: Iterable[UnparsedVersionVar], + prereleases: bool | None = None, + key: None = ..., + ) -> Iterator[UnparsedVersionVar]: ... + + @typing.overload + def filter( + self, + iterable: Iterable[T], + prereleases: bool | None = None, + key: Callable[[T], UnparsedVersion] = ..., + ) -> Iterator[T]: ... + + def filter( + self, + iterable: Iterable[Any], + prereleases: bool | None = None, + key: Callable[[Any], UnparsedVersion] | None = None, + ) -> Iterator[Any]: + """Filter items in the given iterable, that match the specifier. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will follow the recommendation from :pep:`440` + and match prereleases if there are no other versions. + :param key: + A callable that takes a single argument (an item from the iterable) and + returns a version string or :class:`Version` instance to be used for + filtering. + + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.2.3", "1.3", Version("1.4")])) + ['1.2.3', '1.3', ] + >>> list(Specifier(">=1.2.3").filter(["1.2", "1.5a1"])) + ['1.5a1'] + >>> list(Specifier(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(Specifier(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + >>> list(Specifier(">=1.2.3").filter( + ... [{"ver": "1.2"}, {"ver": "1.3"}], + ... key=lambda x: x["ver"])) + [{'ver': '1.3'}] + """ + prereleases_versions = [] + found_non_prereleases = False + + # Determine if to include prereleases by default + include_prereleases = ( + prereleases if prereleases is not None else self.prereleases + ) + + # Get the matching operator + operator_callable = self._get_operator(self.operator) + + # Filter versions + for version in iterable: + parsed_version = _coerce_version(version if key is None else key(version)) + match = False + if parsed_version is None: + # === operator can match arbitrary (non-version) strings + if self.operator == "===" and self._compare_arbitrary( + version, self.version + ): + yield version + elif self.operator == "===": + match = self._compare_arbitrary( + version if key is None else key(version), self.version + ) + else: + match = operator_callable(parsed_version, self.version) + + if match and parsed_version is not None: + # If it's not a prerelease or prereleases are allowed, yield it directly + if not parsed_version.is_prerelease or include_prereleases: + found_non_prereleases = True + yield version + # Otherwise collect prereleases for potential later use + elif prereleases is None and self._prereleases is not False: + prereleases_versions.append(version) + + # If no non-prereleases were found and prereleases weren't + # explicitly forbidden, yield the collected prereleases + if ( + not found_non_prereleases + and prereleases is None + and self._prereleases is not False + ): + yield from prereleases_versions + + +_prefix_regex = re.compile(r"([0-9]+)((?:a|b|c|rc)[0-9]+)") + + +def _pep440_filter_prereleases( + iterable: Iterable[Any], key: Callable[[Any], UnparsedVersion] | None +) -> Iterator[Any]: + """Filter per PEP 440: exclude prereleases unless no finals exist.""" + # Two lists used: + # * all_nonfinal to preserve order if no finals exist + # * arbitrary_strings for streaming when first final found + all_nonfinal: list[Any] = [] + arbitrary_strings: list[Any] = [] + + found_final = False + for item in iterable: + parsed = _coerce_version(item if key is None else key(item)) + + if parsed is None: + # Arbitrary strings are always included as it is not + # possible to determine if they are prereleases, + # and they have already passed all specifiers. + if found_final: + yield item + else: + arbitrary_strings.append(item) + all_nonfinal.append(item) + continue + + if not parsed.is_prerelease: + # Final release found - flush arbitrary strings, then yield + if not found_final: + yield from arbitrary_strings + found_final = True + yield item + continue + + # Prerelease - buffer if no finals yet, otherwise skip + if not found_final: + all_nonfinal.append(item) + + # No finals found - yield all buffered items + if not found_final: + yield from all_nonfinal + + +def _version_split(version: str) -> list[str]: + """Split version into components. + + The split components are intended for version comparison. The logic does + not attempt to retain the original version string, so joining the + components back with :func:`_version_join` may not produce the original + version string. + """ + result: list[str] = [] + + epoch, _, rest = version.rpartition("!") + result.append(epoch or "0") + + for item in rest.split("."): + match = _prefix_regex.fullmatch(item) + if match: + result.extend(match.groups()) + else: + result.append(item) + return result + + +def _version_join(components: list[str]) -> str: + """Join split version components into a version string. + + This function assumes the input came from :func:`_version_split`, where the + first component must be the epoch (either empty or numeric), and all other + components numeric. + """ + epoch, *rest = components + return f"{epoch}!{'.'.join(rest)}" + + +def _is_not_suffix(segment: str) -> bool: + return not any( + segment.startswith(prefix) for prefix in ("dev", "a", "b", "rc", "post") + ) + + +def _numeric_prefix_len(split: list[str]) -> int: + """Count leading numeric components in a :func:`_version_split` result. + + >>> _numeric_prefix_len(["0", "1", "2", "a1"]) + 3 + """ + count = 0 + for segment in split: + if not segment.isdigit(): + break + count += 1 + return count + + +def _left_pad(split: list[str], target_numeric_len: int) -> list[str]: + """Pad a :func:`_version_split` result with ``"0"`` segments to reach + ``target_numeric_len`` numeric components. Suffix segments are preserved. + + >>> _left_pad(["0", "1", "a1"], 4) + ['0', '1', '0', '0', 'a1'] + """ + numeric_len = _numeric_prefix_len(split) + pad_needed = target_numeric_len - numeric_len + if pad_needed <= 0: + return split + return [*split[:numeric_len], *(["0"] * pad_needed), *split[numeric_len:]] + + +def _operator_cost(op_entry: tuple[CallableOperator, str, str]) -> int: + """Sort key for Cost Based Ordering of specifier operators in _filter_versions. + + Operators run sequentially on a shrinking candidate set, so operators that + reject the most versions should run first to minimize work for later ones. + + Tier 0: Exact equality (==, ===), likely to narrow candidates to one version + Tier 1: Range checks (>=, <=, >, <), cheap and usually reject a large portion + Tier 2: Wildcard equality (==.*) and compatible release (~=), more expensive + Tier 3: Exact !=, cheap but rarely rejects + Tier 4: Wildcard !=.*, expensive and rarely rejects + """ + _, ver, op = op_entry + if op == "==": + return 0 if not ver.endswith(".*") else 2 + if op in (">=", "<=", ">", "<"): + return 1 + if op == "~=": + return 2 + if op == "!=": + return 3 if not ver.endswith(".*") else 4 + if op == "===": + return 0 + + raise ValueError(f"Unknown operator: {op!r}") # pragma: no cover + + +class SpecifierSet(BaseSpecifier): + """This class abstracts handling of a set of version specifiers. + + It can be passed a single specifier (``>=3.0``), a comma-separated list of + specifiers (``>=3.0,!=3.1``), or no specifier at all. + + Instances are safe to serialize with :mod:`pickle`. They use a stable + format so the same pickle can be loaded in future packaging + releases. + + .. versionchanged:: 26.2 + + Added a stable pickle format. Pickles created with + packaging 26.2+ can be unpickled with future releases. + Backward compatibility with pickles from + packaging < 26.2 is supported but may be removed in a future + release. + """ + + __slots__ = ( + "_canonicalized", + "_has_arbitrary", + "_is_unsatisfiable", + "_prereleases", + "_resolved_ops", + "_specs", + ) + + def __init__( + self, + specifiers: str | Iterable[Specifier] = "", + prereleases: bool | None = None, + ) -> None: + """Initialize a SpecifierSet instance. + + :param specifiers: + The string representation of a specifier or a comma-separated list of + specifiers which will be parsed and normalized before use. + May also be an iterable of ``Specifier`` instances, which will be used + as is. + :param prereleases: + This tells the SpecifierSet if it should accept prerelease versions if + applicable or not. The default of ``None`` will autodetect it from the + given specifiers. + + :raises InvalidSpecifier: + If the given ``specifiers`` are not parseable than this exception will be + raised. + """ + + if isinstance(specifiers, str): + # Split on `,` to break each individual specifier into its own item, and + # strip each item to remove leading/trailing whitespace. + split_specifiers = [s.strip() for s in specifiers.split(",") if s.strip()] + + self._specs: tuple[Specifier, ...] = tuple(map(Specifier, split_specifiers)) + # Fast substring check; avoids iterating parsed specs. + self._has_arbitrary = "===" in specifiers + else: + self._specs = tuple(specifiers) + # Substring check works for both Specifier objects and plain + # strings (setuptools passes lists of strings). + self._has_arbitrary = any("===" in str(s) for s in self._specs) + + self._canonicalized = len(self._specs) <= 1 + self._resolved_ops: list[tuple[CallableOperator, str, str]] | None = None + + # Store our prereleases value so we can use it later to determine if + # we accept prereleases or not. + self._prereleases = prereleases + + self._is_unsatisfiable: bool | None = None + + def _canonical_specs(self) -> tuple[Specifier, ...]: + """Deduplicate, sort, and cache specs for order-sensitive operations.""" + if not self._canonicalized: + self._specs = tuple(dict.fromkeys(sorted(self._specs, key=str))) + self._canonicalized = True + self._resolved_ops = None + self._is_unsatisfiable = None + return self._specs + + @property + def prereleases(self) -> bool | None: + # If we have been given an explicit prerelease modifier, then we'll + # pass that through here. + if self._prereleases is not None: + return self._prereleases + + # If we don't have any specifiers, and we don't have a forced value, + # then we'll just return None since we don't know if this should have + # pre-releases or not. + if not self._specs: + return None + + # Otherwise we'll see if any of the given specifiers accept + # prereleases, if any of them do we'll return True, otherwise False. + if any(s.prereleases for s in self._specs): + return True + + return None + + @prereleases.setter + def prereleases(self, value: bool | None) -> None: + self._prereleases = value + self._is_unsatisfiable = None + + def __getstate__(self) -> tuple[tuple[Specifier, ...], bool | None]: + # Return state as a 2-item tuple for compactness: + # (specs, prereleases) + # Cache members are excluded and will be recomputed on demand. + return (self._specs, self._prereleases) + + def __setstate__(self, state: object) -> None: + # Always discard cached values - they will be recomputed on demand. + self._resolved_ops = None + self._is_unsatisfiable = None + + if isinstance(state, tuple): + if len(state) == 2: + # New format (26.2+): (specs, prereleases) + specs, prereleases = state + if ( + isinstance(specs, tuple) + and all(isinstance(s, Specifier) for s in specs) + and _validate_pre(prereleases) + ): + self._specs = specs + self._prereleases = prereleases + self._canonicalized = len(specs) <= 1 + self._has_arbitrary = any("===" in str(s) for s in specs) + return + if len(state) == 2 and isinstance(state[1], dict): + # Format (packaging 26.0-26.1): (None, {slot: value}). + _, slot_dict = state + specs = slot_dict.get("_specs", ()) + prereleases = slot_dict.get("_prereleases") + # Convert frozenset to tuple (26.0 stored as frozenset) + if isinstance(specs, frozenset): + specs = tuple(sorted(specs, key=str)) + if ( + isinstance(specs, tuple) + and all(isinstance(s, Specifier) for s in specs) + and _validate_pre(prereleases) + ): + self._specs = specs + self._prereleases = prereleases + self._canonicalized = len(self._specs) <= 1 + self._has_arbitrary = any("===" in str(s) for s in self._specs) + return + if isinstance(state, dict): + # Old format (packaging <= 25.x, no __slots__): state is a plain dict. + specs = state.get("_specs", ()) + prereleases = state.get("_prereleases") + # Convert frozenset to tuple (26.0 stored as frozenset) + if isinstance(specs, frozenset): + specs = tuple(sorted(specs, key=str)) + if ( + isinstance(specs, tuple) + and all(isinstance(s, Specifier) for s in specs) + and _validate_pre(prereleases) + ): + self._specs = specs + self._prereleases = prereleases + self._canonicalized = len(self._specs) <= 1 + self._has_arbitrary = any("===" in str(s) for s in self._specs) + return + + raise TypeError(f"Cannot restore SpecifierSet from {state!r}") + + def __repr__(self) -> str: + """A representation of the specifier set that shows all internal state. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> SpecifierSet('>=1.0.0,!=2.0.0') + =1.0.0')> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=False) + =1.0.0', prereleases=False)> + >>> SpecifierSet('>=1.0.0,!=2.0.0', prereleases=True) + =1.0.0', prereleases=True)> + """ + pre = ( + f", prereleases={self.prereleases!r}" + if self._prereleases is not None + else "" + ) + + return f"<{self.__class__.__name__}({str(self)!r}{pre})>" + + def __str__(self) -> str: + """A string representation of the specifier set that can be round-tripped. + + Note that the ordering of the individual specifiers within the set may not + match the input string. + + >>> str(SpecifierSet(">=1.0.0,!=1.0.1")) + '!=1.0.1,>=1.0.0' + >>> str(SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False)) + '!=1.0.1,>=1.0.0' + """ + return ",".join(str(s) for s in self._canonical_specs()) + + def __hash__(self) -> int: + return hash(self._canonical_specs()) + + def __and__(self, other: SpecifierSet | str) -> SpecifierSet: + """Return a SpecifierSet which is a combination of the two sets. + + :param other: The other object to combine with. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") & '<=2.0.0,!=2.0.1' + =1.0.0')> + >>> SpecifierSet(">=1.0.0,!=1.0.1") & SpecifierSet('<=2.0.0,!=2.0.1') + =1.0.0')> + """ + if isinstance(other, str): + other = SpecifierSet(other) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + specifier = SpecifierSet() + specifier._specs = self._specs + other._specs + specifier._canonicalized = len(specifier._specs) <= 1 + specifier._has_arbitrary = self._has_arbitrary or other._has_arbitrary + specifier._resolved_ops = None + + # Combine prerelease settings: use common or non-None value + if self._prereleases is None or self._prereleases == other._prereleases: + specifier._prereleases = other._prereleases + elif other._prereleases is None: + specifier._prereleases = self._prereleases + else: + raise ValueError( + "Cannot combine SpecifierSets with True and False prerelease overrides." + ) + + return specifier + + def __eq__(self, other: object) -> bool: + """Whether or not the two SpecifierSet-like objects are equal. + + :param other: The other object to check against. + + The value of :attr:`prereleases` is ignored. + + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> (SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False) == + ... SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True)) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == ">=1.0.0,!=1.0.1" + True + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1") == SpecifierSet(">=1.0.0,!=1.0.2") + False + """ + if isinstance(other, (str, Specifier)): + other = SpecifierSet(str(other)) + elif not isinstance(other, SpecifierSet): + return NotImplemented + + return self._canonical_specs() == other._canonical_specs() + + def __len__(self) -> int: + """Returns the number of specifiers in this specifier set.""" + return len(self._specs) + + def __iter__(self) -> Iterator[Specifier]: + """ + Returns an iterator over all the underlying :class:`Specifier` instances + in this specifier set. + + >>> sorted(SpecifierSet(">=1.0.0,!=1.0.1"), key=str) + [, =1.0.0')>] + """ + return iter(self._specs) + + def _get_ranges(self) -> Sequence[_VersionRange]: + """Intersect all specifiers into a single list of version ranges. + + Returns an empty list when unsatisfiable. ``===`` specs are + modeled as full range; string matching is checked separately + by :meth:`_check_arbitrary_unsatisfiable`. + """ + specs = self._specs + + result: Sequence[_VersionRange] | None = None + for s in specs: + if result is None: + result = s._to_ranges() + else: + result = _intersect_ranges(result, s._to_ranges()) + if not result: + break + + if result is None: # pragma: no cover + raise RuntimeError("_get_ranges called with no specs") + return result + + def is_unsatisfiable(self) -> bool: + """Check whether this specifier set can never be satisfied. + + Returns True if no version can satisfy all specifiers simultaneously. + + >>> SpecifierSet(">=2.0,<1.0").is_unsatisfiable() + True + >>> SpecifierSet(">=1.0,<2.0").is_unsatisfiable() + False + >>> SpecifierSet("").is_unsatisfiable() + False + >>> SpecifierSet("==1.0,!=1.0").is_unsatisfiable() + True + """ + cached = self._is_unsatisfiable + if cached is not None: + return cached + + if not self._specs: + self._is_unsatisfiable = False + return False + + result = not self._get_ranges() + + if not result: + result = self._check_arbitrary_unsatisfiable() + + if not result and self.prereleases is False: + result = self._check_prerelease_only_ranges() + + self._is_unsatisfiable = result + return result + + def _check_prerelease_only_ranges(self) -> bool: + """With prereleases=False, check if every range contains only + pre-release versions (which would be excluded from matching).""" + for lower, upper in self._get_ranges(): + nearest = _nearest_non_prerelease(lower.version) + if nearest is None: + return False + if upper.version is None or nearest < upper.version: + return False + if nearest == upper.version and upper.inclusive: + return False + return True + + def _check_arbitrary_unsatisfiable(self) -> bool: + """Check === (arbitrary equality) specs for unsatisfiability. + + === uses case-insensitive string comparison, so the only candidate + that can match ``===V`` is the literal string V. This method + checks whether that candidate is excluded by other specifiers. + """ + arbitrary = [s for s in self._specs if s.operator == "==="] + if not arbitrary: + return False + + # Multiple === must agree on the same string (case-insensitive). + first = arbitrary[0].version.lower() + if any(s.version.lower() != first for s in arbitrary[1:]): + return True + + # The sole candidate is the === version string. Check whether + # it can satisfy every standard spec. + candidate = _coerce_version(arbitrary[0].version) + + # With prereleases=False, a prerelease candidate is excluded + # by contains() before the === string check even runs. + if ( + self.prereleases is False + and candidate is not None + and candidate.is_prerelease + ): + return True + + standard = [s for s in self._specs if s.operator != "==="] + if not standard: + return False + + if candidate is None: + # Unparsable string cannot satisfy any standard spec. + return True + + return not all(s.contains(candidate) for s in standard) + + def __contains__(self, item: UnparsedVersion) -> bool: + """Return whether or not the item is contained in this specifier. + + :param item: The item to check for. + + This is used for the ``in`` operator and behaves the same as + :meth:`contains` with no ``prereleases`` argument passed. + + >>> "1.2.3" in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> Version("1.2.3") in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> "1.0.1" in SpecifierSet(">=1.0.0,!=1.0.1") + False + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1") + True + >>> "1.3.0a1" in SpecifierSet(">=1.0.0,!=1.0.1", prereleases=True) + True + """ + return self.contains(item) + + def contains( + self, + item: UnparsedVersion, + prereleases: bool | None = None, + installed: bool | None = None, + ) -> bool: + """Return whether or not the item is contained in this SpecifierSet. + + :param item: + The item to check for, which can be a version string or a + :class:`Version` instance. + :param prereleases: + Whether or not to match prereleases with this SpecifierSet. If set to + ``None`` (the default), it will follow the recommendation from :pep:`440` + and match prereleases, as there are no other versions. + :param installed: + Whether or not the item is installed. If set to ``True``, it will + accept prerelease versions even if the specifier does not allow them. + + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.2.3") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains(Version("1.2.3")) + True + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.0.1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1") + True + >>> SpecifierSet(">=1.0.0,!=1.0.1", prereleases=False).contains("1.3.0a1") + False + >>> SpecifierSet(">=1.0.0,!=1.0.1").contains("1.3.0a1", prereleases=True) + True + """ + version = _coerce_version(item) + + if version is not None and installed and version.is_prerelease: + prereleases = True + + # When item is a string and === is involved, keep it as-is + # so the comparison isn't done against the normalized form. + if version is None or (self._has_arbitrary and not isinstance(item, Version)): + check_item = item + else: + check_item = version + return bool(list(self.filter([check_item], prereleases=prereleases))) + + @typing.overload + def filter( + self, + iterable: Iterable[UnparsedVersionVar], + prereleases: bool | None = None, + key: None = ..., + ) -> Iterator[UnparsedVersionVar]: ... + + @typing.overload + def filter( + self, + iterable: Iterable[T], + prereleases: bool | None = None, + key: Callable[[T], UnparsedVersion] = ..., + ) -> Iterator[T]: ... + + def filter( + self, + iterable: Iterable[Any], + prereleases: bool | None = None, + key: Callable[[Any], UnparsedVersion] | None = None, + ) -> Iterator[Any]: + """Filter items in the given iterable, that match the specifiers in this set. + + :param iterable: + An iterable that can contain version strings and :class:`Version` instances. + The items in the iterable will be filtered according to the specifier. + :param prereleases: + Whether or not to allow prereleases in the returned iterator. If set to + ``None`` (the default), it will follow the recommendation from :pep:`440` + and match prereleases if there are no other versions. + :param key: + A callable that takes a single argument (an item from the iterable) and + returns a version string or :class:`Version` instance to be used for + filtering. + + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.3", Version("1.4")])) + ['1.3', ] + >>> list(SpecifierSet(">=1.2.3").filter(["1.2", "1.5a1"])) + ['1.5a1'] + >>> list(SpecifierSet(">=1.2.3").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + >>> list(SpecifierSet(">=1.2.3", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + >>> list(SpecifierSet(">=1.2.3").filter( + ... [{"ver": "1.2"}, {"ver": "1.3"}], + ... key=lambda x: x["ver"])) + [{'ver': '1.3'}] + + An "empty" SpecifierSet will filter items based on the presence of prerelease + versions in the set. + + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"])) + ['1.3'] + >>> list(SpecifierSet("").filter(["1.5a1"])) + ['1.5a1'] + >>> list(SpecifierSet("", prereleases=True).filter(["1.3", "1.5a1"])) + ['1.3', '1.5a1'] + >>> list(SpecifierSet("").filter(["1.3", "1.5a1"], prereleases=True)) + ['1.3', '1.5a1'] + """ + # Determine if we're forcing a prerelease or not, if we're not forcing + # one for this particular filter call, then we'll use whatever the + # SpecifierSet thinks for whether or not we should support prereleases. + if prereleases is None and self.prereleases is not None: + prereleases = self.prereleases + + # Filter versions that match all specifiers using Cost Based Ordering. + if self._specs: + # When prereleases is None, we need to let all versions through + # the individual filters, then decide about prereleases at the end + # based on whether any non-prereleases matched ALL specs. + + # Fast path: single specifier, delegate directly. + if len(self._specs) == 1: + filtered = self._specs[0].filter( + iterable, + prereleases=True if prereleases is None else prereleases, + key=key, + ) + else: + filtered = self._filter_versions( + iterable, + key, + prereleases=True if prereleases is None else prereleases, + ) + + if prereleases is not None: + return filtered + + return _pep440_filter_prereleases(filtered, key) + + # Handle Empty SpecifierSet. + if prereleases is True: + return iter(iterable) + + if prereleases is False: + return ( + item + for item in iterable + if ( + (version := _coerce_version(item if key is None else key(item))) + is None + or not version.is_prerelease + ) + ) + + # PEP 440: exclude prereleases unless no final releases matched + return _pep440_filter_prereleases(iterable, key) + + def _filter_versions( + self, + iterable: Iterable[Any], + key: Callable[[Any], UnparsedVersion] | None, + prereleases: bool | None = None, + ) -> Iterator[Any]: + """Filter versions against all specifiers in a single pass. + + Uses Cost Based Ordering: specifiers are sorted by _operator_cost so + that cheap range operators reject versions early, avoiding expensive + wildcard or compatible operators on versions that would have been + rejected anyway. + """ + # Pre-resolve operators and sort (cached after first call). + if self._resolved_ops is None: + self._resolved_ops = sorted( + ( + (spec._get_operator(spec.operator), spec.version, spec.operator) + for spec in self._specs + ), + key=_operator_cost, + ) + ops = self._resolved_ops + exclude_prereleases = prereleases is False + + for item in iterable: + parsed = _coerce_version(item if key is None else key(item)) + + if parsed is None: + # Only === can match non-parseable versions. + if all( + op == "===" and str(item).lower() == ver.lower() + for _, ver, op in ops + ): + yield item + elif exclude_prereleases and parsed.is_prerelease: + pass + elif all( + str(item if key is None else key(item)).lower() == ver.lower() + if op == "===" + else op_fn(parsed, ver) + for op_fn, ver, op in ops + ): + # Short-circuits on the first failing operator. + yield item diff --git a/micromamba_root/Lib/site-packages/packaging/tags.py b/micromamba_root/Lib/site-packages/packaging/tags.py new file mode 100644 index 0000000000000000000000000000000000000000..9980ab3c63c0c4caf0045af55751a19a4d68ed92 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/tags.py @@ -0,0 +1,932 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import logging +import operator +import platform +import re +import struct +import subprocess +import sys +import sysconfig +from importlib.machinery import EXTENSION_SUFFIXES +from typing import ( + TYPE_CHECKING, + Iterable, + Iterator, + Sequence, + Tuple, + TypeVar, + cast, +) + +from . import _manylinux, _musllinux + +if TYPE_CHECKING: + from collections.abc import Callable, Iterable + from typing import AbstractSet + + +__all__ = [ + "INTERPRETER_SHORT_NAMES", + "AppleVersion", + "PythonVersion", + "Tag", + "UnsortedTagsError", + "android_platforms", + "compatible_tags", + "cpython_tags", + "create_compatible_tags_selector", + "generic_tags", + "interpreter_name", + "interpreter_version", + "ios_platforms", + "mac_platforms", + "parse_tag", + "platform_tags", + "sys_tags", +] + + +def __dir__() -> list[str]: + return __all__ + + +logger = logging.getLogger(__name__) + +PythonVersion = Sequence[int] +AppleVersion = Tuple[int, int] +_T = TypeVar("_T") + +INTERPRETER_SHORT_NAMES: dict[str, str] = { + "python": "py", # Generic. + "cpython": "cp", + "pypy": "pp", + "ironpython": "ip", + "jython": "jy", +} + + +# This function can be unit tested without reloading the module +# (Unlike _32_BIT_INTERPRETER) +def _compute_32_bit_interpreter() -> bool: + return struct.calcsize("P") == 4 + + +_32_BIT_INTERPRETER = _compute_32_bit_interpreter() + + +class UnsortedTagsError(ValueError): + """ + Raised when a tag component is not in sorted order per PEP 425. + """ + + +class Tag: + """ + A representation of the tag triple for a wheel. + + Instances are considered immutable and thus are hashable. Equality checking + is also supported. + + Instances are safe to serialize with :mod:`pickle`. They use a stable + format so the same pickle can be loaded in future packaging releases. + + .. versionchanged:: 26.2 + + Added a stable pickle format. Pickles created with packaging 26.2+ can + be unpickled with future releases. Backward compatibility with pickles + from packaging < 26.2 is supported but may be removed in a future + release. + """ + + __slots__ = ["_abi", "_hash", "_interpreter", "_platform"] + + def __init__(self, interpreter: str, abi: str, platform: str) -> None: + """ + :param str interpreter: The interpreter name, e.g. ``"py"`` + (see :attr:`INTERPRETER_SHORT_NAMES` for mapping + well-known interpreter names to their short names). + :param str abi: The ABI that a wheel supports, e.g. ``"cp37m"``. + :param str platform: The OS/platform the wheel supports, + e.g. ``"win_amd64"``. + """ + self._interpreter = interpreter.lower() + self._abi = abi.lower() + self._platform = platform.lower() + # The __hash__ of every single element in a Set[Tag] will be evaluated each time + # that a set calls its `.disjoint()` method, which may be called hundreds of + # times when scanning a page of links for packages with tags matching that + # Set[Tag]. Pre-computing the value here produces significant speedups for + # downstream consumers. + self._hash = hash((self._interpreter, self._abi, self._platform)) + + @property + def interpreter(self) -> str: + """ + The interpreter name, e.g. ``"py"`` (see + :attr:`INTERPRETER_SHORT_NAMES` for mapping well-known interpreter + names to their short names). + """ + return self._interpreter + + @property + def abi(self) -> str: + """ + The supported ABI. + """ + return self._abi + + @property + def platform(self) -> str: + """ + The OS/platform. + """ + return self._platform + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Tag): + return NotImplemented + + return ( + (self._hash == other._hash) # Short-circuit ASAP for perf reasons. + and (self._platform == other._platform) + and (self._abi == other._abi) + and (self._interpreter == other._interpreter) + ) + + def __hash__(self) -> int: + return self._hash + + def __str__(self) -> str: + return f"{self._interpreter}-{self._abi}-{self._platform}" + + def __repr__(self) -> str: + return f"<{self} @ {id(self)}>" + + def __getstate__(self) -> tuple[str, str, str]: + # Return state as a 3-item tuple: (interpreter, abi, platform). + # Cache member _hash is excluded and will be recomputed. + return (self._interpreter, self._abi, self._platform) + + def __setstate__(self, state: object) -> None: + if isinstance(state, tuple): + if len(state) == 3 and all(isinstance(s, str) for s in state): + # New format (26.2+): (interpreter, abi, platform) + self._interpreter, self._abi, self._platform = state + self._hash = hash((self._interpreter, self._abi, self._platform)) + return + if len(state) == 2 and isinstance(state[1], dict): + # Old format (packaging <= 26.1, __slots__): (None, {slot: value}). + _, slots = state + try: + interpreter = slots["_interpreter"] + abi = slots["_abi"] + platform = slots["_platform"] + except KeyError: + raise TypeError(f"Cannot restore Tag from {state!r}") from None + if not all( + isinstance(value, str) for value in (interpreter, abi, platform) + ): + raise TypeError(f"Cannot restore Tag from {state!r}") + self._interpreter = interpreter.lower() + self._abi = abi.lower() + self._platform = platform.lower() + self._hash = hash((self._interpreter, self._abi, self._platform)) + return + raise TypeError(f"Cannot restore Tag from {state!r}") + + +def parse_tag(tag: str, *, validate_order: bool = False) -> frozenset[Tag]: + """ + Parses the provided tag (e.g. `py3-none-any`) into a frozenset of + :class:`Tag` instances. + + Returning a set is required due to the possibility that the tag is a + `compressed tag set`_, e.g. ``"py2.py3-none-any"`` which supports both + Python 2 and Python 3. + + If **validate_order** is true, compressed tag set components are checked + to be in sorted order as required by PEP 425. + + :param str tag: The tag to parse, e.g. ``"py3-none-any"``. + :param bool validate_order: Check whether compressed tag set components + are in sorted order. + :raises UnsortedTagsError: If **validate_order** is true and any compressed tag + set component is not in sorted order. + + .. versionadded:: 26.1 + The *validate_order* parameter. + """ + tags = set() + interpreters, abis, platforms = tag.split("-") + if validate_order: + for component in (interpreters, abis, platforms): + parts = component.split(".") + if parts != sorted(parts): + raise UnsortedTagsError( + f"Tag component {component!r} is not in sorted order per PEP 425" + ) + for interpreter in interpreters.split("."): + for abi in abis.split("."): + for platform_ in platforms.split("."): + tags.add(Tag(interpreter, abi, platform_)) + return frozenset(tags) + + +def _get_config_var(name: str, warn: bool = False) -> int | str | None: + value: int | str | None = sysconfig.get_config_var(name) + if value is None and warn: + logger.debug( + "Config variable '%s' is unset, Python ABI tag may be incorrect", name + ) + return value + + +def _normalize_string(string: str) -> str: + return string.replace(".", "_").replace("-", "_").replace(" ", "_") + + +def _is_threaded_cpython(abis: list[str]) -> bool: + """ + Determine if the ABI corresponds to a threaded (`--disable-gil`) build. + + The threaded builds are indicated by a "t" in the abiflags. + """ + if len(abis) == 0: + return False + # expect e.g., cp313 + m = re.match(r"cp\d+(.*)", abis[0]) + if not m: + return False + abiflags = m.group(1) + return "t" in abiflags + + +def _abi3_applies(python_version: PythonVersion, threading: bool) -> bool: + """ + Determine if the Python version supports abi3. + + PEP 384 was first implemented in Python 3.2. The free-threaded + builds do not support abi3. + """ + return len(python_version) > 1 and tuple(python_version) >= (3, 2) and not threading + + +def _abi3t_applies(python_version: PythonVersion, threading: bool) -> bool: + """ + Determine if the Python version supports abi3t. + + PEP 803 was first implemented in Python 3.15 but, per PEP 803, this + returns tags going back to Python 3.2 to mirror the abi3 + implementation and leave open the possibility of abi3t wheels + supporting older Python versions. + + """ + return len(python_version) > 1 and tuple(python_version) >= (3, 2) and threading + + +def _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]: + py_version = tuple(py_version) # To allow for version comparison. + abis = [] + version = _version_nodot(py_version[:2]) + threading = debug = pymalloc = ucs4 = "" + with_debug = _get_config_var("Py_DEBUG", warn) + has_refcount = hasattr(sys, "gettotalrefcount") + # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled + # extension modules is the best option. + # https://github.com/pypa/pip/issues/3383#issuecomment-173267692 + has_ext = "_d.pyd" in EXTENSION_SUFFIXES + if with_debug or (with_debug is None and (has_refcount or has_ext)): + debug = "d" + if py_version >= (3, 13) and _get_config_var("Py_GIL_DISABLED", warn): + threading = "t" + if py_version < (3, 8): + with_pymalloc = _get_config_var("WITH_PYMALLOC", warn) + if with_pymalloc or with_pymalloc is None: + pymalloc = "m" + if py_version < (3, 3): + unicode_size = _get_config_var("Py_UNICODE_SIZE", warn) + if unicode_size == 4 or ( + unicode_size is None and sys.maxunicode == 0x10FFFF + ): + ucs4 = "u" + elif debug: + # Debug builds can also load "normal" extension modules. + # We can also assume no UCS-4 or pymalloc requirement. + abis.append(f"cp{version}{threading}") + abis.insert(0, f"cp{version}{threading}{debug}{pymalloc}{ucs4}") + return abis + + +def cpython_tags( + python_version: PythonVersion | None = None, + abis: Iterable[str] | None = None, + platforms: Iterable[str] | None = None, + *, + warn: bool = False, +) -> Iterator[Tag]: + """ + Yields the tags for the CPython interpreter. + + The specific tags generated are: + + - ``cp--`` + - ``cp--`` + - ``cp-none-`` + - ``cp--`` where "older version" is all older + minor versions down to Python 3.2 (when ``abi3`` was introduced) + + If ``python_version`` only provides a major-only version then only + user-provided ABIs via ``abis`` and the ``none`` ABI will be used. + + The ``stable_abi`` will be either ``abi3`` or ``abi3t`` if `abi` is a + GIL-enabled ABI like `"cp315"` or a free-threaded ABI like `"cp315t"`, + respectively. + + :param Sequence python_version: A one- or two-item sequence representing the + targeted Python version. Defaults to + ``sys.version_info[:2]``. + :param Iterable abis: Iterable of compatible ABIs. Defaults to the ABIs + compatible with the current system. + :param Iterable platforms: Iterable of compatible platforms. Defaults to the + platforms compatible with the current system. + :param bool warn: Whether warnings should be logged. Defaults to ``False``. + """ + if not python_version: + python_version = sys.version_info[:2] + + interpreter = f"cp{_version_nodot(python_version[:2])}" + + if abis is None: + abis = _cpython_abis(python_version, warn) if len(python_version) > 1 else [] + abis = list(abis) + # 'abi3' and 'none' are explicitly handled later. + for explicit_abi in ("abi3", "none"): + try: + abis.remove(explicit_abi) + except ValueError: # noqa: PERF203 + pass + + platforms = list(platforms or platform_tags()) + for abi in abis: + for platform_ in platforms: + yield Tag(interpreter, abi, platform_) + + threading = _is_threaded_cpython(abis) + use_abi3 = _abi3_applies(python_version, threading) + use_abi3t = _abi3t_applies(python_version, threading) + + if use_abi3: + yield from (Tag(interpreter, "abi3", platform_) for platform_ in platforms) + if use_abi3t: + yield from (Tag(interpreter, "abi3t", platform_) for platform_ in platforms) + + yield from (Tag(interpreter, "none", platform_) for platform_ in platforms) + + if use_abi3 or use_abi3t: + for minor_version in range(python_version[1] - 1, 1, -1): + for platform_ in platforms: + version = _version_nodot((python_version[0], minor_version)) + interpreter = f"cp{version}" + if use_abi3: + yield Tag(interpreter, "abi3", platform_) + if use_abi3t: + # Support for abi3t was introduced in Python 3.15, but in + # principle abi3t wheels are possible for older limited API + # versions, so allow things like ("cp37", "abi3t", "platform") + yield Tag(interpreter, "abi3t", platform_) + + +def _generic_abi() -> list[str]: + """ + Return the ABI tag based on EXT_SUFFIX. + """ + # The following are examples of `EXT_SUFFIX`. + # We want to keep the parts which are related to the ABI and remove the + # parts which are related to the platform: + # - linux: '.cpython-310-x86_64-linux-gnu.so' => cp310 + # - mac: '.cpython-310-darwin.so' => cp310 + # - win: '.cp310-win_amd64.pyd' => cp310 + # - win: '.pyd' => cp37 (uses _cpython_abis()) + # - pypy: '.pypy38-pp73-x86_64-linux-gnu.so' => pypy38_pp73 + # - graalpy: '.graalpy-38-native-x86_64-darwin.dylib' + # => graalpy_38_native + + ext_suffix = _get_config_var("EXT_SUFFIX", warn=True) + if not isinstance(ext_suffix, str) or ext_suffix[0] != ".": + raise SystemError("invalid sysconfig.get_config_var('EXT_SUFFIX')") + parts = ext_suffix.split(".") + if len(parts) < 3: + # CPython3.7 and earlier uses ".pyd" on Windows. + return _cpython_abis(sys.version_info[:2]) + soabi = parts[1] + if soabi.startswith("cpython"): + # non-windows + abi = "cp" + soabi.split("-")[1] + elif soabi.startswith("cp"): + # windows + abi = soabi.split("-")[0] + elif soabi.startswith("pypy"): + abi = "-".join(soabi.split("-")[:2]) + elif soabi.startswith("graalpy"): + abi = "-".join(soabi.split("-")[:3]) + elif soabi: + # pyston, ironpython, others? + abi = soabi + else: + return [] + return [_normalize_string(abi)] + + +def generic_tags( + interpreter: str | None = None, + abis: Iterable[str] | None = None, + platforms: Iterable[str] | None = None, + *, + warn: bool = False, +) -> Iterator[Tag]: + """ + Yields the tags for an interpreter which requires no specialization. + + This function should be used if one of the other interpreter-specific + functions provided by this module is not appropriate (i.e. not calculating + tags for a CPython interpreter). + + The specific tags generated are: + + - ``--`` + + The ``"none"`` ABI will be added if it was not explicitly provided. + + :param str interpreter: The name of the interpreter. Defaults to being + calculated. + :param Iterable abis: Iterable of compatible ABIs. Defaults to the ABIs + compatible with the current system. + :param Iterable platforms: Iterable of compatible platforms. Defaults to the + platforms compatible with the current system. + :param bool warn: Whether warnings should be logged. Defaults to ``False``. + """ + if not interpreter: + interp_name = interpreter_name() + interp_version = interpreter_version(warn=warn) + interpreter = f"{interp_name}{interp_version}" + abis = _generic_abi() if abis is None else list(abis) + platforms = list(platforms or platform_tags()) + if "none" not in abis: + abis.append("none") + for abi in abis: + for platform_ in platforms: + yield Tag(interpreter, abi, platform_) + + +def _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]: + """ + Yields Python versions in descending order. + + After the latest version, the major-only version will be yielded, and then + all previous versions of that major version. + """ + if len(py_version) > 1: + yield f"py{_version_nodot(py_version[:2])}" + yield f"py{py_version[0]}" + if len(py_version) > 1: + for minor in range(py_version[1] - 1, -1, -1): + yield f"py{_version_nodot((py_version[0], minor))}" + + +def compatible_tags( + python_version: PythonVersion | None = None, + interpreter: str | None = None, + platforms: Iterable[str] | None = None, +) -> Iterator[Tag]: + """ + Yields the tags for an interpreter compatible with the Python version + specified by ``python_version``. + + The specific tags generated are: + + - ``py*-none-`` + - ``-none-any`` if ``interpreter`` is provided + - ``py*-none-any`` + + :param Sequence python_version: A one- or two-item sequence representing the + compatible version of Python. Defaults to + ``sys.version_info[:2]``. + :param str interpreter: The name of the interpreter (if known), e.g. + ``"cp38"``. Defaults to the current interpreter. + :param Iterable platforms: Iterable of compatible platforms. Defaults to the + platforms compatible with the current system. + """ + if not python_version: + python_version = sys.version_info[:2] + platforms = list(platforms or platform_tags()) + for version in _py_interpreter_range(python_version): + for platform_ in platforms: + yield Tag(version, "none", platform_) + if interpreter: + yield Tag(interpreter, "none", "any") + for version in _py_interpreter_range(python_version): + yield Tag(version, "none", "any") + + +def _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str: + if not is_32bit: + return arch + + if arch.startswith("ppc"): + return "ppc" + + return "i386" + + +def _mac_binary_formats(version: AppleVersion, cpu_arch: str) -> list[str]: + formats = [cpu_arch] + if cpu_arch == "x86_64": + if version < (10, 4): + return [] + formats.extend(["intel", "fat64", "fat32"]) + + elif cpu_arch == "i386": + if version < (10, 4): + return [] + formats.extend(["intel", "fat32", "fat"]) + + elif cpu_arch == "ppc64": + # TODO: Need to care about 32-bit PPC for ppc64 through 10.2? + if version > (10, 5) or version < (10, 4): + return [] + formats.append("fat64") + + elif cpu_arch == "ppc": + if version > (10, 6): + return [] + formats.extend(["fat32", "fat"]) + + if cpu_arch in {"arm64", "x86_64"}: + formats.append("universal2") + + if cpu_arch in {"x86_64", "i386", "ppc64", "ppc", "intel"}: + formats.append("universal") + + return formats + + +def mac_platforms( + version: AppleVersion | None = None, arch: str | None = None +) -> Iterator[str]: + """ + Yields the :attr:`~Tag.platform` tags for macOS. + + The `version` parameter is a two-item tuple specifying the macOS version to + generate platform tags for. The `arch` parameter is the CPU architecture to + generate platform tags for. Both parameters default to the appropriate value + for the current system. + + :param tuple version: A two-item tuple representing the version of macOS. + Defaults to the current system's version. + :param str arch: The CPU architecture. Defaults to the architecture of the + current system, e.g. ``"x86_64"``. + + .. note:: + Equivalent support for the other major platforms is purposefully not + provided: + + - On Windows, platform compatibility is statically specified + - On Linux, code must be run on the system itself to determine + compatibility + """ + version_str, _, cpu_arch = platform.mac_ver() + if version is None: + version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) + if version == (10, 16): + # When built against an older macOS SDK, Python will report macOS 10.16 + # instead of the real version. + version_str = subprocess.run( + [ + sys.executable, + "-sS", + "-c", + "import platform; print(platform.mac_ver()[0])", + ], + check=True, + env={"SYSTEM_VERSION_COMPAT": "0"}, + stdout=subprocess.PIPE, + text=True, + ).stdout + version = cast("AppleVersion", tuple(map(int, version_str.split(".")[:2]))) + + if arch is None: + arch = _mac_arch(cpu_arch) + + if (10, 0) <= version < (11, 0): + # Prior to Mac OS 11, each yearly release of Mac OS bumped the + # "minor" version number. The major version was always 10. + major_version = 10 + for minor_version in range(version[1], -1, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + if version >= (11, 0): + # Starting with Mac OS 11, each yearly release bumps the major version + # number. The minor versions are now the midyear updates. + minor_version = 0 + for major_version in range(version[0], 10, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + if version >= (11, 0): + # Mac OS 11 on x86_64 is compatible with binaries from previous releases. + # Arm64 support was introduced in 11.0, so no Arm binaries from previous + # releases exist. + # + # However, the "universal2" binary format can have a + # macOS version earlier than 11.0 when the x86_64 part of the binary supports + # that version of macOS. + major_version = 10 + if arch == "x86_64": + for minor_version in range(16, 3, -1): + compat_version = major_version, minor_version + binary_formats = _mac_binary_formats(compat_version, arch) + for binary_format in binary_formats: + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + else: + for minor_version in range(16, 3, -1): + compat_version = major_version, minor_version + binary_format = "universal2" + yield f"macosx_{major_version}_{minor_version}_{binary_format}" + + +def ios_platforms( + version: AppleVersion | None = None, multiarch: str | None = None +) -> Iterator[str]: + """ + + Yields the :attr:`~Tag.platform` tags for iOS. + + :param tuple version: A two-item tuple representing the version of iOS. + Defaults to the current system's version. + :param str multiarch: The CPU architecture+ABI to be used. This should be in + the format by ``sys.implementation._multiarch`` (e.g., + ``arm64_iphoneos`` or ``x86_64_iphonesimulator``). + Defaults to the current system's multiarch value. + + .. note:: + Behavior of this method is undefined if invoked on non-iOS platforms + without providing explicit version and multiarch arguments. + """ + if version is None: + # if iOS is the current platform, ios_ver *must* be defined. However, + # it won't exist for CPython versions before 3.13, which causes a mypy + # error. + _, release, _, _ = platform.ios_ver() # type: ignore[attr-defined, unused-ignore] + version = cast("AppleVersion", tuple(map(int, release.split(".")[:2]))) + + if multiarch is None: + multiarch = sys.implementation._multiarch + multiarch = multiarch.replace("-", "_") + + ios_platform_template = "ios_{major}_{minor}_{multiarch}" + + # Consider any iOS major.minor version from the version requested, down to + # 12.0. 12.0 is the first iOS version that is known to have enough features + # to support CPython. Consider every possible minor release up to X.9. There + # highest the minor has ever gone is 8 (14.8 and 15.8) but having some extra + # candidates that won't ever match doesn't really hurt, and it saves us from + # having to keep an explicit list of known iOS versions in the code. Return + # the results descending order of version number. + + # If the requested major version is less than 12, there won't be any matches. + if version[0] < 12: + return + + # Consider the actual X.Y version that was requested. + yield ios_platform_template.format( + major=version[0], minor=version[1], multiarch=multiarch + ) + + # Consider every minor version from X.0 to the minor version prior to the + # version requested by the platform. + for minor in range(version[1] - 1, -1, -1): + yield ios_platform_template.format( + major=version[0], minor=minor, multiarch=multiarch + ) + + for major in range(version[0] - 1, 11, -1): + for minor in range(9, -1, -1): + yield ios_platform_template.format( + major=major, minor=minor, multiarch=multiarch + ) + + +def android_platforms( + api_level: int | None = None, abi: str | None = None +) -> Iterator[str]: + """ + Yields the :attr:`~Tag.platform` tags for Android. If this function is invoked on + non-Android platforms, the ``api_level`` and ``abi`` arguments are required. + + :param int api_level: The maximum `API level + `__ to return. Defaults + to the current system's version, as returned by ``platform.android_ver``. + :param str abi: The `Android ABI `__, + e.g. ``arm64_v8a``. Defaults to the current system's ABI , as returned by + ``sysconfig.get_platform``. Hyphens and periods will be replaced with + underscores. + """ + if platform.system() != "Android" and (api_level is None or abi is None): + raise TypeError( + "on non-Android platforms, the api_level and abi arguments are required" + ) + + if api_level is None: + # Python 3.13 was the first version to return platform.system() == "Android", + # and also the first version to define platform.android_ver(). + api_level = platform.android_ver().api_level # type: ignore[attr-defined] + + if abi is None: + abi = sysconfig.get_platform().split("-")[-1] + abi = _normalize_string(abi) + + # 16 is the minimum API level known to have enough features to support CPython + # without major patching. Yield every API level from the maximum down to the + # minimum, inclusive. + min_api_level = 16 + for ver in range(api_level, min_api_level - 1, -1): + yield f"android_{ver}_{abi}" + + +def _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]: + linux = _normalize_string(sysconfig.get_platform()) + if not linux.startswith("linux_"): + # we should never be here, just yield the sysconfig one and return + yield linux + return + if is_32bit: + if linux == "linux_x86_64": + linux = "linux_i686" + elif linux == "linux_aarch64": + linux = "linux_armv8l" + _, arch = linux.split("_", 1) + archs = {"armv8l": ["armv8l", "armv7l"]}.get(arch, [arch]) + yield from _manylinux.platform_tags(archs) + yield from _musllinux.platform_tags(archs) + for arch in archs: + yield f"linux_{arch}" + + +def _emscripten_platforms() -> Iterator[str]: + pyemscripten_platform_version = sysconfig.get_config_var( + "PYEMSCRIPTEN_PLATFORM_VERSION" + ) + if pyemscripten_platform_version: + yield f"pyemscripten_{pyemscripten_platform_version}_wasm32" + yield from _generic_platforms() + + +def _generic_platforms() -> Iterator[str]: + yield _normalize_string(sysconfig.get_platform()) + + +def platform_tags() -> Iterator[str]: + """ + Yields the :attr:`~Tag.platform` tags for the running interpreter. + """ + if platform.system() == "Darwin": + return mac_platforms() + elif platform.system() == "iOS": + return ios_platforms() + elif platform.system() == "Android": + return android_platforms() + elif platform.system() == "Linux": + return _linux_platforms() + elif platform.system() == "Emscripten": + return _emscripten_platforms() + else: + return _generic_platforms() + + +def interpreter_name() -> str: + """ + Returns the name of the running interpreter. + + Some implementations have a reserved, two-letter abbreviation which will + be returned when appropriate. + + This typically acts as the prefix to the :attr:`~Tag.interpreter` tag. + """ + name = sys.implementation.name + return INTERPRETER_SHORT_NAMES.get(name) or name + + +def interpreter_version(*, warn: bool = False) -> str: + """ + Returns the running interpreter's version. + + This typically acts as the suffix to the :attr:`~Tag.interpreter` tag. + + :param bool warn: Whether warnings should be logged. Defaults to ``False``. + """ + version = _get_config_var("py_version_nodot", warn=warn) + return str(version) if version else _version_nodot(sys.version_info[:2]) + + +def _version_nodot(version: PythonVersion) -> str: + return "".join(map(str, version)) + + +def sys_tags(*, warn: bool = False) -> Iterator[Tag]: + """ + Yields the sequence of tag triples that the running interpreter supports. + + The iterable is ordered so that the best-matching tag is first in the + sequence. The exact preferential order to tags is interpreter-specific, but + in general the tag importance is in the order of: + + 1. Interpreter + 2. Platform + 3. ABI + + This order is due to the fact that an ABI is inherently tied to the + platform, but platform-specific code is not necessarily tied to the ABI. The + interpreter is the most important tag as it dictates basic support for any + wheel. + + The function returns an iterable in order to allow for the possible + short-circuiting of tag generation if the entire sequence is not necessary + and tag calculation happens to be expensive. + + :param bool warn: Whether warnings should be logged. Defaults to ``False``. + + .. versionchanged:: 21.3 + Added the `pp3-none-any` tag (:issue:`311`). + .. versionchanged:: 27.0 + Added the `abi3t` tag (:issue:`1099`). + """ + + interp_name = interpreter_name() + if interp_name == "cp": + yield from cpython_tags(warn=warn) + else: + yield from generic_tags() + + if interp_name == "pp": + interp = "pp3" + elif interp_name == "cp": + interp = "cp" + interpreter_version(warn=warn) + else: + interp = None + yield from compatible_tags(interpreter=interp) + + +def create_compatible_tags_selector( + tags: Iterable[Tag], +) -> Callable[[Iterable[tuple[_T, AbstractSet[Tag]]]], Iterator[_T]]: + """Create a callable to select things compatible with supported tags. + + This function accepts an ordered sequence of tags, with the preferred + tags first. + + The returned callable accepts an iterable of tuples (thing, set[Tag]), + and returns an iterator of things, with the things with the best + matching tags first. + + Example to select compatible wheel filenames: + + >>> from packaging import tags + >>> from packaging.utils import parse_wheel_filename + >>> selector = tags.create_compatible_tags_selector(tags.sys_tags()) + >>> filenames = ["foo-1.0-py3-none-any.whl", "foo-1.0-py2-none-any.whl"] + >>> list(selector([ + ... (filename, parse_wheel_filename(filename)[-1]) for filename in filenames + ... ])) + ['foo-1.0-py3-none-any.whl'] + + .. versionadded:: 26.1 + """ + tag_ranks: dict[Tag, int] = {} + for rank, tag in enumerate(tags): + tag_ranks.setdefault(tag, rank) # ignore duplicate tags, keep first + supported_tags = tag_ranks.keys() + + def selector( + tagged_things: Iterable[tuple[_T, AbstractSet[Tag]]], + ) -> Iterator[_T]: + ranked_things: list[tuple[_T, int]] = [] + for thing, thing_tags in tagged_things: + supported_thing_tags = thing_tags & supported_tags + if supported_thing_tags: + thing_rank = min(tag_ranks[t] for t in supported_thing_tags) + ranked_things.append((thing, thing_rank)) + return iter( + thing for thing, _ in sorted(ranked_things, key=operator.itemgetter(1)) + ) + + return selector diff --git a/micromamba_root/Lib/site-packages/packaging/utils.py b/micromamba_root/Lib/site-packages/packaging/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cbd3be27c4211f73330a318debf6a490b8b9d8ba --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/utils.py @@ -0,0 +1,296 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import re +from typing import NewType, Tuple, Union, cast + +from .tags import Tag, UnsortedTagsError, parse_tag +from .version import InvalidVersion, Version, _TrimmedRelease + +__all__ = [ + "BuildTag", + "InvalidName", + "InvalidSdistFilename", + "InvalidWheelFilename", + "NormalizedName", + "canonicalize_name", + "canonicalize_version", + "is_normalized_name", + "parse_sdist_filename", + "parse_wheel_filename", +] + + +def __dir__() -> list[str]: + return __all__ + + +BuildTag = Union[Tuple[()], Tuple[int, str]] + +NormalizedName = NewType("NormalizedName", str) +""" +A :class:`typing.NewType` of :class:`str`, representing a normalized name. +""" + + +class InvalidName(ValueError): + """ + An invalid distribution name; users should refer to the packaging user guide. + """ + + +class InvalidWheelFilename(ValueError): + """ + An invalid wheel filename was found, users should refer to PEP 427. + """ + + +class InvalidSdistFilename(ValueError): + """ + An invalid sdist filename was found, users should refer to the packaging user guide. + """ + + +# Core metadata spec for `Name` +_validate_regex = re.compile( + r"[a-z0-9]|[a-z0-9][a-z0-9._-]*[a-z0-9]", re.IGNORECASE | re.ASCII +) +_normalized_regex = re.compile(r"[a-z0-9]|[a-z0-9]([a-z0-9-](?!--))*[a-z0-9]", re.ASCII) +# PEP 427: The build number must start with a digit. +_build_tag_regex = re.compile(r"(\d+)(.*)", re.ASCII) + + +def canonicalize_name(name: str, *, validate: bool = False) -> NormalizedName: + """ + This function takes a valid Python package or extra name, and returns the + normalized form of it. + + The return type is typed as :class:`NormalizedName`. This allows type + checkers to help require that a string has passed through this function + before use. + + If **validate** is true, then the function will check if **name** is a valid + distribution name before normalizing. + + :param str name: The name to normalize. + :param bool validate: Check whether the name is a valid distribution name. + :raises InvalidName: If **validate** is true and the name is not an + acceptable distribution name. + + >>> from packaging.utils import canonicalize_name + >>> canonicalize_name("Django") + 'django' + >>> canonicalize_name("oslo.concurrency") + 'oslo-concurrency' + >>> canonicalize_name("requests") + 'requests' + """ + if validate and not _validate_regex.fullmatch(name): + raise InvalidName(f"name is invalid: {name!r}") + # Ensure all ``.`` and ``_`` are ``-`` + # Emulates ``re.sub(r"[-_.]+", "-", name).lower()`` from PEP 503 + # Much faster than re, and even faster than str.translate + value = name.lower().replace("_", "-").replace(".", "-") + # Condense repeats (faster than regex) + while "--" in value: + value = value.replace("--", "-") + return cast("NormalizedName", value) + + +def is_normalized_name(name: str) -> bool: + """ + Check if a name is already normalized (i.e. :func:`canonicalize_name` would + roundtrip to the same value). + + :param str name: The name to check. + + >>> from packaging.utils import is_normalized_name + >>> is_normalized_name("requests") + True + >>> is_normalized_name("Django") + False + """ + return _normalized_regex.fullmatch(name) is not None + + +def canonicalize_version( + version: Version | str, *, strip_trailing_zero: bool = True +) -> str: + """Return a canonical form of a version as a string. + + This function takes a string representing a package version (or a + :class:`~packaging.version.Version` instance), and returns the + normalized form of it. By default, it strips trailing zeros from + the release segment. + + >>> from packaging.utils import canonicalize_version + >>> canonicalize_version('1.0.1') + '1.0.1' + + Per PEP 625, versions may have multiple canonical forms, differing + only by trailing zeros. + + >>> canonicalize_version('1.0.0') + '1' + >>> canonicalize_version('1.0.0', strip_trailing_zero=False) + '1.0.0' + + Invalid versions are returned unaltered. + + >>> canonicalize_version('foo bar baz') + 'foo bar baz' + + >>> canonicalize_version('1.4.0.0.0') + '1.4' + """ + if isinstance(version, str): + try: + version = Version(version) + except InvalidVersion: + return str(version) + return str(_TrimmedRelease(version) if strip_trailing_zero else version) + + +def parse_wheel_filename( + filename: str, + *, + validate_order: bool = False, +) -> tuple[NormalizedName, Version, BuildTag, frozenset[Tag]]: + """ + This function takes the filename of a wheel file, and parses it, + returning a tuple of name, version, build number, and tags. + + The name part of the tuple is normalized and typed as + :class:`NormalizedName`. The version portion is an instance of + :class:`~packaging.version.Version`. The build number is ``()`` if + there is no build number in the wheel filename, otherwise a + two-item tuple of an integer for the leading digits and + a string for the rest of the build number. The tags portion is a + frozen set of :class:`~packaging.tags.Tag` instances (as the tag + string format allows multiple tags to be combined into a single + string). + + If **validate_order** is true, compressed tag set components are + checked to be in sorted order as required by PEP 425. + + :param str filename: The name of the wheel file. + :param bool validate_order: Check whether compressed tag set components + are in sorted order. + :raises InvalidWheelFilename: If the filename in question + does not follow the :ref:`wheel specification + `. + + >>> from packaging.utils import parse_wheel_filename + >>> from packaging.tags import Tag + >>> from packaging.version import Version + >>> name, ver, build, tags = parse_wheel_filename("foo-1.0-py3-none-any.whl") + >>> name + 'foo' + >>> ver == Version('1.0') + True + >>> tags == {Tag("py3", "none", "any")} + True + >>> not build + True + + .. versionadded:: 26.1 + The *validate_order* parameter. + """ + if not filename.endswith(".whl"): + raise InvalidWheelFilename( + f"Invalid wheel filename (extension must be '.whl'): {filename!r}" + ) + + filename = filename[:-4] + dashes = filename.count("-") + if dashes not in (4, 5): + raise InvalidWheelFilename( + f"Invalid wheel filename (wrong number of parts): {filename!r}" + ) + + parts = filename.split("-", dashes - 2) + name_part = parts[0] + # See PEP 427 for the rules on escaping the project name. + if "__" in name_part or re.match(r"^[\w\d._]*$", name_part, re.UNICODE) is None: + raise InvalidWheelFilename(f"Invalid project name: {filename!r}") + name = canonicalize_name(name_part) + + try: + version = Version(parts[1]) + except InvalidVersion as e: + raise InvalidWheelFilename( + f"Invalid wheel filename (invalid version): {filename!r}" + ) from e + + if dashes == 5: + build_part = parts[2] + build_match = _build_tag_regex.match(build_part) + if build_match is None: + raise InvalidWheelFilename( + f"Invalid build number: {build_part} in {filename!r}" + ) + build = cast("BuildTag", (int(build_match.group(1)), build_match.group(2))) + else: + build = () + tag_str = parts[-1] + try: + tags = parse_tag(tag_str, validate_order=validate_order) + except UnsortedTagsError: + raise InvalidWheelFilename( + f"Invalid wheel filename (compressed tag set components must be in " + f"sorted order per PEP 425): {filename!r}" + ) from None + return (name, version, build, tags) + + +def parse_sdist_filename(filename: str) -> tuple[NormalizedName, Version]: + """ + This function takes the filename of a sdist file (as specified + in the `Source distribution format`_ documentation), and parses + it, returning a tuple of the normalized name and version as + represented by an instance of :class:`~packaging.version.Version`. + + :param str filename: The name of the sdist file. + :raises InvalidSdistFilename: If the filename does not end + with an sdist extension (``.zip`` or ``.tar.gz``), or if it does not + contain a dash separating the name and the version of the distribution. + + >>> from packaging.utils import parse_sdist_filename + >>> from packaging.version import Version + >>> name, ver = parse_sdist_filename("foo-1.0.tar.gz") + >>> name + 'foo' + >>> ver == Version('1.0') + True + + .. _Source distribution format: https://packaging.python.org/specifications/source-distribution-format/#source-distribution-file-name + """ + if filename.endswith(".tar.gz"): + file_stem = filename[: -len(".tar.gz")] + elif filename.endswith(".zip"): + file_stem = filename[: -len(".zip")] + else: + raise InvalidSdistFilename( + f"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):" + f" {filename!r}" + ) + + # We are requiring a PEP 440 version, which cannot contain dashes, + # so we split on the last dash. + name_part, sep, version_part = file_stem.rpartition("-") + if not sep: + raise InvalidSdistFilename(f"Invalid sdist filename: {filename!r}") + + name = canonicalize_name(name_part) + + try: + version = Version(version_part) + except InvalidVersion as e: + raise InvalidSdistFilename( + f"Invalid sdist filename (invalid version): {filename!r}" + ) from e + + return (name, version) diff --git a/micromamba_root/Lib/site-packages/packaging/version.py b/micromamba_root/Lib/site-packages/packaging/version.py new file mode 100644 index 0000000000000000000000000000000000000000..97f23fd9ad66a66ecfb8ebbabebc08d4cc51d683 --- /dev/null +++ b/micromamba_root/Lib/site-packages/packaging/version.py @@ -0,0 +1,1231 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +""" +.. testsetup:: + + from packaging.version import parse, normalize_pre, Version, _cmpkey +""" + +from __future__ import annotations + +import re +import sys +import typing +from typing import ( + Any, + Callable, + Literal, + NamedTuple, + SupportsInt, + Tuple, + TypedDict, + Union, +) + +if typing.TYPE_CHECKING: + from typing_extensions import Self, Unpack + +if sys.version_info >= (3, 13): # pragma: no cover + from warnings import deprecated as _deprecated +elif typing.TYPE_CHECKING: + from typing_extensions import deprecated as _deprecated +else: # pragma: no cover + import functools + import warnings + + def _deprecated(message: str) -> object: + def decorator(func: Callable[[...], object]) -> object: + @functools.wraps(func) + def wrapper(*args: object, **kwargs: object) -> object: + warnings.warn( + message, + category=DeprecationWarning, + stacklevel=2, + ) + return func(*args, **kwargs) + + return wrapper + + return decorator + + +_LETTER_NORMALIZATION = { + "alpha": "a", + "beta": "b", + "c": "rc", + "pre": "rc", + "preview": "rc", + "rev": "post", + "r": "post", +} + +__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "normalize_pre", "parse"] + + +def __dir__() -> list[str]: + return __all__ + + +LocalType = Tuple[Union[int, str], ...] + +CmpLocalType = Tuple[Tuple[int, str], ...] +CmpSuffix = Tuple[int, int, int, int, int, int] +CmpKey = Union[ + Tuple[int, Tuple[int, ...], CmpSuffix], + Tuple[int, Tuple[int, ...], CmpSuffix, CmpLocalType], +] +VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] + + +class _VersionReplace(TypedDict, total=False): + epoch: int | None + release: tuple[int, ...] | None + pre: tuple[str, int] | None + post: int | None + dev: int | None + local: str | None + + +def normalize_pre(letter: str, /) -> str: + """Normalize the pre-release segment of a version string. + + Returns a lowercase version of the string if not a known pre-release + identifier. + + >>> normalize_pre('alpha') + 'a' + >>> normalize_pre('BETA') + 'b' + >>> normalize_pre('rc') + 'rc' + + :param letter: + + .. versionadded:: 26.1 + """ + letter = letter.lower() + return _LETTER_NORMALIZATION.get(letter, letter) + + +def parse(version: str) -> Version: + """Parse the given version string. + + This is identical to the :class:`Version` constructor. + + >>> parse('1.0.dev1') + + + :param version: The version string to parse. + :raises InvalidVersion: When the version string is not a valid version. + """ + return Version(version) + + +class InvalidVersion(ValueError): + """Raised when a version string is not a valid version. + + >>> Version("invalid") + Traceback (most recent call last): + ... + packaging.version.InvalidVersion: Invalid version: 'invalid' + """ + + +class _BaseVersion: + __slots__ = () + + # This can also be a normal member (see the packaging_legacy package); + # we are just requiring it to be readable. Actually defining a property + # has runtime effect on subclasses, so it's typing only. + if typing.TYPE_CHECKING: + + @property + def _key(self) -> tuple[Any, ...]: ... + + def __hash__(self) -> int: + return hash(self._key) + + # Please keep the duplicated `isinstance` check + # in the six comparisons hereunder + # unless you find a way to avoid adding overhead function calls. + def __lt__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key < other._key + + def __le__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key <= other._key + + def __eq__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key == other._key + + def __ge__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key >= other._key + + def __gt__(self, other: _BaseVersion) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key > other._key + + def __ne__(self, other: object) -> bool: + if not isinstance(other, _BaseVersion): + return NotImplemented + + return self._key != other._key + + +# Deliberately not anchored to the start and end of the string, to make it +# easier for 3rd party code to reuse + +# Note that ++ doesn't behave identically on CPython and PyPy, so not using it here +_VERSION_PATTERN = r""" + v?+ # optional leading v + (?a: + (?:(?P[0-9]+)!)?+ # epoch + (?P[0-9]+(?:\.[0-9]+)*+) # release segment + (?P
                                          # pre-release
+            [._-]?+
+            (?Palpha|a|beta|b|preview|pre|c|rc)
+            [._-]?+
+            (?P[0-9]+)?
+        )?+
+        (?P                                         # post release
+            (?:-(?P[0-9]+))
+            |
+            (?:
+                [._-]?
+                (?Ppost|rev|r)
+                [._-]?
+                (?P[0-9]+)?
+            )
+        )?+
+        (?P                                          # dev release
+            [._-]?+
+            (?Pdev)
+            [._-]?+
+            (?P[0-9]+)?
+        )?+
+    )
+    (?a:\+
+        (?P                                        # local version
+            [a-z0-9]+
+            (?:[._-][a-z0-9]+)*+
+        )
+    )?+
+"""
+
+_VERSION_PATTERN_OLD = _VERSION_PATTERN.replace("*+", "*").replace("?+", "?")
+
+# Possessive qualifiers were added in Python 3.11.
+# CPython 3.11.0-3.11.4 had a bug: https://github.com/python/cpython/pull/107795
+# Older PyPy also had a bug.
+VERSION_PATTERN = (
+    _VERSION_PATTERN_OLD
+    if (sys.implementation.name == "cpython" and sys.version_info < (3, 11, 5))
+    or (sys.implementation.name == "pypy" and sys.version_info < (3, 11, 13))
+    or sys.version_info < (3, 11)
+    else _VERSION_PATTERN
+)
+"""
+A string containing the regular expression used to match a valid version.
+
+The pattern is not anchored at either end, and is intended for embedding in larger
+expressions (for example, matching a version number as part of a file name). The
+regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE``
+flags set.
+
+.. versionchanged:: 26.0
+
+   The regex now uses possessive qualifiers on Python 3.11 if they are
+   supported (CPython 3.11.5+, PyPy 3.11.13+).
+
+:meta hide-value:
+"""
+
+
+# Validation pattern for local version in replace()
+_LOCAL_PATTERN = re.compile(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", re.IGNORECASE | re.ASCII)
+
+# Fast path: If a version has only digits and dots then we
+# can skip the regex and parse it as a release segment
+_SIMPLE_VERSION_INDICATORS = frozenset(".0123456789")
+
+
+def _validate_epoch(value: object, /) -> int:
+    epoch = value or 0
+    if isinstance(epoch, int) and epoch >= 0:
+        return epoch
+    msg = f"epoch must be non-negative integer, got {epoch}"
+    raise InvalidVersion(msg)
+
+
+def _validate_release(value: object, /) -> tuple[int, ...]:
+    release = (0,) if value is None else value
+    if (
+        isinstance(release, tuple)
+        and len(release) > 0
+        and all(isinstance(i, int) and i >= 0 for i in release)
+    ):
+        return release
+    msg = f"release must be a non-empty tuple of non-negative integers, got {release}"
+    raise InvalidVersion(msg)
+
+
+def _validate_pre(value: object, /) -> tuple[Literal["a", "b", "rc"], int] | None:
+    if value is None:
+        return value
+    if isinstance(value, tuple) and len(value) == 2:
+        letter, number = value
+        letter = normalize_pre(letter)
+        if letter in {"a", "b", "rc"} and isinstance(number, int) and number >= 0:
+            # type checkers can't infer the Literal type here on letter
+            return (letter, number)  # type: ignore[return-value]
+    msg = f"pre must be a tuple of ('a'|'b'|'rc', non-negative int), got {value}"
+    raise InvalidVersion(msg)
+
+
+def _validate_post(value: object, /) -> tuple[Literal["post"], int] | None:
+    if value is None:
+        return value
+    if isinstance(value, int) and value >= 0:
+        return ("post", value)
+    msg = f"post must be non-negative integer, got {value}"
+    raise InvalidVersion(msg)
+
+
+def _validate_dev(value: object, /) -> tuple[Literal["dev"], int] | None:
+    if value is None:
+        return value
+    if isinstance(value, int) and value >= 0:
+        return ("dev", value)
+    msg = f"dev must be non-negative integer, got {value}"
+    raise InvalidVersion(msg)
+
+
+def _validate_local(value: object, /) -> LocalType | None:
+    if value is None:
+        return value
+    if isinstance(value, str) and _LOCAL_PATTERN.fullmatch(value):
+        return _parse_local_version(value)
+    msg = f"local must be a valid version string, got {value!r}"
+    raise InvalidVersion(msg)
+
+
+# Backward compatibility for internals before 26.0. Do not use.
+class _Version(NamedTuple):
+    epoch: int
+    release: tuple[int, ...]
+    dev: tuple[Literal["dev"], int] | None
+    pre: tuple[Literal["a", "b", "rc"], int] | None
+    post: tuple[Literal["post"], int] | None
+    local: LocalType | None
+
+
+class Version(_BaseVersion):
+    """This class abstracts handling of a project's versions.
+
+    A :class:`Version` instance is comparison aware and can be compared and
+    sorted using the standard Python interfaces.
+
+    >>> v1 = Version("1.0a5")
+    >>> v2 = Version("1.0")
+    >>> v1
+    
+    >>> v2
+    
+    >>> v1 < v2
+    True
+    >>> v1 == v2
+    False
+    >>> v1 > v2
+    False
+    >>> v1 >= v2
+    False
+    >>> v1 <= v2
+    True
+
+    :class:`Version` is immutable; use :meth:`__replace__` to change
+    part of a version.
+
+    Instances are safe to serialize with :mod:`pickle`. They use a stable
+    format so the same pickle can be loaded in future packaging releases.
+
+    .. versionchanged:: 26.2
+
+        Added a stable pickle format. Pickles created with packaging 26.2+ can
+        be unpickled with future releases.  Backward compatibility with pickles
+        from packaging < 26.2 is supported but may be removed in a future
+        release.
+    """
+
+    __slots__ = (
+        "_dev",
+        "_epoch",
+        "_hash_cache",
+        "_key_cache",
+        "_local",
+        "_post",
+        "_pre",
+        "_release",
+    )
+    __match_args__ = ("_str",)
+    """
+    Pattern matching is supported on Python 3.10+.
+
+    .. versionadded:: 26.0
+
+    :meta hide-value:
+    """
+
+    _regex = re.compile(r"\s*" + VERSION_PATTERN + r"\s*", re.VERBOSE | re.IGNORECASE)
+
+    _epoch: int
+    _release: tuple[int, ...]
+    _dev: tuple[Literal["dev"], int] | None
+    _pre: tuple[Literal["a", "b", "rc"], int] | None
+    _post: tuple[Literal["post"], int] | None
+    _local: LocalType | None
+
+    _hash_cache: int | None
+    _key_cache: CmpKey | None
+
+    def __init__(self, version: str) -> None:
+        """Initialize a Version object.
+
+        :param version:
+            The string representation of a version which will be parsed and normalized
+            before use.
+        :raises InvalidVersion:
+            If the ``version`` does not conform to PEP 440 in any way then this
+            exception will be raised.
+        """
+        if _SIMPLE_VERSION_INDICATORS.issuperset(version):
+            try:
+                self._release = tuple(map(int, version.split(".")))
+            except ValueError:
+                # Empty parts (from "1..2", ".1", etc.) are invalid versions.
+                # Any other ValueError (e.g. int str-digits limit) should
+                # propagate to the caller.
+                if "" in version.split("."):
+                    raise InvalidVersion(f"Invalid version: {version!r}") from None
+                # TODO: remove "no cover" when Python 3.9 is dropped.
+                raise  # pragma: no cover
+
+            self._epoch = 0
+            self._pre = None
+            self._post = None
+            self._dev = None
+            self._local = None
+            self._key_cache = None
+            self._hash_cache = None
+            return
+
+        # Validate the version and parse it into pieces
+        match = self._regex.fullmatch(version)
+        if not match:
+            raise InvalidVersion(f"Invalid version: {version!r}")
+        self._epoch = int(match.group("epoch")) if match.group("epoch") else 0
+        self._release = tuple(map(int, match.group("release").split(".")))
+        # We can type ignore the assignments below because the regex guarantees
+        # the correct strings
+        self._pre = _parse_letter_version(match.group("pre_l"), match.group("pre_n"))  # type: ignore[assignment]
+        self._post = _parse_letter_version(  # type: ignore[assignment]
+            match.group("post_l"), match.group("post_n1") or match.group("post_n2")
+        )
+        self._dev = _parse_letter_version(match.group("dev_l"), match.group("dev_n"))  # type: ignore[assignment]
+        self._local = _parse_local_version(match.group("local"))
+
+        # Key which will be used for sorting
+        self._key_cache = None
+        self._hash_cache = None
+
+    @classmethod
+    def from_parts(
+        cls,
+        *,
+        epoch: int = 0,
+        release: tuple[int, ...],
+        pre: tuple[str, int] | None = None,
+        post: int | None = None,
+        dev: int | None = None,
+        local: str | None = None,
+    ) -> Self:
+        """
+        Return a new version composed of the various parts.
+
+        This allows you to build a version without going though a string and
+        running a regular expression. It normalizes pre-release strings. The
+        ``release=`` keyword argument is required.
+
+        >>> Version.from_parts(release=(1,2,3))
+        
+        >>> Version.from_parts(release=(0,1,0), pre=("b", 1))
+        
+
+        :param epoch:
+        :param release: This version tuple is required
+
+        .. versionadded:: 26.1
+        """
+        _epoch = _validate_epoch(epoch)
+        _release = _validate_release(release)
+        _pre = _validate_pre(pre) if pre is not None else None
+        _post = _validate_post(post) if post is not None else None
+        _dev = _validate_dev(dev) if dev is not None else None
+        _local = _validate_local(local) if local is not None else None
+
+        new_version = cls.__new__(cls)
+        new_version._key_cache = None
+        new_version._hash_cache = None
+        new_version._epoch = _epoch
+        new_version._release = _release
+        new_version._pre = _pre
+        new_version._post = _post
+        new_version._dev = _dev
+        new_version._local = _local
+
+        return new_version
+
+    def __replace__(self, **kwargs: Unpack[_VersionReplace]) -> Self:
+        """
+        __replace__(*, epoch=..., release=..., pre=..., post=..., dev=..., local=...)
+
+        Return a new version with parts replaced.
+
+        This returns a new version (unless no parts were changed). The
+        pre-release is normalized. Setting a value to ``None`` clears it.
+
+        >>> v = Version("1.2.3")
+        >>> v.__replace__(pre=("a", 1))
+        
+
+        :param int | None epoch:
+        :param tuple[int, ...] | None release:
+        :param tuple[str, int] | None pre:
+        :param int | None post:
+        :param int | None dev:
+        :param str | None local:
+
+        .. versionadded:: 26.0
+        .. versionchanged:: 26.1
+
+           The pre-release portion is now normalized.
+        """
+        epoch = _validate_epoch(kwargs["epoch"]) if "epoch" in kwargs else self._epoch
+        release = (
+            _validate_release(kwargs["release"])
+            if "release" in kwargs
+            else self._release
+        )
+        pre = _validate_pre(kwargs["pre"]) if "pre" in kwargs else self._pre
+        post = _validate_post(kwargs["post"]) if "post" in kwargs else self._post
+        dev = _validate_dev(kwargs["dev"]) if "dev" in kwargs else self._dev
+        local = _validate_local(kwargs["local"]) if "local" in kwargs else self._local
+
+        if (
+            epoch == self._epoch
+            and release == self._release
+            and pre == self._pre
+            and post == self._post
+            and dev == self._dev
+            and local == self._local
+        ):
+            return self
+
+        new_version = self.__class__.__new__(self.__class__)
+        new_version._key_cache = None
+        new_version._hash_cache = None
+        new_version._epoch = epoch
+        new_version._release = release
+        new_version._pre = pre
+        new_version._post = post
+        new_version._dev = dev
+        new_version._local = local
+
+        return new_version
+
+    @property
+    def _key(self) -> CmpKey:
+        if self._key_cache is None:
+            self._key_cache = _cmpkey(
+                self._epoch,
+                self._release,
+                self._pre,
+                self._post,
+                self._dev,
+                self._local,
+            )
+        return self._key_cache
+
+    # __hash__ must be defined when __eq__ is overridden,
+    # otherwise Python sets __hash__ to None.
+    def __hash__(self) -> int:
+        if (cached_hash := self._hash_cache) is not None:
+            return cached_hash
+
+        if (key := self._key_cache) is None:
+            self._key_cache = key = _cmpkey(
+                self._epoch,
+                self._release,
+                self._pre,
+                self._post,
+                self._dev,
+                self._local,
+            )
+        self._hash_cache = cached_hash = hash(key)
+        return cached_hash
+
+    # Override comparison methods to use direct _key_cache access
+    # This is faster than property access, especially before Python 3.12
+    def __lt__(self, other: _BaseVersion) -> bool:
+        if isinstance(other, Version):
+            if self._key_cache is None:
+                self._key_cache = _cmpkey(
+                    self._epoch,
+                    self._release,
+                    self._pre,
+                    self._post,
+                    self._dev,
+                    self._local,
+                )
+            if other._key_cache is None:
+                other._key_cache = _cmpkey(
+                    other._epoch,
+                    other._release,
+                    other._pre,
+                    other._post,
+                    other._dev,
+                    other._local,
+                )
+            return self._key_cache < other._key_cache
+
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return super().__lt__(other)
+
+    def __le__(self, other: _BaseVersion) -> bool:
+        if isinstance(other, Version):
+            if self._key_cache is None:
+                self._key_cache = _cmpkey(
+                    self._epoch,
+                    self._release,
+                    self._pre,
+                    self._post,
+                    self._dev,
+                    self._local,
+                )
+            if other._key_cache is None:
+                other._key_cache = _cmpkey(
+                    other._epoch,
+                    other._release,
+                    other._pre,
+                    other._post,
+                    other._dev,
+                    other._local,
+                )
+            return self._key_cache <= other._key_cache
+
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return super().__le__(other)
+
+    def __eq__(self, other: object) -> bool:
+        if isinstance(other, Version):
+            if self._key_cache is None:
+                self._key_cache = _cmpkey(
+                    self._epoch,
+                    self._release,
+                    self._pre,
+                    self._post,
+                    self._dev,
+                    self._local,
+                )
+            if other._key_cache is None:
+                other._key_cache = _cmpkey(
+                    other._epoch,
+                    other._release,
+                    other._pre,
+                    other._post,
+                    other._dev,
+                    other._local,
+                )
+            return self._key_cache == other._key_cache
+
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return super().__eq__(other)
+
+    def __ge__(self, other: _BaseVersion) -> bool:
+        if isinstance(other, Version):
+            if self._key_cache is None:
+                self._key_cache = _cmpkey(
+                    self._epoch,
+                    self._release,
+                    self._pre,
+                    self._post,
+                    self._dev,
+                    self._local,
+                )
+            if other._key_cache is None:
+                other._key_cache = _cmpkey(
+                    other._epoch,
+                    other._release,
+                    other._pre,
+                    other._post,
+                    other._dev,
+                    other._local,
+                )
+            return self._key_cache >= other._key_cache
+
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return super().__ge__(other)
+
+    def __gt__(self, other: _BaseVersion) -> bool:
+        if isinstance(other, Version):
+            if self._key_cache is None:
+                self._key_cache = _cmpkey(
+                    self._epoch,
+                    self._release,
+                    self._pre,
+                    self._post,
+                    self._dev,
+                    self._local,
+                )
+            if other._key_cache is None:
+                other._key_cache = _cmpkey(
+                    other._epoch,
+                    other._release,
+                    other._pre,
+                    other._post,
+                    other._dev,
+                    other._local,
+                )
+            return self._key_cache > other._key_cache
+
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return super().__gt__(other)
+
+    def __ne__(self, other: object) -> bool:
+        if isinstance(other, Version):
+            if self._key_cache is None:
+                self._key_cache = _cmpkey(
+                    self._epoch,
+                    self._release,
+                    self._pre,
+                    self._post,
+                    self._dev,
+                    self._local,
+                )
+            if other._key_cache is None:
+                other._key_cache = _cmpkey(
+                    other._epoch,
+                    other._release,
+                    other._pre,
+                    other._post,
+                    other._dev,
+                    other._local,
+                )
+            return self._key_cache != other._key_cache
+
+        if not isinstance(other, _BaseVersion):
+            return NotImplemented
+
+        return super().__ne__(other)
+
+    def __getstate__(
+        self,
+    ) -> tuple[
+        int,
+        tuple[int, ...],
+        tuple[str, int] | None,
+        tuple[str, int] | None,
+        tuple[str, int] | None,
+        LocalType | None,
+    ]:
+        # Return state as a 6-item tuple for compactness:
+        #   (epoch, release, pre, post, dev, local)
+        # Cache members are excluded and will be recomputed on demand
+        return (
+            self._epoch,
+            self._release,
+            self._pre,
+            self._post,
+            self._dev,
+            self._local,
+        )
+
+    def __setstate__(self, state: object) -> None:
+        # Always discard cached values — they may contain stale references
+        # (e.g. packaging._structures.InfinityType from pre-26.1 pickles)
+        # and will be recomputed on demand from the core fields above.
+        self._key_cache = None
+        self._hash_cache = None
+
+        if isinstance(state, tuple):
+            if len(state) == 6:
+                # New format (26.2+): (epoch, release, pre, post, dev, local)
+                (
+                    self._epoch,
+                    self._release,
+                    self._pre,
+                    self._post,
+                    self._dev,
+                    self._local,
+                ) = state
+                return
+            if len(state) == 2:
+                # Format (packaging 26.0-26.1): (None, {slot: value}).
+                _, slot_dict = state
+                if isinstance(slot_dict, dict):
+                    self._epoch = slot_dict["_epoch"]
+                    self._release = slot_dict["_release"]
+                    self._pre = slot_dict.get("_pre")
+                    self._post = slot_dict.get("_post")
+                    self._dev = slot_dict.get("_dev")
+                    self._local = slot_dict.get("_local")
+                    return
+        if isinstance(state, dict):
+            # Old format (packaging <= 25.x, no __slots__): state is a plain
+            # dict with "_version" (_Version NamedTuple) and "_key" entries.
+            version_nt = state.get("_version")
+            if version_nt is not None:
+                self._epoch = version_nt.epoch
+                self._release = version_nt.release
+                self._pre = version_nt.pre
+                self._post = version_nt.post
+                self._dev = version_nt.dev
+                self._local = version_nt.local
+                return
+
+        raise TypeError(f"Cannot restore Version from {state!r}")
+
+    @property
+    @_deprecated("Version._version is private and will be removed soon")
+    def _version(self) -> _Version:
+        return _Version(
+            self._epoch, self._release, self._dev, self._pre, self._post, self._local
+        )
+
+    @_version.setter
+    @_deprecated("Version._version is private and will be removed soon")
+    def _version(self, value: _Version) -> None:
+        self._epoch = value.epoch
+        self._release = value.release
+        self._dev = value.dev
+        self._pre = value.pre
+        self._post = value.post
+        self._local = value.local
+        self._key_cache = None
+        self._hash_cache = None
+
+    def __repr__(self) -> str:
+        """A representation of the Version that shows all internal state.
+
+        >>> Version('1.0.0')
+        
+        """
+        return f"<{self.__class__.__name__}({str(self)!r})>"
+
+    def __str__(self) -> str:
+        """A string representation of the version that can be round-tripped.
+
+        >>> str(Version("1.0a5"))
+        '1.0a5'
+        """
+        # This is a hot function, so not calling self.base_version
+        version = ".".join(map(str, self.release))
+
+        # Epoch
+        if self.epoch:
+            version = f"{self.epoch}!{version}"
+
+        # Pre-release
+        if self.pre is not None:
+            version += "".join(map(str, self.pre))
+
+        # Post-release
+        if self.post is not None:
+            version += f".post{self.post}"
+
+        # Development release
+        if self.dev is not None:
+            version += f".dev{self.dev}"
+
+        # Local version segment
+        if self.local is not None:
+            version += f"+{self.local}"
+
+        return version
+
+    @property
+    def _str(self) -> str:
+        """Internal property for match_args"""
+        return str(self)
+
+    @property
+    def epoch(self) -> int:
+        """The epoch of the version.
+
+        >>> Version("2.0.0").epoch
+        0
+        >>> Version("1!2.0.0").epoch
+        1
+        """
+        return self._epoch
+
+    @property
+    def release(self) -> tuple[int, ...]:
+        """The components of the "release" segment of the version.
+
+        >>> Version("1.2.3").release
+        (1, 2, 3)
+        >>> Version("2.0.0").release
+        (2, 0, 0)
+        >>> Version("1!2.0.0.post0").release
+        (2, 0, 0)
+
+        Includes trailing zeroes but not the epoch or any pre-release / development /
+        post-release suffixes.
+        """
+        return self._release
+
+    @property
+    def pre(self) -> tuple[Literal["a", "b", "rc"], int] | None:
+        """The pre-release segment of the version.
+
+        >>> print(Version("1.2.3").pre)
+        None
+        >>> Version("1.2.3a1").pre
+        ('a', 1)
+        >>> Version("1.2.3b1").pre
+        ('b', 1)
+        >>> Version("1.2.3rc1").pre
+        ('rc', 1)
+        """
+        return self._pre
+
+    @property
+    def post(self) -> int | None:
+        """The post-release number of the version.
+
+        >>> print(Version("1.2.3").post)
+        None
+        >>> Version("1.2.3.post1").post
+        1
+        """
+        return self._post[1] if self._post else None
+
+    @property
+    def dev(self) -> int | None:
+        """The development number of the version.
+
+        >>> print(Version("1.2.3").dev)
+        None
+        >>> Version("1.2.3.dev1").dev
+        1
+        """
+        return self._dev[1] if self._dev else None
+
+    @property
+    def local(self) -> str | None:
+        """The local version segment of the version.
+
+        >>> print(Version("1.2.3").local)
+        None
+        >>> Version("1.2.3+abc").local
+        'abc'
+        """
+        if self._local:
+            return ".".join(str(x) for x in self._local)
+        else:
+            return None
+
+    @property
+    def public(self) -> str:
+        """The public portion of the version.
+
+        This returns a string. If you want a :class:`Version` again and care
+        about performance, use ``v.__replace__(local=None)`` instead.
+
+        >>> Version("1.2.3").public
+        '1.2.3'
+        >>> Version("1.2.3+abc").public
+        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").public
+        '1!1.2.3.dev1'
+        """
+        return str(self).split("+", 1)[0]
+
+    @property
+    def base_version(self) -> str:
+        """The "base version" of the version.
+
+        This returns a string. If you want a :class:`Version` again and care
+        about performance, use
+        ``v.__replace__(pre=None, post=None, dev=None, local=None)`` instead.
+
+        >>> Version("1.2.3").base_version
+        '1.2.3'
+        >>> Version("1.2.3+abc").base_version
+        '1.2.3'
+        >>> Version("1!1.2.3dev1+abc").base_version
+        '1!1.2.3'
+
+        The "base version" is the public version of the project without any pre or post
+        release markers.
+        """
+        release_segment = ".".join(map(str, self.release))
+        return f"{self.epoch}!{release_segment}" if self.epoch else release_segment
+
+    @property
+    def is_prerelease(self) -> bool:
+        """Whether this version is a pre-release.
+
+        >>> Version("1.2.3").is_prerelease
+        False
+        >>> Version("1.2.3a1").is_prerelease
+        True
+        >>> Version("1.2.3b1").is_prerelease
+        True
+        >>> Version("1.2.3rc1").is_prerelease
+        True
+        >>> Version("1.2.3dev1").is_prerelease
+        True
+        """
+        return self.dev is not None or self.pre is not None
+
+    @property
+    def is_postrelease(self) -> bool:
+        """Whether this version is a post-release.
+
+        >>> Version("1.2.3").is_postrelease
+        False
+        >>> Version("1.2.3.post1").is_postrelease
+        True
+        """
+        return self.post is not None
+
+    @property
+    def is_devrelease(self) -> bool:
+        """Whether this version is a development release.
+
+        >>> Version("1.2.3").is_devrelease
+        False
+        >>> Version("1.2.3.dev1").is_devrelease
+        True
+        """
+        return self.dev is not None
+
+    @property
+    def major(self) -> int:
+        """The first item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").major
+        1
+        """
+        return self.release[0] if len(self.release) >= 1 else 0
+
+    @property
+    def minor(self) -> int:
+        """The second item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").minor
+        2
+        >>> Version("1").minor
+        0
+        """
+        return self.release[1] if len(self.release) >= 2 else 0
+
+    @property
+    def micro(self) -> int:
+        """The third item of :attr:`release` or ``0`` if unavailable.
+
+        >>> Version("1.2.3").micro
+        3
+        >>> Version("1").micro
+        0
+        """
+        return self.release[2] if len(self.release) >= 3 else 0
+
+
+class _TrimmedRelease(Version):
+    __slots__ = ()
+
+    def __init__(self, version: str | Version) -> None:
+        if isinstance(version, Version):
+            self._epoch = version._epoch
+            self._release = version._release
+            self._dev = version._dev
+            self._pre = version._pre
+            self._post = version._post
+            self._local = version._local
+            self._key_cache = version._key_cache
+            return
+        super().__init__(version)  # pragma: no cover
+
+    @property
+    def release(self) -> tuple[int, ...]:
+        """
+        Release segment without any trailing zeros.
+
+        >>> _TrimmedRelease('1.0.0').release
+        (1,)
+        >>> _TrimmedRelease('0.0').release
+        (0,)
+        """
+        # This leaves one 0.
+        rel = super().release
+        len_release = len(rel)
+        i = len_release
+        while i > 1 and rel[i - 1] == 0:
+            i -= 1
+        return rel if i == len_release else rel[:i]
+
+
+def _parse_letter_version(
+    letter: str | None, number: str | bytes | SupportsInt | None
+) -> tuple[str, int] | None:
+    if letter:
+        # We normalize any letters to their lower case form
+        letter = letter.lower()
+
+        # We consider some words to be alternate spellings of other words and
+        # in those cases we want to normalize the spellings to our preferred
+        # spelling.
+        letter = _LETTER_NORMALIZATION.get(letter, letter)
+
+        # We consider there to be an implicit 0 in a pre-release if there is
+        # not a numeral associated with it.
+        return letter, int(number or 0)
+
+    if number:
+        # We assume if we are given a number, but we are not given a letter
+        # then this is using the implicit post release syntax (e.g. 1.0-1)
+        return "post", int(number)
+
+    return None
+
+
+_local_version_separators = re.compile(r"[\._-]")
+
+
+def _parse_local_version(local: str | None) -> LocalType | None:
+    """
+    Takes a string like ``"abc.1.twelve"`` and turns it into
+    ``("abc", 1, "twelve")``.
+    """
+    if local is not None:
+        return tuple(
+            part.lower() if not part.isdigit() else int(part)
+            for part in _local_version_separators.split(local)
+        )
+    return None
+
+
+# Sort ranks for pre-release: dev-only < a < b < rc < stable (no pre-release).
+_PRE_RANK = {"a": 0, "b": 1, "rc": 2}
+_PRE_RANK_DEV_ONLY = -1  # sorts before a(0)
+_PRE_RANK_STABLE = 3  # sorts after rc(2)
+
+# In local version segments, strings sort before ints per PEP 440.
+_LOCAL_STR_RANK = -1  # sorts before all non-negative ints
+
+# Pre-computed suffix for stable releases (no pre, post, or dev segments).
+# See _cmpkey() for the suffix layout.
+_STABLE_SUFFIX = (_PRE_RANK_STABLE, 0, 0, 0, 1, 0)
+
+
+def _cmpkey(
+    epoch: int,
+    release: tuple[int, ...],
+    pre: tuple[str, int] | None,
+    post: tuple[str, int] | None,
+    dev: tuple[str, int] | None,
+    local: LocalType | None,
+) -> CmpKey:
+    """Build a comparison key for PEP 440 ordering.
+
+    Returns ``(epoch, release, suffix)`` or
+    ``(epoch, release, suffix, local)`` so that plain tuple
+    comparison gives the correct order.
+
+    Trailing zeros are stripped from the release so that ``1.0.0 == 1``.
+
+    The suffix is a flat 6-int tuple that encodes pre/post/dev:
+    ``(pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)``
+
+    pre_rank: dev-only=-1, a=0, b=1, rc=2, no-pre=3
+        Dev-only releases (no pre or post) get -1 so they sort before
+        any alpha/beta/rc.  Releases without a pre-release tag get 3
+        so they sort after rc.
+    post_rank: no-post=0, post=1
+        Releases without a post segment sort before those with one.
+    dev_rank: dev=0, no-dev=1
+        Releases without a dev segment sort after those with one.
+
+    Local segments use ``(n, "")`` for ints and ``(-1, s)`` for strings,
+    following PEP 440: strings sort before ints, strings compare
+    lexicographically, ints compare numerically, and shorter segments
+    sort before longer when prefixes match.  Versions without a local
+    segment sort before those with one (3-tuple < 4-tuple).
+
+    >>> _cmpkey(0, (1, 0, 0), None, None, None, None)
+    (0, (1,), (3, 0, 0, 0, 1, 0))
+    >>> _cmpkey(0, (1,), ("a", 1), None, None, None)
+    (0, (1,), (0, 1, 0, 0, 1, 0))
+    >>> _cmpkey(0, (1,), None, None, None, ("ubuntu", 1))
+    (0, (1,), (3, 0, 0, 0, 1, 0), ((-1, 'ubuntu'), (1, '')))
+    """
+    # Strip trailing zeros: 1.0.0 compares equal to 1.
+    len_release = len(release)
+    i = len_release
+    while i and release[i - 1] == 0:
+        i -= 1
+    trimmed = release if i == len_release else release[:i]
+
+    # Fast path: stable release with no local segment.
+    if pre is None and post is None and dev is None and local is None:
+        return epoch, trimmed, _STABLE_SUFFIX
+
+    if pre is None and post is None and dev is not None:
+        # dev-only (e.g. 1.0.dev1) sorts before all pre-releases.
+        pre_rank, pre_n = _PRE_RANK_DEV_ONLY, 0
+    elif pre is None:
+        pre_rank, pre_n = _PRE_RANK_STABLE, 0
+    else:
+        pre_rank, pre_n = _PRE_RANK[pre[0]], pre[1]
+
+    post_rank = 0 if post is None else 1
+    post_n = 0 if post is None else post[1]
+
+    dev_rank = 1 if dev is None else 0
+    dev_n = 0 if dev is None else dev[1]
+
+    suffix = (pre_rank, pre_n, post_rank, post_n, dev_rank, dev_n)
+
+    if local is None:
+        return epoch, trimmed, suffix
+
+    cmp_local: CmpLocalType = tuple(
+        (seg, "") if isinstance(seg, int) else (_LOCAL_STR_RANK, seg) for seg in local
+    )
+    return epoch, trimmed, suffix, cmp_local
diff --git a/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/INSTALLER b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/INSTALLER
@@ -0,0 +1 @@
+conda
\ No newline at end of file
diff --git a/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/LICENSE b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..eb23dca86fa1737cd203b29ccd7077625ad532d8
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/LICENSE
@@ -0,0 +1,19 @@
+Copyright (c) 2007-2012 Christoph Haas 
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/METADATA b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..ddb0981eca1ab8c3d185244759c6e61984dc5cfc
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/METADATA
@@ -0,0 +1,257 @@
+Metadata-Version: 2.1
+Name: paginate
+Version: 0.5.7
+Summary: Divides large result sets into pages for easier browsing
+Home-page: https://github.com/Signum/paginate
+Author: Christoph Haas
+Author-email: email@christoph-haas.de
+License: MIT
+Keywords: pagination paginate pages
+Classifier: Programming Language :: Python
+Classifier: Development Status :: 4 - Beta
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Framework :: Pyramid
+Classifier: Framework :: Flask
+Classifier: Framework :: Pylons
+Classifier: Framework :: Django
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Provides-Extra: dev
+Requires-Dist: pytest; extra == "dev"
+Requires-Dist: tox; extra == "dev"
+Provides-Extra: lint
+Requires-Dist: black; extra == "lint"
+
+What is pagination?
+---------------------
+This module helps dividing large lists of items into pages. The user is shown one page at a time and
+can navigate to other pages. Imagine you are offering a company phonebook and let the user search
+the entries. If the search result contains 23 entries but you may want to display no more than 10
+entries at once. The first page contains entries 1-10, the second 11-20 and the third 21-23. See the
+documentation of the "Page" class for more information. 
+
+How do I use this module?
+---------------------------
+The paginate module contains extensive in-line documentation with examples.
+
+Concerning WebHelpers
+-----------------------
+This is a standalone module. Former versions were included in the WebHelpers Python module as
+webhelpers.paginate and were tightly coupled with the WebHelpers and the Pylons web framework. This
+version aims to be useful independent of any web framework.
+
+Subclassing Page()
+------------------
+This module supports pagination through list-like objects. To paginate though other types of objects
+you can subclass the paginate.Page() class and provide a wrapper class that defines how to access
+elements of that special collection.
+
+You can find examples in other paginate_* modules like paginate_sqlalchemy. Basically you would have
+to provide a class that implements the __init__, __getitem__ and __len__ methods.
+
+It is trivial to make pagination for other datastores like Elasticsearch/Solr extending the base class.
+
+Example::
+
+    class SqlalchemyOrmWrapper(object):
+        """Wrapper class to access elements of a collection."""
+        def __init__(self, obj):
+            self.obj = obj
+
+        def __getitem__(self, range):
+            # Return a range of objects of an sqlalchemy.orm.query.Query object
+            return self.obj[range]
+
+        def __len__(self):
+            # Count the number of objects in an sqlalchemy.orm.query.Query object
+            return self.obj.count()
+
+Then you can create your own Page class that uses the above wrapper class::
+
+    class SqlalchemyOrmPage(paginate.Page):
+        """A pagination page that deals with SQLAlchemy ORM objects."""
+        def __init__(self, *args, **kwargs):
+            super(SqlalchemyOrmPage, self).__init__(*args, wrapper_class=SqlalchemyOrmWrapper, **kwargs)
+    
+As you can see it does not do much. It basically calls paginate.Page.__init__ and adds
+wrapper_class=SqlalchemyOrmWrapper as an argument. The paginate.Page instance will use that wrapper
+class to access the elements.
+
+
+Generating HTML code for current page
+-------------------------------------
+
+Example::
+
+    p = paginate.Page([], page=15, items_per_page=15, item_count=1010)
+    # item_count is optional, but we pass a dummy empty resultset for this example
+    pattern = '$link_first $link_previous ~4~ $link_next $link_last (Page $page our of $page_count - total $item_count)'
+    p.pager(pattern, url='http://foo.com?x=$page', dotdot_attr={'x':5}, link_attr={'y':6}, curpage_attr={'z':77})
+    # *_attr arguments are optional and can be used to attach additional classes/attrs to tags
+
+
+Results in::
+
+    '<< < 1 .. 11 12 13 14 15 16 17 18 19 .. 68 > >> (Page 15 our of 68 - total items 1010)'
+
+Using url maker to generate links to specific result ranges
+-----------------------------------------------------------
+
+You can pass `url_maker` Callback to generate the URL of other pages, given its numbers.
+Must accept one int parameter and return a URI string.
+
+Example::
+
+    def url_maker(page_number):
+        return str('foo/%s' % page_number)
+    page = paginate.Page(range(100), page=1, url_maker=url_maker)
+    eq_(page.pager(), '1 2 3 .. 5')
+
+
+
+Alternatively if you will not pass the link builder function, the pager() method can also accept `url` argument that contains URL that page links will point to.
+Make sure it contains the string $page which will be replaced by the actual page number.
+Must be given unless a url_maker is specified to __init__, in which case this parameter is ignored.
+
+Using link information for custom paginator templates
+-----------------------------------------------------
+
+If you do not like the default HTML format produced by paginator you can use link_map() function to generate
+a dictionary of links you can use in your own template.
+
+Example::
+
+    p.link_map('$link_first $link_previous ~4~ $link_next $link_last (Page $page our of $page_count - total items $item_count)',url='URL?x=$page',dotdot_attr={'class':'D'}, link_attr={'class':"L"}, curpage_attr={'class':"C"})
+
+Returns something like::
+
+    {'current_page': {'attrs': {'class': 'C'}, 'href': 'URL?x=15', 'value': 15},
+     'first_page': {'attrs': {'class': 'L'}, 'href': 'URL?x=1', 'type': 'first_page', 'value': 1},
+     'last_page': {'attrs': {'class': 'L'}, 'href': 'URL?x=68', 'type': 'last_page', 'value': 68},
+     'next_page': {'attrs': {'class': 'L'}, 'href': 'URL?x=16', 'type': 'next_page', 'value': 16},
+     'previous_page': {'attrs': {'class': 'L'}, 'href': 'URL?x=14', 'type': 'previous_page', 'value': 14},
+     'range_pages': [{'attrs': {'class': 'D'}, 'href': '', 'type': 'span', 'value': '..'},
+      {'attrs': {'class': 'L'}, 'href': 'URL?x=11', 'type': 'page', 'value': '11'},
+      {'attrs': {'class': 'L'}, 'href': 'URL?x=12', 'type': 'page', 'value': '12'},
+      {'attrs': {'class': 'L'}, 'href': 'URL?x=13', 'type': 'page', 'value': '13'},
+      {'attrs': {'class': 'L'}, 'href': 'URL?x=14', 'type': 'page', 'value': '14'},
+      {'attrs': {'class': 'C'}, 'href': 'URL?x=15', 'type': 'current_page', 'value': 15},
+      {'attrs': {'class': 'L'}, 'href': 'URL?x=16', 'type': 'page', 'value': '16'},
+      {'attrs': {'class': 'L'}, 'href': 'URL?x=17', 'type': 'page', 'value': '17'},
+      {'attrs': {'class': 'L'}, 'href': 'URL?x=18', 'type': 'page', 'value': '18'},
+      {'attrs': {'class': 'L'}, 'href': 'URL?x=19', 'type': 'page', 'value': '19'},
+      {'attrs': {'class': 'D'}, 'href': '', 'type': 'span', 'value': '..'}],
+      'radius': 4}
+
+
+Using link_tag callable to generate custom link markup
+------------------------------------------------------
+
+In case you want to generate custom link markup for your project - for example for use with bootstrap,
+`pager()` accepts `link_tag` argument that expects a callable that can be used to easily override the way links are
+generated.
+
+
+Example::
+
+    from paginate import Page, make_html_tag
+
+    def paginate_link_tag(item):
+        """
+        Create an A-HREF tag that points to another page usable in paginate.
+        """
+        a_tag = Page.default_link_tag(item)
+        if item['type'] == 'current_page':
+            return make_html_tag('li', a_tag, **{'class':'active'})
+        return make_html_tag('li', a_tag)
+
+    paginator.pager(
+    curpage_attr={'class':'current_page'},
+    dotdot_attr={'class':'spacer'},
+    symbol_first='',
+    symbol_last='',
+    symbol_previous='',
+    symbol_next='',
+    link_tag=paginate_link_tag)
+
+
+
+Version 0.5.6 - 2016-11-22
+--------------------------
+Changes:
+- Fixed metadata for pypi
+
+Version 0.5.5 - 2016-11-22
+--------------------------
+Changes:
+- Python 2.7/3.4+ compatibility improvements
+
+Version 0.5.4 - 2016-04-25
+--------------------------
+Changes:
+- Added radius size config option
+
+
+Version 0.5.3 - 2016-03-09
+--------------------------
+Changes:
+- Unocode related fixes
+
+Version 0.5.2 - 2015-08-29
+--------------------------
+Changes:
+- Handle the slice prior to handling the length - for better experience with
+  various databases that include item count in results
+- bugfixes
+
+Version 0.5.1 - 2015-10-22
+--------------------------
+Changes:
+- bugfixes
+
+
+Version 0.5.0 - 2015-08-29
+--------------------------
+Changes:
+- link_tag callable can now be passed to generate custom link markup
+- page object now has link_map() method that returns a mapping of information useful for generating
+  custom markup based on paginator data
+
+Version 0.4.0 - 2012-12-06
+--------------------------
+Paginate has prior been maintained as webhelpers.paginate in the _webhelpers_ packages.
+This version is a standalone version that should be useful outside of the webhelpers'
+context.
+
+Changes:
+- Python 3 compatibility.
+- SQLAlchemyObject and SQLAlchemyQuery collections are not automatically detected any more.
+  Instead you can use the respective Page class from the paginate_sqlalchemy module also
+  available on PyPi.
+- presliced_list parameter no longer supported
+- 'page_nr' and 'current_page' had been deprecated already and are now removed. Please use 'page'
+  instead.
+- No automatic URL generation. You need to pass a 'url' argument to the Page.pager() method
+  containing a $page placeholder where you want the page number to be put in. Beware that the URL
+  is not quote-escaped any further.
+- The Page.pager() does not automatically add CSS classes any more. If you want the old
+  behavior you need to pass these parameters explicitly:
+  link_attr={'class':'pager_link'}
+  curpage_attr={'class':'pager_curpage'}
+  dotdot_attr={'class':'pager_dotdot'}
+- The partial_param parameter from Page.pager() is gone. You should use your own URLs for
+  AJAX/partial updates in the 'url' parameter.
+- The page_param parameter from Page.pager() is also gone as URL generation has been severely
+  simplified.
+- The string returned from Page.pager() consists of escaped HTML already. So you need to tell
+  your web framework to use the string verbatim and without further escaping.
+  The parameters symbol_first, symbol_last, symbol_previous and symbol_next use
+  < and > instead of "<" and ">" now.
+- Page.__repr__ now returns a brief representation. E.g. 
+  Page.__str__ returns the verbose view you may be used to.
+
+Version 0.3.2 - 2008-01-31
+--------------------------
+Public release on PyPi
diff --git a/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/RECORD b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..d6ff34ab12b464cccea053aa99dc94390d2e13a5
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/RECORD
@@ -0,0 +1,12 @@
+paginate-0.5.7.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+paginate-0.5.7.dist-info/LICENSE,sha256=NS5bJ2ki8uNikxu-0tzS6UMxpFtqQaG0ZagwCt3MFVM,1089
+paginate-0.5.7.dist-info/METADATA,sha256=IXhPrBnV1Vh-U1NFr1wC8JOmsc1AZmZJhgf6tpRAIzw,11403
+paginate-0.5.7.dist-info/RECORD,,
+paginate-0.5.7.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+paginate-0.5.7.dist-info/WHEEL,sha256=pxeNX5JdtCe58PUSYP9upmc7jdRPgvT0Gm9kb1SHlVw,109
+paginate-0.5.7.dist-info/direct_url.json,sha256=qsSV3jpcg21ItWyyw8nZKSDK7zd9gB5JQ5rD5Hg_iZo,104
+paginate-0.5.7.dist-info/top_level.txt,sha256=V11BSlhXV51xs_pyEUTJlxmHjRaF4J63Mz8c4_cVBjI,9
+paginate/__init__.py,sha256=S5VN_fIJSP_sp6FS8p1ZWJN_4jxjBBEBIKKX_zmo5qM,31945
+paginate/__pycache__/__init__.cpython-39.pyc,,
+paginate/__pycache__/ext_reverse.cpython-39.pyc,,
+paginate/ext_reverse.py,sha256=rdxUjUblCqsbdjk1LynStRzG6RTxn1H1_Z5UVhMjnx4,413
diff --git a/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/REQUESTED b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/WHEEL b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..104f3874635f24f0d2918dfeaf6a59652274460c
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/WHEEL
@@ -0,0 +1,6 @@
+Wheel-Version: 1.0
+Generator: setuptools (75.6.0)
+Root-Is-Purelib: true
+Tag: py2-none-any
+Tag: py3-none-any
+
diff --git a/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/direct_url.json b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/direct_url.json
new file mode 100644
index 0000000000000000000000000000000000000000..d6e0cde07896a6531cbf6e276747b495d2212744
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/direct_url.json
@@ -0,0 +1 @@
+{"dir_info": {}, "url": "file:///home/conda/feedstock_root/build_artifacts/paginate_1734618550153/work"}
\ No newline at end of file
diff --git a/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/top_level.txt b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..797db53e22e17766a2892ae626fd04431ae7ff93
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/paginate-0.5.7.dist-info/top_level.txt
@@ -0,0 +1 @@
+paginate
diff --git a/micromamba_root/Lib/site-packages/paginate/__init__.py b/micromamba_root/Lib/site-packages/paginate/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..52e2c3ac3c712312d46194cc04ec46a68940557c
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/paginate/__init__.py
@@ -0,0 +1,863 @@
+# Copyright (c) 2007-2012 Christoph Haas 
+# See the file LICENSE for copying permission.
+
+"""
+paginate: helps split up large collections into individual pages
+================================================================
+
+What is pagination?
+---------------------
+
+This module helps split large lists of items into pages. The user is shown one page at a time and
+can navigate to other pages. Imagine you are offering a company phonebook and let the user search
+the entries. The entire search result may contains 23 entries but you want to display no more than
+10 entries at once. The first page contains entries 1-10, the second 11-20 and the third 21-23.
+Each "Page" instance represents the items of one of these three pages.
+
+See the documentation of the "Page" class for more information.
+
+How do I use it?
+------------------
+
+A page of items is represented by the *Page* object. A *Page* gets initialized with these arguments:
+
+- The collection of items to pick a range from. Usually just a list.
+- The page number you want to display. Default is 1: the first page.
+
+Now we can make up a collection and create a Page instance of it::
+
+    # Create a sample collection of 1000 items
+    >> my_collection = range(1000)
+
+    # Create a Page object for the 3rd page (20 items per page is the default)
+    >> my_page = Page(my_collection, page=3)
+
+    # The page object can be printed as a string to get its details
+    >> str(my_page)
+    Page:
+    Collection type:  
+    Current page:     3
+    First item:       41
+    Last item:        60
+    First page:       1
+    Last page:        50
+    Previous page:    2
+    Next page:        4
+    Items per page:   20
+    Number of items:  1000
+    Number of pages:  50
+
+    # Print a list of items on the current page
+    >> my_page.items
+    [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
+
+    # The *Page* object can be used as an iterator:
+    >> for my_item in my_page: print(my_item)
+    40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
+
+    # The .pager() method returns an HTML fragment with links to surrounding pages.
+    >> my_page.pager(url="http://example.org/foo/page=$page")
+
+    1
+    2
+    3
+    4
+    5
+    ..
+    50'
+
+    # Without the HTML it would just look like:
+    # 1 2 [3] 4 5 .. 50
+
+    # The pager can be customized:
+    >> my_page.pager('$link_previous ~3~ $link_next (Page $page of $page_count)',
+                     url="http://example.org/foo/page=$page")
+
+    <
+    1
+    2
+    3
+    4
+    5
+    6
+    ..
+    50
+    >
+    (Page 3 of 50)
+
+    # Without the HTML it would just look like:
+    # 1 2 [3] 4 5 6 .. 50 > (Page 3 of 50)
+
+    # The url argument to the pager method can be omitted when an url_maker is
+    # given during instantiation:
+    >> my_page = Page(my_collection, page=3,
+                      url_maker=lambda p: "http://example.org/%s" % p)
+    >> page.pager()
+
+There are some interesting parameters that customize the Page's behavior. See the documentation on
+``Page`` and ``Page.pager()``.
+
+
+Notes
+-------
+
+Page numbers and item numbers start at 1. This concept has been used because users expect that the
+first page has number 1 and the first item on a page also has number 1. So if you want to use the
+page's items by their index number please note that you have to subtract 1.
+"""
+
+__author__ = "Christoph Haas"
+__copyright__ = "Copyright 2007-2016 Christoph Haas and contributors"
+__credits__ = ["Mike Orr"]
+__license__ = "MIT"
+__version__ = "0.5.4"
+__maintainer__ = "Marcin Lulek, Luke Crooks"
+__email__ = "info@webreactor.eu, luke@pumalo.org"
+__status__ = "Beta"
+
+
+import re
+from string import Template
+import sys
+
+# are we running at least python 3.x ?
+PY3 = sys.version_info[0] >= 3
+
+if PY3:
+    unicode = str
+
+
+# Since the items on a page are mainly a list we subclass the "list" type
+class Page(list):
+    """A list/iterator representing the items on one page of a larger collection.
+
+    An instance of the "Page" class is created from a _collection_ which is any
+    list-like object that allows random access to its elements.
+
+    The instance works as an iterator running from the first item to the last item on the given
+    page. The Page.pager() method creates a link list allowing the user to go to other pages.
+
+    A "Page" does not only carry the items on a certain page. It gives you additional information
+    about the page in these "Page" object attributes:
+
+    item_count
+        Number of items in the collection
+
+        **WARNING:** Unless you pass in an item_count, a count will be
+        performed on the collection every time a Page instance is created.
+
+    page
+        Number of the current page
+
+    items_per_page
+        Maximal number of items displayed on a page
+
+    first_page
+        Number of the first page - usually 1 :)
+
+    last_page
+        Number of the last page
+
+    previous_page
+        Number of the previous page. If this is the first page it returns None.
+
+    next_page
+        Number of the next page. If this is the last page it returns None.
+
+    page_count
+        Number of pages
+
+    items
+        Sequence/iterator of items on the current page
+
+    first_item
+        Index of first item on the current page - starts with 1
+
+    last_item
+        Index of last item on the current page
+    """
+
+    def __init__(
+        self,
+        collection,
+        page=1,
+        items_per_page=20,
+        item_count=None,
+        wrapper_class=None,
+        url_maker=None,
+        **kwargs
+    ):
+        """Create a "Page" instance.
+
+        Parameters:
+
+        collection
+            Sequence representing the collection of items to page through.
+
+        page
+            The requested page number - starts with 1. Default: 1.
+
+        items_per_page
+            The maximal number of items to be displayed per page.
+            Default: 20.
+
+        item_count (optional)
+            The total number of items in the collection - if known.
+            If this parameter is not given then the paginator will count
+            the number of elements in the collection every time a "Page"
+            is created. Giving this parameter will speed up things. In a busy
+            real-life application you may want to cache the number of items.
+
+        url_maker (optional)
+            Callback to generate the URL of other pages, given its numbers.
+            Must accept one int parameter and return a URI string.
+        """
+        if collection is not None:
+            if wrapper_class is None:
+                # Default case. The collection is already a list-type object.
+                self.collection = collection
+            else:
+                # Special case. A custom wrapper class is used to access elements of the collection.
+                self.collection = wrapper_class(collection)
+        else:
+            self.collection = []
+
+        self.collection_type = type(collection)
+
+        if url_maker is not None:
+            self.url_maker = url_maker
+        else:
+            self.url_maker = self._default_url_maker
+
+        # Assign kwargs to self
+        self.kwargs = kwargs
+
+        # The self.page is the number of the current page.
+        # The first page has the number 1!
+        try:
+            self.page = int(page)  # make it int() if we get it as a string
+        except (ValueError, TypeError):
+            self.page = 1
+        # normally page should be always at least 1 but the original maintainer
+        # decided that for empty collection and empty page it can be...0? (based on tests)
+        # preserving behavior for BW compat
+        if self.page < 1:
+            self.page = 1
+
+        self.items_per_page = items_per_page
+
+        # We subclassed "list" so we need to call its init() method
+        # and fill the new list with the items to be displayed on the page.
+        # We use list() so that the items on the current page are retrieved
+        # only once. In an SQL context that could otherwise lead to running the
+        # same SQL query every time items would be accessed.
+        # We do this here, prior to calling len() on the collection so that a
+        # wrapper class can execute a query with the knowledge of what the
+        # slice will be (for efficiency) and, in the same query, ask for the
+        # total number of items and only execute one query.
+        try:
+            first = (self.page - 1) * items_per_page
+            last = first + items_per_page
+            self.items = list(self.collection[first:last])
+        except (KeyError, TypeError) as exc:
+            raise TypeError(
+                "Your collection of type {} cannot be handled "
+                "by paginate.".format(type(self.collection))
+            )
+
+        # Unless the user tells us how many items the collections has
+        # we calculate that ourselves.
+        if item_count is not None:
+            self.item_count = item_count
+        else:
+            self.item_count = len(self.collection)
+
+        # Compute the number of the first and last available page
+        if self.item_count > 0:
+            self.first_page = 1
+            self.page_count = ((self.item_count - 1) // self.items_per_page) + 1
+            self.last_page = self.first_page + self.page_count - 1
+
+            # Make sure that the requested page number is the range of valid pages
+            if self.page > self.last_page:
+                self.page = self.last_page
+            elif self.page < self.first_page:
+                self.page = self.first_page
+
+            # Note: the number of items on this page can be less than
+            #       items_per_page if the last page is not full
+            self.first_item = (self.page - 1) * items_per_page + 1
+            self.last_item = min(self.first_item + items_per_page - 1, self.item_count)
+
+            # Links to previous and next page
+            if self.page > self.first_page:
+                self.previous_page = self.page - 1
+            else:
+                self.previous_page = None
+
+            if self.page < self.last_page:
+                self.next_page = self.page + 1
+            else:
+                self.next_page = None
+
+        # No items available
+        else:
+            self.first_page = None
+            self.page_count = 0
+            self.last_page = None
+            self.first_item = None
+            self.last_item = None
+            self.previous_page = None
+            self.next_page = None
+            self.items = []
+
+        # This is a subclass of the 'list' type. Initialise the list now.
+        list.__init__(self, self.items)
+
+    def __str__(self):
+        return (
+            "Page:\n"
+            "Collection type:        {0.collection_type}\n"
+            "Current page:           {0.page}\n"
+            "First item:             {0.first_item}\n"
+            "Last item:              {0.last_item}\n"
+            "First page:             {0.first_page}\n"
+            "Last page:              {0.last_page}\n"
+            "Previous page:          {0.previous_page}\n"
+            "Next page:              {0.next_page}\n"
+            "Items per page:         {0.items_per_page}\n"
+            "Total number of items:  {0.item_count}\n"
+            "Number of pages:        {0.page_count}\n"
+        ).format(self)
+
+    def __repr__(self):
+        return "".format(self.page, self.page_count)
+
+    def pager(
+        self,
+        format="~2~",
+        url=None,
+        show_if_single_page=False,
+        separator=" ",
+        symbol_first="<<",
+        symbol_last=">>",
+        symbol_previous="<",
+        symbol_next=">",
+        link_attr=None,
+        curpage_attr=None,
+        dotdot_attr=None,
+        link_tag=None,
+    ):
+        """
+        Return string with links to other pages (e.g. '1 .. 5 6 7 [8] 9 10 11 .. 50').
+
+        format:
+            Format string that defines how the pager is rendered. The string
+            can contain the following $-tokens that are substituted by the
+            string.Template module:
+
+            - $first_page: number of first reachable page
+            - $last_page: number of last reachable page
+            - $page: number of currently selected page
+            - $page_count: number of reachable pages
+            - $items_per_page: maximal number of items per page
+            - $first_item: index of first item on the current page
+            - $last_item: index of last item on the current page
+            - $item_count: total number of items
+            - $link_first: link to first page (unless this is first page)
+            - $link_last: link to last page (unless this is last page)
+            - $link_previous: link to previous page (unless this is first page)
+            - $link_next: link to next page (unless this is last page)
+
+            To render a range of pages the token '~3~' can be used. The
+            number sets the radius of pages around the current page.
+            Example for a range with radius 3:
+
+            '1 .. 5 6 7 [8] 9 10 11 .. 50'
+
+            Default: '~2~'
+
+        url
+            The URL that page links will point to. Make sure it contains the string
+            $page which will be replaced by the actual page number.
+            Must be given unless a url_maker is specified to __init__, in which
+            case this parameter is ignored.
+
+        symbol_first
+            String to be displayed as the text for the $link_first link above.
+
+            Default: '<<' (<<)
+
+        symbol_last
+            String to be displayed as the text for the $link_last link above.
+
+            Default: '>>' (>>)
+
+        symbol_previous
+            String to be displayed as the text for the $link_previous link above.
+
+            Default: '<' (<)
+
+        symbol_next
+            String to be displayed as the text for the $link_next link above.
+
+            Default: '>' (>)
+
+        separator:
+            String that is used to separate page links/numbers in the above range of pages.
+
+            Default: ' '
+
+        show_if_single_page:
+            if True the navigator will be shown even if there is only one page.
+
+            Default: False
+
+        link_attr (optional)
+            A dictionary of attributes that get added to A-HREF links pointing to other pages. Can
+            be used to define a CSS style or class to customize the look of links.
+
+            Example: { 'style':'border: 1px solid green' }
+            Example: { 'class':'pager_link' }
+
+        curpage_attr (optional)
+            A dictionary of attributes that get added to the current page number in the pager (which
+            is obviously not a link). If this dictionary is not empty then the elements will be
+            wrapped in a SPAN tag with the given attributes.
+
+            Example: { 'style':'border: 3px solid blue' }
+            Example: { 'class':'pager_curpage' }
+
+        dotdot_attr (optional)
+            A dictionary of attributes that get added to the '..' string in the pager (which is
+            obviously not a link). If this dictionary is not empty then the elements will be wrapped
+            in a SPAN tag with the given attributes.
+
+            Example: { 'style':'color: #808080' }
+            Example: { 'class':'pager_dotdot' }
+
+        link_tag (optional)
+            A callable that accepts single argument `page` (page link information)
+            and generates string with html that represents the link for specific page.
+            Page objects are supplied from `link_map()` so the keys are the same.
+
+
+        """
+        link_attr = link_attr or {}
+        curpage_attr = curpage_attr or {}
+        dotdot_attr = dotdot_attr or {}
+        self.curpage_attr = curpage_attr
+        self.separator = separator
+        self.link_attr = link_attr
+        self.dotdot_attr = dotdot_attr
+        self.url = url
+        self.link_tag = link_tag or self.default_link_tag
+
+        # Don't show navigator if there is no more than one page
+        if self.page_count == 0 or (self.page_count == 1 and not show_if_single_page):
+            return ""
+
+        regex_res = re.search(r"~(\d+)~", format)
+        if regex_res:
+            radius = regex_res.group(1)
+        else:
+            radius = 2
+        radius = int(radius)
+        self.radius = radius
+        link_map = self.link_map(
+            format=format,
+            url=url,
+            show_if_single_page=show_if_single_page,
+            separator=separator,
+            symbol_first=symbol_first,
+            symbol_last=symbol_last,
+            symbol_previous=symbol_previous,
+            symbol_next=symbol_next,
+            link_attr=link_attr,
+            curpage_attr=curpage_attr,
+            dotdot_attr=dotdot_attr,
+        )
+        links_markup = self._range(link_map, radius)
+
+        # Replace ~...~ in token format by range of pages
+        result = re.sub(r"~(\d+)~", links_markup, format)
+
+        link_first = (
+            self.page > self.first_page and self.link_tag(link_map["first_page"]) or ""
+        )
+        link_last = (
+            self.page < self.last_page and self.link_tag(link_map["last_page"]) or ""
+        )
+        link_previous = (
+            self.previous_page and self.link_tag(link_map["previous_page"]) or ""
+        )
+        link_next = self.next_page and self.link_tag(link_map["next_page"]) or ""
+        # Interpolate '$' variables
+        result = Template(result).safe_substitute(
+            {
+                "first_page": self.first_page,
+                "last_page": self.last_page,
+                "page": self.page,
+                "page_count": self.page_count,
+                "items_per_page": self.items_per_page,
+                "first_item": self.first_item,
+                "last_item": self.last_item,
+                "item_count": self.item_count,
+                "link_first": link_first,
+                "link_last": link_last,
+                "link_previous": link_previous,
+                "link_next": link_next,
+            }
+        )
+
+        return result
+
+    def link_map(
+        self,
+        format="~2~",
+        url=None,
+        show_if_single_page=False,
+        separator=" ",
+        symbol_first="<<",
+        symbol_last=">>",
+        symbol_previous="<",
+        symbol_next=">",
+        link_attr=None,
+        curpage_attr=None,
+        dotdot_attr=None,
+    ):
+        """ Return map with links to other pages if default pager() function is not suitable solution.
+        format:
+            Format string that defines how the pager would be normally rendered rendered. Uses same arguments as pager()
+            method, but returns a simple dictionary in form of:
+            {'current_page': {'attrs': {},
+                                     'href': 'http://example.org/foo/page=1',
+                                     'value': 1},
+                    'first_page': {'attrs': {},
+                                   'href': 'http://example.org/foo/page=1',
+                                   'type': 'first_page',
+                                   'value': 1},
+                    'last_page': {'attrs': {},
+                                  'href': 'http://example.org/foo/page=8',
+                                  'type': 'last_page',
+                                  'value': 8},
+                    'next_page': {'attrs': {}, 'href': 'HREF', 'type': 'next_page', 'value': 2},
+                    'previous_page': None,
+                    'range_pages': [{'attrs': {},
+                                     'href': 'http://example.org/foo/page=1',
+                                     'type': 'current_page',
+                                     'value': 1},
+                                     ....
+                                    {'attrs': {}, 'href': '', 'type': 'span', 'value': '..'}]}
+
+
+            The string can contain the following $-tokens that are substituted by the
+            string.Template module:
+
+            - $first_page: number of first reachable page
+            - $last_page: number of last reachable page
+            - $page: number of currently selected page
+            - $page_count: number of reachable pages
+            - $items_per_page: maximal number of items per page
+            - $first_item: index of first item on the current page
+            - $last_item: index of last item on the current page
+            - $item_count: total number of items
+            - $link_first: link to first page (unless this is first page)
+            - $link_last: link to last page (unless this is last page)
+            - $link_previous: link to previous page (unless this is first page)
+            - $link_next: link to next page (unless this is last page)
+
+            To render a range of pages the token '~3~' can be used. The
+            number sets the radius of pages around the current page.
+            Example for a range with radius 3:
+
+            '1 .. 5 6 7 [8] 9 10 11 .. 50'
+
+            Default: '~2~'
+
+        url
+            The URL that page links will point to. Make sure it contains the string
+            $page which will be replaced by the actual page number.
+            Must be given unless a url_maker is specified to __init__, in which
+            case this parameter is ignored.
+
+        symbol_first
+            String to be displayed as the text for the $link_first link above.
+
+            Default: '<<' (<<)
+
+        symbol_last
+            String to be displayed as the text for the $link_last link above.
+
+            Default: '>>' (>>)
+
+        symbol_previous
+            String to be displayed as the text for the $link_previous link above.
+
+            Default: '<' (<)
+
+        symbol_next
+            String to be displayed as the text for the $link_next link above.
+
+            Default: '>' (>)
+
+        separator:
+            String that is used to separate page links/numbers in the above range of pages.
+
+            Default: ' '
+
+        show_if_single_page:
+            if True the navigator will be shown even if there is only one page.
+
+            Default: False
+
+        link_attr (optional)
+            A dictionary of attributes that get added to A-HREF links pointing to other pages. Can
+            be used to define a CSS style or class to customize the look of links.
+
+            Example: { 'style':'border: 1px solid green' }
+            Example: { 'class':'pager_link' }
+
+        curpage_attr (optional)
+            A dictionary of attributes that get added to the current page number in the pager (which
+            is obviously not a link). If this dictionary is not empty then the elements will be
+            wrapped in a SPAN tag with the given attributes.
+
+            Example: { 'style':'border: 3px solid blue' }
+            Example: { 'class':'pager_curpage' }
+
+        dotdot_attr (optional)
+            A dictionary of attributes that get added to the '..' string in the pager (which is
+            obviously not a link). If this dictionary is not empty then the elements will be wrapped
+            in a SPAN tag with the given attributes.
+
+            Example: { 'style':'color: #808080' }
+            Example: { 'class':'pager_dotdot' }
+        """
+        link_attr = link_attr or {}
+        curpage_attr = curpage_attr or {}
+        dotdot_attr = dotdot_attr or {}
+        self.curpage_attr = curpage_attr
+        self.separator = separator
+        self.link_attr = link_attr
+        self.dotdot_attr = dotdot_attr
+        self.url = url
+
+        regex_res = re.search(r"~(\d+)~", format)
+        if regex_res:
+            radius = regex_res.group(1)
+        else:
+            radius = 2
+        radius = int(radius)
+        self.radius = radius
+
+        # Compute the first and last page number within the radius
+        # e.g. '1 .. 5 6 [7] 8 9 .. 12'
+        # -> leftmost_page  = 5
+        # -> rightmost_page = 9
+        leftmost_page = (
+            max(self.first_page, (self.page - radius)) if self.first_page else None
+        )
+        rightmost_page = (
+            min(self.last_page, (self.page + radius)) if self.last_page else None
+        )
+
+        nav_items = {
+            "first_page": None,
+            "last_page": None,
+            "previous_page": None,
+            "next_page": None,
+            "current_page": None,
+            "radius": self.radius,
+            "range_pages": [],
+        }
+
+        if leftmost_page is None or rightmost_page is None:
+            return nav_items
+
+        nav_items["first_page"] = {
+            "type": "first_page",
+            "value": unicode(symbol_first),
+            "attrs": self.link_attr,
+            "number": self.first_page,
+            "href": self.url_maker(self.first_page),
+        }
+
+        # Insert dots if there are pages between the first page
+        # and the currently displayed page range
+        if leftmost_page - self.first_page > 1:
+            # Wrap in a SPAN tag if dotdot_attr is set
+            nav_items["range_pages"].append(
+                {
+                    "type": "span",
+                    "value": "..",
+                    "attrs": self.dotdot_attr,
+                    "href": "",
+                    "number": None,
+                }
+            )
+
+        for thispage in range(leftmost_page, rightmost_page + 1):
+            # Highlight the current page number and do not use a link
+            if thispage == self.page:
+                # Wrap in a SPAN tag if curpage_attr is set
+                nav_items["range_pages"].append(
+                    {
+                        "type": "current_page",
+                        "value": unicode(thispage),
+                        "number": thispage,
+                        "attrs": self.curpage_attr,
+                        "href": self.url_maker(thispage),
+                    }
+                )
+                nav_items["current_page"] = {
+                    "value": thispage,
+                    "attrs": self.curpage_attr,
+                    "type": "current_page",
+                    "href": self.url_maker(thispage),
+                }
+            # Otherwise create just a link to that page
+            else:
+                nav_items["range_pages"].append(
+                    {
+                        "type": "page",
+                        "value": unicode(thispage),
+                        "number": thispage,
+                        "attrs": self.link_attr,
+                        "href": self.url_maker(thispage),
+                    }
+                )
+
+        # Insert dots if there are pages between the displayed
+        # page numbers and the end of the page range
+        if self.last_page - rightmost_page > 1:
+            # Wrap in a SPAN tag if dotdot_attr is set
+            nav_items["range_pages"].append(
+                {
+                    "type": "span",
+                    "value": "..",
+                    "attrs": self.dotdot_attr,
+                    "href": "",
+                    "number": None,
+                }
+            )
+
+        # Create a link to the very last page (unless we are on the last
+        # page or there would be no need to insert '..' spacers)
+        nav_items["last_page"] = {
+            "type": "last_page",
+            "value": unicode(symbol_last),
+            "attrs": self.link_attr,
+            "href": self.url_maker(self.last_page),
+            "number": self.last_page,
+        }
+
+        nav_items["previous_page"] = {
+            "type": "previous_page",
+            "value": unicode(symbol_previous),
+            "attrs": self.link_attr,
+            "number": self.previous_page or self.first_page,
+            "href": self.url_maker(self.previous_page or self.first_page),
+        }
+
+        nav_items["next_page"] = {
+            "type": "next_page",
+            "value": unicode(symbol_next),
+            "attrs": self.link_attr,
+            "number": self.next_page or self.last_page,
+            "href": self.url_maker(self.next_page or self.last_page),
+        }
+
+        return nav_items
+
+    def _range(self, link_map, radius):
+        """
+        Return range of linked pages to substitute placeholder in pattern
+        """
+
+        leftmost_page = max(self.first_page, (self.page - radius))
+        rightmost_page = min(self.last_page, (self.page + radius))
+
+        nav_items = []
+        # Create a link to the first page (unless we are on the first page
+        # or there would be no need to insert '..' spacers)
+        if self.page != self.first_page and self.first_page < leftmost_page:
+            page = link_map["first_page"].copy()
+            page["value"] = unicode(page["number"])
+            nav_items.append(self.link_tag(page))
+
+        for item in link_map["range_pages"]:
+            nav_items.append(self.link_tag(item))
+
+        # Create a link to the very last page (unless we are on the last
+        # page or there would be no need to insert '..' spacers)
+        if self.page != self.last_page and rightmost_page < self.last_page:
+            page = link_map["last_page"].copy()
+            page["value"] = unicode(page["number"])
+            nav_items.append(self.link_tag(page))
+
+        return self.separator.join(nav_items)
+
+    def _default_url_maker(self, page_number):
+        if self.url is None:
+            raise Exception(
+                "You need to specify a 'url' parameter containing a '$page' placeholder."
+            )
+
+        if "$page" not in self.url:
+            raise Exception("The 'url' parameter must contain a '$page' placeholder.")
+
+        return self.url.replace("$page", unicode(page_number))
+
+    @staticmethod
+    def default_link_tag(item):
+        """
+        Create an A-HREF tag that points to another page.
+        """
+        text = item["value"]
+        target_url = item["href"]
+
+        if not item["href"] or item["type"] in ("span", "current_page"):
+            if item["attrs"]:
+                text = make_html_tag("span", **item["attrs"]) + text + ""
+            return text
+
+        return make_html_tag("a", text=text, href=target_url, **item["attrs"])
+
+
+def make_html_tag(tag, text=None, **params):
+    """Create an HTML tag string.
+
+    tag
+        The HTML tag to use (e.g. 'a', 'span' or 'div')
+
+    text
+        The text to enclose between opening and closing tag. If no text is specified then only
+        the opening tag is returned.
+
+    Example::
+        make_html_tag('a', text="Hello", href="/another/page")
+        -> Hello
+
+    To use reserved Python keywords like "class" as a parameter prepend it with
+    an underscore. Instead of "class='green'" use "_class='green'".
+
+    Warning: Quotes and apostrophes are not escaped."""
+    params_string = ""
+
+    # Parameters are passed. Turn the dict into a string like "a=1 b=2 c=3" string.
+    for key, value in sorted(params.items()):
+        # Strip off a leading underscore from the attribute's key to allow attributes like '_class'
+        # to be used as a CSS class specification instead of the reserved Python keyword 'class'.
+        key = key.lstrip("_")
+
+        params_string += u' {0}="{1}"'.format(key, value)
+
+    # Create the tag string
+    tag_string = u"<{0}{1}>".format(tag, params_string)
+
+    # Add text and closing tag if required.
+    if text:
+        tag_string += u"{0}".format(text, tag)
+
+    return tag_string
diff --git a/micromamba_root/Lib/site-packages/paginate/ext_reverse.py b/micromamba_root/Lib/site-packages/paginate/ext_reverse.py
new file mode 100644
index 0000000000000000000000000000000000000000..36a6f907969fc7030ad39c38385812d0b59de7fe
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/paginate/ext_reverse.py
@@ -0,0 +1,14 @@
+"""Test class to just return reverse elements in a range"""
+
+import paginate
+
+
+class ReversePage(paginate.Page):
+    # def __init__(self, *args, **kwargs):
+    #     super(ReversePage, self).__init__(*args, **kwargs)
+
+    def __getitem__(self, key):
+        # if isinstance(key, slice):
+        #     return list(reversed(self.collection))[key]
+        # else:
+        return list(reversed(self.collection))[key]
diff --git a/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/INSTALLER b/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..f79e4cb9aaf0b2d9e8ba78861e2071317b2384b3
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/INSTALLER
@@ -0,0 +1 @@
+conda
\ No newline at end of file
diff --git a/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/METADATA b/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..f2d4d6451ba88584ff864bc18bb7852c903b888f
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/METADATA
@@ -0,0 +1,392 @@
+Metadata-Version: 2.4
+Name: pathspec
+Version: 1.1.1
+Summary: Utility library for gitignore style pattern matching of file paths.
+Author-email: "Caleb P. Burns" 
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Topic :: Utilities
+License-File: LICENSE
+Requires-Dist: hyperscan >=0.7 ; extra == "hyperscan"
+Requires-Dist: typing-extensions >=4 ; extra == "optional"
+Requires-Dist: google-re2 >=1.1 ; extra == "re2"
+Project-URL: Change Log, https://python-path-specification.readthedocs.io/en/latest/changes.html
+Project-URL: Documentation, https://python-path-specification.readthedocs.io/en/latest/index.html
+Project-URL: Issue Tracker, https://github.com/cpburnz/python-pathspec/issues
+Project-URL: Source Code, https://github.com/cpburnz/python-pathspec
+Provides-Extra: hyperscan
+Provides-Extra: optional
+Provides-Extra: re2
+
+
+PathSpec
+========
+
+*pathspec* is a utility library for pattern matching of file paths. So far this
+only includes Git's `gitignore`_ pattern matching.
+
+.. _`gitignore`: http://git-scm.com/docs/gitignore
+
+
+Tutorial
+--------
+
+Say you have a "Projects" directory and you want to back it up, but only
+certain files, and ignore others depending on certain conditions::
+
+	>>> from pathspec import PathSpec
+	>>> # The gitignore-style patterns for files to select, but we're including
+	>>> # instead of ignoring.
+	>>> spec_text = """
+	...
+	... # This is a comment because the line begins with a hash: "#"
+	...
+	... # Include several project directories (and all descendants) relative to
+	... # the current directory. To reference only a directory you must end with a
+	... # slash: "/"
+	... /project-a/
+	... /project-b/
+	... /project-c/
+	...
+	... # Patterns can be negated by prefixing with exclamation mark: "!"
+	...
+	... # Ignore temporary files beginning or ending with "~" and ending with
+	... # ".swp".
+	... !~*
+	... !*~
+	... !*.swp
+	...
+	... # These are python projects so ignore compiled python files from
+	... # testing.
+	... !*.pyc
+	...
+	... # Ignore the build directories but only directly under the project
+	... # directories.
+	... !/*/build/
+	...
+	... """
+
+The ``PathSpec`` class provides an abstraction around pattern implementations,
+and we want to compile our patterns as "gitignore" patterns. You could call it a
+wrapper for a list of compiled patterns::
+
+	>>> spec = PathSpec.from_lines('gitignore', spec_text.splitlines())
+
+If we wanted to manually compile the patterns, we can use the ``GitIgnoreBasicPattern``
+class directly. It is used in the background for "gitignore" which internally
+converts patterns to regular expressions::
+
+	>>> from pathspec.patterns.gitignore.basic import GitIgnoreBasicPattern
+	>>> patterns = map(GitIgnoreBasicPattern, spec_text.splitlines())
+	>>> spec = PathSpec(patterns)
+
+``PathSpec.from_lines()`` is a class method which simplifies that.
+
+If you want to load the patterns from file, you can pass the file object
+directly as well::
+
+	>>> with open('patterns.list', 'r') as fh:
+	>>>     spec = PathSpec.from_lines('gitignore', fh)
+
+You can perform matching on a whole directory tree with::
+
+	>>> matches = set(spec.match_tree_files('path/to/directory'))
+
+Or you can perform matching on a specific set of file paths with::
+
+	>>> matches = set(spec.match_files(file_paths))
+
+Or check to see if an individual file matches::
+
+	>>> is_matched = spec.match_file(file_path)
+
+There's actually two implementations of "gitignore". The basic implementation is
+used by ``PathSpec`` and follows patterns as documented by `gitignore`_.
+However, Git's behavior differs from the documented patterns. There's some
+edge-cases, and in particular, Git allows including files from excluded
+directories which appears to contradict the documentation. ``GitIgnoreSpec``
+handles these cases to more closely replicate Git's behavior::
+
+	>>> from pathspec import GitIgnoreSpec
+	>>> spec = GitIgnoreSpec.from_lines(spec_text.splitlines())
+
+You do not specify the style of pattern for ``GitIgnoreSpec`` because it should
+always use ``GitIgnoreSpecPattern`` internally.
+
+
+Performance
+-----------
+
+Running lots of regular expression matches against thousands of files in Python
+is slow. Alternate regular expression backends can be used to improve
+performance. ``PathSpec`` and ``GitIgnoreSpec`` both accept a ``backend``
+parameter to control the backend. The default is "best" to automatically choose
+the best available backend. There are currently 3 backends.
+
+The "simple" backend is the default and it simply uses Python's ``re.Pattern``
+objects that are normally created. This can be the fastest when there's only 1
+or 2 patterns.
+
+The "hyperscan" backend uses the `hyperscan`_ library. Hyperscan tends to be at
+least 2 times faster than "simple", and generally slower than "re2". This can be
+faster than "re2" under the right conditions with pattern counts of 1-25.
+
+The "re2" backend uses the `google-re2`_ library (not to be confused with the
+*re2* library on PyPI which is unrelated and abandoned). Google's re2 tends to
+be significantly faster than "simple", and 3 times faster than "hyperscan" at
+high pattern counts.
+
+See `benchmarks_backends.md`_ for comparisons between native Python regular
+expressions and the optional backends.
+
+
+.. _`benchmarks_backends.md`: https://github.com/cpburnz/python-pathspec/blob/master/benchmarks_backends.md
+.. _`google-re2`: https://pypi.org/project/google-re2/
+.. _`hyperscan`: https://pypi.org/project/hyperscan/
+
+
+FAQ
+---
+
+
+1. How do I ignore files like *.gitignore*?
++++++++++++++++++++++++++++++++++++++++++++
+
+``GitIgnoreSpec`` (and ``PathSpec``) positively match files by default. To find
+the files to keep, and exclude files like *.gitignore*, you need to set
+``negate=True`` to flip the results::
+
+	>>> from pathspec import GitIgnoreSpec
+	>>> spec = GitIgnoreSpec.from_lines([...])
+	>>> keep_files = set(spec.match_tree_files('path/to/directory', negate=True))
+	>>> ignore_files = set(spec.match_tree_files('path/to/directory'))
+
+
+License
+-------
+
+*pathspec* is licensed under the `Mozilla Public License Version 2.0`_. See
+`LICENSE`_ or the `FAQ`_ for more information.
+
+In summary, you may use *pathspec* with any closed or open source project
+without affecting the license of the larger work so long as you:
+
+- give credit where credit is due,
+
+- and release any custom changes made to *pathspec*.
+
+.. _`Mozilla Public License Version 2.0`: http://www.mozilla.org/MPL/2.0
+.. _`LICENSE`: LICENSE
+.. _`FAQ`: http://www.mozilla.org/MPL/2.0/FAQ.html
+
+
+Source
+------
+
+The source code for *pathspec* is available from the GitHub repo
+`cpburnz/python-pathspec`_.
+
+.. _`cpburnz/python-pathspec`: https://github.com/cpburnz/python-pathspec
+
+
+Installation
+------------
+
+*pathspec* is available for install through `PyPI`_::
+
+	pip install pathspec
+
+*pathspec* can also be built from source. The following packages will be
+required:
+
+- `build`_ (>=0.6.0)
+
+*pathspec* can then be built and installed with::
+
+	python -m build
+	pip install dist/pathspec-*-py3-none-any.whl
+
+The following optional dependencies can be installed:
+
+- `google-re2`_: Enables optional "re2" backend.
+- `hyperscan`_: Enables optional "hyperscan" backend.
+- `typing-extensions`_: Improves some type hints.
+
+.. _`PyPI`: http://pypi.python.org/pypi/pathspec
+.. _`build`: https://pypi.org/project/build/
+.. _`typing-extensions`: https://pypi.org/project/typing-extensions/
+
+
+Documentation
+-------------
+
+Documentation for *pathspec* is available on `Read the Docs`_.
+
+The full change history can be found in `CHANGES.rst`_ and `Change History`_.
+
+An upgrade guide is available in `UPGRADING.rst`_ and `Upgrade Guide`_.
+
+.. _`CHANGES.rst`: https://github.com/cpburnz/python-pathspec/blob/master/CHANGES.rst
+.. _`Change History`: https://python-path-specification.readthedocs.io/en/stable/changes.html
+.. _`Read the Docs`: https://python-path-specification.readthedocs.io
+.. _`UPGRADING.rst`: https://github.com/cpburnz/python-pathspec/blob/master/UPGRADING.rst
+.. _`Upgrade Guide`: https://python-path-specification.readthedocs.io/en/stable/upgrading.html
+
+
+Other Languages
+---------------
+
+The related project `pathspec-ruby`_ (by *highb*) provides a similar library as
+a `Ruby gem`_.
+
+.. _`pathspec-ruby`: https://github.com/highb/pathspec-ruby
+.. _`Ruby gem`: https://rubygems.org/gems/pathspec
+
+
+Change History
+==============
+
+
+1.1.1 (2026-04-26)
+------------------
+
+Improvements:
+
+- Improved type checking with mypy and pyright.
+
+Bug fixes:
+
+- Fixed typing on `PathSpec[TPattern]` to `PathSpec[TPattern_co]`.
+- Added missing variant type-hint `type[Pattern]` to `PathSpec.from_lines()` parameter `pattern_factory`.
+- Fixed possible type error when using `+` and `+=` operators on `PathSpec`.
+
+
+1.1.0 (2026-04-22)
+------------------
+
+New features:
+
+- `Issue #108`_: Specialize pattern type for `PathSpec` as `PathSpec[TPattern]` for better debugging of `PathSpec().patterns`.
+
+Bug fixes:
+
+- `Issue #93`_: Git discards invalid range notation. `GitIgnoreSpecPattern` now discards patterns with invalid range notation like Git.
+- `Pull #106`_: Fix escape() not escaping backslash characters.
+
+Improvements:
+
+- `Pull #110`_: Nicer debug print outs (and str for regex pattern).
+
+
+.. _`Pull #106`: https://github.com/cpburnz/python-pathspec/pull/106
+.. _`Issue #108`: https://github.com/cpburnz/python-pathspec/issues/108
+.. _`Pull #110`: https://github.com/cpburnz/python-pathspec/pull/110
+
+
+1.0.4 (2026-01-26)
+------------------
+
+Bug fixes:
+
+- `Issue #103`_: Using re2 fails if pyre2 is also installed.
+
+.. _`Issue #103`: https://github.com/cpburnz/python-pathspec/issues/103
+
+
+1.0.3 (2026-01-09)
+------------------
+
+Bug fixes:
+
+- `Issue #101`_: pyright strict errors with pathspec >= 1.0.0.
+- `Issue #102`_: No module named 'tomllib'.
+
+
+.. _`Issue #101`: https://github.com/cpburnz/python-pathspec/issues/101
+.. _`Issue #102`: https://github.com/cpburnz/python-pathspec/issues/102
+
+
+1.0.2 (2026-01-07)
+------------------
+
+Bug fixes:
+
+- Type hint `collections.abc.Callable` does not properly replace `typing.Callable` until Python 3.9.2.
+
+
+1.0.1 (2026-01-06)
+------------------
+
+Bug fixes:
+
+- `Issue #100`_: ValueError(f"{patterns=!r} cannot be empty.") when using black.
+
+
+.. _`Issue #100`: https://github.com/cpburnz/python-pathspec/issues/100
+
+
+1.0.0 (2026-01-05)
+------------------
+
+Major changes:
+
+- `Issue #91`_: Dropped support of EoL Python 3.8.
+- Added concept of backends to allow for faster regular expression matching. The backend can be controlled using the `backend` argument to `PathSpec()`, `PathSpec.from_lines()`, `GitIgnoreSpec()`, and `GitIgnoreSpec.from_lines()`.
+- Renamed "gitwildmatch" pattern back to "gitignore". The "gitignore" pattern behaves slightly differently when used with `PathSpec` (*gitignore* as documented) than with `GitIgnoreSpec` (replicates *Git*'s edge cases).
+
+API changes:
+
+- Breaking: protected method `pathspec.pathspec.PathSpec._match_file()` (with a leading underscore) has been removed and replaced by backends. This does not affect normal usage of `PathSpec` or `GitIgnoreSpec`. Only custom subclasses will be affected. If this breaks your usage, let me know by `opening an issue `_.
+- Deprecated: "gitwildmatch" is now an alias for "gitignore".
+- Deprecated: `pathspec.patterns.GitWildMatchPattern` is now an alias for `pathspec.patterns.gitignore.spec.GitIgnoreSpecPattern`.
+- Deprecated: `pathspec.patterns.gitwildmatch` module has been replaced by the `pathspec.patterns.gitignore` package.
+- Deprecated: `pathspec.patterns.gitwildmatch.GitWildMatchPattern` is now an alias for `pathspec.patterns.gitignore.spec.GitIgnoreSpecPattern`.
+- Deprecated: `pathspec.patterns.gitwildmatch.GitWildMatchPatternError` is now an alias for `pathspec.patterns.gitignore.GitIgnorePatternError`.
+- Removed: `pathspec.patterns.gitwildmatch.GitIgnorePattern` has been deprecated since v0.4 (2016-07-15).
+- Signature of method `pathspec.pattern.RegexPattern.match_file()` has been changed from `def match_file(self, file: str) -> RegexMatchResult | None` to `def match_file(self, file: AnyStr) -> RegexMatchResult | None` to reflect usage.
+- Signature of class method `pathspec.pattern.RegexPattern.pattern_to_regex()` has been changed from `def pattern_to_regex(cls, pattern: str) -> tuple[str, bool]` to `def pattern_to_regex(cls, pattern: AnyStr) -> tuple[AnyStr | None, bool | None]` to reflect usage and documentation.
+
+New features:
+
+- Added optional "hyperscan" backend using `hyperscan`_ library. It will automatically be used when installed. This dependency can be installed with ``pip install 'pathspec[hyperscan]'``.
+- Added optional "re2" backend using the `google-re2`_ library. It will automatically be used when installed. This dependency can be installed with ``pip install 'pathspec[re2]'``.
+- Added optional dependency on `typing-extensions`_ library to improve some type hints.
+
+Bug fixes:
+
+- `Issue #93`_: Do not remove leading spaces.
+- `Issue #95`_: Matching for files inside folder does not seem to behave like .gitignore's.
+- `Issue #98`_: UnboundLocalError in RegexPattern when initialized with `pattern=None`.
+- Type hint on return value of `pathspec.pattern.RegexPattern.match_file()` to match documentation.
+
+Improvements:
+
+- Mark Python 3.13 and 3.14 as supported.
+- No-op patterns are now filtered out when matching files, slightly improving performance.
+- Fix performance regression in `iter_tree_files()` from v0.10.
+
+
+.. _`Issue #38`: https://github.com/cpburnz/python-pathspec/issues/38
+.. _`Issue #91`: https://github.com/cpburnz/python-pathspec/issues/91
+.. _`Issue #93`: https://github.com/cpburnz/python-pathspec/issues/93
+.. _`Issue #95`: https://github.com/cpburnz/python-pathspec/issues/95
+.. _`Issue #98`: https://github.com/cpburnz/python-pathspec/issues/98
+.. _`google-re2`: https://pypi.org/project/google-re2/
+.. _`hyperscan`: https://pypi.org/project/hyperscan/
+.. _`typing-extensions`: https://pypi.org/project/typing-extensions/
+
diff --git a/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/RECORD b/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..553fa7bfb9c0f171c76231ba4cd06c539fbce8d4
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/RECORD
@@ -0,0 +1,70 @@
+pathspec-1.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pathspec-1.1.1.dist-info/METADATA,sha256=aN4_FYtlkvCG54dUyWIJLzKnYZRKtmpmDA1irXnEtps,14797
+pathspec-1.1.1.dist-info/RECORD,,
+pathspec-1.1.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pathspec-1.1.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
+pathspec-1.1.1.dist-info/direct_url.json,sha256=qrLXxpWOtcBKICsQY_2plAQQa9PRRIcyBIrvK8bf13g,104
+pathspec-1.1.1.dist-info/licenses/LICENSE,sha256=-rPda9qyJvHAhjCx3ZF-Efy07F4eAg4sFvg6ChOGPoU,16726
+pathspec/__init__.py,sha256=0PnZCecVo4UjsfA0EFGsAUikyz1jSDFmQP9gCoKXW_Y,1408
+pathspec/__pycache__/__init__.cpython-310.pyc,,
+pathspec/__pycache__/_meta.cpython-310.pyc,,
+pathspec/__pycache__/_typing.cpython-310.pyc,,
+pathspec/__pycache__/_version.cpython-310.pyc,,
+pathspec/__pycache__/backend.cpython-310.pyc,,
+pathspec/__pycache__/gitignore.cpython-310.pyc,,
+pathspec/__pycache__/pathspec.cpython-310.pyc,,
+pathspec/__pycache__/pattern.cpython-310.pyc,,
+pathspec/__pycache__/util.cpython-310.pyc,,
+pathspec/_backends/__init__.py,sha256=CjgX4uSPMC5UH4iy_IrdFXrcLQ_gwK8MKW5Qbspz_uE,130
+pathspec/_backends/__pycache__/__init__.cpython-310.pyc,,
+pathspec/_backends/__pycache__/_utils.cpython-310.pyc,,
+pathspec/_backends/__pycache__/agg.cpython-310.pyc,,
+pathspec/_backends/_utils.py,sha256=mDjbGpndOyVkt9Fue0WDWKTkk-jVqOejof9Bv9pzArE,1066
+pathspec/_backends/agg.py,sha256=naHFqYXMR53hwtgHtEHrwNJEBFpbUWbdMbF0zguxHlE,2505
+pathspec/_backends/hyperscan/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pathspec/_backends/hyperscan/__pycache__/__init__.cpython-310.pyc,,
+pathspec/_backends/hyperscan/__pycache__/_base.cpython-310.pyc,,
+pathspec/_backends/hyperscan/__pycache__/base.cpython-310.pyc,,
+pathspec/_backends/hyperscan/__pycache__/gitignore.cpython-310.pyc,,
+pathspec/_backends/hyperscan/__pycache__/pathspec.cpython-310.pyc,,
+pathspec/_backends/hyperscan/_base.py,sha256=-yUX_rC8BSBNRyYChOAnvyU9UXReBwuynTEnlIKLSIw,1773
+pathspec/_backends/hyperscan/base.py,sha256=offQUvR_OWAzFygzw29847UInHaTZs6X-NtHTDTKVsI,673
+pathspec/_backends/hyperscan/gitignore.py,sha256=HtqCXYgmcoaAXAMRupOmzd1sCXpswpdv3caKhAV1ooc,6963
+pathspec/_backends/hyperscan/pathspec.py,sha256=q7MC80zYi78q6hagL8RkOZDiREtAqTNHP1Be_-XuAi8,6803
+pathspec/_backends/re2/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pathspec/_backends/re2/__pycache__/__init__.cpython-310.pyc,,
+pathspec/_backends/re2/__pycache__/_base.cpython-310.pyc,,
+pathspec/_backends/re2/__pycache__/base.cpython-310.pyc,,
+pathspec/_backends/re2/__pycache__/gitignore.cpython-310.pyc,,
+pathspec/_backends/re2/__pycache__/pathspec.cpython-310.pyc,,
+pathspec/_backends/re2/_base.py,sha256=0YzYQdbk0jHm9XzMuSq9eobbwgIq26RL5Vu1HkiPlZU,2299
+pathspec/_backends/re2/base.py,sha256=YYb-OKG3fWpFr6OKrQoG64mp6PYK8y5hGfvU_iEq_gs,488
+pathspec/_backends/re2/gitignore.py,sha256=cZHhuxx2sniR7VVnh4AYllWEYEdiisWBrKrcHE-31yM,5237
+pathspec/_backends/re2/pathspec.py,sha256=E-zNpMlX02yPnubgfvpdOIkY_QYke4gK0EjuI9fhZpo,5063
+pathspec/_backends/simple/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pathspec/_backends/simple/__pycache__/__init__.cpython-310.pyc,,
+pathspec/_backends/simple/__pycache__/gitignore.cpython-310.pyc,,
+pathspec/_backends/simple/__pycache__/pathspec.cpython-310.pyc,,
+pathspec/_backends/simple/gitignore.py,sha256=ATJ4VbGw1OHX5hCiqowBUTLmIZYW5dkgyUMkZuSCvh0,2893
+pathspec/_backends/simple/pathspec.py,sha256=Zzebst2evN8-juZr5w6VBwIox7LToYT4K2zD4Jp3M7U,2095
+pathspec/_meta.py,sha256=3raB7FQfJ5no3_DM1XcpravBr5S08CXbW6yhvm-SaUM,3073
+pathspec/_typing.py,sha256=JCBrMgYD6_xzTTY3P2P448jFySb43MmBpxBIjRUDl-g,1756
+pathspec/_version.py,sha256=B03_czsMKuIV3aMDcldxDOHZCl3kasFBNFKGskkxtkA,64
+pathspec/backend.py,sha256=HhLF4jn7r5kP2XA3brkw06DauAl_yrWzFYD-al6rOns,1470
+pathspec/gitignore.py,sha256=5JFKJ6kOG_REx655uCoGgVPrjcUckMo2Xz6TlEinNtY,5698
+pathspec/pathspec.py,sha256=02LdZ_vyMOGHFk_16JDAJ1Ef31YlytG5JfOR7fAyZQI,16892
+pathspec/pattern.py,sha256=S1EQefNCChwRti6sPfiD6TgCcrdYAriEYoCnW8jH4Yg,7269
+pathspec/patterns/__init__.py,sha256=TFwidji4ur0owf9sXkLyKsp90Ab81IA-Ny6JNqcnJ-U,406
+pathspec/patterns/__pycache__/__init__.cpython-310.pyc,,
+pathspec/patterns/__pycache__/gitwildmatch.cpython-310.pyc,,
+pathspec/patterns/gitignore/__init__.py,sha256=MaSAZd0DDg0vCH9k1LslaJjBJw5DkX4ty-FuLmB1z_4,422
+pathspec/patterns/gitignore/__pycache__/__init__.cpython-310.pyc,,
+pathspec/patterns/gitignore/__pycache__/base.cpython-310.pyc,,
+pathspec/patterns/gitignore/__pycache__/basic.cpython-310.pyc,,
+pathspec/patterns/gitignore/__pycache__/spec.cpython-310.pyc,,
+pathspec/patterns/gitignore/base.py,sha256=m-_BvFVpioNZvfH8WS8gIW_ibPUvjXpZJakiLloEs_s,5639
+pathspec/patterns/gitignore/basic.py,sha256=6uBAEki0K0GnYyODMai2t5d8RPGMIhm7AVmfOOjAcoA,10131
+pathspec/patterns/gitignore/spec.py,sha256=oa6fljMBz1_GHMt5dFFGmb7urEy3S0xsioA4aAbE2gE,10598
+pathspec/patterns/gitwildmatch.py,sha256=bF2PUtc9gOFHuFwHJ035x91y3R8An5dIY5oRibylsco,1463
+pathspec/py.typed,sha256=wq7wwDeyBungK6DsiV4O-IujgKzARwHz94uQshdpdEU,68
+pathspec/util.py,sha256=t_IxYVzB-FNBPihJTQxzZgY9mF4XJSPeI9gW9_Prz60,25551
diff --git a/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/REQUESTED b/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/WHEEL b/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: flit 3.12.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/direct_url.json b/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/direct_url.json
new file mode 100644
index 0000000000000000000000000000000000000000..e5a53caba7382248dc397ac1adf2de77be1e44de
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec-1.1.1.dist-info/direct_url.json
@@ -0,0 +1 @@
+{"dir_info": {}, "url": "file:///home/conda/feedstock_root/build_artifacts/pathspec_1777271521463/work"}
\ No newline at end of file
diff --git a/micromamba_root/Lib/site-packages/pathspec/__init__.py b/micromamba_root/Lib/site-packages/pathspec/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f41cfee8b4f0ddfc2b365d9e237efb8bc997bdd2
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec/__init__.py
@@ -0,0 +1,68 @@
+"""
+The *pathspec* package provides pattern matching for file paths. So far this
+only includes Git's *gitignore* patterns.
+
+The following classes are imported and made available from the root of the
+`pathspec` package:
+
+-	:class:`pathspec.gitignore.GitIgnoreSpec`
+
+-	:class:`pathspec.pathspec.PathSpec`
+
+-	:class:`pathspec.pattern.Pattern`
+
+-	:class:`pathspec.pattern.RegexPattern`
+
+-	:class:`pathspec.util.RecursionError`
+
+The following functions are also imported:
+
+-	:func:`pathspec.util.lookup_pattern`
+
+The following deprecated functions are also imported to maintain backward
+compatibility:
+
+-	:func:`pathspec.util.iter_tree`
+
+-	:func:`pathspec.util.match_files`
+"""
+
+from .gitignore import (
+	GitIgnoreSpec)
+from .pathspec import (
+	PathSpec)
+from .pattern import (
+	Pattern,
+	RegexPattern)
+from .util import (
+	RecursionError,
+	iter_tree,  # Deprecated since 0.10.0.
+	lookup_pattern,
+	match_files)  # Deprecated since 0.10.0.
+
+from ._meta import (
+	__author__,
+	__copyright__,
+	__credits__,
+	__license__)
+from ._version import (
+	__version__)
+
+# Load pattern implementations.
+from . import patterns
+
+# Declare private imports as part of the public interface. Deprecated imports
+# are deliberately excluded.
+__all__ = [
+	'GitIgnoreSpec',
+	'PathSpec',
+	'Pattern',
+	'RecursionError',
+	'RegexPattern',
+	'__author__',
+	'__copyright__',
+	'__credits__',
+	'__license__',
+	'__version__',
+	'lookup_pattern',
+]
diff --git a/micromamba_root/Lib/site-packages/pathspec/_meta.py b/micromamba_root/Lib/site-packages/pathspec/_meta.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fe86534931d47635c3a9cc8358432738640bb9e
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec/_meta.py
@@ -0,0 +1,70 @@
+"""
+This module contains the project meta-data.
+"""
+
+__author__ = "Caleb P. Burns"
+__copyright__ = "Copyright © 2013-2026 Caleb P. Burns"
+__credits__ = [
+	"Hong Minhee ",
+	"Brandon High ",
+	"029xue ",
+	"Michael Huynh ",
+	"Nick Humrich ",
+	"David Fraser ",
+	"Charles Samborski ",
+	"George Hickman ",
+	"Vincent Driessen ",
+	"Adrien Vergé ",
+	"Anders Blomdell ",
+	"Xavier Thomas ",
+	"Wim Jeantine-Glenn ",
+	"Hugo van Kemenade ",
+	"Dan Cecile ",
+	"MrOutis ",
+	"Jon Dufresne ",
+	"Greg Roodt ",
+	"Florin T. ",
+	"Ben Felder ",
+	"Nicholas Hollander ",
+	"KOLANICH ",
+	"Jon Hays ",
+	"Isaac0616 ",
+	"Sebastiaan Zeeff ",
+	"Roel Adriaans ",
+	"Ravi Selker ",
+	"Johan Vergeer ",
+	"danjer ",
+	"Jan-Hein Bührman ",
+	"Wim-Peter Dirks ",
+	"Karthikeyan Singaravelan ",
+	"John Vandenberg ",
+	"John T. Wodder II ",
+	"Tomasz Kłoczko ",
+	"Oren ",
+	"SP Mohanty ",
+	"Richard Si ",
+	"Jakub Kuczys ",
+	"Michał Górny ",
+	"Bartłomiej Żak ",
+	"Matthias ",
+	"Avasam ",
+	"Anıl Karagenç ",
+	"Yannic Schröder ",
+	"axesider ",
+	"TomRuk ",
+	"Oleh Prypin ",
+	"Lumina ",
+	"Kurt McKee ",
+	"Dobatymo ",
+	"Tomoki Nakamaru ",
+	"Sebastien Eskenazi ",
+	"Bar Vered ",
+	"Tzach Shabtay ",
+	"Adam Dangoor ",
+	"Marcel Telka ",
+	"Dmytro Kostochko ",
+	"Kadir Can Ozden ",
+	"Henry Schreiner ",
+	"Yilei ",
+]
+__license__ = "MPL 2.0"
diff --git a/micromamba_root/Lib/site-packages/pathspec/_typing.py b/micromamba_root/Lib/site-packages/pathspec/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffb4867d9d77e64961367d1cd1c0ce59c2f6d62c
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec/_typing.py
@@ -0,0 +1,64 @@
+"""
+This module provides stubs for type hints not supported by all relevant Python
+versions.
+
+NOTICE: This project should have zero required dependencies, which means it
+cannot simply require :module:`typing_extensions`, and I do not want to maintain
+a vendored copy of :module:`typing_extensions`.
+"""
+
+import functools
+import warnings
+from typing import (
+	Any,
+	Callable,  # Replaced by `collections.abc.Callable` in 3.9.2.
+	Optional,  # Replaced by `X | None` in 3.10.
+	TypeVar)
+try:
+	from typing import AnyStr  # Removed in 3.18.
+except ImportError:
+	AnyStr = TypeVar('AnyStr', str, bytes)  # type: ignore[misc]
+try:
+	from typing import Never  # Added in 3.11.
+except ImportError:
+	from typing import NoReturn as Never
+
+F = TypeVar('F', bound=Callable[..., Any])
+
+try:
+	from warnings import deprecated  # Added in 3.13.  # type: ignore
+except ImportError:
+	try:
+		from typing_extensions import deprecated  # type: ignore
+	except ImportError:
+		def deprecated(  # type: ignore[no-redef]
+			message: str,
+			/, *,
+			category: Optional[type[Warning]] = DeprecationWarning,
+			stacklevel: int = 1,
+		) -> Callable[[F], F]:
+			def decorator(f: F) -> F:
+				@functools.wraps(f)
+				def wrapper(*a, **k):
+					warnings.warn(message, category=category, stacklevel=stacklevel+1)
+					return f(*a, **k)
+				return wrapper  # type: ignore[return-value]
+			return decorator
+
+try:
+	from typing import override  # Added in 3.12.
+except ImportError:
+	try:
+		from typing_extensions import override
+	except ImportError:
+		def override(f: F, /) -> F:
+			return f
+
+
+def assert_unreachable(message: str) -> Never:
+	"""
+	The code path is unreachable. Raises an :class:`AssertionError`.
+
+	*message* (:class:`str`) is the error message.
+	"""
+	raise AssertionError(message)
diff --git a/micromamba_root/Lib/site-packages/pathspec/_version.py b/micromamba_root/Lib/site-packages/pathspec/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e5c07a71ada7dc5555146ec783770ce70bd1ea7
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec/_version.py
@@ -0,0 +1,5 @@
+"""
+This module defines the version.
+"""
+
+__version__ = "1.1.1"
diff --git a/micromamba_root/Lib/site-packages/pathspec/backend.py b/micromamba_root/Lib/site-packages/pathspec/backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cfbe0340c7f16ecc3167ca9747f2649c91bec45
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec/backend.py
@@ -0,0 +1,51 @@
+"""
+This module defines the necessary classes and type hints for exposing the bare
+minimum of the internal implementations for the pattern (regular expression)
+matching backends. The exact structure of the backends is not solidified and is
+subject to change.
+"""
+
+from collections.abc import (
+	Sequence)
+from typing import (
+	Callable,  # Replaced by `collections.abc.Callable` in 3.9.2.
+	Literal,
+	Optional)  # Replaced by `X | None` in 3.10.
+
+from .pattern import (
+	Pattern)
+
+BackendNamesHint = Literal['best', 'hyperscan', 're2', 'simple']
+"""
+The supported backend values.
+"""
+
+_TestBackendFactoryHint = Optional[Callable[[Sequence[Pattern]], '_Backend']]
+"""
+Type hint for the test backend factory argument.
+"""
+
+
+class _Backend(object):
+	"""
+	.. warning:: This class is not part of the public API. It is subject to
+		change.
+
+	The :class:`_Backend` class is the abstract base class defining how to match
+	files against patterns.
+	"""
+
+	def match_file(self, file: str) -> tuple[Optional[bool], Optional[int]]:
+		"""
+		Check the file against the patterns.
+
+		*file* (:class:`str`) is the normalized file path to check.
+
+		Returns a :class:`tuple` containing whether to include *file* (:class:`bool`
+		or :data:`None`), and the index of the last matched pattern (:class:`int` or
+		:data:`None`).
+		"""
+		raise NotImplementedError((
+			f"{self.__class__.__module__}.{self.__class__.__qualname__}.match_file() "
+			f"must be implemented."
+		))  # NotImplementedError
diff --git a/micromamba_root/Lib/site-packages/pathspec/gitignore.py b/micromamba_root/Lib/site-packages/pathspec/gitignore.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e8e6f8f8efc39d8196f568ddc3f7209a5f0279c
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec/gitignore.py
@@ -0,0 +1,172 @@
+"""
+This module provides :class:`.GitIgnoreSpec` which replicates *.gitignore*
+behavior, and handles edge-cases where Git's behavior differs from what's
+documented. Git allows including files from excluded directories which directly
+contradicts the documentation. This uses :class:`.GitIgnoreSpecPattern` to fully
+replicate Git's handling.
+"""
+from __future__ import annotations
+
+from collections.abc import (
+	Iterable,
+	Sequence)
+from typing import (
+	Callable,  # Replaced by `collections.abc.Callable` in 3.9.2.
+	Optional,  # Replaced by `X | None` in 3.10.
+	TypeVar,
+	Union,  # Replaced by `X | Y` in 3.10.
+	cast,
+	overload)
+
+from pathspec.backend import (
+	BackendNamesHint,
+	_Backend,
+	_TestBackendFactoryHint)
+from pathspec._backends.agg import (
+	make_gitignore_backend)
+from pathspec.pathspec import (
+	PathSpec)
+from pathspec.pattern import (
+	Pattern)
+from pathspec.patterns.gitignore.basic import (
+	GitIgnoreBasicPattern)
+from pathspec.patterns.gitignore.spec import (
+	GitIgnoreSpecPattern)
+from pathspec._typing import (
+	AnyStr,  # Removed in 3.18.
+	override)  # Added in 3.12.
+from pathspec.util import (
+	_is_iterable,
+	lookup_pattern)
+
+Self = TypeVar("Self", bound='GitIgnoreSpec')
+"""
+:class:`.GitIgnoreSpec` self type hint to support Python v<3.11 using PEP 673
+recommendation.
+"""
+
+
+class GitIgnoreSpec(PathSpec[GitIgnoreSpecPattern]):
+	"""
+	The :class:`GitIgnoreSpec` class extends :class:`.PathSpec` to replicate
+	*gitignore* behavior. This is uses :class:`.GitIgnoreSpecPattern` to fully
+	replicate Git's handling.
+	"""
+
+	def __eq__(self, other: object) -> bool:
+		"""
+		Tests the equality of this gitignore-spec with *other* (:class:`.GitIgnoreSpec`)
+		by comparing their :attr:`self.patterns <.PathSpec.patterns>` attributes. A
+		non-:class:`GitIgnoreSpec` will not compare equal.
+		"""
+		if isinstance(other, GitIgnoreSpec):
+			return super().__eq__(other)
+		elif isinstance(other, PathSpec):
+			return False
+		else:
+			return NotImplemented
+
+	# Support reversed order of arguments from PathSpec.
+	@overload  # type: ignore[override]
+	@classmethod
+	def from_lines(
+		cls: type[Self],
+		pattern_factory: Union[str, type[Pattern], Callable[[AnyStr], Pattern], None],
+		lines: Iterable[AnyStr],
+		*,
+		backend: Union[BackendNamesHint, str, None] = None,
+		_test_backend_factory: _TestBackendFactoryHint = None,
+	) -> Self:
+		...
+
+	@overload
+	@classmethod
+	def from_lines(
+		cls: type[Self],
+		lines: Iterable[AnyStr],
+		pattern_factory: Union[str, type[Pattern], Callable[[AnyStr], Pattern], None] = None,
+		*,
+		backend: Union[BackendNamesHint, str, None] = None,
+		_test_backend_factory: _TestBackendFactoryHint = None,
+	) -> Self:
+		...
+
+	@override  # type: ignore[misc]
+	@classmethod
+	def from_lines(  # type: ignore
+		cls: type[Self],
+		lines: Iterable[AnyStr],
+		pattern_factory: Union[str, type[Pattern], Callable[[AnyStr], Pattern], None] = None,
+		*,
+		backend: Union[BackendNamesHint, str, None] = None,
+		_test_backend_factory: _TestBackendFactoryHint = None,
+	) -> Self:
+		"""
+		Compiles the pattern lines.
+
+		*lines* (:class:`~collections.abc.Iterable`) yields each uncompiled pattern
+		(:class:`str`). This simply has to yield each line, so it can be a
+		:class:`io.TextIOBase` (e.g., from :func:`open` or :class:`io.StringIO`) or
+		the result from :meth:`str.splitlines`.
+
+		*pattern_factory* does not need to be set for :class:`GitIgnoreSpec`. If
+		set, it should be either ``"gitignore"`` or :class:`.GitIgnoreSpecPattern`.
+		There is no guarantee it will work with any other pattern class. Default is
+		:data:`None` for :class:`.GitIgnoreSpecPattern`.
+
+		*backend* (:class:`str` or :data:`None`) is the pattern (regular expression)
+		matching backend to use. Default is :data:`None` for "best" to use the best
+		available backend. Priority of backends is: "re2", "hyperscan", "simple".
+		The "simple" backend is always available.
+
+		Returns the :class:`GitIgnoreSpec` instance.
+		"""
+		if (isinstance(lines, (str, bytes)) or callable(lines)) and _is_iterable(pattern_factory):
+			# Support reversed order of arguments from PathSpec.
+			pattern_factory, lines = lines, pattern_factory  # type: ignore
+
+		use_factory: Callable[[AnyStr], GitIgnoreSpecPattern]
+		if pattern_factory is None:
+			use_factory = GitIgnoreSpecPattern  # type: ignore[assignment]
+		elif pattern_factory == 'gitignore':
+			# Force use of GitIgnoreSpecPattern for "gitignore" to handle edge-cases.
+			# This makes usage easier.
+			use_factory = GitIgnoreSpecPattern  # type: ignore[assignment]
+		elif isinstance(pattern_factory, str):
+			use_factory = lookup_pattern(pattern_factory)  # type: ignore[assignment]
+		else:
+			use_factory = pattern_factory  # type: ignore[assignment]
+
+		if (
+			isinstance(use_factory, type)
+			and issubclass(use_factory, GitIgnoreBasicPattern)
+		):
+			raise TypeError((
+				f"pattern_factory={pattern_factory!r} (resolved to {use_factory}) "
+				f"cannot be {GitIgnoreBasicPattern} because it will give unexpected "
+				f"results."
+			))  # TypeError
+
+		self = super().from_lines(use_factory, lines, backend=backend, _test_backend_factory=_test_backend_factory)  # type: ignore[arg-type,type-var]
+		return self  # type: ignore[return-value]
+
+	@override
+	@staticmethod
+	def _make_backend(
+		name: BackendNamesHint,
+		patterns: Sequence[Pattern],
+	) -> _Backend:
+		"""
+		.. warning:: This method is not part of the public API. It is subject to
+			change.
+
+		Create the backend for the patterns.
+
+		*name* (:class:`str`) is the name of the backend.
+
+		*patterns* (:class:`~collections.abc.Sequence` of :class:`.Pattern`)
+		contains the compiled patterns.
+
+		Returns the backend (:class:`._Backend`).
+		"""
+		return make_gitignore_backend(name, patterns)
diff --git a/micromamba_root/Lib/site-packages/pathspec/pathspec.py b/micromamba_root/Lib/site-packages/pathspec/pathspec.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e3872acf6555883bd4e1864b8767d3f7a2694aa
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec/pathspec.py
@@ -0,0 +1,527 @@
+"""
+This module provides :class:`.PathSpec` which is an object-oriented interface
+for pattern matching of files.
+"""
+from __future__ import annotations
+
+from collections.abc import (
+	Collection,
+	Iterable,
+	Iterator,
+	Sequence)
+from itertools import (
+	zip_longest)
+from typing import (
+	Callable,  # Replaced by `collections.abc.Callable` in 3.9.2.
+	Generic,
+	Literal,
+	Optional,  # Replaced by `X | None` in 3.10.
+	TypeVar,
+	Union,  # Replaced by `X | Y` in 3.10.
+	cast,
+	overload)
+
+Self = TypeVar("Self", bound='PathSpec')
+"""
+:class:`.PathSpec` self type hint to support Python v<3.11 using PEP 673
+recommendation.
+"""
+
+from pathspec import util
+from pathspec.backend import (
+	BackendNamesHint,
+	_Backend,
+	_TestBackendFactoryHint)
+from pathspec._backends.agg import (
+	make_pathspec_backend)
+from pathspec.pattern import (
+	Pattern)
+from pathspec.patterns.gitignore.basic import (
+	GitIgnoreBasicPattern)
+from pathspec._typing import (
+	AnyStr,  # Removed in 3.18.
+	deprecated)  # Added in 3.13.
+from pathspec.util import (
+	CheckResult,
+	StrPath,
+	TPattern,
+	TPattern_co,
+	TStrPath,
+	TreeEntry,
+	_is_iterable,
+	normalize_file)
+
+
+class PathSpec(Generic[TPattern_co]):
+	"""
+	The :class:`PathSpec` class is a wrapper around a list of compiled
+	:class:`.Pattern` instances.
+	"""
+
+	def __init__(
+		self,
+		patterns: Union[Sequence[TPattern_co], Iterable[TPattern_co]],
+		*,
+		backend: Union[BackendNamesHint, str, None] = None,
+		_test_backend_factory: _TestBackendFactoryHint = None,
+	) -> None:
+		"""
+		Initializes the :class:`.PathSpec` instance.
+
+		*patterns* (:class:`~collections.abc.Sequence` or :class:`~collections.abc.Iterable`)
+		contains each compiled pattern (:class:`.Pattern`). If not a sequence, it
+		will be converted to a :class:`list`.
+
+		*backend* (:class:`str` or :data:`None`) is the pattern (regular expression)
+		matching backend to use. Default is :data:`None` for "best" to use the best
+		available backend. Priority of backends is: "re2", "hyperscan", "simple".
+		The "simple" backend is always available.
+		"""
+		if isinstance(patterns, Sequence):
+			use_patterns = patterns
+		else:
+			use_patterns = list(patterns)
+
+		if backend is None:
+			backend = 'best'
+
+		backend_name = cast(BackendNamesHint, backend)
+		if _test_backend_factory is not None:
+			use_backend = _test_backend_factory(use_patterns)
+		else:
+			use_backend = self._make_backend(backend_name, use_patterns)
+
+		self._backend: _Backend = use_backend
+		"""
+		*_backend* (:class:`._Backend`) is the pattern (regular expression) matching
+		backend.
+		"""
+
+		self._backend_name: BackendNamesHint = backend_name
+		"""
+		*_backend_name* (:class:`str`) is the name of backend to use.
+		"""
+
+		self.patterns: Sequence[TPattern_co] = use_patterns
+		"""
+		*patterns* (:class:`~collections.abc.Sequence` of :class:`.Pattern`)
+		contains the compiled patterns.
+		"""
+
+	def __repr__(self) -> str:
+		"""
+		Returns a debug representation of this path-spec.
+		"""
+		return f"{self.__class__.__name__}(patterns={self.patterns!r}, backend={self._backend_name!r})"
+
+	def __add__(self: Self, other: PathSpec) -> Self:
+		"""
+		Combines the :attr:`self.patterns <.PathSpec.patterns>` patterns from two
+		:class:`PathSpec` instances.
+		"""
+		if isinstance(other, PathSpec):
+			return self.__class__([*self.patterns, *other.patterns], backend=self._backend_name)
+		else:
+			return NotImplemented
+
+	def __eq__(self, other: object) -> bool:
+		"""
+		Tests the equality of this path-spec with *other* (:class:`PathSpec`) by
+		comparing their :attr:`self.patterns <.PathSpec.patterns>` attributes.
+		"""
+		if isinstance(other, PathSpec):
+			paired_patterns = zip_longest(self.patterns, other.patterns)
+			return all(a == b for a, b in paired_patterns)
+		else:
+			return NotImplemented
+
+	def __iadd__(self: Self, other: PathSpec) -> Self:  # type: ignore[misc]
+		"""
+		Adds the :attr:`self.patterns <.PathSpec.patterns>` from *other*
+		(:class:`PathSpec`) to this instance.
+		"""
+		if isinstance(other, PathSpec):
+			self.patterns = [*self.patterns, *other.patterns]
+			self._backend = self._make_backend(self._backend_name, self.patterns)
+			return self
+		else:
+			return NotImplemented
+
+	def __len__(self) -> int:
+		"""
+		Returns the number of :attr:`self.patterns <.PathSpec.patterns>` this
+		path-spec contains (:class:`int`).
+		"""
+		return len(self.patterns)
+
+	def check_file(
+		self,
+		file: TStrPath,
+		separators: Optional[Collection[str]] = None,
+	) -> CheckResult[TStrPath]:
+		"""
+		Check the files against this path-spec.
+
+		*file* (:class:`str` or :class:`os.PathLike`) is the file path to be matched
+		against :attr:`self.patterns <.PathSpec.patterns>`.
+
+		*separators* (:class:`~collections.abc.Collection` of :class:`str`; or
+		:data:`None`) optionally contains the path separators to normalize. See
+		:func:`.normalize_file` for more information.
+
+		Returns the file check result (:class:`.CheckResult`).
+		"""
+		norm_file = normalize_file(file, separators)
+		include, index = self._backend.match_file(norm_file)
+		return CheckResult(file, include, index)
+
+	def check_files(
+		self,
+		files: Iterable[TStrPath],
+		separators: Optional[Collection[str]] = None,
+	) -> Iterator[CheckResult[TStrPath]]:
+		"""
+		Check the files against this path-spec.
+
+		*files* (:class:`~collections.abc.Iterable` of :class:`str` or
+		:class:`os.PathLike`) contains the file paths to be checked against
+		:attr:`self.patterns <.PathSpec.patterns>`.
+
+		*separators* (:class:`~collections.abc.Collection` of :class:`str`; or
+		:data:`None`) optionally contains the path separators to normalize. See
+		:func:`.normalize_file` for more information.
+
+		Returns an :class:`~collections.abc.Iterator` yielding each file check
+		result (:class:`.CheckResult`).
+		"""
+		if not _is_iterable(files):
+			raise TypeError(f"files:{files!r} is not an iterable.")
+
+		for orig_file in files:
+			norm_file = normalize_file(orig_file, separators)
+			include, index = self._backend.match_file(norm_file)
+			yield CheckResult(orig_file, include, index)
+
+	def check_tree_files(
+		self,
+		root: StrPath,
+		on_error: Optional[Callable[[OSError], None]] = None,
+		follow_links: Optional[bool] = None,
+	) -> Iterator[CheckResult[str]]:
+		"""
+		Walks the specified root path for all files and checks them against this
+		path-spec.
+
+		*root* (:class:`str` or :class:`os.PathLike`) is the root directory to
+		search for files.
+
+		*on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally
+		is the error handler for file-system exceptions. It will be called with the
+		exception (:exc:`OSError`). Reraise the exception to abort the walk. Default
+		is :data:`None` to ignore file-system exceptions.
+
+		*follow_links* (:class:`bool` or :data:`None`) optionally is whether to walk
+		symbolic links that resolve to directories. Default is :data:`None` for
+		:data:`True`.
+
+		*negate* (:class:`bool` or :data:`None`) is whether to negate the match
+		results of the patterns. If :data:`True`, a pattern matching a file will
+		exclude the file rather than include it. Default is :data:`None` for
+		:data:`False`.
+
+		Returns an :class:`~collections.abc.Iterator` yielding each file check
+		result (:class:`.CheckResult`).
+		"""
+		files = util.iter_tree_files(root, on_error=on_error, follow_links=follow_links)
+		yield from self.check_files(files)
+
+	@overload
+	@classmethod
+	def from_lines(
+		cls: type[PathSpec],
+		pattern_factory: Literal['gitignore'],
+		lines: Iterable[AnyStr],
+		*,
+		backend: Union[BackendNamesHint, str, None] = None,
+		_test_backend_factory: _TestBackendFactoryHint = None,
+	) -> PathSpec[GitIgnoreBasicPattern]:
+		...
+
+	@overload
+	@classmethod
+	def from_lines(
+		cls: type[PathSpec],
+		pattern_factory: str,
+		lines: Iterable[AnyStr],
+		*,
+		backend: Union[BackendNamesHint, str, None] = None,
+		_test_backend_factory: _TestBackendFactoryHint = None,
+	) -> PathSpec[Pattern]:
+		...
+
+	@overload
+	@classmethod
+	def from_lines(
+		cls: type[PathSpec],
+		pattern_factory: type[TPattern],
+		lines: Iterable[AnyStr],
+		*,
+		backend: Union[BackendNamesHint, str, None] = None,
+		_test_backend_factory: _TestBackendFactoryHint = None,
+	) -> PathSpec[TPattern]:
+		...
+
+	@overload
+	@classmethod
+	def from_lines(
+		cls: type[PathSpec],
+		pattern_factory: Callable[[AnyStr], TPattern],
+		lines: Iterable[AnyStr],
+		*,
+		backend: Union[BackendNamesHint, str, None] = None,
+		_test_backend_factory: _TestBackendFactoryHint = None,
+	) -> PathSpec[TPattern]:
+		...
+
+	@classmethod
+	def from_lines(
+		cls: type[Self],
+		pattern_factory: Union[str, type[Pattern], Callable[[AnyStr], Pattern]],
+		lines: Iterable[AnyStr],
+		*,
+		backend: Union[BackendNamesHint, str, None] = None,
+		_test_backend_factory: _TestBackendFactoryHint = None,
+	) -> Self:
+		"""
+		Compiles the pattern lines.
+
+		*pattern_factory* can be either the name of a registered pattern factory
+		(:class:`str`), or a :class:`~collections.abc.Callable` used to compile
+		patterns. It must accept an uncompiled pattern (:class:`str`) and return the
+		compiled pattern (:class:`.Pattern`).
+
+		*lines* (:class:`~collections.abc.Iterable`) yields each uncompiled pattern
+		(:class:`str`). This simply has to yield each line so that it can be a
+		:class:`io.TextIOBase` (e.g., from :func:`open` or :class:`io.StringIO`) or
+		the result from :meth:`str.splitlines`.
+
+		*backend* (:class:`str` or :data:`None`) is the pattern (or regular
+		expression) matching backend to use. Default is :data:`None` for "best" to
+		use the best available backend. Priority of backends is: "re2", "hyperscan",
+		"simple". The "simple" backend is always available.
+
+		Returns the :class:`PathSpec` instance.
+		"""
+		use_factory: Callable[[AnyStr], Pattern]
+		if isinstance(pattern_factory, str):
+			use_factory = util.lookup_pattern(pattern_factory)  # type: ignore[assignment]
+		elif callable(pattern_factory):
+			use_factory = pattern_factory  # type: ignore[assignment]
+		else:
+			raise TypeError(f"pattern_factory:{pattern_factory!r} is not callable.")
+
+		if not _is_iterable(lines):
+			raise TypeError(f"lines:{lines!r} is not an iterable.")
+
+		patterns = [use_factory(__line) for __line in lines if __line]  # type: ignore[arg-type]
+		self = cls(patterns, backend=backend, _test_backend_factory=_test_backend_factory)
+		return self
+
+	@staticmethod
+	def _make_backend(
+		name: BackendNamesHint,
+		patterns: Sequence[Pattern],
+	) -> _Backend:
+		"""
+		.. warning:: This method is not part of the public API. It is subject to
+			change.
+
+		Create the backend for the patterns.
+
+		*name* (:class:`str`) is the name of the backend.
+
+		*patterns* (:class:`~collections.abc.Sequence` of :class:`.Pattern`)
+		contains the compiled patterns.
+
+		Returns the matcher (:class:`._Backend`).
+		"""
+		return make_pathspec_backend(name, patterns)
+
+	def match_entries(
+		self,
+		entries: Iterable[TreeEntry],
+		separators: Optional[Collection[str]] = None,
+		*,
+		negate: Optional[bool] = None,
+	) -> Iterator[TreeEntry]:
+		"""
+		Matches the entries to this path-spec.
+
+		*entries* (:class:`~collections.abc.Iterable` of :class:`.TreeEntry`)
+		contains the entries to be matched against :attr:`self.patterns <.PathSpec.patterns>`.
+
+		*separators* (:class:`~collections.abc.Collection` of :class:`str`; or
+		:data:`None`) optionally contains the path separators to normalize. See
+		:func:`.normalize_file` for more information.
+
+		*negate* (:class:`bool` or :data:`None`) is whether to negate the match
+		results of the patterns. If :data:`True`, a pattern matching a file will
+		exclude the file rather than include it. Default is :data:`None` for
+		:data:`False`.
+
+		Returns the matched entries (:class:`~collections.abc.Iterator` of
+		:class:`.TreeEntry`).
+		"""
+		if not _is_iterable(entries):
+			raise TypeError(f"entries:{entries!r} is not an iterable.")
+
+		for entry in entries:
+			norm_file = normalize_file(entry.path, separators)
+			include, _index = self._backend.match_file(norm_file)
+
+			if negate:
+				include = not include
+
+			if include:
+				yield entry
+
+	def match_file(
+		self,
+		file: StrPath,
+		separators: Optional[Collection[str]] = None,
+	) -> bool:
+		"""
+		Matches the file to this path-spec.
+
+		*file* (:class:`str` or :class:`os.PathLike`) is the file path to be matched
+		against :attr:`self.patterns <.PathSpec.patterns>`.
+
+		*separators* (:class:`~collections.abc.Collection` of :class:`str`)
+		optionally contains the path separators to normalize. See
+		:func:`.normalize_file` for more information.
+
+		Returns :data:`True` if *file* matched; otherwise, :data:`False`.
+		"""
+		norm_file = normalize_file(file, separators)
+		include, _index = self._backend.match_file(norm_file)
+		return bool(include)
+
+	def match_files(
+		self,
+		files: Iterable[TStrPath],
+		separators: Optional[Collection[str]] = None,
+		*,
+		negate: Optional[bool] = None,
+	) -> Iterator[TStrPath]:
+		"""
+		Matches the files to this path-spec.
+
+		*files* (:class:`~collections.abc.Iterable` of :class:`str` or
+		:class:`os.PathLike`) contains the file paths to be matched against
+		:attr:`self.patterns <.PathSpec.patterns>`.
+
+		*separators* (:class:`~collections.abc.Collection` of :class:`str`; or
+		:data:`None`) optionally contains the path separators to normalize. See
+		:func:`.normalize_file` for more information.
+
+		*negate* (:class:`bool` or :data:`None`) is whether to negate the match
+		results of the patterns. If :data:`True`, a pattern matching a file will
+		exclude the file rather than include it. Default is :data:`None` for
+		:data:`False`.
+
+		Returns the matched files (:class:`~collections.abc.Iterator` of
+		:class:`str` or :class:`os.PathLike`).
+		"""
+		if not _is_iterable(files):
+			raise TypeError(f"files:{files!r} is not an iterable.")
+
+		for orig_file in files:
+			norm_file = normalize_file(orig_file, separators)
+			include, _index = self._backend.match_file(norm_file)
+
+			if negate:
+				include = not include
+
+			if include:
+				yield orig_file
+
+	def match_tree_entries(
+		self,
+		root: StrPath,
+		on_error: Optional[Callable[[OSError], None]] = None,
+		follow_links: Optional[bool] = None,
+		*,
+		negate: Optional[bool] = None,
+	) -> Iterator[TreeEntry]:
+		"""
+		Walks the specified root path for all files and matches them to this
+		path-spec.
+
+		*root* (:class:`str` or :class:`os.PathLike`) is the root directory to
+		search.
+
+		*on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally
+		is the error handler for file-system exceptions. It will be called with the
+		exception (:exc:`OSError`). Reraise the exception to abort the walk. Default
+		is :data:`None` to ignore file-system exceptions.
+
+		*follow_links* (:class:`bool` or :data:`None`) optionally is whether to walk
+		symbolic links that resolve to directories. Default is :data:`None` for
+		:data:`True`.
+
+		*negate* (:class:`bool` or :data:`None`) is whether to negate the match
+		results of the patterns. If :data:`True`, a pattern matching a file will
+		exclude the file rather than include it. Default is :data:`None` for
+		:data:`False`.
+
+		Returns the matched files (:class:`~collections.abc.Iterator` of
+		:class:`.TreeEntry`).
+		"""
+		entries = util.iter_tree_entries(root, on_error=on_error, follow_links=follow_links)
+		yield from self.match_entries(entries, negate=negate)
+
+	# NOTICE: The deprecation warning was only added in 1.0.0 (from 2026-01-05).
+	@deprecated((
+		"PathSpec.match_tree() is deprecated. Use .match_tree_files() instead."
+	))
+	def match_tree(self, *args, **kw) -> Iterator[str]:
+		"""
+		.. version-deprecated:: 0.3.2
+			This is an alias for the :meth:`self.match_tree_files <.PathSpec.match_tree_files>`
+			method.
+		"""
+		return self.match_tree_files(*args, **kw)
+
+	def match_tree_files(
+		self,
+		root: StrPath,
+		on_error: Optional[Callable[[OSError], None]] = None,
+		follow_links: Optional[bool] = None,
+		*,
+		negate: Optional[bool] = None,
+	) -> Iterator[str]:
+		"""
+		Walks the specified root path for all files and matches them to this
+		path-spec.
+
+		*root* (:class:`str` or :class:`os.PathLike`) is the root directory to
+		search for files.
+
+		*on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally
+		is the error handler for file-system exceptions. It will be called with the
+		exception (:exc:`OSError`). Reraise the exception to abort the walk. Default
+		is :data:`None` to ignore file-system exceptions.
+
+		*follow_links* (:class:`bool` or :data:`None`) optionally is whether to walk
+		symbolic links that resolve to directories. Default is :data:`None` for
+		:data:`True`.
+
+		*negate* (:class:`bool` or :data:`None`) is whether to negate the match
+		results of the patterns. If :data:`True`, a pattern matching a file will
+		exclude the file rather than include it. Default is :data:`None` for
+		:data:`False`.
+
+		Returns the matched files (:class:`~collections.abc.Iterable` of :class:`str`).
+		"""
+		files = util.iter_tree_files(root, on_error=on_error, follow_links=follow_links)
+		yield from self.match_files(files, negate=negate)
diff --git a/micromamba_root/Lib/site-packages/pathspec/pattern.py b/micromamba_root/Lib/site-packages/pathspec/pattern.py
new file mode 100644
index 0000000000000000000000000000000000000000..83dd0670c99c7696e27eb2662c79dfd6b1479c89
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec/pattern.py
@@ -0,0 +1,259 @@
+"""
+This module provides the base definition for patterns.
+"""
+from __future__ import annotations
+
+import re
+from collections.abc import (
+	Iterable,
+	Iterator)
+from dataclasses import (
+	dataclass)
+from typing import (
+	Any,
+	Optional,  # Replaced by `X | None` in 3.10.
+	TypeVar,
+	Union)  # Replaced by `X | Y` in 3.10.
+
+from ._typing import (
+	AnyStr,  # Removed in 3.18.
+	deprecated,  # Added in 3.13.
+	override)  # Added in 3.12.
+
+RegexPatternSelf = TypeVar("RegexPatternSelf", bound='RegexPattern')
+"""
+:class:`.RegexPattern` self type hint to support Python v<3.11 using PEP 673
+recommendation.
+"""
+
+class Pattern(object):
+	"""
+	The :class:`Pattern` class is the abstract definition of a pattern.
+	"""
+
+	# Make the class dict-less.
+	__slots__ = (
+		'include',
+	)
+
+	def __init__(self, include: Optional[bool]) -> None:
+		"""
+		Initializes the :class:`Pattern` instance.
+
+		*include* (:class:`bool` or :data:`None`) is whether the matched files
+		should be included (:data:`True`), excluded (:data:`False`), or is a
+		null-operation (:data:`None`).
+		"""
+
+		self.include = include
+		"""
+		*include* (:class:`bool` or :data:`None`) is whether the matched files
+		should be included (:data:`True`), excluded (:data:`False`), or is a
+		null-operation (:data:`None`).
+		"""
+
+	@deprecated((
+		"Pattern.match() is deprecated. Use Pattern.match_file() with a loop for "
+		"similar results."
+	))
+	def match(self, files: Iterable[str]) -> Iterator[str]:
+		"""
+		.. version-deprecated:: 0.10.0
+			This method is no longer used. Use the :meth:`self.match_file <.Pattern.match_file>`
+			method with a loop for similar results.
+
+		Matches this pattern against the specified files.
+
+		*files* (:class:`~collections.abc.Iterable` of :class:`str`) contains each
+		file relative to the root directory.
+
+		Returns an :class:`~collections.abc.Iterable` yielding each matched file
+		path (:class:`str`).
+		"""
+		for file in files:
+			if self.match_file(file) is not None:
+				yield file
+
+	def match_file(self, file: str) -> Optional[Any]:
+		"""
+		Matches this pattern against the specified file.
+
+		*file* (:class:`str`) is the normalized file path to match against.
+
+		Returns the match result if *file* matched; otherwise, :data:`None`.
+		"""
+		raise NotImplementedError((
+			"{cls.__module__}.{cls.__qualname__} must override match_file()."
+		).format(cls=self.__class__))
+
+
+class RegexPattern(Pattern):
+	"""
+	The :class:`RegexPattern` class is an implementation of a pattern using
+	regular expressions.
+	"""
+
+	# Keep the class dict-less.
+	__slots__ = (
+		'pattern',
+		'regex',
+	)
+
+	def __init__(
+		self,
+		pattern: Union[AnyStr, re.Pattern, None],
+		include: Optional[bool] = None,
+	) -> None:
+		"""
+		Initializes the :class:`RegexPattern` instance.
+
+		*pattern* (:class:`str`, :class:`bytes`, :class:`re.Pattern`, or
+		:data:`None`) is the pattern to compile into a regular expression.
+
+		*include* (:class:`bool` or :data:`None`) must be :data:`None` unless
+		*pattern* is a precompiled regular expression (:class:`re.Pattern`) in which
+		case it is whether matched files should be included (:data:`True`), excluded
+		(:data:`False`), or is a null operation (:data:`None`).
+
+			.. note:: Subclasses do not need to support the *include* parameter.
+		"""
+		regex: Optional[re.Pattern] = None
+		if isinstance(pattern, (str, bytes)):
+			assert include is None, (
+				f"{include=!r} must be null when {pattern=!r} is a string."
+			)
+			raw_regex, include = self.pattern_to_regex(pattern)
+			# NOTE: Make sure to allow a null regular expression to be
+			# returned for a null-operation.
+			if include is not None:
+				assert raw_regex is not None, (
+					f"{raw_regex=!r} must be non-null when {include=!r} is not None."
+				)
+				regex = re.compile(raw_regex)
+
+		elif pattern is not None and hasattr(pattern, 'match'):
+			# Assume pattern is a precompiled regular expression.
+			# - NOTE: Use specified *include*.
+			regex = pattern
+
+		elif pattern is None:
+			# NOTE: Make sure to allow a null pattern to be passed for a null
+			# operation.
+			assert include is None, (
+				f"{include=!r} must be null when {pattern=!r} is null."
+			)
+
+		else:
+			raise TypeError(f"{pattern=!r} is not a string, re.Pattern, or None.")
+
+		super(RegexPattern, self).__init__(include)
+
+		self.pattern: Union[str, bytes, re.Pattern, None] = pattern
+		"""
+		*pattern* (:class:`str`, :class:`bytes`, :class:`re.Pattern`, or
+		:data:`None`) is the uncompiled, input pattern. This is for reference.
+		"""
+
+		self.regex: Optional[re.Pattern] = regex
+		"""
+		*regex* (:class:`re.Pattern` or :data:`None`) is the compiled regular
+		expression for the pattern.
+		"""
+
+	def __repr__(self) -> str:
+		"""
+		Returns a debug representation of this regex pattern.
+		"""
+		return f"{self.__class__.__name__}(pattern={self.pattern!r}, include={self.include!r})"
+
+	def __str__(self) -> str:
+		"""
+		Returns a string representation of this regex pattern. Equivalent to uncompiled pattern.
+
+		The string representation is the uncompiled pattern if it is not
+		:data:`None`; otherwise, an empty string.
+		"""
+		return str(self.pattern or "")
+
+	def __copy__(self: RegexPatternSelf) -> RegexPatternSelf:
+		"""
+		Performa a shallow copy of the pattern.
+
+		Returns the copy (:class:`RegexPattern`).
+		"""
+		other = self.__class__(self.regex, self.include)
+		other.pattern = self.pattern
+		return other
+
+	def __eq__(self, other: object) -> bool:
+		"""
+		Tests the equality of this regex pattern with *other* (:class:`RegexPattern`)
+		by comparing their :attr:`~Pattern.include` and :attr:`~RegexPattern.regex`
+		attributes.
+		"""
+		if isinstance(other, RegexPattern):
+			return self.include == other.include and self.regex == other.regex
+		else:
+			return NotImplemented
+
+	@override
+	def match_file(self, file: AnyStr) -> Optional[RegexMatchResult]:
+		"""
+		Matches this pattern against the specified file.
+
+		*file* (:class:`str` or :class:`bytes`) is the file path relative to the
+		root directory (e.g., "relative/path/to/file").
+
+		Returns the match result (:class:`.RegexMatchResult`) if *file* matched;
+		otherwise, :data:`None`.
+		"""
+		if (
+			(regex := self.regex) is not None
+			and (match := regex.search(file)) is not None
+		):
+			return RegexMatchResult(match)
+
+		return None
+
+	@classmethod
+	def pattern_to_regex(
+		cls,
+		pattern: AnyStr,
+	) -> tuple[Optional[AnyStr], Optional[bool]]:
+		"""
+		Convert the pattern into an uncompiled regular expression.
+
+		*pattern* (:class:`str` or :class:`bytes`) is the pattern to convert into a
+		regular expression.
+
+		Returns a :class:`tuple` containing:
+
+			-	*pattern* (:class:`str`, :class:`bytes` or :data:`None`) is the
+				uncompiled regular expression .
+
+			-	*include* (:class:`bool` or :data:`None`) is whether matched files
+				should be included (:data:`True`), excluded (:data:`False`), or is a
+				null-operation (:data:`None`).
+
+			.. note:: The default implementation simply returns *pattern* and
+			   :data:`True`.
+		"""
+		return (pattern, True)
+
+
+@dataclass()
+class RegexMatchResult(object):
+	"""
+	The :class:`RegexMatchResult` data class is used to return information about
+	the matched regular expression.
+	"""
+
+	# Keep the class dict-less.
+	__slots__ = (
+		'match',
+	)
+
+	match: re.Match
+	"""
+	*match* (:class:`re.Match`) is the regex match result.
+	"""
diff --git a/micromamba_root/Lib/site-packages/pathspec/py.typed b/micromamba_root/Lib/site-packages/pathspec/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..b01eaaf7abc7ebeef7dba1c0c3ae07f854dbc1d3
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec/py.typed
@@ -0,0 +1 @@
+# Marker file for PEP 561.  The pathspec package uses inline types.
diff --git a/micromamba_root/Lib/site-packages/pathspec/util.py b/micromamba_root/Lib/site-packages/pathspec/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..e847ff8c2ceea486c1815265bb29231e55d66fc2
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pathspec/util.py
@@ -0,0 +1,864 @@
+"""
+This module provides utility methods for dealing with path-specs.
+"""
+from __future__ import annotations
+
+import os
+import os.path
+import pathlib
+import posixpath
+import stat
+from collections.abc import (
+	Collection,
+	Iterable,
+	Iterator,
+	Sequence)
+from dataclasses import (
+	dataclass)
+from typing import (
+	Any,
+	Callable,  # Replaced by `collections.abc.Callable` in 3.9.2.
+	Generic,
+	Optional,  # Replaced by `X | None` in 3.10.
+	TypeVar,
+	Union,  # Replaced by `X | Y` in 3.10.
+	cast)
+
+from .pattern import (
+	Pattern)
+from ._typing import (
+	AnyStr,  # Removed in 3.18.
+	deprecated)  # Added in 3.13.
+
+StrPath = Union[str, os.PathLike[str]]
+
+TPattern = TypeVar('TPattern', bound=Pattern)
+"""
+Type variable for :class:`.Pattern`. This is used by :class:`pathspec.pathspec.PathSpec`
+to specialize the type of patterns.
+"""
+
+TPattern_co = TypeVar('TPattern_co', bound=Pattern, covariant=True)
+"""
+Type variable for :class:`.Pattern` that is covariant. This is used by
+:class:`pathspec.pathspec.PathSpec` to specialize the type of patterns.
+"""
+
+TStrPath = TypeVar('TStrPath', bound=StrPath)
+"""
+Type variable for :class:`str` or :class:`os.PathLike`.
+"""
+
+NORMALIZE_PATH_SEPS = [
+	cast(str, __sep)
+	for __sep in [os.sep, os.altsep]
+	if __sep and __sep != posixpath.sep
+]
+"""
+*NORMALIZE_PATH_SEPS* (:class:`list` of :class:`str`) contains the path
+separators that need to be normalized to the POSIX separator for the current
+operating system. The separators are determined by examining :data:`os.sep` and
+:data:`os.altsep`.
+"""
+
+_registered_patterns: dict[str, Callable[[Union[str, bytes]], Pattern]] = {}
+"""
+*_registered_patterns* (:class:`dict`) maps a name (:class:`str`) to the
+registered pattern factory (:class:`~collections.abc.Callable`).
+"""
+
+
+def append_dir_sep(path: pathlib.Path) -> str:
+	"""
+	Appends the path separator to the path if the path is a directory. This can be
+	used to aid in distinguishing between directories and files on the file-system
+	by relying on the presence of a trailing path separator.
+
+	*path* (:class:`pathlib.Path`) is the path to use.
+
+	Returns the path (:class:`str`).
+	"""
+	str_path = str(path)
+	if path.is_dir():
+		str_path += os.sep
+
+	return str_path
+
+
+def check_match_file(
+	patterns: Iterable[tuple[int, Pattern]],
+	file: str,
+	is_reversed: Optional[bool] = None,
+) -> tuple[Optional[bool], Optional[int]]:
+	"""
+	Check the file against the patterns.
+
+	*patterns* (:class:`~collections.abc.Iterable`) yields each indexed pattern
+	(:class:`tuple`) which contains the pattern index (:class:`int`) and actua
+	pattern (:class:`.Pattern`).
+
+	*file* (:class:`str`) is the normalized file path to be matched against
+	*patterns*.
+
+	*is_reversed* (:class:`bool` or :data:`None`) is whether the order of the
+	patterns has been reversed. Default is :data:`None` for :data:`False`.
+	Reversing the order of the patterns is an optimization.
+
+	Returns a :class:`tuple` containing whether to include *file* (:class:`bool`
+	or :data:`None`), and the index of the last matched pattern (:class:`int` or
+	:data:`None`).
+	"""
+	if is_reversed:
+		# Check patterns in reverse order. The first pattern that matches takes
+		# precedence.
+		for index, pattern in patterns:
+			if pattern.include is not None and pattern.match_file(file) is not None:
+				return pattern.include, index
+
+		return None, None
+
+	else:
+		# Check all patterns. The last pattern that matches takes precedence.
+		out_include: Optional[bool] = None
+		out_index: Optional[int] = None
+		for index, pattern in patterns:
+			if pattern.include is not None and pattern.match_file(file) is not None:
+				out_include = pattern.include
+				out_index = index
+
+		return out_include, out_index
+
+
+def detailed_match_files(
+	patterns: Iterable[Pattern],
+	files: Iterable[str],
+	all_matches: Optional[bool] = None,
+) -> dict[str, MatchDetail]:
+	"""
+	Matches the files to the patterns, and returns which patterns matched the
+	files.
+
+	*patterns* (:class:`~collections.abc.Iterable` of :class:`.Pattern`) contains
+	the patterns to use.
+
+	*files* (:class:`~collections.abc.Iterable` of :class:`str`) contains the
+	normalized file paths to be matched against *patterns*.
+
+	*all_matches* (:class:`bool` or :data:`None`) is whether to return all matches
+	patterns (:data:`True`), or only the last matched pattern (:data:`False`).
+	Default is :data:`None` for :data:`False`.
+
+	Returns the matched files (:class:`dict`) which maps each matched file
+	(:class:`str`) to the patterns that matched in order (:class:`.MatchDetail`).
+	"""
+	all_files = files if isinstance(files, Collection) else list(files)
+	return_files: dict[str, MatchDetail] = {}
+	for pattern in patterns:
+		if pattern.include is not None:
+			result_files = pattern.match(all_files)  # TODO: Replace with `.match_file()`.
+			if pattern.include:
+				# Add files and record pattern.
+				for result_file in result_files:
+					if result_file in return_files:
+						# We know here that .patterns is a list, because we made it here
+						if all_matches:
+							return_files[result_file].patterns.append(pattern)  # type: ignore[attr-defined]
+						else:
+							return_files[result_file].patterns[0] = pattern  # type: ignore[index]
+					else:
+						return_files[result_file] = MatchDetail([pattern])
+
+			else:
+				# Remove files.
+				for file in result_files:
+					del return_files[file]
+
+	return return_files
+
+
+def _filter_check_patterns(
+	patterns: Iterable[Pattern],
+) -> list[tuple[int, Pattern]]:
+	"""
+	Filters out null-patterns.
+
+	*patterns* (:class:`~collections.abc.Iterable` of :class:`.Pattern`) contains
+	the patterns.
+
+	Returns a :class:`list` containing each indexed pattern (:class:`tuple`) which
+	contains the pattern index (:class:`int`) and the actual pattern
+	(:class:`.Pattern`).
+	"""
+	return [
+		(__index, __pat)
+		for __index, __pat in enumerate(patterns)
+		if __pat.include is not None
+	]
+
+
+def _is_iterable(value: Any) -> bool:
+	"""
+	Check whether the value is an iterable (excludes strings).
+
+	*value* is the value to check,
+
+	Returns whether *value* is an iterable (:class:`bool`).
+	"""
+	return isinstance(value, Iterable) and not isinstance(value, (str, bytes))
+
+
+@deprecated((
+	"pathspec.util.iter_tree() is deprecated. Use iter_tree_files() instead."
+))
+def iter_tree(root, on_error=None, follow_links=None):
+	"""
+	.. version-deprecated:: 0.10.0
+		This is an alias for the :func:`.iter_tree_files` function.
+	"""
+	return iter_tree_files(root, on_error=on_error, follow_links=follow_links)
+
+
+def iter_tree_entries(
+	root: StrPath,
+	on_error: Optional[Callable[[OSError], None]] = None,
+	follow_links: Optional[bool] = None,
+) -> Iterator['TreeEntry']:
+	"""
+	Walks the specified directory for all files and directories.
+
+	*root* (:class:`str` or :class:`os.PathLike`) is the root directory to search.
+
+	*on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally is
+	the error handler for file-system exceptions. It will be called with the
+	exception (:exc:`OSError`). Reraise the exception to abort the walk. Default
+	is :data:`None` to ignore file-system exceptions.
+
+	*follow_links* (:class:`bool` or :data:`None`) optionally is whether to walk
+	symbolic links that resolve to directories. Default is :data:`None` for
+	:data:`True`.
+
+	Raises :exc:`.RecursionError` if recursion is detected.
+
+	Returns an :class:`~collections.abc.Iterator` yielding each file or directory
+	entry (:class:`.TreeEntry`) relative to *root*.
+	"""
+	if on_error is not None and not callable(on_error):
+		raise TypeError(f"on_error:{on_error!r} is not callable.")
+
+	if follow_links is None:
+		follow_links = True
+
+	yield from _iter_tree_entries_next(os.path.abspath(root), '', {}, on_error, follow_links)
+
+
+def _iter_tree_entries_next(
+	root_full: str,
+	dir_rel: str,
+	memo: dict[str, str],
+	on_error: Optional[Callable[[OSError], None]],
+	follow_links: bool,
+) -> Iterator['TreeEntry']:
+	"""
+	Scan the directory for all descendant files.
+
+	*root_full* (:class:`str`) the absolute path to the root directory.
+
+	*dir_rel* (:class:`str`) the path to the directory to scan relative to
+	*root_full*.
+
+	*memo* (:class:`dict`) keeps track of ancestor directories encountered. Maps
+	each ancestor real path (:class:`str`) to relative path (:class:`str`).
+
+	*on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally is
+	the error handler for file-system exceptions.
+
+	*follow_links* (:class:`bool`) is whether to walk symbolic links that resolve
+	to directories.
+
+	Yields each entry (:class:`.TreeEntry`).
+	"""
+	dir_full = os.path.join(root_full, dir_rel)
+	dir_real = os.path.realpath(dir_full)
+
+	# Remember each encountered ancestor directory and its canonical (real) path.
+	# If a canonical path is encountered more than once, recursion has occurred.
+	if dir_real not in memo:
+		memo[dir_real] = dir_rel
+	else:
+		raise RecursionError(real_path=dir_real, first_path=memo[dir_real], second_path=dir_rel)
+
+	with os.scandir(dir_full) as scan_iter:
+		node_ent: os.DirEntry
+		for node_ent in scan_iter:
+			node_rel = os.path.join(dir_rel, node_ent.name)
+
+			# Inspect child node.
+			try:
+				node_lstat = node_ent.stat(follow_symlinks=False)
+			except OSError as e:
+				if on_error is not None:
+					on_error(e)
+				continue
+
+			if node_ent.is_symlink():
+				# Child node is a link, inspect the target node.
+				try:
+					node_stat = node_ent.stat()
+				except OSError as e:
+					if on_error is not None:
+						on_error(e)
+					continue
+			else:
+				node_stat = node_lstat
+
+			if node_ent.is_dir(follow_symlinks=follow_links):
+				# Child node is a directory, recurse into it and yield its descendant
+				# files.
+				yield TreeEntry(node_ent.name, node_rel, node_lstat, node_stat)
+
+				yield from _iter_tree_entries_next(root_full, node_rel, memo, on_error, follow_links)
+
+			elif node_ent.is_file() or node_ent.is_symlink():
+				# Child node is either a file or an unfollowed link, yield it.
+				yield TreeEntry(node_ent.name, node_rel, node_lstat, node_stat)
+
+	# NOTE: Make sure to remove the canonical (real) path of the directory from
+	# the ancestors memo once we are done with it. This allows the same directory
+	# to appear multiple times. If this is not done, the second occurrence of the
+	# directory will be incorrectly interpreted as a recursion. See
+	# .
+	del memo[dir_real]
+
+
+def iter_tree_files(
+	root: StrPath,
+	on_error: Optional[Callable[[OSError], None]] = None,
+	follow_links: Optional[bool] = None,
+) -> Iterator[str]:
+	"""
+	Walks the specified directory for all files.
+
+	*root* (:class:`str` or :class:`os.PathLike`) is the root directory to search
+	for files.
+
+	*on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally is
+	the error handler for file-system exceptions. It will be called with the
+	exception (:exc:`OSError`). Reraise the exception to abort the walk. Default
+	is :data:`None` to ignore file-system exceptions.
+
+	*follow_links* (:class:`bool` or :data:`None`) optionally is whether to walk
+	symbolic links that resolve to directories. Default is :data:`None` for
+	:data:`True`.
+
+	Raises :exc:`.RecursionError` if recursion is detected.
+
+	Returns an :class:`~collections.abc.Iterator` yielding the path to each file
+	(:class:`str`) relative to *root*.
+	"""
+	if on_error is not None and not callable(on_error):
+		raise TypeError(f"on_error:{on_error!r} is not callable.")
+
+	if follow_links is None:
+		follow_links = True
+
+	yield from _iter_tree_files_next(os.path.abspath(root), '', {}, on_error, follow_links)
+
+
+def _iter_tree_files_next(
+	root_full: str,
+	dir_rel: str,
+	memo: dict[str, str],
+	on_error: Optional[Callable[[OSError], None]],
+	follow_links: bool,
+) -> Iterator[str]:
+	"""
+	Scan the directory for all descendant files.
+
+	*root_full* (:class:`str`) the absolute path to the root directory.
+
+	*dir_rel* (:class:`str`) the path to the directory to scan relative to
+	*root_full*.
+
+	*memo* (:class:`dict`) keeps track of ancestor directories encountered. Maps
+	each ancestor real path (:class:`str`) to relative path (:class:`str`).
+
+	*on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally is
+	the error handler for file-system exceptions.
+
+	*follow_links* (:class:`bool`) is whether to walk symbolic links that resolve
+	to directories.
+
+	Yields each file path (:class:`str`).
+	"""
+	dir_full = os.path.join(root_full, dir_rel)
+	dir_real = os.path.realpath(dir_full)
+
+	# Remember each encountered ancestor directory and its canonical (real) path.
+	# If a canonical path is encountered more than once, recursion has occurred.
+	if dir_real not in memo:
+		memo[dir_real] = dir_rel
+	else:
+		raise RecursionError(real_path=dir_real, first_path=memo[dir_real], second_path=dir_rel)
+
+	with os.scandir(dir_full) as scan_iter:
+		node_ent: os.DirEntry
+		for node_ent in scan_iter:
+			node_rel = os.path.join(dir_rel, node_ent.name)
+
+			if node_ent.is_dir(follow_symlinks=follow_links):
+				# Child node is a directory, recurse into it and yield its descendant
+				# files.
+				yield from _iter_tree_files_next(root_full, node_rel, memo, on_error, follow_links)
+
+			elif node_ent.is_file():
+				# Child node is a file, yield it.
+				yield node_rel
+
+			elif not follow_links and node_ent.is_symlink():
+				# Child node is an unfollowed link, yield it.
+				yield node_rel
+
+	# NOTE: Make sure to remove the canonical (real) path of the directory from
+	# the ancestors memo once we are done with it. This allows the same directory
+	# to appear multiple times. If this is not done, the second occurrence of the
+	# directory will be incorrectly interpreted as a recursion. See
+	# .
+	del memo[dir_real]
+
+
+def lookup_pattern(name: str) -> Callable[[AnyStr], Pattern]:
+	"""
+	Looks up a registered pattern factory by name.
+
+	*name* (:class:`str`) is the name of the pattern factory.
+
+	Returns the registered pattern factory (:class:`~collections.abc.Callable`).
+	If no pattern factory is registered, raises :exc:`KeyError`.
+	"""
+	return _registered_patterns[name]  # type: ignore[return-value]
+
+
+def match_file(patterns: Iterable[Pattern], file: str) -> bool:
+	"""
+	Matches the file to the patterns.
+
+	*patterns* (:class:`~collections.abc.Iterable` of :class:`.Pattern`) contains
+	the patterns to use.
+
+	*file* (:class:`str`) is the normalized file path to be matched against
+	*patterns*.
+
+	Returns :data:`True` if *file* matched; otherwise, :data:`False`.
+	"""
+	matched = False
+	for pattern in patterns:
+		if pattern.include is not None and pattern.match_file(file) is not None:
+			matched = pattern.include
+
+	return matched
+
+
+@deprecated((
+	"pathspec.util.match_files() is deprecated. Use match_file() with a loop for "
+	"better results."
+))
+def match_files(
+	patterns: Iterable[Pattern],
+	files: Iterable[str],
+) -> set[str]:
+	"""
+	.. version-deprecated:: 0.10.0
+		This function is no longer used. Use the :func:`.match_file` function with a
+		loop for better results.
+
+	Matches the files to the patterns.
+
+	*patterns* (:class:`~collections.abc.Iterable` of :class:`.Pattern`) contains
+	the patterns to use.
+
+	*files* (:class:`~collections.abc.Iterable` of :class:`str`) contains the
+	normalized file paths to be matched against *patterns*.
+
+	Returns the matched files (:class:`set` of :class:`str`).
+	"""
+	use_patterns = [__pat for __pat in patterns if __pat.include is not None]
+
+	return_files = set()
+	for file in files:
+		if match_file(use_patterns, file):
+			return_files.add(file)
+
+	return return_files
+
+
+def normalize_file(
+	file: StrPath,
+	separators: Optional[Collection[str]] = None,
+) -> str:
+	"""
+	Normalizes the file path to use the POSIX path separator (i.e., ``"/"``), and
+	make the paths relative (remove leading ``"/"``).
+
+	*file* (:class:`str` or :class:`os.PathLike`) is the file path.
+
+	*separators* (:class:`~collections.abc.Collection` of :class:`str`; or
+	:data:`None`) optionally contains the path separators to normalize. This does
+	not need to include the POSIX path separator (``"/"``), but including it will
+	not affect the results. Default is ``None`` for :data:`.NORMALIZE_PATH_SEPS`.
+	To prevent normalization, pass an empty container (e.g., an empty tuple
+	``()``).
+
+	Returns the normalized file path (:class:`str`).
+	"""
+	# Normalize path separators.
+	if separators is None:
+		separators = NORMALIZE_PATH_SEPS
+
+	assert separators is not None, separators
+
+	# Convert path object to string.
+	norm_file: str = os.fspath(file)
+
+	for sep in separators:
+		norm_file = norm_file.replace(sep, posixpath.sep)
+
+	if norm_file.startswith('/'):
+		# Make path relative.
+		norm_file = norm_file[1:]
+
+	elif norm_file.startswith('./'):
+		# Remove current directory prefix.
+		norm_file = norm_file[2:]
+
+	return norm_file
+
+
+@deprecated((
+	"pathspec.util.normalize_files() is deprecated. Use normalize_file() with a "
+	"loop for better results."
+))
+def normalize_files(
+	files: Iterable[StrPath],
+	separators: Optional[Collection[str]] = None,
+) -> dict[str, list[StrPath]]:
+	"""
+	.. version-deprecated:: 0.10.0
+		This function is no longer used. Use the :func:`.normalize_file` function
+		with a loop for better results.
+
+	Normalizes the file paths to use the POSIX path separator.
+
+	*files* (:class:`~collections.abc.Iterable` of :class:`str` or
+	:class:`os.PathLike`) contains the file paths to be normalized.
+
+	*separators* (:class:`~collections.abc.Collection` of :class:`str`; or
+	:data:`None`) optionally contains the path separators to normalize. See
+	:func:`.normalize_file` for more information.
+
+	Returns a :class:`dict` mapping each normalized file path (:class:`str`) to
+	the original file paths (:class:`list` of :class:`str` or
+	:class:`os.PathLike`).
+	"""
+	norm_files: dict[str, list[StrPath]] = {}
+	for path in files:
+		norm_file = normalize_file(path, separators=separators)
+		if norm_file in norm_files:
+			norm_files[norm_file].append(path)
+		else:
+			norm_files[norm_file] = [path]
+
+	return norm_files
+
+
+def register_pattern(
+	name: str,
+	pattern_factory: Union[Callable[[Union[str, bytes]], Pattern], type[Pattern]],
+	override: Optional[bool] = None,
+) -> None:
+	"""
+	Registers the specified pattern factory.
+
+	*name* (:class:`str`) is the name to register the pattern factory under.
+
+	*pattern_factory* (:class:`~collections.abc.Callable`) is used to compile
+	patterns. It must accept an uncompiled pattern (:class:`str`) and return the
+	compiled pattern (:class:`.Pattern`).
+
+	*override* (:class:`bool` or :data:`None`) optionally is whether to allow
+	overriding an already registered pattern under the same name (:data:`True`),
+	instead of raising an :exc:`.AlreadyRegisteredError` (:data:`False`). Default
+	is :data:`None` for :data:`False`.
+	"""
+	if not isinstance(name, str):
+		raise TypeError(f"{name=!r} is not a string.")
+
+	if not callable(pattern_factory):
+		raise TypeError(f"{pattern_factory=!r} is not callable.")
+
+	if name in _registered_patterns and not override:
+		raise AlreadyRegisteredError(name, _registered_patterns[name])
+
+	_registered_patterns[name] = pattern_factory  # type: ignore
+
+
+class AlreadyRegisteredError(Exception):
+	"""
+	The :exc:`AlreadyRegisteredError` exception is raised when a pattern factory
+	is registered under a name already in use.
+	"""
+
+	def __init__(
+		self,
+		name: str,
+		pattern_factory: Callable[[Union[str, bytes]], Pattern],
+	) -> None:
+		"""
+		Initializes the :exc:`AlreadyRegisteredError` instance.
+
+		*name* (:class:`str`) is the name of the registered pattern.
+
+		*pattern_factory* (:class:`~collections.abc.Callable`) is the registered
+		pattern factory.
+		"""
+		super().__init__(name, pattern_factory)
+
+	@property
+	def message(self) -> str:
+		"""
+		*message* (:class:`str`) is the error message.
+		"""
+		return (
+			f"{self.name!r} is already registered for pattern factory="
+			f"{self.pattern_factory!r}."
+		)
+
+	@property
+	def name(self) -> str:
+		"""
+		*name* (:class:`str`) is the name of the registered pattern.
+		"""
+		return self.args[0]
+
+	@property
+	def pattern_factory(self) -> Callable[[Union[str, bytes]], Pattern]:
+		"""
+		*pattern_factory* (:class:`~collections.abc.Callable`) is the registered
+		pattern factory.
+		"""
+		return self.args[1]
+
+
+class RecursionError(Exception):
+	"""
+	The :exc:`RecursionError` exception is raised when recursion is detected.
+	"""
+
+	def __init__(
+		self,
+		real_path: str,
+		first_path: str,
+		second_path: str,
+	) -> None:
+		"""
+		Initializes the :exc:`RecursionError` instance.
+
+		*real_path* (:class:`str`) is the real path that recursion was encountered
+		on.
+
+		*first_path* (:class:`str`) is the first path encountered for *real_path*.
+
+		*second_path* (:class:`str`) is the second path encountered for *real_path*.
+		"""
+		super().__init__(real_path, first_path, second_path)
+
+	@property
+	def first_path(self) -> str:
+		"""
+		*first_path* (:class:`str`) is the first path encountered for
+		:attr:`self.real_path `.
+		"""
+		return self.args[1]
+
+	@property
+	def message(self) -> str:
+		"""
+		*message* (:class:`str`) is the error message.
+		"""
+		return (
+			f"Real path {self.real_path!r} was encountered at {self.first_path!r} "
+			f"and then {self.second_path!r}."
+		)
+
+	@property
+	def real_path(self) -> str:
+		"""
+		*real_path* (:class:`str`) is the real path that recursion was
+		encountered on.
+		"""
+		return self.args[0]
+
+	@property
+	def second_path(self) -> str:
+		"""
+		*second_path* (:class:`str`) is the second path encountered for
+		:attr:`self.real_path `.
+		"""
+		return self.args[2]
+
+
+@dataclass(frozen=True)
+class CheckResult(Generic[TStrPath]):
+	"""
+	The :class:`CheckResult` class contains information about the file and which
+	pattern matched it.
+	"""
+
+	# Make the class dict-less.
+	__slots__ = (
+		'file',
+		'include',
+		'index',
+	)
+
+	file: TStrPath
+	"""
+	*file* (:class:`str` or :class:`os.PathLike`) is the file path.
+	"""
+
+	include: Optional[bool]
+	"""
+	*include* (:class:`bool` or :data:`None`) is whether to include or exclude the
+	file. If :data:`None`, no pattern matched.
+	"""
+
+	index: Optional[int]
+	"""
+	*index* (:class:`int` or :data:`None`) is the index of the last pattern that
+	matched. If :data:`None`, no pattern matched.
+	"""
+
+
+class MatchDetail(object):
+	"""
+	The :class:`.MatchDetail` class contains information about
+	"""
+
+	# Make the class dict-less.
+	__slots__ = ('patterns',)
+
+	def __init__(self, patterns: Sequence[Pattern]) -> None:
+		"""
+		Initialize the :class:`.MatchDetail` instance.
+
+		*patterns* (:class:`~collections.abc.Sequence` of :class:`.Pattern`)
+		contains the patterns that matched the file in the order they were encountered.
+		"""
+
+		self.patterns = patterns
+		"""
+		*patterns* (:class:`~collections.abc.Sequence` of :class:`.Pattern`)
+		contains the patterns that matched the file in the order they were
+		encountered.
+		"""
+
+
+class TreeEntry(object):
+	"""
+	The :class:`TreeEntry` class contains information about a file-system entry.
+	"""
+
+	# Make the class dict-less.
+	__slots__ = ('_lstat', 'name', 'path', '_stat')
+
+	def __init__(
+		self,
+		name: str,
+		path: str,
+		lstat: os.stat_result,
+		stat: os.stat_result,
+	) -> None:
+		"""
+		Initialize the :class:`TreeEntry` instance.
+
+		*name* (:class:`str`) is the base name of the entry.
+
+		*path* (:class:`str`) is the relative path of the entry.
+
+		*lstat* (:class:`os.stat_result`) is the stat result of the direct entry.
+
+		*stat* (:class:`os.stat_result`) is the stat result of the entry,
+		potentially linked.
+		"""
+
+		self._lstat: os.stat_result = lstat
+		"""
+		*_lstat* (:class:`os.stat_result`) is the stat result of the direct entry.
+		"""
+
+		self.name: str = name
+		"""
+		*name* (:class:`str`) is the base name of the entry.
+		"""
+
+		self.path: str = path
+		"""
+		*path* (:class:`str`) is the path of the entry.
+		"""
+
+		self._stat: os.stat_result = stat
+		"""
+		*_stat* (:class:`os.stat_result`) is the stat result of the linked entry.
+		"""
+
+	def is_dir(self, follow_links: Optional[bool] = None) -> bool:
+		"""
+		Get whether the entry is a directory.
+
+		*follow_links* (:class:`bool` or :data:`None`) is whether to follow symbolic
+		links. If this is :data:`True`, a symlink to a directory will result in
+		:data:`True`. Default is :data:`None` for :data:`True`.
+
+		Returns whether the entry is a directory (:class:`bool`).
+		"""
+		if follow_links is None:
+			follow_links = True
+
+		node_stat = self._stat if follow_links else self._lstat
+		return stat.S_ISDIR(node_stat.st_mode)
+
+	def is_file(self, follow_links: Optional[bool] = None) -> bool:
+		"""
+		Get whether the entry is a regular file.
+
+		*follow_links* (:class:`bool` or :data:`None`) is whether to follow symbolic
+		links. If this is :data:`True`, a symlink to a regular file will result in
+		:data:`True`. Default is :data:`None` for :data:`True`.
+
+		Returns whether the entry is a regular file (:class:`bool`).
+		"""
+		if follow_links is None:
+			follow_links = True
+
+		node_stat = self._stat if follow_links else self._lstat
+		return stat.S_ISREG(node_stat.st_mode)
+
+	def is_symlink(self) -> bool:
+		"""
+		Returns whether the entry is a symbolic link (:class:`bool`).
+		"""
+		return stat.S_ISLNK(self._lstat.st_mode)
+
+	def stat(self, follow_links: Optional[bool] = None) -> os.stat_result:
+		"""
+		Get the cached stat result for the entry.
+
+		*follow_links* (:class:`bool` or :data:`None`) is whether to follow symbolic
+		links. If this is :data:`True`, the stat result of the linked file will be
+		returned. Default is :data:`None` for :data:`True`.
+
+		Returns that stat result (:class:`os.stat_result`).
+		"""
+		if follow_links is None:
+			follow_links = True
+
+		return self._stat if follow_links else self._lstat
diff --git a/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/INSTALLER b/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a34a7e56db35cc4c85bfa166244b3d63a6a240d4
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/INSTALLER
@@ -0,0 +1 @@
+conda
diff --git a/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/METADATA b/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..f9ac753abd2e2389768e6e5a530a20d4fc92925a
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/METADATA
@@ -0,0 +1,100 @@
+Metadata-Version: 2.4
+Name: platformdirs
+Version: 4.9.6
+Summary: A small Python package for determining appropriate platform-specific dirs, e.g. a `user data dir`.
+Project-URL: Changelog, https://platformdirs.readthedocs.io/en/latest/changelog.html
+Project-URL: Documentation, https://platformdirs.readthedocs.io
+Project-URL: Homepage, https://github.com/tox-dev/platformdirs
+Project-URL: Source, https://github.com/tox-dev/platformdirs
+Project-URL: Tracker, https://github.com/tox-dev/platformdirs/issues
+Maintainer-email: Bernát Gábor , Julian Berman , Ofek Lev , Ronny Pfannschmidt 
+License-Expression: MIT
+License-File: LICENSE
+Keywords: appdirs,application,cache,directory,log,user
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.10
+Description-Content-Type: text/markdown
+
+# platformdirs
+
+[![PyPI version](https://badge.fury.io/py/platformdirs.svg)](https://badge.fury.io/py/platformdirs)
+[![Python versions](https://img.shields.io/pypi/pyversions/platformdirs.svg)](https://pypi.python.org/pypi/platformdirs/)
+[![CI](https://github.com/tox-dev/platformdirs/actions/workflows/check.yaml/badge.svg)](https://github.com/platformdirs/platformdirs/actions)
+[![Downloads](https://static.pepy.tech/badge/platformdirs/month)](https://pepy.tech/project/platformdirs)
+
+A Python package for determining platform-specific directories (e.g. user data, config, cache, logs). Handles the
+differences between macOS, Windows, Linux/Unix, and Android so you don't have to.
+
+## Quick start
+
+```python
+from platformdirs import PlatformDirs
+
+dirs = PlatformDirs("MyApp", "MyCompany")
+dirs.user_data_dir  # ~/.local/share/MyApp (Linux)
+dirs.user_config_dir  # ~/.config/MyApp (Linux)
+dirs.user_cache_dir  # ~/.cache/MyApp (Linux)
+dirs.user_state_dir  # ~/.local/state/MyApp (Linux)
+dirs.user_log_dir  # ~/.local/state/MyApp/log (Linux)
+dirs.user_documents_dir  # ~/Documents
+dirs.user_downloads_dir  # ~/Downloads
+dirs.user_runtime_dir  # /run/user//MyApp (Linux)
+```
+
+For Path objects instead of strings:
+
+```python
+from platformdirs import PlatformDirs
+
+dirs = PlatformDirs("MyApp", "MyCompany")
+dirs.user_data_path  # pathlib.Path('~/.local/share/MyApp')
+dirs.user_config_path  # pathlib.Path('~/.config/MyApp')
+```
+
+Convenience functions for quick access:
+
+```python
+from platformdirs import user_data_dir, user_config_path
+
+user_data_dir("MyApp", "MyCompany")  # returns str
+user_config_path("MyApp", "MyCompany")  # returns pathlib.Path
+```
+
+## Directory types
+
+- **Data**: Persistent application data (`user_data_dir`, `site_data_dir`)
+- **Config**: Configuration files and settings (`user_config_dir`, `site_config_dir`)
+- **Cache**: Cached data that can be regenerated (`user_cache_dir`, `site_cache_dir`)
+- **State**: Non-essential runtime state like window positions (`user_state_dir`, `site_state_dir`)
+- **Logs**: Log files (`user_log_dir`, `site_log_dir`)
+- **Runtime**: Runtime files like sockets and PIDs (`user_runtime_dir`, `site_runtime_dir`)
+
+Each type has both `user_*` (per-user, writable) and `site_*` (system-wide, read-only for users) variants.
+
+## Documentation
+
+Full documentation is available at [platformdirs.readthedocs.io](https://platformdirs.readthedocs.io):
+
+- **[Getting started tutorial](https://platformdirs.readthedocs.io/en/latest/tutorial.html)** -- learn core concepts
+  through real-world examples
+- **[How-to guides](https://platformdirs.readthedocs.io/en/latest/howto.html)** -- recipes for common tasks and
+  platform-specific tips
+- **[API reference](https://platformdirs.readthedocs.io/en/latest/api.html)** -- complete list of functions and classes
+- **[Platform details](https://platformdirs.readthedocs.io/en/latest/platforms.html)** -- default paths for each
+  operating system
+
+Contributions are welcome! See [CONTRIBUTING.md](https://github.com/tox-dev/platformdirs/blob/main/CONTRIBUTING.md) for
+details.
diff --git a/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/RECORD b/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..121da99a2ee4e2e87cfdf2485e0bea2556ef3ef9
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/RECORD
@@ -0,0 +1,26 @@
+platformdirs-4.9.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+platformdirs-4.9.6.dist-info/METADATA,sha256=fcQ31pBPq10bZSesG9_gMETprVNkna3BQ0cabyRyknw,4683
+platformdirs-4.9.6.dist-info/RECORD,,
+platformdirs-4.9.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+platformdirs-4.9.6.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
+platformdirs-4.9.6.dist-info/direct_url.json,sha256=7ALWV2hpXSYTI-4SJMeFtlIyCBn5qd81pvnFw8yuamA,123
+platformdirs-4.9.6.dist-info/licenses/LICENSE,sha256=KeD9YukphQ6G6yjD_czwzv30-pSHkBHP-z0NS-1tTbY,1089
+platformdirs/__init__.py,sha256=hL_ZyhsQ5EfYf4W_Tr4O6F0lAOKLvQi0TZ4e_WGCIc4,30718
+platformdirs/__main__.py,sha256=MvM6fKJpBAeiTZckNJGSihXFKkS46tS9_P5gySZg3RI,1633
+platformdirs/__pycache__/__init__.cpython-310.pyc,,
+platformdirs/__pycache__/__main__.cpython-310.pyc,,
+platformdirs/__pycache__/_xdg.cpython-310.pyc,,
+platformdirs/__pycache__/android.cpython-310.pyc,,
+platformdirs/__pycache__/api.cpython-310.pyc,,
+platformdirs/__pycache__/macos.cpython-310.pyc,,
+platformdirs/__pycache__/unix.cpython-310.pyc,,
+platformdirs/__pycache__/version.cpython-310.pyc,,
+platformdirs/__pycache__/windows.cpython-310.pyc,,
+platformdirs/_xdg.py,sha256=vNBb4Vsp3vx5HoecsYGUwVsB1bfYthZcjRk51FLYUeo,6391
+platformdirs/android.py,sha256=nbEJY4dyNjF-OM5RalA0WJIQHCUy8OKioGDS9G_-ZGg,10591
+platformdirs/api.py,sha256=0LkLOlJtbqEglJFpyynWP6zSMDEX23akdJERcTDxWWc,13415
+platformdirs/macos.py,sha256=I36WswNPKMAAFvG57sRTur0NbnXpV_hhhupSx9P4gOw,8090
+platformdirs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+platformdirs/unix.py,sha256=QgTxP8EwOAeaKpnCgXdNZ9fnmnKpeoe1ICv_e1fFov4,12259
+platformdirs/version.py,sha256=XATFcF2M-IkX5aM0WcHYRA1fkcF1XWXoNC1YG1bPbk0,704
+platformdirs/windows.py,sha256=eQFkbOcRcI5YplmPx59FOd7yXJlhq27PpL7HVaC7se4,14564
diff --git a/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/REQUESTED b/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/WHEEL b/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..b1b94fd58e7e9ed0ef3449473bc48de68afcc3fe
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/WHEEL
@@ -0,0 +1,4 @@
+Wheel-Version: 1.0
+Generator: hatchling 1.29.0
+Root-Is-Purelib: true
+Tag: py3-none-any
diff --git a/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/direct_url.json b/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/direct_url.json
new file mode 100644
index 0000000000000000000000000000000000000000..46979cc362341edbda83998058e8e6d452bac76a
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs-4.9.6.dist-info/direct_url.json
@@ -0,0 +1 @@
+{"dir_info": {}, "url": "file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_platformdirs_1775741140/work"}
\ No newline at end of file
diff --git a/micromamba_root/Lib/site-packages/platformdirs/__init__.py b/micromamba_root/Lib/site-packages/platformdirs/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ab450ea953e237bb7ffcdf83f0c76200507cdc1
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs/__init__.py
@@ -0,0 +1,857 @@
+"""Utilities for determining application-specific dirs.
+
+Provides convenience functions (e.g. :func:`user_data_dir`, :func:`user_config_path`), a :data:`PlatformDirs` class that
+auto-detects the current platform, and the :class:`~platformdirs.api.PlatformDirsABC` base class.
+
+See  for details and usage.
+
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from typing import TYPE_CHECKING
+
+from .api import PlatformDirsABC
+from .version import __version__
+from .version import __version_tuple__ as __version_info__
+
+if TYPE_CHECKING:
+    from pathlib import Path
+    from typing import Literal
+
+if sys.platform == "win32":
+    from platformdirs.windows import Windows as _Result
+elif sys.platform == "darwin":
+    from platformdirs.macos import MacOS as _Result
+else:
+    from platformdirs.unix import Unix as _Result
+
+
+def _set_platform_dir_class() -> type[PlatformDirsABC]:
+    if os.getenv("ANDROID_DATA") == "/data" and os.getenv("ANDROID_ROOT") == "/system":
+        if os.getenv("SHELL") or os.getenv("PREFIX"):
+            return _Result
+
+        from platformdirs.android import _android_folder  # noqa: PLC0415
+
+        if _android_folder() is not None:
+            from platformdirs.android import Android  # noqa: PLC0415
+
+            return Android  # return to avoid redefinition of a result
+
+    return _Result
+
+
+if TYPE_CHECKING:
+    # Work around mypy issue: https://github.com/python/mypy/issues/10962
+    PlatformDirs = _Result
+else:
+    PlatformDirs = _set_platform_dir_class()  #: Currently active platform
+AppDirs = PlatformDirs  #: Backwards compatibility with appdirs
+
+
+def user_data_dir(  # noqa: PLR0913, PLR0917
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :param use_site_for_root: See `use_site_for_root `.
+
+    :returns: data directory tied to the user
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+        use_site_for_root=use_site_for_root,
+    ).user_data_dir
+
+
+def site_data_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `multipath `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: data directory shared by users
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_data_dir
+
+
+def user_config_dir(  # noqa: PLR0913, PLR0917
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :param use_site_for_root: See `use_site_for_root `.
+
+    :returns: config directory tied to the user
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+        use_site_for_root=use_site_for_root,
+    ).user_config_dir
+
+
+def site_config_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `multipath `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: config directory shared by users
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_config_dir
+
+
+def user_cache_dir(  # noqa: PLR0913, PLR0917
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :param use_site_for_root: See `use_site_for_root `.
+
+    :returns: cache directory tied to the user
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+        use_site_for_root=use_site_for_root,
+    ).user_cache_dir
+
+
+def site_cache_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: cache directory shared by users
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_cache_dir
+
+
+def user_state_dir(  # noqa: PLR0913, PLR0917
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :param use_site_for_root: See `use_site_for_root `.
+
+    :returns: state directory tied to the user
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+        use_site_for_root=use_site_for_root,
+    ).user_state_dir
+
+
+def site_state_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: state directory shared by users
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        ensure_exists=ensure_exists,
+    ).site_state_dir
+
+
+def user_log_dir(  # noqa: PLR0913, PLR0917
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :param use_site_for_root: See `use_site_for_root `.
+
+    :returns: log directory tied to the user
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+        use_site_for_root=use_site_for_root,
+    ).user_log_dir
+
+
+def site_log_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: log directory shared by users
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_log_dir
+
+
+def user_documents_dir() -> str:
+    """:returns: documents directory tied to the user"""
+    return PlatformDirs().user_documents_dir
+
+
+def user_downloads_dir() -> str:
+    """:returns: downloads directory tied to the user"""
+    return PlatformDirs().user_downloads_dir
+
+
+def user_pictures_dir() -> str:
+    """:returns: pictures directory tied to the user"""
+    return PlatformDirs().user_pictures_dir
+
+
+def user_videos_dir() -> str:
+    """:returns: videos directory tied to the user"""
+    return PlatformDirs().user_videos_dir
+
+
+def user_music_dir() -> str:
+    """:returns: music directory tied to the user"""
+    return PlatformDirs().user_music_dir
+
+
+def user_desktop_dir() -> str:
+    """:returns: desktop directory tied to the user"""
+    return PlatformDirs().user_desktop_dir
+
+
+def user_bin_dir() -> str:
+    """:returns: bin directory tied to the user"""
+    return PlatformDirs().user_bin_dir
+
+
+def site_bin_dir() -> str:
+    """:returns: bin directory shared by users"""
+    return PlatformDirs().site_bin_dir
+
+
+def user_applications_dir() -> str:
+    """:returns: applications directory tied to the user"""
+    return PlatformDirs().user_applications_dir
+
+
+def site_applications_dir(
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param multipath: See `multipath `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: applications directory shared by users
+
+    """
+    return PlatformDirs(
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_applications_dir
+
+
+def user_runtime_dir(  # noqa: PLR0913, PLR0917
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :param use_site_for_root: See `use_site_for_root `.
+
+    :returns: runtime directory tied to the user
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+        use_site_for_root=use_site_for_root,
+    ).user_runtime_dir
+
+
+def site_runtime_dir(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> str:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: runtime directory shared by users
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_runtime_dir
+
+
+def user_data_path(  # noqa: PLR0913, PLR0917
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :param use_site_for_root: See `use_site_for_root `.
+
+    :returns: data path tied to the user
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+        use_site_for_root=use_site_for_root,
+    ).user_data_path
+
+
+def site_data_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `multipath `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: data path shared by users
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_data_path
+
+
+def user_config_path(  # noqa: PLR0913, PLR0917
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :param use_site_for_root: See `use_site_for_root `.
+
+    :returns: config path tied to the user
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+        use_site_for_root=use_site_for_root,
+    ).user_config_path
+
+
+def site_config_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param multipath: See `multipath `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: config path shared by users
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_config_path
+
+
+def site_cache_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: cache path shared by users
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_cache_path
+
+
+def user_cache_path(  # noqa: PLR0913, PLR0917
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :param use_site_for_root: See `use_site_for_root `.
+
+    :returns: cache path tied to the user
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+        use_site_for_root=use_site_for_root,
+    ).user_cache_path
+
+
+def user_state_path(  # noqa: PLR0913, PLR0917
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    roaming: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param roaming: See `roaming `.
+    :param ensure_exists: See `ensure_exists `.
+    :param use_site_for_root: See `use_site_for_root `.
+
+    :returns: state path tied to the user
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        roaming=roaming,
+        ensure_exists=ensure_exists,
+        use_site_for_root=use_site_for_root,
+    ).user_state_path
+
+
+def site_state_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: state path shared by users
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        ensure_exists=ensure_exists,
+    ).site_state_path
+
+
+def user_log_path(  # noqa: PLR0913, PLR0917
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :param use_site_for_root: See `use_site_for_root `.
+
+    :returns: log path tied to the user
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+        use_site_for_root=use_site_for_root,
+    ).user_log_path
+
+
+def site_log_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: log path shared by users
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_log_path
+
+
+def user_documents_path() -> Path:
+    """:returns: documents path tied to the user"""
+    return PlatformDirs().user_documents_path
+
+
+def user_downloads_path() -> Path:
+    """:returns: downloads path tied to the user"""
+    return PlatformDirs().user_downloads_path
+
+
+def user_pictures_path() -> Path:
+    """:returns: pictures path tied to the user"""
+    return PlatformDirs().user_pictures_path
+
+
+def user_videos_path() -> Path:
+    """:returns: videos path tied to the user"""
+    return PlatformDirs().user_videos_path
+
+
+def user_music_path() -> Path:
+    """:returns: music path tied to the user"""
+    return PlatformDirs().user_music_path
+
+
+def user_desktop_path() -> Path:
+    """:returns: desktop path tied to the user"""
+    return PlatformDirs().user_desktop_path
+
+
+def user_bin_path() -> Path:
+    """:returns: bin path tied to the user"""
+    return PlatformDirs().user_bin_path
+
+
+def site_bin_path() -> Path:
+    """:returns: bin path shared by users"""
+    return PlatformDirs().site_bin_path
+
+
+def user_applications_path() -> Path:
+    """:returns: applications path tied to the user"""
+    return PlatformDirs().user_applications_path
+
+
+def site_applications_path(
+    multipath: bool = False,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param multipath: See `multipath `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: applications path shared by users
+
+    """
+    return PlatformDirs(
+        multipath=multipath,
+        ensure_exists=ensure_exists,
+    ).site_applications_path
+
+
+def user_runtime_path(  # noqa: PLR0913, PLR0917
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+    use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+    :param use_site_for_root: See `use_site_for_root `.
+
+    :returns: runtime path tied to the user
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+        use_site_for_root=use_site_for_root,
+    ).user_runtime_path
+
+
+def site_runtime_path(
+    appname: str | None = None,
+    appauthor: str | Literal[False] | None = None,
+    version: str | None = None,
+    opinion: bool = True,  # noqa: FBT001, FBT002
+    ensure_exists: bool = False,  # noqa: FBT001, FBT002
+) -> Path:
+    """:param appname: See `appname `.
+    :param appauthor: See `appauthor `.
+    :param version: See `version `.
+    :param opinion: See `opinion `.
+    :param ensure_exists: See `ensure_exists `.
+
+    :returns: runtime path shared by users
+
+    """
+    return PlatformDirs(
+        appname=appname,
+        appauthor=appauthor,
+        version=version,
+        opinion=opinion,
+        ensure_exists=ensure_exists,
+    ).site_runtime_path
+
+
+__all__ = [
+    "AppDirs",
+    "PlatformDirs",
+    "PlatformDirsABC",
+    "__version__",
+    "__version_info__",
+    "site_applications_dir",
+    "site_applications_path",
+    "site_bin_dir",
+    "site_bin_path",
+    "site_cache_dir",
+    "site_cache_path",
+    "site_config_dir",
+    "site_config_path",
+    "site_data_dir",
+    "site_data_path",
+    "site_log_dir",
+    "site_log_path",
+    "site_runtime_dir",
+    "site_runtime_path",
+    "site_state_dir",
+    "site_state_path",
+    "user_applications_dir",
+    "user_applications_path",
+    "user_bin_dir",
+    "user_bin_path",
+    "user_cache_dir",
+    "user_cache_path",
+    "user_config_dir",
+    "user_config_path",
+    "user_data_dir",
+    "user_data_path",
+    "user_desktop_dir",
+    "user_desktop_path",
+    "user_documents_dir",
+    "user_documents_path",
+    "user_downloads_dir",
+    "user_downloads_path",
+    "user_log_dir",
+    "user_log_path",
+    "user_music_dir",
+    "user_music_path",
+    "user_pictures_dir",
+    "user_pictures_path",
+    "user_runtime_dir",
+    "user_runtime_path",
+    "user_state_dir",
+    "user_state_path",
+    "user_videos_dir",
+    "user_videos_path",
+]
diff --git a/micromamba_root/Lib/site-packages/platformdirs/__main__.py b/micromamba_root/Lib/site-packages/platformdirs/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2490ffbbe1bbc1626bc961ca3e1e6a8a1effc083
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs/__main__.py
@@ -0,0 +1,61 @@
+"""Main entry point."""
+
+from __future__ import annotations
+
+from platformdirs import PlatformDirs, __version__
+
+PROPS = (
+    "user_data_dir",
+    "user_config_dir",
+    "user_cache_dir",
+    "user_state_dir",
+    "user_log_dir",
+    "user_documents_dir",
+    "user_downloads_dir",
+    "user_pictures_dir",
+    "user_videos_dir",
+    "user_music_dir",
+    "user_bin_dir",
+    "site_bin_dir",
+    "user_applications_dir",
+    "user_runtime_dir",
+    "site_data_dir",
+    "site_config_dir",
+    "site_cache_dir",
+    "site_state_dir",
+    "site_log_dir",
+    "site_applications_dir",
+    "site_runtime_dir",
+)
+
+
+def main() -> None:
+    """Run the main entry point."""
+    app_name = "MyApp"
+    app_author = "MyCompany"
+
+    print(f"-- platformdirs {__version__} --")  # noqa: T201
+
+    print("-- app dirs (with optional 'version')")  # noqa: T201
+    dirs = PlatformDirs(app_name, app_author, version="1.0")
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+    print("\n-- app dirs (without optional 'version')")  # noqa: T201
+    dirs = PlatformDirs(app_name, app_author)
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+    print("\n-- app dirs (without optional 'appauthor')")  # noqa: T201
+    dirs = PlatformDirs(app_name)
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+    print("\n-- app dirs (with disabled 'appauthor')")  # noqa: T201
+    dirs = PlatformDirs(app_name, appauthor=False)
+    for prop in PROPS:
+        print(f"{prop}: {getattr(dirs, prop)}")  # noqa: T201
+
+
+if __name__ == "__main__":
+    main()
diff --git a/micromamba_root/Lib/site-packages/platformdirs/_xdg.py b/micromamba_root/Lib/site-packages/platformdirs/_xdg.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ffbf93eb57c0a82184e8c069810f9ecc638927f
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs/_xdg.py
@@ -0,0 +1,143 @@
+"""XDG environment variable mixin for Unix and macOS."""
+
+from __future__ import annotations
+
+import os
+
+from .api import PlatformDirsABC
+
+
+class XDGMixin(PlatformDirsABC):
+    """Mixin that checks XDG environment variables, falling back to platform-specific defaults via ``super()``."""
+
+    @property
+    def user_data_dir(self) -> str:
+        """:returns: data directory tied to the user, from ``$XDG_DATA_HOME`` if set, else platform default"""
+        if path := os.environ.get("XDG_DATA_HOME", "").strip():
+            return self._append_app_name_and_version(path)
+        return super().user_data_dir
+
+    @property
+    def _site_data_dirs(self) -> list[str]:
+        if xdg_dirs := os.environ.get("XDG_DATA_DIRS", "").strip():
+            return [self._append_app_name_and_version(p) for p in xdg_dirs.split(os.pathsep) if p.strip()]
+        return super()._site_data_dirs
+
+    @property
+    def site_data_dir(self) -> str:
+        """:returns: data directories shared by users, from ``$XDG_DATA_DIRS`` if set, else platform default"""
+        dirs = self._site_data_dirs
+        return os.pathsep.join(dirs) if self.multipath else dirs[0]
+
+    @property
+    def user_config_dir(self) -> str:
+        """:returns: config directory tied to the user, from ``$XDG_CONFIG_HOME`` if set, else platform default"""
+        if path := os.environ.get("XDG_CONFIG_HOME", "").strip():
+            return self._append_app_name_and_version(path)
+        return super().user_config_dir
+
+    @property
+    def _site_config_dirs(self) -> list[str]:
+        if xdg_dirs := os.environ.get("XDG_CONFIG_DIRS", "").strip():
+            return [self._append_app_name_and_version(p) for p in xdg_dirs.split(os.pathsep) if p.strip()]
+        return super()._site_config_dirs
+
+    @property
+    def site_config_dir(self) -> str:
+        """:returns: config directories shared by users, from ``$XDG_CONFIG_DIRS`` if set, else platform default"""
+        dirs = self._site_config_dirs
+        return os.pathsep.join(dirs) if self.multipath else dirs[0]
+
+    @property
+    def user_cache_dir(self) -> str:
+        """:returns: cache directory tied to the user, from ``$XDG_CACHE_HOME`` if set, else platform default"""
+        if path := os.environ.get("XDG_CACHE_HOME", "").strip():
+            return self._append_app_name_and_version(path)
+        return super().user_cache_dir
+
+    @property
+    def user_state_dir(self) -> str:
+        """:returns: state directory tied to the user, from ``$XDG_STATE_HOME`` if set, else platform default"""
+        if path := os.environ.get("XDG_STATE_HOME", "").strip():
+            return self._append_app_name_and_version(path)
+        return super().user_state_dir
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """:returns: runtime directory tied to the user, from ``$XDG_RUNTIME_DIR`` if set, else platform default"""
+        if path := os.environ.get("XDG_RUNTIME_DIR", "").strip():
+            return self._append_app_name_and_version(path)
+        return super().user_runtime_dir
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:returns: runtime directory shared by users, from ``$XDG_RUNTIME_DIR`` if set, else platform default"""
+        if path := os.environ.get("XDG_RUNTIME_DIR", "").strip():
+            return self._append_app_name_and_version(path)
+        return super().site_runtime_dir
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:returns: documents directory tied to the user, from ``$XDG_DOCUMENTS_DIR`` if set, else platform default"""
+        if path := os.environ.get("XDG_DOCUMENTS_DIR", "").strip():
+            return os.path.expanduser(path)  # noqa: PTH111
+        return super().user_documents_dir
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:returns: downloads directory tied to the user, from ``$XDG_DOWNLOAD_DIR`` if set, else platform default"""
+        if path := os.environ.get("XDG_DOWNLOAD_DIR", "").strip():
+            return os.path.expanduser(path)  # noqa: PTH111
+        return super().user_downloads_dir
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:returns: pictures directory tied to the user, from ``$XDG_PICTURES_DIR`` if set, else platform default"""
+        if path := os.environ.get("XDG_PICTURES_DIR", "").strip():
+            return os.path.expanduser(path)  # noqa: PTH111
+        return super().user_pictures_dir
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:returns: videos directory tied to the user, from ``$XDG_VIDEOS_DIR`` if set, else platform default"""
+        if path := os.environ.get("XDG_VIDEOS_DIR", "").strip():
+            return os.path.expanduser(path)  # noqa: PTH111
+        return super().user_videos_dir
+
+    @property
+    def user_music_dir(self) -> str:
+        """:returns: music directory tied to the user, from ``$XDG_MUSIC_DIR`` if set, else platform default"""
+        if path := os.environ.get("XDG_MUSIC_DIR", "").strip():
+            return os.path.expanduser(path)  # noqa: PTH111
+        return super().user_music_dir
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:returns: desktop directory tied to the user, from ``$XDG_DESKTOP_DIR`` if set, else platform default"""
+        if path := os.environ.get("XDG_DESKTOP_DIR", "").strip():
+            return os.path.expanduser(path)  # noqa: PTH111
+        return super().user_desktop_dir
+
+    @property
+    def user_applications_dir(self) -> str:
+        """:returns: applications directory tied to the user, from ``$XDG_DATA_HOME`` if set, else platform default"""
+        if path := os.environ.get("XDG_DATA_HOME", "").strip():
+            return os.path.join(os.path.expanduser(path), "applications")  # noqa: PTH111, PTH118
+        return super().user_applications_dir
+
+    @property
+    def _site_applications_dirs(self) -> list[str]:
+        if xdg_dirs := os.environ.get("XDG_DATA_DIRS", "").strip():
+            return [os.path.join(p, "applications") for p in xdg_dirs.split(os.pathsep) if p.strip()]  # noqa: PTH118
+        return super()._site_applications_dirs
+
+    @property
+    def site_applications_dir(self) -> str:
+        """:returns: applications directories shared by users, from ``$XDG_DATA_DIRS`` if set, else platform default"""
+        dirs = self._site_applications_dirs
+        return os.pathsep.join(dirs) if self.multipath else dirs[0]
+
+
+__all__ = [
+    "XDGMixin",
+]
diff --git a/micromamba_root/Lib/site-packages/platformdirs/android.py b/micromamba_root/Lib/site-packages/platformdirs/android.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c798b95e3136dc1a750fd5fd6f7c37799caa46c
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs/android.py
@@ -0,0 +1,275 @@
+"""Android."""
+
+from __future__ import annotations
+
+import os
+import re
+import sys
+from functools import lru_cache
+from typing import TYPE_CHECKING, cast
+
+from .api import PlatformDirsABC
+
+
+class Android(PlatformDirsABC):  # noqa: PLR0904
+    """Platform directories for Android.
+
+    Follows the guidance `from here `_. Directories are typically located
+    under the app's private storage (``/data/user///``).
+
+    Makes use of the `appname `, `version
+    `, `opinion `, `ensure_exists
+    `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """:returns: data directory tied to the user, e.g. ``/data/user///files/``"""
+        return self._append_app_name_and_version(cast("str", _android_folder()), "files")
+
+    @property
+    def site_data_dir(self) -> str:
+        """:returns: data directory shared by users, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def user_config_dir(self) -> str:
+        """:returns: config directory tied to the user, e.g. ``/data/user///shared_prefs/``"""
+        return self._append_app_name_and_version(cast("str", _android_folder()), "shared_prefs")
+
+    @property
+    def site_config_dir(self) -> str:
+        """:returns: config directory shared by users, same as `user_config_dir`"""
+        return self.user_config_dir
+
+    @property
+    def user_cache_dir(self) -> str:
+        """:returns: cache directory tied to the user, e.g.,``/data/user///cache/``"""
+        return self._append_app_name_and_version(cast("str", _android_folder()), "cache")
+
+    @property
+    def site_cache_dir(self) -> str:
+        """:returns: cache directory shared by users, same as `user_cache_dir`"""
+        return self.user_cache_dir
+
+    @property
+    def user_state_dir(self) -> str:
+        """:returns: state directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def site_state_dir(self) -> str:
+        """:returns: state directory shared by users, same as `user_state_dir`"""
+        return self.user_state_dir
+
+    @property
+    def user_log_dir(self) -> str:
+        """:returns: log directory tied to the user, same as `user_cache_dir` if not opinionated else ``log`` in it, e.g. ``/data/user///cache//log``"""
+        path = self.user_cache_dir
+        if self.opinion:
+            path = os.path.join(path, "log")  # noqa: PTH118
+            self._optionally_create_directory(path)
+        return path
+
+    @property
+    def site_log_dir(self) -> str:
+        """:returns: log directory shared by users, same as `user_log_dir`"""
+        return self.user_log_dir
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:returns: documents directory tied to the user e.g. ``/storage/emulated/0/Documents``"""
+        return _android_documents_folder()
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:returns: downloads directory tied to the user e.g. ``/storage/emulated/0/Downloads``"""
+        return _android_downloads_folder()
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:returns: pictures directory tied to the user e.g. ``/storage/emulated/0/Pictures``"""
+        return _android_pictures_folder()
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:returns: videos directory tied to the user e.g. ``/storage/emulated/0/DCIM/Camera``"""
+        return _android_videos_folder()
+
+    @property
+    def user_music_dir(self) -> str:
+        """:returns: music directory tied to the user e.g. ``/storage/emulated/0/Music``"""
+        return _android_music_folder()
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:returns: desktop directory tied to the user e.g. ``/storage/emulated/0/Desktop``"""
+        return "/storage/emulated/0/Desktop"
+
+    @property
+    def user_bin_dir(self) -> str:
+        """:returns: bin directory tied to the user, e.g. ``/data/user///files/bin``"""
+        return os.path.join(cast("str", _android_folder()), "files", "bin")  # noqa: PTH118
+
+    @property
+    def site_bin_dir(self) -> str:
+        """:returns: bin directory shared by users, same as `user_bin_dir`"""
+        return self.user_bin_dir
+
+    @property
+    def user_applications_dir(self) -> str:
+        """:returns: applications directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def site_applications_dir(self) -> str:
+        """:returns: applications directory shared by users, same as `user_applications_dir`"""
+        return self.user_applications_dir
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """:returns: runtime directory tied to the user, same as `user_cache_dir` if not opinionated else ``tmp`` in it, e.g. ``/data/user///cache//tmp``"""
+        path = self.user_cache_dir
+        if self.opinion:
+            path = os.path.join(path, "tmp")  # noqa: PTH118
+            self._optionally_create_directory(path)
+        return path
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:returns: runtime directory shared by users, same as `user_runtime_dir`"""
+        return self.user_runtime_dir
+
+
+@lru_cache(maxsize=1)
+def _android_folder() -> str | None:  # noqa: C901
+    """:returns: base folder for the Android OS or None if it cannot be found"""
+    result: str | None = None
+    # type checker isn't happy with our "import android", just don't do this when type checking see
+    # https://stackoverflow.com/a/61394121
+    if not TYPE_CHECKING:
+        try:
+            # First try to get a path to android app using python4android (if available)...
+            from android import mActivity  # noqa: PLC0415
+
+            context = cast("android.content.Context", mActivity.getApplicationContext())  # noqa: F821
+            result = context.getFilesDir().getParentFile().getAbsolutePath()
+        except Exception:  # noqa: BLE001
+            result = None
+    if result is None:
+        try:
+            # ...and fall back to using plain pyjnius, if python4android isn't available or doesn't deliver any useful
+            # result...
+            from jnius import autoclass  # noqa: PLC0415  # ty: ignore[unresolved-import]
+
+            context = autoclass("android.content.Context")
+            result = context.getFilesDir().getParentFile().getAbsolutePath()
+        except Exception:  # noqa: BLE001
+            result = None
+    if result is None:
+        # and if that fails, too, find an android folder looking at path on the sys.path
+        # warning: only works for apps installed under /data, not adopted storage etc.
+        pattern = re.compile(r"/data/(data|user/\d+)/(.+)/files")
+        for path in sys.path:
+            if pattern.match(path):
+                result = path.split("/files")[0]
+                break
+        else:
+            result = None
+    if result is None:
+        # one last try: find an android folder looking at path on the sys.path taking adopted storage paths into
+        # account
+        pattern = re.compile(r"/mnt/expand/[a-fA-F0-9-]{36}/(data|user/\d+)/(.+)/files")
+        for path in sys.path:
+            if pattern.match(path):
+                result = path.split("/files")[0]
+                break
+        else:
+            result = None
+    return result
+
+
+@lru_cache(maxsize=1)
+def _android_documents_folder() -> str:
+    """:returns: documents folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415  # ty: ignore[unresolved-import]
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        documents_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DOCUMENTS).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        documents_dir = "/storage/emulated/0/Documents"
+
+    return documents_dir
+
+
+@lru_cache(maxsize=1)
+def _android_downloads_folder() -> str:
+    """:returns: downloads folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415  # ty: ignore[unresolved-import]
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        downloads_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        downloads_dir = "/storage/emulated/0/Downloads"
+
+    return downloads_dir
+
+
+@lru_cache(maxsize=1)
+def _android_pictures_folder() -> str:
+    """:returns: pictures folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415  # ty: ignore[unresolved-import]
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        pictures_dir: str = context.getExternalFilesDir(environment.DIRECTORY_PICTURES).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        pictures_dir = "/storage/emulated/0/Pictures"
+
+    return pictures_dir
+
+
+@lru_cache(maxsize=1)
+def _android_videos_folder() -> str:
+    """:returns: videos folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415  # ty: ignore[unresolved-import]
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        videos_dir: str = context.getExternalFilesDir(environment.DIRECTORY_DCIM).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        videos_dir = "/storage/emulated/0/DCIM/Camera"
+
+    return videos_dir
+
+
+@lru_cache(maxsize=1)
+def _android_music_folder() -> str:
+    """:returns: music folder for the Android OS"""
+    # Get directories with pyjnius
+    try:
+        from jnius import autoclass  # noqa: PLC0415  # ty: ignore[unresolved-import]
+
+        context = autoclass("android.content.Context")
+        environment = autoclass("android.os.Environment")
+        music_dir: str = context.getExternalFilesDir(environment.DIRECTORY_MUSIC).getAbsolutePath()
+    except Exception:  # noqa: BLE001
+        music_dir = "/storage/emulated/0/Music"
+
+    return music_dir
+
+
+__all__ = [
+    "Android",
+]
diff --git a/micromamba_root/Lib/site-packages/platformdirs/api.py b/micromamba_root/Lib/site-packages/platformdirs/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e3b9a97c6538c8456ffcd196407eb040238013d
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs/api.py
@@ -0,0 +1,413 @@
+"""Base API."""
+
+from __future__ import annotations
+
+import os
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Iterator
+    from typing import Literal
+
+
+class PlatformDirsABC(ABC):  # noqa: PLR0904
+    """Abstract base class defining all platform directory properties, their :class:`~pathlib.Path` variants, and iterators.
+
+    Platform-specific subclasses (e.g. :class:`~platformdirs.windows.Windows`, :class:`~platformdirs.macos.MacOS`,
+    :class:`~platformdirs.unix.Unix`) implement the abstract properties to return the appropriate paths for each
+    operating system.
+
+    """
+
+    def __init__(  # noqa: PLR0913, PLR0917
+        self,
+        appname: str | None = None,
+        appauthor: str | Literal[False] | None = None,
+        version: str | None = None,
+        roaming: bool = False,  # noqa: FBT001, FBT002
+        multipath: bool = False,  # noqa: FBT001, FBT002
+        opinion: bool = True,  # noqa: FBT001, FBT002
+        ensure_exists: bool = False,  # noqa: FBT001, FBT002
+        use_site_for_root: bool = False,  # noqa: FBT001, FBT002
+    ) -> None:
+        """Create a new platform directory.
+
+        :param appname: See `appname`.
+        :param appauthor: See `appauthor`.
+        :param version: See `version`.
+        :param roaming: See `roaming`.
+        :param multipath: See `multipath`.
+        :param opinion: See `opinion`.
+        :param ensure_exists: See `ensure_exists`.
+        :param use_site_for_root: See `use_site_for_root`.
+
+        """
+        self.appname = appname  #: The name of the application.
+        self.appauthor = appauthor
+        """The name of the app author or distributing body for this application.
+
+        Typically, it is the owning company name. Defaults to `appname`. You may pass ``False`` to disable it.
+
+        .. note::
+
+            On Windows, the directory structure is ``//``. When ``appauthor`` is ``None`` (the
+            default), it falls back to ``appname``, resulting in ``//`` (e.g.
+            ``AppData/Local/myapp/myapp``). Pass ``appauthor=False`` to omit the author directory entirely and get
+            ``/``.
+
+        """
+        self.version = version
+        """An optional version path element to append to the path.
+
+        You might want to use this if you want multiple versions of your app to be able to run independently. If used,
+        this would typically be ``.``.
+
+        """
+        self.roaming = roaming
+        """Whether to use the roaming appdata directory on Windows.
+
+        That means that for users on a Windows network setup for roaming profiles, this user data will be synced on
+        login (see `here `_).
+
+        """
+        self.multipath = multipath
+        """An optional parameter which indicates that the entire list of data dirs should be returned.
+
+        By default, the first item would only be returned. Only affects ``site_data_dir`` and ``site_config_dir`` on
+        Unix and macOS.
+
+        """
+        self.opinion = opinion
+        """Whether to use opinionated values.
+
+        When enabled, appends an additional subdirectory for certain directories: e.g. ``Cache`` for cache and ``Logs``
+        for logs on Windows, ``log`` for logs on Unix.
+
+        """
+        self.ensure_exists = ensure_exists
+        """Optionally create the directory (and any missing parents) upon access if it does not exist.
+
+        By default, no directories are created.
+
+        """
+        self.use_site_for_root = use_site_for_root
+        """Whether to redirect ``user_*_dir`` calls to their ``site_*_dir`` equivalents when running as root (uid 0).
+
+        Only has an effect on Unix. Disabled by default for backwards compatibility. When enabled, XDG user environment
+        variables (e.g. ``XDG_DATA_HOME``) are bypassed for the redirected directories.
+
+        """
+
+    def _append_app_name_and_version(self, *base: str) -> str:
+        params = list(base[1:])
+        if self.appname:
+            params.append(self.appname)
+            if self.version:
+                params.append(self.version)
+        path = os.path.join(base[0], *params)  # noqa: PTH118
+        self._optionally_create_directory(path)
+        return path
+
+    def _optionally_create_directory(self, path: str) -> None:
+        if self.ensure_exists:
+            Path(path).mkdir(parents=True, exist_ok=True)
+
+    def _first_item_as_path_if_multipath(self, directory: str) -> Path:
+        if self.multipath:
+            # If multipath is True, the first path is returned.
+            directory = directory.partition(os.pathsep)[0]
+        return Path(directory)
+
+    @property
+    @abstractmethod
+    def user_data_dir(self) -> str:
+        """:returns: data directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_data_dir(self) -> str:
+        """:returns: data directory shared by users"""
+
+    @property
+    def _site_data_dirs(self) -> list[str]:
+        raise NotImplementedError
+
+    @property
+    @abstractmethod
+    def user_config_dir(self) -> str:
+        """:returns: config directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_config_dir(self) -> str:
+        """:returns: config directory shared by users"""
+
+    @property
+    def _site_config_dirs(self) -> list[str]:
+        raise NotImplementedError
+
+    @property
+    @abstractmethod
+    def user_cache_dir(self) -> str:
+        """:returns: cache directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_cache_dir(self) -> str:
+        """:returns: cache directory shared by users"""
+
+    @property
+    @abstractmethod
+    def user_state_dir(self) -> str:
+        """:returns: state directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_state_dir(self) -> str:
+        """:returns: state directory shared by users"""
+
+    @property
+    @abstractmethod
+    def user_log_dir(self) -> str:
+        """:returns: log directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_log_dir(self) -> str:
+        """:returns: log directory shared by users"""
+
+    @property
+    @abstractmethod
+    def user_documents_dir(self) -> str:
+        """:returns: documents directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_downloads_dir(self) -> str:
+        """:returns: downloads directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_pictures_dir(self) -> str:
+        """:returns: pictures directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_videos_dir(self) -> str:
+        """:returns: videos directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_music_dir(self) -> str:
+        """:returns: music directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_desktop_dir(self) -> str:
+        """:returns: desktop directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def user_bin_dir(self) -> str:
+        """:returns: bin directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_bin_dir(self) -> str:
+        """:returns: bin directory shared by users"""
+
+    @property
+    @abstractmethod
+    def user_applications_dir(self) -> str:
+        """:returns: applications directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_applications_dir(self) -> str:
+        """:returns: applications directory shared by users"""
+
+    @property
+    def _site_applications_dirs(self) -> list[str]:
+        raise NotImplementedError
+
+    @property
+    @abstractmethod
+    def user_runtime_dir(self) -> str:
+        """:returns: runtime directory tied to the user"""
+
+    @property
+    @abstractmethod
+    def site_runtime_dir(self) -> str:
+        """:returns: runtime directory shared by users"""
+
+    @property
+    def user_data_path(self) -> Path:
+        """:returns: data path tied to the user"""
+        return Path(self.user_data_dir)
+
+    @property
+    def site_data_path(self) -> Path:
+        """:returns: data path shared by users"""
+        return Path(self.site_data_dir)
+
+    @property
+    def user_config_path(self) -> Path:
+        """:returns: config path tied to the user"""
+        return Path(self.user_config_dir)
+
+    @property
+    def site_config_path(self) -> Path:
+        """:returns: config path shared by users"""
+        return Path(self.site_config_dir)
+
+    @property
+    def user_cache_path(self) -> Path:
+        """:returns: cache path tied to the user"""
+        return Path(self.user_cache_dir)
+
+    @property
+    def site_cache_path(self) -> Path:
+        """:returns: cache path shared by users"""
+        return Path(self.site_cache_dir)
+
+    @property
+    def user_state_path(self) -> Path:
+        """:returns: state path tied to the user"""
+        return Path(self.user_state_dir)
+
+    @property
+    def site_state_path(self) -> Path:
+        """:returns: state path shared by users"""
+        return Path(self.site_state_dir)
+
+    @property
+    def user_log_path(self) -> Path:
+        """:returns: log path tied to the user"""
+        return Path(self.user_log_dir)
+
+    @property
+    def site_log_path(self) -> Path:
+        """:returns: log path shared by users"""
+        return Path(self.site_log_dir)
+
+    @property
+    def user_documents_path(self) -> Path:
+        """:returns: documents path tied to the user"""
+        return Path(self.user_documents_dir)
+
+    @property
+    def user_downloads_path(self) -> Path:
+        """:returns: downloads path tied to the user"""
+        return Path(self.user_downloads_dir)
+
+    @property
+    def user_pictures_path(self) -> Path:
+        """:returns: pictures path tied to the user"""
+        return Path(self.user_pictures_dir)
+
+    @property
+    def user_videos_path(self) -> Path:
+        """:returns: videos path tied to the user"""
+        return Path(self.user_videos_dir)
+
+    @property
+    def user_music_path(self) -> Path:
+        """:returns: music path tied to the user"""
+        return Path(self.user_music_dir)
+
+    @property
+    def user_desktop_path(self) -> Path:
+        """:returns: desktop path tied to the user"""
+        return Path(self.user_desktop_dir)
+
+    @property
+    def user_bin_path(self) -> Path:
+        """:returns: bin path tied to the user"""
+        return Path(self.user_bin_dir)
+
+    @property
+    def site_bin_path(self) -> Path:
+        """:returns: bin path shared by users"""
+        return Path(self.site_bin_dir)
+
+    @property
+    def user_applications_path(self) -> Path:
+        """:returns: applications path tied to the user"""
+        return Path(self.user_applications_dir)
+
+    @property
+    def site_applications_path(self) -> Path:
+        """:returns: applications path shared by users"""
+        return Path(self.site_applications_dir)
+
+    @property
+    def user_runtime_path(self) -> Path:
+        """:returns: runtime path tied to the user"""
+        return Path(self.user_runtime_dir)
+
+    @property
+    def site_runtime_path(self) -> Path:
+        """:returns: runtime path shared by users"""
+        return Path(self.site_runtime_dir)
+
+    def iter_config_dirs(self) -> Iterator[str]:
+        """:yield: all user and site configuration directories."""
+        yield self.user_config_dir
+        yield self.site_config_dir
+
+    def iter_data_dirs(self) -> Iterator[str]:
+        """:yield: all user and site data directories."""
+        yield self.user_data_dir
+        yield self.site_data_dir
+
+    def iter_cache_dirs(self) -> Iterator[str]:
+        """:yield: all user and site cache directories."""
+        yield self.user_cache_dir
+        yield self.site_cache_dir
+
+    def iter_state_dirs(self) -> Iterator[str]:
+        """:yield: all user and site state directories."""
+        yield self.user_state_dir
+        yield self.site_state_dir
+
+    def iter_log_dirs(self) -> Iterator[str]:
+        """:yield: all user and site log directories."""
+        yield self.user_log_dir
+        yield self.site_log_dir
+
+    def iter_runtime_dirs(self) -> Iterator[str]:
+        """:yield: all user and site runtime directories."""
+        yield self.user_runtime_dir
+        yield self.site_runtime_dir
+
+    def iter_config_paths(self) -> Iterator[Path]:
+        """:yield: all user and site configuration paths."""
+        for path in self.iter_config_dirs():
+            yield Path(path)
+
+    def iter_data_paths(self) -> Iterator[Path]:
+        """:yield: all user and site data paths."""
+        for path in self.iter_data_dirs():
+            yield Path(path)
+
+    def iter_cache_paths(self) -> Iterator[Path]:
+        """:yield: all user and site cache paths."""
+        for path in self.iter_cache_dirs():
+            yield Path(path)
+
+    def iter_state_paths(self) -> Iterator[Path]:
+        """:yield: all user and site state paths."""
+        for path in self.iter_state_dirs():
+            yield Path(path)
+
+    def iter_log_paths(self) -> Iterator[Path]:
+        """:yield: all user and site log paths."""
+        for path in self.iter_log_dirs():
+            yield Path(path)
+
+    def iter_runtime_paths(self) -> Iterator[Path]:
+        """:yield: all user and site runtime paths."""
+        for path in self.iter_runtime_dirs():
+            yield Path(path)
diff --git a/micromamba_root/Lib/site-packages/platformdirs/macos.py b/micromamba_root/Lib/site-packages/platformdirs/macos.py
new file mode 100644
index 0000000000000000000000000000000000000000..26447e396e38d61be2f9cc4bbb5ce4f0dcf3bb93
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs/macos.py
@@ -0,0 +1,193 @@
+"""macOS."""
+
+from __future__ import annotations
+
+import os.path
+import sys
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+    from collections.abc import Iterator
+
+from ._xdg import XDGMixin
+from .api import PlatformDirsABC
+
+if TYPE_CHECKING:
+    from pathlib import Path
+
+
+class _MacOSDefaults(PlatformDirsABC):  # noqa: PLR0904
+    """Default platform directories for macOS without XDG environment variable overrides.
+
+    Follows the guidance from `Apple's File System Programming Guide
+    `_.
+    The XDG env var handling is in :class:`~platformdirs._xdg.XDGMixin`.
+
+    """
+
+    def _base_user_app_support_dir(self) -> str:
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Application Support"))  # noqa: PTH111
+
+    def _base_site_dirs(self) -> list[str]:
+        is_homebrew = "/opt/python" in sys.prefix
+        homebrew_prefix = sys.prefix.split("/opt/python")[0] if is_homebrew else ""
+        path_list = [self._append_app_name_and_version(f"{homebrew_prefix}/share")] if is_homebrew else []
+        path_list.append(self._append_app_name_and_version("/Library/Application Support"))
+        return path_list
+
+    @property
+    def user_data_dir(self) -> str:
+        """:returns: data directory tied to the user, e.g. ``~/Library/Application Support/$appname/$version``"""
+        return self._base_user_app_support_dir()
+
+    @property
+    def _site_data_dirs(self) -> list[str]:
+        return self._base_site_dirs()
+
+    @property
+    def site_data_path(self) -> Path:
+        """:returns: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_data_dir)
+
+    @property
+    def user_config_dir(self) -> str:
+        """:returns: config directory tied to the user, same as `user_data_dir`"""
+        return self._base_user_app_support_dir()
+
+    @property
+    def _site_config_dirs(self) -> list[str]:
+        return self._base_site_dirs()
+
+    @property
+    def user_cache_dir(self) -> str:
+        """:returns: cache directory tied to the user, e.g. ``~/Library/Caches/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches"))  # noqa: PTH111
+
+    @property
+    def site_cache_dir(self) -> str:
+        """:returns: cache directory shared by users, e.g. ``/Library/Caches/$appname/$version``. If we're using a Python binary managed by `Homebrew `_, the directory will be under the Homebrew prefix, e.g. ``$homebrew_prefix/var/cache/$appname/$version``. If `multipath ` is enabled, and we're in Homebrew, the response is a multi-path string separated by ":", e.g. ``$homebrew_prefix/var/cache/$appname/$version:/Library/Caches/$appname/$version``"""
+        is_homebrew = "/opt/python" in sys.prefix
+        homebrew_prefix = sys.prefix.split("/opt/python")[0] if is_homebrew else ""
+        path_list = [self._append_app_name_and_version(f"{homebrew_prefix}/var/cache")] if is_homebrew else []
+        path_list.append(self._append_app_name_and_version("/Library/Caches"))
+        if self.multipath:
+            return os.pathsep.join(path_list)
+        return path_list[0]
+
+    @property
+    def site_cache_path(self) -> Path:
+        """:returns: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_cache_dir)
+
+    @property
+    def user_state_dir(self) -> str:
+        """:returns: state directory tied to the user, same as `user_data_dir`"""
+        return self._base_user_app_support_dir()
+
+    @property
+    def site_state_dir(self) -> str:
+        """:returns: state directory shared by users, same as `site_data_dir`"""
+        return self._base_site_dirs()[0]
+
+    @property
+    def user_log_dir(self) -> str:
+        """:returns: log directory tied to the user, e.g. ``~/Library/Logs/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Logs"))  # noqa: PTH111
+
+    @property
+    def site_log_dir(self) -> str:
+        """:returns: log directory shared by users, e.g. ``/Library/Logs/$appname/$version``"""
+        return self._append_app_name_and_version("/Library/Logs")
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:returns: documents directory tied to the user, e.g. ``~/Documents``"""
+        return os.path.expanduser("~/Documents")  # noqa: PTH111
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:returns: downloads directory tied to the user, e.g. ``~/Downloads``"""
+        return os.path.expanduser("~/Downloads")  # noqa: PTH111
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:returns: pictures directory tied to the user, e.g. ``~/Pictures``"""
+        return os.path.expanduser("~/Pictures")  # noqa: PTH111
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:returns: videos directory tied to the user, e.g. ``~/Movies``"""
+        return os.path.expanduser("~/Movies")  # noqa: PTH111
+
+    @property
+    def user_music_dir(self) -> str:
+        """:returns: music directory tied to the user, e.g. ``~/Music``"""
+        return os.path.expanduser("~/Music")  # noqa: PTH111
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:returns: desktop directory tied to the user, e.g. ``~/Desktop``"""
+        return os.path.expanduser("~/Desktop")  # noqa: PTH111
+
+    @property
+    def user_bin_dir(self) -> str:
+        """:returns: bin directory tied to the user, e.g. ``~/.local/bin``"""
+        return os.path.expanduser("~/.local/bin")  # noqa: PTH111
+
+    @property
+    def site_bin_dir(self) -> str:
+        """:returns: bin directory shared by users, e.g. ``/usr/local/bin``"""
+        return "/usr/local/bin"
+
+    @property
+    def user_applications_dir(self) -> str:
+        """:returns: applications directory tied to the user, e.g. ``~/Applications``"""
+        return os.path.expanduser("~/Applications")  # noqa: PTH111
+
+    @property
+    def _site_applications_dirs(self) -> list[str]:
+        return ["/Applications"]
+
+    @property
+    def site_applications_dir(self) -> str:
+        """:returns: applications directory shared by users, e.g. ``/Applications``"""
+        dirs = self._site_applications_dirs
+        return os.pathsep.join(dirs) if self.multipath else dirs[0]
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """:returns: runtime directory tied to the user, e.g. ``~/Library/Caches/TemporaryItems/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/Library/Caches/TemporaryItems"))  # noqa: PTH111
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:returns: runtime directory shared by users, same as `user_runtime_dir`"""
+        return self.user_runtime_dir
+
+    def iter_config_dirs(self) -> Iterator[str]:
+        """:yield: all user and site configuration directories."""
+        yield self.user_config_dir
+        yield from self._site_config_dirs
+
+    def iter_data_dirs(self) -> Iterator[str]:
+        """:yield: all user and site data directories."""
+        yield self.user_data_dir
+        yield from self._site_data_dirs
+
+
+class MacOS(XDGMixin, _MacOSDefaults):
+    """Platform directories for the macOS operating system.
+
+    Follows the guidance from `Apple documentation
+    `_.
+    Makes use of the `appname `, `version
+    `, `ensure_exists `.
+
+    XDG environment variables (e.g. ``$XDG_DATA_HOME``) are supported and take precedence over macOS defaults.
+
+    """
+
+
+__all__ = [
+    "MacOS",
+]
diff --git a/micromamba_root/Lib/site-packages/platformdirs/py.typed b/micromamba_root/Lib/site-packages/platformdirs/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/Lib/site-packages/platformdirs/unix.py b/micromamba_root/Lib/site-packages/platformdirs/unix.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ec5a6bc71839e1ade4fee8f84035ac3dc11454b
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs/unix.py
@@ -0,0 +1,296 @@
+"""Unix."""
+
+from __future__ import annotations
+
+import os
+import sys
+from configparser import ConfigParser
+from functools import cached_property
+from pathlib import Path
+from tempfile import gettempdir
+from typing import TYPE_CHECKING, NoReturn
+
+from ._xdg import XDGMixin
+from .api import PlatformDirsABC
+
+if TYPE_CHECKING:
+    from collections.abc import Iterator
+
+if sys.platform == "win32":
+
+    def getuid() -> NoReturn:
+        msg = "should only be used on Unix"
+        raise RuntimeError(msg)
+
+else:
+    from os import getuid
+
+
+class _UnixDefaults(PlatformDirsABC):  # noqa: PLR0904
+    """Default directories for Unix/Linux without XDG environment variable overrides.
+
+    The XDG env var handling is in :class:`~platformdirs._xdg.XDGMixin`.
+
+    """
+
+    @cached_property
+    def _use_site(self) -> bool:
+        return self.use_site_for_root and getuid() == 0
+
+    @property
+    def user_data_dir(self) -> str:
+        """:returns: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or ``$XDG_DATA_HOME/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/.local/share"))  # noqa: PTH111
+
+    @property
+    def _site_data_dirs(self) -> list[str]:
+        return [self._append_app_name_and_version("/usr/local/share"), self._append_app_name_and_version("/usr/share")]
+
+    @property
+    def user_config_dir(self) -> str:
+        """:returns: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or ``$XDG_CONFIG_HOME/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/.config"))  # noqa: PTH111
+
+    @property
+    def _site_config_dirs(self) -> list[str]:
+        return [self._append_app_name_and_version("/etc/xdg")]
+
+    @property
+    def user_cache_dir(self) -> str:
+        """:returns: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or ``$XDG_CACHE_HOME/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/.cache"))  # noqa: PTH111
+
+    @property
+    def site_cache_dir(self) -> str:
+        """:returns: cache directory shared by users, e.g. ``/var/cache/$appname/$version``"""
+        return self._append_app_name_and_version("/var/cache")
+
+    @property
+    def user_state_dir(self) -> str:
+        """:returns: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or ``$XDG_STATE_HOME/$appname/$version``"""
+        return self._append_app_name_and_version(os.path.expanduser("~/.local/state"))  # noqa: PTH111
+
+    @property
+    def site_state_dir(self) -> str:
+        """:returns: state directory shared by users, e.g. ``/var/lib/$appname/$version``"""
+        return self._append_app_name_and_version("/var/lib")
+
+    @property
+    def user_log_dir(self) -> str:
+        """:returns: log directory tied to the user, same as `user_state_dir` if not opinionated else ``log`` in it"""
+        path = self.user_state_dir
+        if self.opinion:
+            path = os.path.join(path, "log")  # noqa: PTH118
+            self._optionally_create_directory(path)
+        return path
+
+    @property
+    def site_log_dir(self) -> str:
+        """:returns: log directory shared by users, e.g. ``/var/log/$appname/$version``
+
+        Unlike `user_log_dir`, ``opinion`` has no effect since ``/var/log`` is inherently a log directory.
+
+        """
+        return self._append_app_name_and_version("/var/log")
+
+    @property
+    def user_documents_dir(self) -> str:
+        """:returns: documents directory tied to the user, e.g. ``~/Documents``"""
+        return _get_user_media_dir("XDG_DOCUMENTS_DIR", "~/Documents")
+
+    @property
+    def user_downloads_dir(self) -> str:
+        """:returns: downloads directory tied to the user, e.g. ``~/Downloads``"""
+        return _get_user_media_dir("XDG_DOWNLOAD_DIR", "~/Downloads")
+
+    @property
+    def user_pictures_dir(self) -> str:
+        """:returns: pictures directory tied to the user, e.g. ``~/Pictures``"""
+        return _get_user_media_dir("XDG_PICTURES_DIR", "~/Pictures")
+
+    @property
+    def user_videos_dir(self) -> str:
+        """:returns: videos directory tied to the user, e.g. ``~/Videos``"""
+        return _get_user_media_dir("XDG_VIDEOS_DIR", "~/Videos")
+
+    @property
+    def user_music_dir(self) -> str:
+        """:returns: music directory tied to the user, e.g. ``~/Music``"""
+        return _get_user_media_dir("XDG_MUSIC_DIR", "~/Music")
+
+    @property
+    def user_desktop_dir(self) -> str:
+        """:returns: desktop directory tied to the user, e.g. ``~/Desktop``"""
+        return _get_user_media_dir("XDG_DESKTOP_DIR", "~/Desktop")
+
+    @property
+    def user_bin_dir(self) -> str:
+        """:returns: bin directory tied to the user, e.g. ``~/.local/bin``"""
+        return os.path.expanduser("~/.local/bin")  # noqa: PTH111
+
+    @property
+    def site_bin_dir(self) -> str:
+        """:returns: bin directory shared by users, e.g. ``/usr/local/bin``"""
+        return "/usr/local/bin"
+
+    @property
+    def user_applications_dir(self) -> str:
+        """:returns: applications directory tied to the user, e.g. ``~/.local/share/applications``"""
+        return os.path.join(os.path.expanduser("~/.local/share"), "applications")  # noqa: PTH111, PTH118
+
+    @property
+    def _site_applications_dirs(self) -> list[str]:
+        return [os.path.join(p, "applications") for p in ["/usr/local/share", "/usr/share"]]  # noqa: PTH118
+
+    @property
+    def site_applications_dir(self) -> str:
+        """:returns: applications directory shared by users, e.g. ``/usr/share/applications``"""
+        dirs = self._site_applications_dirs
+        return os.pathsep.join(dirs) if self.multipath else dirs[0]
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """:returns: runtime directory tied to the user, e.g. ``$XDG_RUNTIME_DIR/$appname/$version``.
+
+        If ``$XDG_RUNTIME_DIR`` is unset, tries the platform default (``/tmp/run/user/$(id -u)`` on OpenBSD, ``/var/run/user/$(id -u)`` on FreeBSD/NetBSD, ``/run/user/$(id -u)`` otherwise). If the default is not writable, falls back to a temporary directory.
+
+        """
+        if sys.platform.startswith("openbsd"):
+            path = f"/tmp/run/user/{getuid()}"  # noqa: S108
+        elif sys.platform.startswith(("freebsd", "netbsd")):
+            path = f"/var/run/user/{getuid()}"
+        else:
+            path = f"/run/user/{getuid()}"
+        if not os.access(path, os.W_OK):
+            path = f"{gettempdir()}/runtime-{getuid()}"
+        return self._append_app_name_and_version(path)
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:returns: runtime directory shared by users, e.g. ``/run/$appname/$version`` or ``$XDG_RUNTIME_DIR/$appname/$version``.
+
+        Note that this behaves almost exactly like `user_runtime_dir` if ``$XDG_RUNTIME_DIR`` is set, but will fall back to paths associated to the root user instead of a regular logged-in user if it's not set.
+
+        If you wish to ensure that a logged-in root user path is returned e.g. ``/run/user/0``, use `user_runtime_dir` instead.
+
+        For FreeBSD/OpenBSD/NetBSD, it would return ``/var/run/$appname/$version`` if ``$XDG_RUNTIME_DIR`` is not set.
+
+        """
+        if sys.platform.startswith(("freebsd", "openbsd", "netbsd")):
+            path = "/var/run"
+        else:
+            path = "/run"
+        return self._append_app_name_and_version(path)
+
+    @property
+    def site_data_path(self) -> Path:
+        """:returns: data path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_data_dir)
+
+    @property
+    def site_config_path(self) -> Path:
+        """:returns: config path shared by users, returns the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_config_dir)
+
+    @property
+    def site_cache_path(self) -> Path:
+        """:returns: cache path shared by users. Only return the first item, even if ``multipath`` is set to ``True``"""
+        return self._first_item_as_path_if_multipath(self.site_cache_dir)
+
+    def iter_config_dirs(self) -> Iterator[str]:
+        """:yield: all user and site configuration directories."""
+        if not self._use_site:
+            yield self.user_config_dir
+        yield from self._site_config_dirs
+
+    def iter_data_dirs(self) -> Iterator[str]:
+        """:yield: all user and site data directories."""
+        if not self._use_site:
+            yield self.user_data_dir
+        yield from self._site_data_dirs
+
+
+class Unix(XDGMixin, _UnixDefaults):
+    """On Unix/Linux, we follow the `XDG Basedir Spec `_.
+
+    The spec allows overriding directories with environment variables. The examples shown are the default values,
+    alongside the name of the environment variable that overrides them. Makes use of the `appname
+    `, `version `, `multipath
+    `, `opinion `, `ensure_exists
+    `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        """:returns: data directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
+        return self.site_data_dir if self._use_site else super().user_data_dir
+
+    @property
+    def user_config_dir(self) -> str:
+        """:returns: config directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
+        return self.site_config_dir if self._use_site else super().user_config_dir
+
+    @property
+    def user_cache_dir(self) -> str:
+        """:returns: cache directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
+        return self.site_cache_dir if self._use_site else super().user_cache_dir
+
+    @property
+    def user_state_dir(self) -> str:
+        """:returns: state directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
+        return self.site_state_dir if self._use_site else super().user_state_dir
+
+    @property
+    def user_log_dir(self) -> str:
+        """:returns: log directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
+        return self.site_log_dir if self._use_site else super().user_log_dir
+
+    @property
+    def user_applications_dir(self) -> str:
+        """:returns: applications directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
+        return self.site_applications_dir if self._use_site else super().user_applications_dir
+
+    @property
+    def user_runtime_dir(self) -> str:
+        """:returns: runtime directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
+        return self.site_runtime_dir if self._use_site else super().user_runtime_dir
+
+    @property
+    def user_bin_dir(self) -> str:
+        """:returns: bin directory tied to the user, or site equivalent when root with ``use_site_for_root``"""
+        return self.site_bin_dir if self._use_site else super().user_bin_dir
+
+
+def _get_user_media_dir(env_var: str, fallback_tilde_path: str) -> str:
+    if media_dir := _get_user_dirs_folder(env_var):
+        return media_dir
+    return os.path.expanduser(fallback_tilde_path)  # noqa: PTH111
+
+
+def _get_user_dirs_folder(key: str) -> str | None:
+    """Return directory from user-dirs.dirs config file.
+
+    See https://freedesktop.org/wiki/Software/xdg-user-dirs/.
+
+    """
+    config_home = os.environ.get("XDG_CONFIG_HOME", "").strip() or os.path.expanduser("~/.config")  # noqa: PTH111
+    user_dirs_config_path = Path(config_home) / "user-dirs.dirs"
+    if user_dirs_config_path.exists():
+        parser = ConfigParser()
+
+        with user_dirs_config_path.open() as stream:
+            parser.read_string(f"[top]\n{stream.read()}")
+
+        if key not in parser["top"]:
+            return None
+
+        path = parser["top"][key].strip('"')
+        return path.replace("$HOME", os.path.expanduser("~"))  # noqa: PTH111
+
+    return None
+
+
+__all__ = [
+    "Unix",
+]
diff --git a/micromamba_root/Lib/site-packages/platformdirs/version.py b/micromamba_root/Lib/site-packages/platformdirs/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..220c58a5247f52206d70af62cee1539e9a17354d
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs/version.py
@@ -0,0 +1,34 @@
+# file generated by setuptools-scm
+# don't change, don't track in version control
+
+__all__ = [
+    "__version__",
+    "__version_tuple__",
+    "version",
+    "version_tuple",
+    "__commit_id__",
+    "commit_id",
+]
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+    from typing import Tuple
+    from typing import Union
+
+    VERSION_TUPLE = Tuple[Union[int, str], ...]
+    COMMIT_ID = Union[str, None]
+else:
+    VERSION_TUPLE = object
+    COMMIT_ID = object
+
+version: str
+__version__: str
+__version_tuple__: VERSION_TUPLE
+version_tuple: VERSION_TUPLE
+commit_id: COMMIT_ID
+__commit_id__: COMMIT_ID
+
+__version__ = version = '4.9.6'
+__version_tuple__ = version_tuple = (4, 9, 6)
+
+__commit_id__ = commit_id = None
diff --git a/micromamba_root/Lib/site-packages/platformdirs/windows.py b/micromamba_root/Lib/site-packages/platformdirs/windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..47403dea5efe90751e3af5a0380430687073279b
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/platformdirs/windows.py
@@ -0,0 +1,369 @@
+"""Windows."""
+
+from __future__ import annotations
+
+import os
+import sys
+from typing import TYPE_CHECKING, Final
+
+from .api import PlatformDirsABC
+
+if TYPE_CHECKING:
+    from collections.abc import Callable
+
+# Not exposed by CPython; defined in the Windows SDK (shlobj_core.h)
+_KF_FLAG_DONT_VERIFY: Final[int] = 0x00004000
+
+
+class Windows(PlatformDirsABC):  # noqa: PLR0904
+    """`MSDN on where to store app data files `_.
+
+    Makes use of the `appname `, `appauthor
+    `, `version `, `roaming
+    `, `opinion `, `ensure_exists
+    `.
+
+    """
+
+    @property
+    def user_data_dir(self) -> str:
+        r""":returns: data directory tied to the user, e.g. ``%USERPROFILE%\AppData\Local\$appauthor\$appname`` (not roaming) or ``%USERPROFILE%\AppData\Roaming\$appauthor\$appname`` (roaming)"""
+        const = "CSIDL_APPDATA" if self.roaming else "CSIDL_LOCAL_APPDATA"
+        path = os.path.normpath(get_win_folder(const))
+        return self._append_parts(path)
+
+    def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:
+        params = []
+        if self.appname:
+            if self.appauthor is not False:
+                author = self.appauthor or self.appname
+                params.append(author)
+            params.append(self.appname)
+            if opinion_value is not None and self.opinion:
+                params.append(opinion_value)
+            if self.version:
+                params.append(self.version)
+        path = os.path.join(path, *params)  # noqa: PTH118
+        self._optionally_create_directory(path)
+        return path
+
+    @property
+    def site_data_dir(self) -> str:
+        r""":returns: data directory shared by users, e.g. ``C:\ProgramData\$appauthor\$appname``"""
+        path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
+        return self._append_parts(path)
+
+    @property
+    def user_config_dir(self) -> str:
+        """:returns: config directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def site_config_dir(self) -> str:
+        """:returns: config directory shared by users, same as `site_data_dir`"""
+        return self.site_data_dir
+
+    @property
+    def user_cache_dir(self) -> str:
+        r""":returns: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g. ``%USERPROFILE%\AppData\Local\$appauthor\$appname\Cache\$version``"""
+        path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA"))
+        return self._append_parts(path, opinion_value="Cache")
+
+    @property
+    def site_cache_dir(self) -> str:
+        r""":returns: cache directory shared by users, e.g. ``C:\ProgramData\$appauthor\$appname\Cache\$version``"""
+        path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
+        return self._append_parts(path, opinion_value="Cache")
+
+    @property
+    def user_state_dir(self) -> str:
+        """:returns: state directory tied to the user, same as `user_data_dir`"""
+        return self.user_data_dir
+
+    @property
+    def site_state_dir(self) -> str:
+        """:returns: state directory shared by users, same as `site_data_dir`"""
+        return self.site_data_dir
+
+    @property
+    def user_log_dir(self) -> str:
+        """:returns: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it"""
+        path = self.user_data_dir
+        if self.opinion:
+            path = os.path.join(path, "Logs")  # noqa: PTH118
+            self._optionally_create_directory(path)
+        return path
+
+    @property
+    def site_log_dir(self) -> str:
+        """:returns: log directory shared by users, same as `site_data_dir` if not opinionated else ``Logs`` in it"""
+        path = self.site_data_dir
+        if self.opinion:
+            path = os.path.join(path, "Logs")  # noqa: PTH118
+            self._optionally_create_directory(path)
+        return path
+
+    @property
+    def user_documents_dir(self) -> str:
+        r""":returns: documents directory tied to the user e.g. ``%USERPROFILE%\Documents``"""
+        return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))
+
+    @property
+    def user_downloads_dir(self) -> str:
+        r""":returns: downloads directory tied to the user e.g. ``%USERPROFILE%\Downloads``"""
+        return os.path.normpath(get_win_folder("CSIDL_DOWNLOADS"))
+
+    @property
+    def user_pictures_dir(self) -> str:
+        r""":returns: pictures directory tied to the user e.g. ``%USERPROFILE%\Pictures``"""
+        return os.path.normpath(get_win_folder("CSIDL_MYPICTURES"))
+
+    @property
+    def user_videos_dir(self) -> str:
+        r""":returns: videos directory tied to the user e.g. ``%USERPROFILE%\Videos``"""
+        return os.path.normpath(get_win_folder("CSIDL_MYVIDEO"))
+
+    @property
+    def user_music_dir(self) -> str:
+        r""":returns: music directory tied to the user e.g. ``%USERPROFILE%\Music``"""
+        return os.path.normpath(get_win_folder("CSIDL_MYMUSIC"))
+
+    @property
+    def user_desktop_dir(self) -> str:
+        r""":returns: desktop directory tied to the user, e.g. ``%USERPROFILE%\Desktop``"""
+        return os.path.normpath(get_win_folder("CSIDL_DESKTOPDIRECTORY"))
+
+    @property
+    def user_bin_dir(self) -> str:
+        r""":returns: bin directory tied to the user, e.g. ``%LOCALAPPDATA%\Programs``"""
+        return os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Programs"))  # noqa: PTH118
+
+    @property
+    def site_bin_dir(self) -> str:
+        """:returns: bin directory shared by users, e.g. ``C:\\ProgramData\bin``"""
+        return os.path.normpath(os.path.join(get_win_folder("CSIDL_COMMON_APPDATA"), "bin"))  # noqa: PTH118
+
+    @property
+    def user_applications_dir(self) -> str:
+        r""":returns: applications directory tied to the user, e.g. ``Start Menu\Programs``"""
+        return os.path.normpath(get_win_folder("CSIDL_PROGRAMS"))
+
+    @property
+    def site_applications_dir(self) -> str:
+        r""":returns: applications directory shared by users, e.g. ``C:\ProgramData\Microsoft\Windows\Start Menu\Programs``"""
+        return os.path.normpath(get_win_folder("CSIDL_COMMON_PROGRAMS"))
+
+    @property
+    def user_runtime_dir(self) -> str:
+        r""":returns: runtime directory tied to the user, e.g. ``%USERPROFILE%\AppData\Local\Temp\$appauthor\$appname``"""
+        path = os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp"))  # noqa: PTH118
+        return self._append_parts(path)
+
+    @property
+    def site_runtime_dir(self) -> str:
+        """:returns: runtime directory shared by users, same as `user_runtime_dir`"""
+        return self.user_runtime_dir
+
+
+def get_win_folder_from_env_vars(csidl_name: str) -> str:
+    """Get folder from environment variables."""
+    result = get_win_folder_if_csidl_name_not_env_var(csidl_name)
+    if result is not None:
+        return result
+
+    env_var_name = {
+        "CSIDL_APPDATA": "APPDATA",
+        "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",
+        "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",
+    }.get(csidl_name)
+    if env_var_name is None:
+        msg = f"Unknown CSIDL name: {csidl_name}"
+        raise ValueError(msg)
+    result = os.environ.get(env_var_name)
+    if result is None:
+        msg = f"Unset environment variable: {env_var_name}"
+        raise ValueError(msg)
+    return result
+
+
+def get_win_folder_if_csidl_name_not_env_var(csidl_name: str) -> str | None:  # noqa: PLR0911
+    """Get a folder for a CSIDL name that does not exist as an environment variable."""
+    if csidl_name == "CSIDL_PERSONAL":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_DOWNLOADS":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Downloads")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_MYPICTURES":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Pictures")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_MYVIDEO":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Videos")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_MYMUSIC":
+        return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Music")  # noqa: PTH118
+
+    if csidl_name == "CSIDL_PROGRAMS":
+        return os.path.join(  # noqa: PTH118
+            os.path.normpath(os.environ["APPDATA"]),
+            "Microsoft",
+            "Windows",
+            "Start Menu",
+            "Programs",
+        )
+
+    if csidl_name == "CSIDL_COMMON_PROGRAMS":
+        return os.path.join(  # noqa: PTH118
+            os.path.normpath(os.environ.get("PROGRAMDATA", os.environ.get("ALLUSERSPROFILE", "C:\\ProgramData"))),
+            "Microsoft",
+            "Windows",
+            "Start Menu",
+            "Programs",
+        )
+    return None
+
+
+def get_win_folder_from_registry(csidl_name: str) -> str:
+    """Get folder from the registry.
+
+    This is a fallback technique at best. I'm not sure if using the registry for these guarantees us the correct answer
+    for all CSIDL_* names.
+
+    """
+    machine_names = {
+        "CSIDL_COMMON_APPDATA",
+        "CSIDL_COMMON_PROGRAMS",
+    }
+    shell_folder_name = {
+        "CSIDL_APPDATA": "AppData",
+        "CSIDL_COMMON_APPDATA": "Common AppData",
+        "CSIDL_LOCAL_APPDATA": "Local AppData",
+        "CSIDL_PERSONAL": "Personal",
+        "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",
+        "CSIDL_MYPICTURES": "My Pictures",
+        "CSIDL_MYVIDEO": "My Video",
+        "CSIDL_MYMUSIC": "My Music",
+        "CSIDL_PROGRAMS": "Programs",
+        "CSIDL_COMMON_PROGRAMS": "Common Programs",
+    }.get(csidl_name)
+    if shell_folder_name is None:
+        msg = f"Unknown CSIDL name: {csidl_name}"
+        raise ValueError(msg)
+    if sys.platform != "win32":  # only needed for mypy type checker to know that this code runs only on Windows
+        raise NotImplementedError
+    import winreg  # noqa: PLC0415
+
+    # Use HKEY_LOCAL_MACHINE for system-wide folders, HKEY_CURRENT_USER for user-specific folders
+    hkey = winreg.HKEY_LOCAL_MACHINE if csidl_name in machine_names else winreg.HKEY_CURRENT_USER
+
+    key = winreg.OpenKey(hkey, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
+    directory, _ = winreg.QueryValueEx(key, shell_folder_name)
+    return str(directory)
+
+
+_KNOWN_FOLDER_GUIDS: dict[str, str] = {
+    "CSIDL_APPDATA": "{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}",
+    "CSIDL_COMMON_APPDATA": "{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}",
+    "CSIDL_LOCAL_APPDATA": "{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}",
+    "CSIDL_PERSONAL": "{FDD39AD0-238F-46AF-ADB4-6C85480369C7}",
+    "CSIDL_MYPICTURES": "{33E28130-4E1E-4676-835A-98395C3BC3BB}",
+    "CSIDL_MYVIDEO": "{18989B1D-99B5-455B-841C-AB7C74E4DDFC}",
+    "CSIDL_MYMUSIC": "{4BD8D571-6D19-48D3-BE97-422220080E43}",
+    "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",
+    "CSIDL_DESKTOPDIRECTORY": "{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}",
+    "CSIDL_PROGRAMS": "{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}",
+    "CSIDL_COMMON_PROGRAMS": "{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}",
+}
+
+
+def get_win_folder_via_ctypes(csidl_name: str) -> str:
+    """Get folder via :func:`SHGetKnownFolderPath`.
+
+    See https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath.
+
+    """
+    if sys.platform != "win32":  # only needed for type checker to know that this code runs only on Windows
+        raise NotImplementedError
+    from ctypes import HRESULT, POINTER, Structure, WinDLL, byref, create_unicode_buffer, wintypes  # noqa: PLC0415
+
+    class _GUID(Structure):
+        _fields_ = [
+            ("Data1", wintypes.DWORD),
+            ("Data2", wintypes.WORD),
+            ("Data3", wintypes.WORD),
+            ("Data4", wintypes.BYTE * 8),
+        ]
+
+    ole32 = WinDLL("ole32")
+    ole32.CLSIDFromString.restype = HRESULT
+    ole32.CLSIDFromString.argtypes = [wintypes.LPCOLESTR, POINTER(_GUID)]
+    ole32.CoTaskMemFree.restype = None
+    ole32.CoTaskMemFree.argtypes = [wintypes.LPVOID]
+
+    shell32 = WinDLL("shell32")
+    shell32.SHGetKnownFolderPath.restype = HRESULT
+    shell32.SHGetKnownFolderPath.argtypes = [POINTER(_GUID), wintypes.DWORD, wintypes.HANDLE, POINTER(wintypes.LPWSTR)]
+
+    kernel32 = WinDLL("kernel32")
+    kernel32.GetShortPathNameW.restype = wintypes.DWORD
+    kernel32.GetShortPathNameW.argtypes = [wintypes.LPWSTR, wintypes.LPWSTR, wintypes.DWORD]
+
+    folder_guid = _KNOWN_FOLDER_GUIDS.get(csidl_name)
+    if folder_guid is None:
+        msg = f"Unknown CSIDL name: {csidl_name}"
+        raise ValueError(msg)
+
+    guid = _GUID()
+    ole32.CLSIDFromString(folder_guid, byref(guid))
+
+    path_ptr = wintypes.LPWSTR()
+    shell32.SHGetKnownFolderPath(byref(guid), _KF_FLAG_DONT_VERIFY, None, byref(path_ptr))
+    result = path_ptr.value
+    ole32.CoTaskMemFree(path_ptr)
+
+    if result is None:
+        msg = f"SHGetKnownFolderPath returned NULL for {csidl_name}"
+        raise ValueError(msg)
+
+    if any(ord(c) > 255 for c in result):  # noqa: PLR2004
+        buf = create_unicode_buffer(1024)
+        if kernel32.GetShortPathNameW(result, buf, 1024):
+            result = buf.value
+
+    return result
+
+
+def _pick_get_win_folder() -> Callable[[str], str]:
+    """Select the best method to resolve Windows folder paths: ctypes, then registry, then environment variables."""
+    try:
+        import ctypes  # noqa: PLC0415, F401
+    except ImportError:
+        pass
+    else:
+        return get_win_folder_via_ctypes
+    try:
+        import winreg  # noqa: PLC0415, F401
+    except ImportError:
+        return get_win_folder_from_env_vars
+    else:
+        return get_win_folder_from_registry
+
+
+_resolve_win_folder = _pick_get_win_folder()
+
+
+def get_win_folder(csidl_name: str) -> str:
+    """Get a Windows folder path, checking for ``WIN_PD_OVERRIDE_*`` environment variable overrides first.
+
+    For example, ``CSIDL_LOCAL_APPDATA`` can be overridden by setting ``WIN_PD_OVERRIDE_LOCAL_APPDATA``.
+
+    """
+    env_var = f"WIN_PD_OVERRIDE_{csidl_name.removeprefix('CSIDL_')}"
+    if override := os.environ.get(env_var, "").strip():
+        return override
+    return _resolve_win_folder(csidl_name)
+
+
+__all__ = [
+    "Windows",
+]
diff --git a/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/INSTALLER b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a34a7e56db35cc4c85bfa166244b3d63a6a240d4
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+conda
diff --git a/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/METADATA b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..12345f88ebe873247f9298feca3e469e7e8af87f
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/METADATA
@@ -0,0 +1,152 @@
+Metadata-Version: 2.4
+Name: pluggy
+Version: 1.6.0
+Summary: plugin and hook calling mechanisms for python
+Author-email: Holger Krekel 
+License: MIT
+Classifier: Development Status :: 6 - Mature
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Operating System :: POSIX
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: MacOS :: MacOS X
+Classifier: Topic :: Software Development :: Testing
+Classifier: Topic :: Software Development :: Libraries
+Classifier: Topic :: Utilities
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Provides-Extra: dev
+Requires-Dist: pre-commit; extra == "dev"
+Requires-Dist: tox; extra == "dev"
+Provides-Extra: testing
+Requires-Dist: pytest; extra == "testing"
+Requires-Dist: pytest-benchmark; extra == "testing"
+Requires-Dist: coverage; extra == "testing"
+Dynamic: license-file
+
+====================================================
+pluggy - A minimalist production ready plugin system
+====================================================
+
+|pypi| |conda-forge| |versions| |github-actions| |gitter| |black| |codecov|
+
+This is the core framework used by the `pytest`_, `tox`_, and `devpi`_ projects.
+
+Please `read the docs`_ to learn more!
+
+A definitive example
+====================
+.. code-block:: python
+
+    import pluggy
+
+    hookspec = pluggy.HookspecMarker("myproject")
+    hookimpl = pluggy.HookimplMarker("myproject")
+
+
+    class MySpec:
+        """A hook specification namespace."""
+
+        @hookspec
+        def myhook(self, arg1, arg2):
+            """My special little hook that you can customize."""
+
+
+    class Plugin_1:
+        """A hook implementation namespace."""
+
+        @hookimpl
+        def myhook(self, arg1, arg2):
+            print("inside Plugin_1.myhook()")
+            return arg1 + arg2
+
+
+    class Plugin_2:
+        """A 2nd hook implementation namespace."""
+
+        @hookimpl
+        def myhook(self, arg1, arg2):
+            print("inside Plugin_2.myhook()")
+            return arg1 - arg2
+
+
+    # create a manager and add the spec
+    pm = pluggy.PluginManager("myproject")
+    pm.add_hookspecs(MySpec)
+
+    # register plugins
+    pm.register(Plugin_1())
+    pm.register(Plugin_2())
+
+    # call our ``myhook`` hook
+    results = pm.hook.myhook(arg1=1, arg2=2)
+    print(results)
+
+
+Running this directly gets us::
+
+    $ python docs/examples/toy-example.py
+    inside Plugin_2.myhook()
+    inside Plugin_1.myhook()
+    [-1, 3]
+
+
+.. badges
+
+.. |pypi| image:: https://img.shields.io/pypi/v/pluggy.svg
+    :target: https://pypi.org/pypi/pluggy
+
+.. |versions| image:: https://img.shields.io/pypi/pyversions/pluggy.svg
+    :target: https://pypi.org/pypi/pluggy
+
+.. |github-actions| image:: https://github.com/pytest-dev/pluggy/workflows/main/badge.svg
+    :target: https://github.com/pytest-dev/pluggy/actions
+
+.. |conda-forge| image:: https://img.shields.io/conda/vn/conda-forge/pluggy.svg
+    :target: https://anaconda.org/conda-forge/pytest
+
+.. |gitter| image:: https://badges.gitter.im/pytest-dev/pluggy.svg
+    :alt: Join the chat at https://gitter.im/pytest-dev/pluggy
+    :target: https://gitter.im/pytest-dev/pluggy?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
+
+.. |black| image:: https://img.shields.io/badge/code%20style-black-000000.svg
+    :target: https://github.com/ambv/black
+
+.. |codecov| image:: https://codecov.io/gh/pytest-dev/pluggy/branch/master/graph/badge.svg
+    :target: https://codecov.io/gh/pytest-dev/pluggy
+    :alt: Code coverage Status
+
+.. links
+.. _pytest:
+    http://pytest.org
+.. _tox:
+    https://tox.readthedocs.org
+.. _devpi:
+    http://doc.devpi.net
+.. _read the docs:
+   https://pluggy.readthedocs.io/en/latest/
+
+
+Support pluggy
+--------------
+
+`Open Collective`_ is an online funding platform for open and transparent communities.
+It provides tools to raise money and share your finances in full transparency.
+
+It is the platform of choice for individuals and companies that want to make one-time or
+monthly donations directly to the project.
+
+``pluggy`` is part of the ``pytest-dev`` project, see more details in the `pytest collective`_.
+
+.. _Open Collective: https://opencollective.com
+.. _pytest collective: https://opencollective.com/pytest
diff --git a/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/RECORD b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..41de6722551ac6c5e422c8d17f10dfb1b5fa0710
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/RECORD
@@ -0,0 +1,25 @@
+pluggy-1.6.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+pluggy-1.6.0.dist-info/METADATA,sha256=dDjDXuJaCV63QW-EtGHC10Qlxec0rVTDkSRTxlJE4Bw,4811
+pluggy-1.6.0.dist-info/RECORD,,
+pluggy-1.6.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+pluggy-1.6.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
+pluggy-1.6.0.dist-info/direct_url.json,sha256=thYBqNdkrnwq0WR6W4I0TvlQnuBUX7LOyRxipkgPtcc,117
+pluggy-1.6.0.dist-info/licenses/LICENSE,sha256=1rZebCE6XQtXeRHTTW5ZSbn1nXbCOMUHGi8_wWz7JgY,1110
+pluggy-1.6.0.dist-info/top_level.txt,sha256=xKSCRhai-v9MckvMuWqNz16c1tbsmOggoMSwTgcpYHE,7
+pluggy/__init__.py,sha256=D6dp1gmEDjtDp8hAwQc-qrgaulnL4iltrqkLDd-g9tg,811
+pluggy/__pycache__/__init__.cpython-39.pyc,,
+pluggy/__pycache__/_callers.cpython-39.pyc,,
+pluggy/__pycache__/_hooks.cpython-39.pyc,,
+pluggy/__pycache__/_manager.cpython-39.pyc,,
+pluggy/__pycache__/_result.cpython-39.pyc,,
+pluggy/__pycache__/_tracing.cpython-39.pyc,,
+pluggy/__pycache__/_version.cpython-39.pyc,,
+pluggy/__pycache__/_warnings.cpython-39.pyc,,
+pluggy/_callers.py,sha256=gEZllGaSYVssZ2UmpNfmYC0bdVgh2jYbAFeYKvuRMjY,5991
+pluggy/_hooks.py,sha256=E6f3nYcI6dbEuO0Gmy61ozgGU_59_e69kC08a06EBuo,25218
+pluggy/_manager.py,sha256=K4Ip_pkEjvT2oOIfQPp8CwAWoXVnENgQRcy9tlGii0o,20219
+pluggy/_result.py,sha256=3Xfy7DrjXbYb7puRquyY2VbidIWNq6Pp7QnuElMdj8Q,3098
+pluggy/_tracing.py,sha256=nXd2BCmDgf8jJxV-HO3PqxR-WV53eWnF8B4AF1nJGgo,2073
+pluggy/_version.py,sha256=QuifT9FwIKV3Bt8At2-CvH3sl5xacVDBQsWlFAqVjbg,704
+pluggy/_warnings.py,sha256=td0AvZBpfamriCC3OqsLwxMh-SzAMjfjmc58T5vP3lw,828
+pluggy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diff --git a/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/REQUESTED b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/WHEEL b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.9.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/direct_url.json b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/direct_url.json
new file mode 100644
index 0000000000000000000000000000000000000000..03175f6a323ce22e81fd5b6a382210b546307299
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/direct_url.json
@@ -0,0 +1 @@
+{"dir_info": {}, "url": "file:///home/conda/feedstock_root/build_artifacts/bld/rattler-build_pluggy_1764896838/work"}
\ No newline at end of file
diff --git a/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/top_level.txt b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..11bdb5c1f5fcdd91af5d587c352039cb8476af49
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy-1.6.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+pluggy
diff --git a/micromamba_root/Lib/site-packages/pluggy/__init__.py b/micromamba_root/Lib/site-packages/pluggy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a651f499d9da137fd61a1aefcd8a031a86372c2
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy/__init__.py
@@ -0,0 +1,30 @@
+__all__ = [
+    "__version__",
+    "PluginManager",
+    "PluginValidationError",
+    "HookCaller",
+    "HookCallError",
+    "HookspecOpts",
+    "HookimplOpts",
+    "HookImpl",
+    "HookRelay",
+    "HookspecMarker",
+    "HookimplMarker",
+    "Result",
+    "PluggyWarning",
+    "PluggyTeardownRaisedWarning",
+]
+from ._hooks import HookCaller
+from ._hooks import HookImpl
+from ._hooks import HookimplMarker
+from ._hooks import HookimplOpts
+from ._hooks import HookRelay
+from ._hooks import HookspecMarker
+from ._hooks import HookspecOpts
+from ._manager import PluginManager
+from ._manager import PluginValidationError
+from ._result import HookCallError
+from ._result import Result
+from ._version import version as __version__
+from ._warnings import PluggyTeardownRaisedWarning
+from ._warnings import PluggyWarning
diff --git a/micromamba_root/Lib/site-packages/pluggy/_callers.py b/micromamba_root/Lib/site-packages/pluggy/_callers.py
new file mode 100644
index 0000000000000000000000000000000000000000..472d5dd05be442ad0dbe8ea5b8ca98b86e569fdc
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy/_callers.py
@@ -0,0 +1,169 @@
+"""
+Call loop machinery
+"""
+
+from __future__ import annotations
+
+from collections.abc import Generator
+from collections.abc import Mapping
+from collections.abc import Sequence
+from typing import cast
+from typing import NoReturn
+import warnings
+
+from ._hooks import HookImpl
+from ._result import HookCallError
+from ._result import Result
+from ._warnings import PluggyTeardownRaisedWarning
+
+
+# Need to distinguish between old- and new-style hook wrappers.
+# Wrapping with a tuple is the fastest type-safe way I found to do it.
+Teardown = Generator[None, object, object]
+
+
+def run_old_style_hookwrapper(
+    hook_impl: HookImpl, hook_name: str, args: Sequence[object]
+) -> Teardown:
+    """
+    backward compatibility wrapper to run a old style hookwrapper as a wrapper
+    """
+
+    teardown: Teardown = cast(Teardown, hook_impl.function(*args))
+    try:
+        next(teardown)
+    except StopIteration:
+        _raise_wrapfail(teardown, "did not yield")
+    try:
+        res = yield
+        result = Result(res, None)
+    except BaseException as exc:
+        result = Result(None, exc)
+    try:
+        teardown.send(result)
+    except StopIteration:
+        pass
+    except BaseException as e:
+        _warn_teardown_exception(hook_name, hook_impl, e)
+        raise
+    else:
+        _raise_wrapfail(teardown, "has second yield")
+    finally:
+        teardown.close()
+    return result.get_result()
+
+
+def _raise_wrapfail(
+    wrap_controller: Generator[None, object, object],
+    msg: str,
+) -> NoReturn:
+    co = wrap_controller.gi_code  # type: ignore[attr-defined]
+    raise RuntimeError(
+        f"wrap_controller at {co.co_name!r} {co.co_filename}:{co.co_firstlineno} {msg}"
+    )
+
+
+def _warn_teardown_exception(
+    hook_name: str, hook_impl: HookImpl, e: BaseException
+) -> None:
+    msg = "A plugin raised an exception during an old-style hookwrapper teardown.\n"
+    msg += f"Plugin: {hook_impl.plugin_name}, Hook: {hook_name}\n"
+    msg += f"{type(e).__name__}: {e}\n"
+    msg += "For more information see https://pluggy.readthedocs.io/en/stable/api_reference.html#pluggy.PluggyTeardownRaisedWarning"  # noqa: E501
+    warnings.warn(PluggyTeardownRaisedWarning(msg), stacklevel=6)
+
+
+def _multicall(
+    hook_name: str,
+    hook_impls: Sequence[HookImpl],
+    caller_kwargs: Mapping[str, object],
+    firstresult: bool,
+) -> object | list[object]:
+    """Execute a call into multiple python functions/methods and return the
+    result(s).
+
+    ``caller_kwargs`` comes from HookCaller.__call__().
+    """
+    __tracebackhide__ = True
+    results: list[object] = []
+    exception = None
+    try:  # run impl and wrapper setup functions in a loop
+        teardowns: list[Teardown] = []
+        try:
+            for hook_impl in reversed(hook_impls):
+                try:
+                    args = [caller_kwargs[argname] for argname in hook_impl.argnames]
+                except KeyError as e:
+                    # coverage bug - this is tested
+                    for argname in hook_impl.argnames:  # pragma: no cover
+                        if argname not in caller_kwargs:
+                            raise HookCallError(
+                                f"hook call must provide argument {argname!r}"
+                            ) from e
+
+                if hook_impl.hookwrapper:
+                    function_gen = run_old_style_hookwrapper(hook_impl, hook_name, args)
+
+                    next(function_gen)  # first yield
+                    teardowns.append(function_gen)
+
+                elif hook_impl.wrapper:
+                    try:
+                        # If this cast is not valid, a type error is raised below,
+                        # which is the desired response.
+                        res = hook_impl.function(*args)
+                        function_gen = cast(Generator[None, object, object], res)
+                        next(function_gen)  # first yield
+                        teardowns.append(function_gen)
+                    except StopIteration:
+                        _raise_wrapfail(function_gen, "did not yield")
+                else:
+                    res = hook_impl.function(*args)
+                    if res is not None:
+                        results.append(res)
+                        if firstresult:  # halt further impl calls
+                            break
+        except BaseException as exc:
+            exception = exc
+    finally:
+        if firstresult:  # first result hooks return a single value
+            result = results[0] if results else None
+        else:
+            result = results
+
+        # run all wrapper post-yield blocks
+        for teardown in reversed(teardowns):
+            try:
+                if exception is not None:
+                    try:
+                        teardown.throw(exception)
+                    except RuntimeError as re:
+                        # StopIteration from generator causes RuntimeError
+                        # even for coroutine usage - see #544
+                        if (
+                            isinstance(exception, StopIteration)
+                            and re.__cause__ is exception
+                        ):
+                            teardown.close()
+                            continue
+                        else:
+                            raise
+                else:
+                    teardown.send(result)
+                # Following is unreachable for a well behaved hook wrapper.
+                # Try to force finalizers otherwise postponed till GC action.
+                # Note: close() may raise if generator handles GeneratorExit.
+                teardown.close()
+            except StopIteration as si:
+                result = si.value
+                exception = None
+                continue
+            except BaseException as e:
+                exception = e
+                continue
+            _raise_wrapfail(teardown, "has second yield")
+
+    if exception is not None:
+        raise exception
+    else:
+        return result
diff --git a/micromamba_root/Lib/site-packages/pluggy/_hooks.py b/micromamba_root/Lib/site-packages/pluggy/_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..97fef0d75fc2c8c3fee866ce8d2cc19f9ab54c7c
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy/_hooks.py
@@ -0,0 +1,714 @@
+"""
+Internal hook annotation, representation and calling machinery.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Generator
+from collections.abc import Mapping
+from collections.abc import Sequence
+from collections.abc import Set
+import inspect
+import sys
+from types import ModuleType
+from typing import Any
+from typing import Callable
+from typing import Final
+from typing import final
+from typing import Optional
+from typing import overload
+from typing import TYPE_CHECKING
+from typing import TypedDict
+from typing import TypeVar
+from typing import Union
+import warnings
+
+from ._result import Result
+
+
+_T = TypeVar("_T")
+_F = TypeVar("_F", bound=Callable[..., object])
+_Namespace = Union[ModuleType, type]
+_Plugin = object
+_HookExec = Callable[
+    [str, Sequence["HookImpl"], Mapping[str, object], bool],
+    Union[object, list[object]],
+]
+_HookImplFunction = Callable[..., Union[_T, Generator[None, Result[_T], None]]]
+
+
+class HookspecOpts(TypedDict):
+    """Options for a hook specification."""
+
+    #: Whether the hook is :ref:`first result only `.
+    firstresult: bool
+    #: Whether the hook is :ref:`historic `.
+    historic: bool
+    #: Whether the hook :ref:`warns when implemented `.
+    warn_on_impl: Warning | None
+    #: Whether the hook warns when :ref:`certain arguments are requested
+    #: `.
+    #:
+    #: .. versionadded:: 1.5
+    warn_on_impl_args: Mapping[str, Warning] | None
+
+
+class HookimplOpts(TypedDict):
+    """Options for a hook implementation."""
+
+    #: Whether the hook implementation is a :ref:`wrapper `.
+    wrapper: bool
+    #: Whether the hook implementation is an :ref:`old-style wrapper
+    #: `.
+    hookwrapper: bool
+    #: Whether validation against a hook specification is :ref:`optional
+    #: `.
+    optionalhook: bool
+    #: Whether to try to order this hook implementation :ref:`first
+    #: `.
+    tryfirst: bool
+    #: Whether to try to order this hook implementation :ref:`last
+    #: `.
+    trylast: bool
+    #: The name of the hook specification to match, see :ref:`specname`.
+    specname: str | None
+
+
+@final
+class HookspecMarker:
+    """Decorator for marking functions as hook specifications.
+
+    Instantiate it with a project_name to get a decorator.
+    Calling :meth:`PluginManager.add_hookspecs` later will discover all marked
+    functions if the :class:`PluginManager` uses the same project name.
+    """
+
+    __slots__ = ("project_name",)
+
+    def __init__(self, project_name: str) -> None:
+        self.project_name: Final = project_name
+
+    @overload
+    def __call__(
+        self,
+        function: _F,
+        firstresult: bool = False,
+        historic: bool = False,
+        warn_on_impl: Warning | None = None,
+        warn_on_impl_args: Mapping[str, Warning] | None = None,
+    ) -> _F: ...
+
+    @overload  # noqa: F811
+    def __call__(  # noqa: F811
+        self,
+        function: None = ...,
+        firstresult: bool = ...,
+        historic: bool = ...,
+        warn_on_impl: Warning | None = ...,
+        warn_on_impl_args: Mapping[str, Warning] | None = ...,
+    ) -> Callable[[_F], _F]: ...
+
+    def __call__(  # noqa: F811
+        self,
+        function: _F | None = None,
+        firstresult: bool = False,
+        historic: bool = False,
+        warn_on_impl: Warning | None = None,
+        warn_on_impl_args: Mapping[str, Warning] | None = None,
+    ) -> _F | Callable[[_F], _F]:
+        """If passed a function, directly sets attributes on the function
+        which will make it discoverable to :meth:`PluginManager.add_hookspecs`.
+
+        If passed no function, returns a decorator which can be applied to a
+        function later using the attributes supplied.
+
+        :param firstresult:
+            If ``True``, the 1:N hook call (N being the number of registered
+            hook implementation functions) will stop at I<=N when the I'th
+            function returns a non-``None`` result. See :ref:`firstresult`.
+
+        :param historic:
+            If ``True``, every call to the hook will be memorized and replayed
+            on plugins registered after the call was made. See :ref:`historic`.
+
+        :param warn_on_impl:
+            If given, every implementation of this hook will trigger the given
+            warning. See :ref:`warn_on_impl`.
+
+        :param warn_on_impl_args:
+            If given, every implementation of this hook which requests one of
+            the arguments in the dict will trigger the corresponding warning.
+            See :ref:`warn_on_impl`.
+
+            .. versionadded:: 1.5
+        """
+
+        def setattr_hookspec_opts(func: _F) -> _F:
+            if historic and firstresult:
+                raise ValueError("cannot have a historic firstresult hook")
+            opts: HookspecOpts = {
+                "firstresult": firstresult,
+                "historic": historic,
+                "warn_on_impl": warn_on_impl,
+                "warn_on_impl_args": warn_on_impl_args,
+            }
+            setattr(func, self.project_name + "_spec", opts)
+            return func
+
+        if function is not None:
+            return setattr_hookspec_opts(function)
+        else:
+            return setattr_hookspec_opts
+
+
+@final
+class HookimplMarker:
+    """Decorator for marking functions as hook implementations.
+
+    Instantiate it with a ``project_name`` to get a decorator.
+    Calling :meth:`PluginManager.register` later will discover all marked
+    functions if the :class:`PluginManager` uses the same project name.
+    """
+
+    __slots__ = ("project_name",)
+
+    def __init__(self, project_name: str) -> None:
+        self.project_name: Final = project_name
+
+    @overload
+    def __call__(
+        self,
+        function: _F,
+        hookwrapper: bool = ...,
+        optionalhook: bool = ...,
+        tryfirst: bool = ...,
+        trylast: bool = ...,
+        specname: str | None = ...,
+        wrapper: bool = ...,
+    ) -> _F: ...
+
+    @overload  # noqa: F811
+    def __call__(  # noqa: F811
+        self,
+        function: None = ...,
+        hookwrapper: bool = ...,
+        optionalhook: bool = ...,
+        tryfirst: bool = ...,
+        trylast: bool = ...,
+        specname: str | None = ...,
+        wrapper: bool = ...,
+    ) -> Callable[[_F], _F]: ...
+
+    def __call__(  # noqa: F811
+        self,
+        function: _F | None = None,
+        hookwrapper: bool = False,
+        optionalhook: bool = False,
+        tryfirst: bool = False,
+        trylast: bool = False,
+        specname: str | None = None,
+        wrapper: bool = False,
+    ) -> _F | Callable[[_F], _F]:
+        """If passed a function, directly sets attributes on the function
+        which will make it discoverable to :meth:`PluginManager.register`.
+
+        If passed no function, returns a decorator which can be applied to a
+        function later using the attributes supplied.
+
+        :param optionalhook:
+            If ``True``, a missing matching hook specification will not result
+            in an error (by default it is an error if no matching spec is
+            found). See :ref:`optionalhook`.
+
+        :param tryfirst:
+            If ``True``, this hook implementation will run as early as possible
+            in the chain of N hook implementations for a specification. See
+            :ref:`callorder`.
+
+        :param trylast:
+            If ``True``, this hook implementation will run as late as possible
+            in the chain of N hook implementations for a specification. See
+            :ref:`callorder`.
+
+        :param wrapper:
+            If ``True`` ("new-style hook wrapper"), the hook implementation
+            needs to execute exactly one ``yield``. The code before the
+            ``yield`` is run early before any non-hook-wrapper function is run.
+            The code after the ``yield`` is run after all non-hook-wrapper
+            functions have run. The ``yield`` receives the result value of the
+            inner calls, or raises the exception of inner calls (including
+            earlier hook wrapper calls). The return value of the function
+            becomes the return value of the hook, and a raised exception becomes
+            the exception of the hook. See :ref:`hookwrapper`.
+
+        :param hookwrapper:
+            If ``True`` ("old-style hook wrapper"), the hook implementation
+            needs to execute exactly one ``yield``. The code before the
+            ``yield`` is run early before any non-hook-wrapper function is run.
+            The code after the ``yield`` is run after all non-hook-wrapper
+            function have run  The ``yield`` receives a :class:`Result` object
+            representing the exception or result outcome of the inner calls
+            (including earlier hook wrapper calls). This option is mutually
+            exclusive with ``wrapper``. See :ref:`old_style_hookwrapper`.
+
+        :param specname:
+            If provided, the given name will be used instead of the function
+            name when matching this hook implementation to a hook specification
+            during registration. See :ref:`specname`.
+
+        .. versionadded:: 1.2.0
+            The ``wrapper`` parameter.
+        """
+
+        def setattr_hookimpl_opts(func: _F) -> _F:
+            opts: HookimplOpts = {
+                "wrapper": wrapper,
+                "hookwrapper": hookwrapper,
+                "optionalhook": optionalhook,
+                "tryfirst": tryfirst,
+                "trylast": trylast,
+                "specname": specname,
+            }
+            setattr(func, self.project_name + "_impl", opts)
+            return func
+
+        if function is None:
+            return setattr_hookimpl_opts
+        else:
+            return setattr_hookimpl_opts(function)
+
+
+def normalize_hookimpl_opts(opts: HookimplOpts) -> None:
+    opts.setdefault("tryfirst", False)
+    opts.setdefault("trylast", False)
+    opts.setdefault("wrapper", False)
+    opts.setdefault("hookwrapper", False)
+    opts.setdefault("optionalhook", False)
+    opts.setdefault("specname", None)
+
+
+_PYPY = hasattr(sys, "pypy_version_info")
+
+
+def varnames(func: object) -> tuple[tuple[str, ...], tuple[str, ...]]:
+    """Return tuple of positional and keywrord argument names for a function,
+    method, class or callable.
+
+    In case of a class, its ``__init__`` method is considered.
+    For methods the ``self`` parameter is not included.
+    """
+    if inspect.isclass(func):
+        try:
+            func = func.__init__
+        except AttributeError:  # pragma: no cover - pypy special case
+            return (), ()
+    elif not inspect.isroutine(func):  # callable object?
+        try:
+            func = getattr(func, "__call__", func)
+        except Exception:  # pragma: no cover - pypy special case
+            return (), ()
+
+    try:
+        # func MUST be a function or method here or we won't parse any args.
+        sig = inspect.signature(
+            func.__func__ if inspect.ismethod(func) else func  # type:ignore[arg-type]
+        )
+    except TypeError:  # pragma: no cover
+        return (), ()
+
+    _valid_param_kinds = (
+        inspect.Parameter.POSITIONAL_ONLY,
+        inspect.Parameter.POSITIONAL_OR_KEYWORD,
+    )
+    _valid_params = {
+        name: param
+        for name, param in sig.parameters.items()
+        if param.kind in _valid_param_kinds
+    }
+    args = tuple(_valid_params)
+    defaults = (
+        tuple(
+            param.default
+            for param in _valid_params.values()
+            if param.default is not param.empty
+        )
+        or None
+    )
+
+    if defaults:
+        index = -len(defaults)
+        args, kwargs = args[:index], tuple(args[index:])
+    else:
+        kwargs = ()
+
+    # strip any implicit instance arg
+    # pypy3 uses "obj" instead of "self" for default dunder methods
+    if not _PYPY:
+        implicit_names: tuple[str, ...] = ("self",)
+    else:  # pragma: no cover
+        implicit_names = ("self", "obj")
+    if args:
+        qualname: str = getattr(func, "__qualname__", "")
+        if inspect.ismethod(func) or ("." in qualname and args[0] in implicit_names):
+            args = args[1:]
+
+    return args, kwargs
+
+
+@final
+class HookRelay:
+    """Hook holder object for performing 1:N hook calls where N is the number
+    of registered plugins."""
+
+    __slots__ = ("__dict__",)
+
+    def __init__(self) -> None:
+        """:meta private:"""
+
+    if TYPE_CHECKING:
+
+        def __getattr__(self, name: str) -> HookCaller: ...
+
+
+# Historical name (pluggy<=1.2), kept for backward compatibility.
+_HookRelay = HookRelay
+
+
+_CallHistory = list[tuple[Mapping[str, object], Optional[Callable[[Any], None]]]]
+
+
+class HookCaller:
+    """A caller of all registered implementations of a hook specification."""
+
+    __slots__ = (
+        "name",
+        "spec",
+        "_hookexec",
+        "_hookimpls",
+        "_call_history",
+    )
+
+    def __init__(
+        self,
+        name: str,
+        hook_execute: _HookExec,
+        specmodule_or_class: _Namespace | None = None,
+        spec_opts: HookspecOpts | None = None,
+    ) -> None:
+        """:meta private:"""
+        #: Name of the hook getting called.
+        self.name: Final = name
+        self._hookexec: Final = hook_execute
+        # The hookimpls list. The caller iterates it *in reverse*. Format:
+        # 1. trylast nonwrappers
+        # 2. nonwrappers
+        # 3. tryfirst nonwrappers
+        # 4. trylast wrappers
+        # 5. wrappers
+        # 6. tryfirst wrappers
+        self._hookimpls: Final[list[HookImpl]] = []
+        self._call_history: _CallHistory | None = None
+        # TODO: Document, or make private.
+        self.spec: HookSpec | None = None
+        if specmodule_or_class is not None:
+            assert spec_opts is not None
+            self.set_specification(specmodule_or_class, spec_opts)
+
+    # TODO: Document, or make private.
+    def has_spec(self) -> bool:
+        return self.spec is not None
+
+    # TODO: Document, or make private.
+    def set_specification(
+        self,
+        specmodule_or_class: _Namespace,
+        spec_opts: HookspecOpts,
+    ) -> None:
+        if self.spec is not None:
+            raise ValueError(
+                f"Hook {self.spec.name!r} is already registered "
+                f"within namespace {self.spec.namespace}"
+            )
+        self.spec = HookSpec(specmodule_or_class, self.name, spec_opts)
+        if spec_opts.get("historic"):
+            self._call_history = []
+
+    def is_historic(self) -> bool:
+        """Whether this caller is :ref:`historic `."""
+        return self._call_history is not None
+
+    def _remove_plugin(self, plugin: _Plugin) -> None:
+        for i, method in enumerate(self._hookimpls):
+            if method.plugin == plugin:
+                del self._hookimpls[i]
+                return
+        raise ValueError(f"plugin {plugin!r} not found")
+
+    def get_hookimpls(self) -> list[HookImpl]:
+        """Get all registered hook implementations for this hook."""
+        return self._hookimpls.copy()
+
+    def _add_hookimpl(self, hookimpl: HookImpl) -> None:
+        """Add an implementation to the callback chain."""
+        for i, method in enumerate(self._hookimpls):
+            if method.hookwrapper or method.wrapper:
+                splitpoint = i
+                break
+        else:
+            splitpoint = len(self._hookimpls)
+        if hookimpl.hookwrapper or hookimpl.wrapper:
+            start, end = splitpoint, len(self._hookimpls)
+        else:
+            start, end = 0, splitpoint
+
+        if hookimpl.trylast:
+            self._hookimpls.insert(start, hookimpl)
+        elif hookimpl.tryfirst:
+            self._hookimpls.insert(end, hookimpl)
+        else:
+            # find last non-tryfirst method
+            i = end - 1
+            while i >= start and self._hookimpls[i].tryfirst:
+                i -= 1
+            self._hookimpls.insert(i + 1, hookimpl)
+
+    def __repr__(self) -> str:
+        return f""
+
+    def _verify_all_args_are_provided(self, kwargs: Mapping[str, object]) -> None:
+        # This is written to avoid expensive operations when not needed.
+        if self.spec:
+            for argname in self.spec.argnames:
+                if argname not in kwargs:
+                    notincall = ", ".join(
+                        repr(argname)
+                        for argname in self.spec.argnames
+                        # Avoid self.spec.argnames - kwargs.keys()
+                        # it doesn't preserve order.
+                        if argname not in kwargs.keys()
+                    )
+                    warnings.warn(
+                        f"Argument(s) {notincall} which are declared in the hookspec "
+                        "cannot be found in this hook call",
+                        stacklevel=2,
+                    )
+                    break
+
+    def __call__(self, **kwargs: object) -> Any:
+        """Call the hook.
+
+        Only accepts keyword arguments, which should match the hook
+        specification.
+
+        Returns the result(s) of calling all registered plugins, see
+        :ref:`calling`.
+        """
+        assert not self.is_historic(), (
+            "Cannot directly call a historic hook - use call_historic instead."
+        )
+        self._verify_all_args_are_provided(kwargs)
+        firstresult = self.spec.opts.get("firstresult", False) if self.spec else False
+        # Copy because plugins may register other plugins during iteration (#438).
+        return self._hookexec(self.name, self._hookimpls.copy(), kwargs, firstresult)
+
+    def call_historic(
+        self,
+        result_callback: Callable[[Any], None] | None = None,
+        kwargs: Mapping[str, object] | None = None,
+    ) -> None:
+        """Call the hook with given ``kwargs`` for all registered plugins and
+        for all plugins which will be registered afterwards, see
+        :ref:`historic`.
+
+        :param result_callback:
+            If provided, will be called for each non-``None`` result obtained
+            from a hook implementation.
+        """
+        assert self._call_history is not None
+        kwargs = kwargs or {}
+        self._verify_all_args_are_provided(kwargs)
+        self._call_history.append((kwargs, result_callback))
+        # Historizing hooks don't return results.
+        # Remember firstresult isn't compatible with historic.
+        # Copy because plugins may register other plugins during iteration (#438).
+        res = self._hookexec(self.name, self._hookimpls.copy(), kwargs, False)
+        if result_callback is None:
+            return
+        if isinstance(res, list):
+            for x in res:
+                result_callback(x)
+
+    def call_extra(
+        self, methods: Sequence[Callable[..., object]], kwargs: Mapping[str, object]
+    ) -> Any:
+        """Call the hook with some additional temporarily participating
+        methods using the specified ``kwargs`` as call parameters, see
+        :ref:`call_extra`."""
+        assert not self.is_historic(), (
+            "Cannot directly call a historic hook - use call_historic instead."
+        )
+        self._verify_all_args_are_provided(kwargs)
+        opts: HookimplOpts = {
+            "wrapper": False,
+            "hookwrapper": False,
+            "optionalhook": False,
+            "trylast": False,
+            "tryfirst": False,
+            "specname": None,
+        }
+        hookimpls = self._hookimpls.copy()
+        for method in methods:
+            hookimpl = HookImpl(None, "", method, opts)
+            # Find last non-tryfirst nonwrapper method.
+            i = len(hookimpls) - 1
+            while i >= 0 and (
+                # Skip wrappers.
+                (hookimpls[i].hookwrapper or hookimpls[i].wrapper)
+                # Skip tryfirst nonwrappers.
+                or hookimpls[i].tryfirst
+            ):
+                i -= 1
+            hookimpls.insert(i + 1, hookimpl)
+        firstresult = self.spec.opts.get("firstresult", False) if self.spec else False
+        return self._hookexec(self.name, hookimpls, kwargs, firstresult)
+
+    def _maybe_apply_history(self, method: HookImpl) -> None:
+        """Apply call history to a new hookimpl if it is marked as historic."""
+        if self.is_historic():
+            assert self._call_history is not None
+            for kwargs, result_callback in self._call_history:
+                res = self._hookexec(self.name, [method], kwargs, False)
+                if res and result_callback is not None:
+                    # XXX: remember firstresult isn't compat with historic
+                    assert isinstance(res, list)
+                    result_callback(res[0])
+
+
+# Historical name (pluggy<=1.2), kept for backward compatibility.
+_HookCaller = HookCaller
+
+
+class _SubsetHookCaller(HookCaller):
+    """A proxy to another HookCaller which manages calls to all registered
+    plugins except the ones from remove_plugins."""
+
+    # This class is unusual: in inhertits from `HookCaller` so all of
+    # the *code* runs in the class, but it delegates all underlying *data*
+    # to the original HookCaller.
+    # `subset_hook_caller` used to be implemented by creating a full-fledged
+    # HookCaller, copying all hookimpls from the original. This had problems
+    # with memory leaks (#346) and historic calls (#347), which make a proxy
+    # approach better.
+    # An alternative implementation is to use a `_getattr__`/`__getattribute__`
+    # proxy, however that adds more overhead and is more tricky to implement.
+
+    __slots__ = (
+        "_orig",
+        "_remove_plugins",
+    )
+
+    def __init__(self, orig: HookCaller, remove_plugins: Set[_Plugin]) -> None:
+        self._orig = orig
+        self._remove_plugins = remove_plugins
+        self.name = orig.name  # type: ignore[misc]
+        self._hookexec = orig._hookexec  # type: ignore[misc]
+
+    @property  # type: ignore[misc]
+    def _hookimpls(self) -> list[HookImpl]:
+        return [
+            impl
+            for impl in self._orig._hookimpls
+            if impl.plugin not in self._remove_plugins
+        ]
+
+    @property
+    def spec(self) -> HookSpec | None:  # type: ignore[override]
+        return self._orig.spec
+
+    @property
+    def _call_history(self) -> _CallHistory | None:  # type: ignore[override]
+        return self._orig._call_history
+
+    def __repr__(self) -> str:
+        return f"<_SubsetHookCaller {self.name!r}>"
+
+
+@final
+class HookImpl:
+    """A hook implementation in a :class:`HookCaller`."""
+
+    __slots__ = (
+        "function",
+        "argnames",
+        "kwargnames",
+        "plugin",
+        "opts",
+        "plugin_name",
+        "wrapper",
+        "hookwrapper",
+        "optionalhook",
+        "tryfirst",
+        "trylast",
+    )
+
+    def __init__(
+        self,
+        plugin: _Plugin,
+        plugin_name: str,
+        function: _HookImplFunction[object],
+        hook_impl_opts: HookimplOpts,
+    ) -> None:
+        """:meta private:"""
+        #: The hook implementation function.
+        self.function: Final = function
+        argnames, kwargnames = varnames(self.function)
+        #: The positional parameter names of ``function```.
+        self.argnames: Final = argnames
+        #: The keyword parameter names of ``function```.
+        self.kwargnames: Final = kwargnames
+        #: The plugin which defined this hook implementation.
+        self.plugin: Final = plugin
+        #: The :class:`HookimplOpts` used to configure this hook implementation.
+        self.opts: Final = hook_impl_opts
+        #: The name of the plugin which defined this hook implementation.
+        self.plugin_name: Final = plugin_name
+        #: Whether the hook implementation is a :ref:`wrapper `.
+        self.wrapper: Final = hook_impl_opts["wrapper"]
+        #: Whether the hook implementation is an :ref:`old-style wrapper
+        #: `.
+        self.hookwrapper: Final = hook_impl_opts["hookwrapper"]
+        #: Whether validation against a hook specification is :ref:`optional
+        #: `.
+        self.optionalhook: Final = hook_impl_opts["optionalhook"]
+        #: Whether to try to order this hook implementation :ref:`first
+        #: `.
+        self.tryfirst: Final = hook_impl_opts["tryfirst"]
+        #: Whether to try to order this hook implementation :ref:`last
+        #: `.
+        self.trylast: Final = hook_impl_opts["trylast"]
+
+    def __repr__(self) -> str:
+        return f""
+
+
+@final
+class HookSpec:
+    __slots__ = (
+        "namespace",
+        "function",
+        "name",
+        "argnames",
+        "kwargnames",
+        "opts",
+        "warn_on_impl",
+        "warn_on_impl_args",
+    )
+
+    def __init__(self, namespace: _Namespace, name: str, opts: HookspecOpts) -> None:
+        self.namespace = namespace
+        self.function: Callable[..., object] = getattr(namespace, name)
+        self.name = name
+        self.argnames, self.kwargnames = varnames(self.function)
+        self.opts = opts
+        self.warn_on_impl = opts.get("warn_on_impl")
+        self.warn_on_impl_args = opts.get("warn_on_impl_args")
diff --git a/micromamba_root/Lib/site-packages/pluggy/_manager.py b/micromamba_root/Lib/site-packages/pluggy/_manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff1e3ce6e300eaed456bf67cf61aa4d15fceeb1f
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy/_manager.py
@@ -0,0 +1,523 @@
+from __future__ import annotations
+
+from collections.abc import Iterable
+from collections.abc import Mapping
+from collections.abc import Sequence
+import inspect
+import types
+from typing import Any
+from typing import Callable
+from typing import cast
+from typing import Final
+from typing import TYPE_CHECKING
+import warnings
+
+from . import _tracing
+from ._callers import _multicall
+from ._hooks import _HookImplFunction
+from ._hooks import _Namespace
+from ._hooks import _Plugin
+from ._hooks import _SubsetHookCaller
+from ._hooks import HookCaller
+from ._hooks import HookImpl
+from ._hooks import HookimplOpts
+from ._hooks import HookRelay
+from ._hooks import HookspecOpts
+from ._hooks import normalize_hookimpl_opts
+from ._result import Result
+
+
+if TYPE_CHECKING:
+    # importtlib.metadata import is slow, defer it.
+    import importlib.metadata
+
+
+_BeforeTrace = Callable[[str, Sequence[HookImpl], Mapping[str, Any]], None]
+_AfterTrace = Callable[[Result[Any], str, Sequence[HookImpl], Mapping[str, Any]], None]
+
+
+def _warn_for_function(warning: Warning, function: Callable[..., object]) -> None:
+    func = cast(types.FunctionType, function)
+    warnings.warn_explicit(
+        warning,
+        type(warning),
+        lineno=func.__code__.co_firstlineno,
+        filename=func.__code__.co_filename,
+    )
+
+
+class PluginValidationError(Exception):
+    """Plugin failed validation.
+
+    :param plugin: The plugin which failed validation.
+    :param message: Error message.
+    """
+
+    def __init__(self, plugin: _Plugin, message: str) -> None:
+        super().__init__(message)
+        #: The plugin which failed validation.
+        self.plugin = plugin
+
+
+class DistFacade:
+    """Emulate a pkg_resources Distribution"""
+
+    def __init__(self, dist: importlib.metadata.Distribution) -> None:
+        self._dist = dist
+
+    @property
+    def project_name(self) -> str:
+        name: str = self.metadata["name"]
+        return name
+
+    def __getattr__(self, attr: str, default: Any | None = None) -> Any:
+        return getattr(self._dist, attr, default)
+
+    def __dir__(self) -> list[str]:
+        return sorted(dir(self._dist) + ["_dist", "project_name"])
+
+
+class PluginManager:
+    """Core class which manages registration of plugin objects and 1:N hook
+    calling.
+
+    You can register new hooks by calling :meth:`add_hookspecs(module_or_class)
+    `.
+
+    You can register plugin objects (which contain hook implementations) by
+    calling :meth:`register(plugin) `.
+
+    For debugging purposes you can call :meth:`PluginManager.enable_tracing`
+    which will subsequently send debug information to the trace helper.
+
+    :param project_name:
+        The short project name. Prefer snake case. Make sure it's unique!
+    """
+
+    def __init__(self, project_name: str) -> None:
+        #: The project name.
+        self.project_name: Final = project_name
+        self._name2plugin: Final[dict[str, _Plugin]] = {}
+        self._plugin_distinfo: Final[list[tuple[_Plugin, DistFacade]]] = []
+        #: The "hook relay", used to call a hook on all registered plugins.
+        #: See :ref:`calling`.
+        self.hook: Final = HookRelay()
+        #: The tracing entry point. See :ref:`tracing`.
+        self.trace: Final[_tracing.TagTracerSub] = _tracing.TagTracer().get(
+            "pluginmanage"
+        )
+        self._inner_hookexec = _multicall
+
+    def _hookexec(
+        self,
+        hook_name: str,
+        methods: Sequence[HookImpl],
+        kwargs: Mapping[str, object],
+        firstresult: bool,
+    ) -> object | list[object]:
+        # called from all hookcaller instances.
+        # enable_tracing will set its own wrapping function at self._inner_hookexec
+        return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
+
+    def register(self, plugin: _Plugin, name: str | None = None) -> str | None:
+        """Register a plugin and return its name.
+
+        :param name:
+            The name under which to register the plugin. If not specified, a
+            name is generated using :func:`get_canonical_name`.
+
+        :returns:
+            The plugin name. If the name is blocked from registering, returns
+            ``None``.
+
+        If the plugin is already registered, raises a :exc:`ValueError`.
+        """
+        plugin_name = name or self.get_canonical_name(plugin)
+
+        if plugin_name in self._name2plugin:
+            if self._name2plugin.get(plugin_name, -1) is None:
+                return None  # blocked plugin, return None to indicate no registration
+            raise ValueError(
+                "Plugin name already registered: "
+                f"{plugin_name}={plugin}\n{self._name2plugin}"
+            )
+
+        if plugin in self._name2plugin.values():
+            raise ValueError(
+                "Plugin already registered under a different name: "
+                f"{plugin_name}={plugin}\n{self._name2plugin}"
+            )
+
+        # XXX if an error happens we should make sure no state has been
+        # changed at point of return
+        self._name2plugin[plugin_name] = plugin
+
+        # register matching hook implementations of the plugin
+        for name in dir(plugin):
+            hookimpl_opts = self.parse_hookimpl_opts(plugin, name)
+            if hookimpl_opts is not None:
+                normalize_hookimpl_opts(hookimpl_opts)
+                method: _HookImplFunction[object] = getattr(plugin, name)
+                hookimpl = HookImpl(plugin, plugin_name, method, hookimpl_opts)
+                name = hookimpl_opts.get("specname") or name
+                hook: HookCaller | None = getattr(self.hook, name, None)
+                if hook is None:
+                    hook = HookCaller(name, self._hookexec)
+                    setattr(self.hook, name, hook)
+                elif hook.has_spec():
+                    self._verify_hook(hook, hookimpl)
+                    hook._maybe_apply_history(hookimpl)
+                hook._add_hookimpl(hookimpl)
+        return plugin_name
+
+    def parse_hookimpl_opts(self, plugin: _Plugin, name: str) -> HookimplOpts | None:
+        """Try to obtain a hook implementation from an item with the given name
+        in the given plugin which is being searched for hook impls.
+
+        :returns:
+            The parsed hookimpl options, or None to skip the given item.
+
+        This method can be overridden by ``PluginManager`` subclasses to
+        customize how hook implementation are picked up. By default, returns the
+        options for items decorated with :class:`HookimplMarker`.
+        """
+        method: object = getattr(plugin, name)
+        if not inspect.isroutine(method):
+            return None
+        try:
+            res: HookimplOpts | None = getattr(
+                method, self.project_name + "_impl", None
+            )
+        except Exception:  # pragma: no cover
+            res = {}  # type: ignore[assignment] #pragma: no cover
+        if res is not None and not isinstance(res, dict):
+            # false positive
+            res = None  # type:ignore[unreachable] #pragma: no cover
+        return res
+
+    def unregister(
+        self, plugin: _Plugin | None = None, name: str | None = None
+    ) -> Any | None:
+        """Unregister a plugin and all of its hook implementations.
+
+        The plugin can be specified either by the plugin object or the plugin
+        name. If both are specified, they must agree.
+
+        Returns the unregistered plugin, or ``None`` if not found.
+        """
+        if name is None:
+            assert plugin is not None, "one of name or plugin needs to be specified"
+            name = self.get_name(plugin)
+            assert name is not None, "plugin is not registered"
+
+        if plugin is None:
+            plugin = self.get_plugin(name)
+            if plugin is None:
+                return None
+
+        hookcallers = self.get_hookcallers(plugin)
+        if hookcallers:
+            for hookcaller in hookcallers:
+                hookcaller._remove_plugin(plugin)
+
+        # if self._name2plugin[name] == None registration was blocked: ignore
+        if self._name2plugin.get(name):
+            assert name is not None
+            del self._name2plugin[name]
+
+        return plugin
+
+    def set_blocked(self, name: str) -> None:
+        """Block registrations of the given name, unregister if already registered."""
+        self.unregister(name=name)
+        self._name2plugin[name] = None
+
+    def is_blocked(self, name: str) -> bool:
+        """Return whether the given plugin name is blocked."""
+        return name in self._name2plugin and self._name2plugin[name] is None
+
+    def unblock(self, name: str) -> bool:
+        """Unblocks a name.
+
+        Returns whether the name was actually blocked.
+        """
+        if self._name2plugin.get(name, -1) is None:
+            del self._name2plugin[name]
+            return True
+        return False
+
+    def add_hookspecs(self, module_or_class: _Namespace) -> None:
+        """Add new hook specifications defined in the given ``module_or_class``.
+
+        Functions are recognized as hook specifications if they have been
+        decorated with a matching :class:`HookspecMarker`.
+        """
+        names = []
+        for name in dir(module_or_class):
+            spec_opts = self.parse_hookspec_opts(module_or_class, name)
+            if spec_opts is not None:
+                hc: HookCaller | None = getattr(self.hook, name, None)
+                if hc is None:
+                    hc = HookCaller(name, self._hookexec, module_or_class, spec_opts)
+                    setattr(self.hook, name, hc)
+                else:
+                    # Plugins registered this hook without knowing the spec.
+                    hc.set_specification(module_or_class, spec_opts)
+                    for hookfunction in hc.get_hookimpls():
+                        self._verify_hook(hc, hookfunction)
+                names.append(name)
+
+        if not names:
+            raise ValueError(
+                f"did not find any {self.project_name!r} hooks in {module_or_class!r}"
+            )
+
+    def parse_hookspec_opts(
+        self, module_or_class: _Namespace, name: str
+    ) -> HookspecOpts | None:
+        """Try to obtain a hook specification from an item with the given name
+        in the given module or class which is being searched for hook specs.
+
+        :returns:
+            The parsed hookspec options for defining a hook, or None to skip the
+            given item.
+
+        This method can be overridden by ``PluginManager`` subclasses to
+        customize how hook specifications are picked up. By default, returns the
+        options for items decorated with :class:`HookspecMarker`.
+        """
+        method = getattr(module_or_class, name)
+        opts: HookspecOpts | None = getattr(method, self.project_name + "_spec", None)
+        return opts
+
+    def get_plugins(self) -> set[Any]:
+        """Return a set of all registered plugin objects."""
+        return {x for x in self._name2plugin.values() if x is not None}
+
+    def is_registered(self, plugin: _Plugin) -> bool:
+        """Return whether the plugin is already registered."""
+        return any(plugin == val for val in self._name2plugin.values())
+
+    def get_canonical_name(self, plugin: _Plugin) -> str:
+        """Return a canonical name for a plugin object.
+
+        Note that a plugin may be registered under a different name
+        specified by the caller of :meth:`register(plugin, name) `.
+        To obtain the name of a registered plugin use :meth:`get_name(plugin)
+        ` instead.
+        """
+        name: str | None = getattr(plugin, "__name__", None)
+        return name or str(id(plugin))
+
+    def get_plugin(self, name: str) -> Any | None:
+        """Return the plugin registered under the given name, if any."""
+        return self._name2plugin.get(name)
+
+    def has_plugin(self, name: str) -> bool:
+        """Return whether a plugin with the given name is registered."""
+        return self.get_plugin(name) is not None
+
+    def get_name(self, plugin: _Plugin) -> str | None:
+        """Return the name the plugin is registered under, or ``None`` if
+        is isn't."""
+        for name, val in self._name2plugin.items():
+            if plugin == val:
+                return name
+        return None
+
+    def _verify_hook(self, hook: HookCaller, hookimpl: HookImpl) -> None:
+        if hook.is_historic() and (hookimpl.hookwrapper or hookimpl.wrapper):
+            raise PluginValidationError(
+                hookimpl.plugin,
+                f"Plugin {hookimpl.plugin_name!r}\nhook {hook.name!r}\n"
+                "historic incompatible with yield/wrapper/hookwrapper",
+            )
+
+        assert hook.spec is not None
+        if hook.spec.warn_on_impl:
+            _warn_for_function(hook.spec.warn_on_impl, hookimpl.function)
+
+        # positional arg checking
+        notinspec = set(hookimpl.argnames) - set(hook.spec.argnames)
+        if notinspec:
+            raise PluginValidationError(
+                hookimpl.plugin,
+                f"Plugin {hookimpl.plugin_name!r} for hook {hook.name!r}\n"
+                f"hookimpl definition: {_formatdef(hookimpl.function)}\n"
+                f"Argument(s) {notinspec} are declared in the hookimpl but "
+                "can not be found in the hookspec",
+            )
+
+        if hook.spec.warn_on_impl_args:
+            for hookimpl_argname in hookimpl.argnames:
+                argname_warning = hook.spec.warn_on_impl_args.get(hookimpl_argname)
+                if argname_warning is not None:
+                    _warn_for_function(argname_warning, hookimpl.function)
+
+        if (
+            hookimpl.wrapper or hookimpl.hookwrapper
+        ) and not inspect.isgeneratorfunction(hookimpl.function):
+            raise PluginValidationError(
+                hookimpl.plugin,
+                f"Plugin {hookimpl.plugin_name!r} for hook {hook.name!r}\n"
+                f"hookimpl definition: {_formatdef(hookimpl.function)}\n"
+                "Declared as wrapper=True or hookwrapper=True "
+                "but function is not a generator function",
+            )
+
+        if hookimpl.wrapper and hookimpl.hookwrapper:
+            raise PluginValidationError(
+                hookimpl.plugin,
+                f"Plugin {hookimpl.plugin_name!r} for hook {hook.name!r}\n"
+                f"hookimpl definition: {_formatdef(hookimpl.function)}\n"
+                "The wrapper=True and hookwrapper=True options are mutually exclusive",
+            )
+
+    def check_pending(self) -> None:
+        """Verify that all hooks which have not been verified against a
+        hook specification are optional, otherwise raise
+        :exc:`PluginValidationError`."""
+        for name in self.hook.__dict__:
+            if name[0] == "_":
+                continue
+            hook: HookCaller = getattr(self.hook, name)
+            if not hook.has_spec():
+                for hookimpl in hook.get_hookimpls():
+                    if not hookimpl.optionalhook:
+                        raise PluginValidationError(
+                            hookimpl.plugin,
+                            f"unknown hook {name!r} in plugin {hookimpl.plugin!r}",
+                        )
+
+    def load_setuptools_entrypoints(self, group: str, name: str | None = None) -> int:
+        """Load modules from querying the specified setuptools ``group``.
+
+        :param group:
+            Entry point group to load plugins.
+        :param name:
+            If given, loads only plugins with the given ``name``.
+
+        :return:
+            The number of plugins loaded by this call.
+        """
+        import importlib.metadata
+
+        count = 0
+        for dist in list(importlib.metadata.distributions()):
+            for ep in dist.entry_points:
+                if (
+                    ep.group != group
+                    or (name is not None and ep.name != name)
+                    # already registered
+                    or self.get_plugin(ep.name)
+                    or self.is_blocked(ep.name)
+                ):
+                    continue
+                plugin = ep.load()
+                self.register(plugin, name=ep.name)
+                self._plugin_distinfo.append((plugin, DistFacade(dist)))
+                count += 1
+        return count
+
+    def list_plugin_distinfo(self) -> list[tuple[_Plugin, DistFacade]]:
+        """Return a list of (plugin, distinfo) pairs for all
+        setuptools-registered plugins."""
+        return list(self._plugin_distinfo)
+
+    def list_name_plugin(self) -> list[tuple[str, _Plugin]]:
+        """Return a list of (name, plugin) pairs for all registered plugins."""
+        return list(self._name2plugin.items())
+
+    def get_hookcallers(self, plugin: _Plugin) -> list[HookCaller] | None:
+        """Get all hook callers for the specified plugin.
+
+        :returns:
+            The hook callers, or ``None`` if ``plugin`` is not registered in
+            this plugin manager.
+        """
+        if self.get_name(plugin) is None:
+            return None
+        hookcallers = []
+        for hookcaller in self.hook.__dict__.values():
+            for hookimpl in hookcaller.get_hookimpls():
+                if hookimpl.plugin is plugin:
+                    hookcallers.append(hookcaller)
+        return hookcallers
+
+    def add_hookcall_monitoring(
+        self, before: _BeforeTrace, after: _AfterTrace
+    ) -> Callable[[], None]:
+        """Add before/after tracing functions for all hooks.
+
+        Returns an undo function which, when called, removes the added tracers.
+
+        ``before(hook_name, hook_impls, kwargs)`` will be called ahead
+        of all hook calls and receive a hookcaller instance, a list
+        of HookImpl instances and the keyword arguments for the hook call.
+
+        ``after(outcome, hook_name, hook_impls, kwargs)`` receives the
+        same arguments as ``before`` but also a :class:`~pluggy.Result` object
+        which represents the result of the overall hook call.
+        """
+        oldcall = self._inner_hookexec
+
+        def traced_hookexec(
+            hook_name: str,
+            hook_impls: Sequence[HookImpl],
+            caller_kwargs: Mapping[str, object],
+            firstresult: bool,
+        ) -> object | list[object]:
+            before(hook_name, hook_impls, caller_kwargs)
+            outcome = Result.from_call(
+                lambda: oldcall(hook_name, hook_impls, caller_kwargs, firstresult)
+            )
+            after(outcome, hook_name, hook_impls, caller_kwargs)
+            return outcome.get_result()
+
+        self._inner_hookexec = traced_hookexec
+
+        def undo() -> None:
+            self._inner_hookexec = oldcall
+
+        return undo
+
+    def enable_tracing(self) -> Callable[[], None]:
+        """Enable tracing of hook calls.
+
+        Returns an undo function which, when called, removes the added tracing.
+        """
+        hooktrace = self.trace.root.get("hook")
+
+        def before(
+            hook_name: str, methods: Sequence[HookImpl], kwargs: Mapping[str, object]
+        ) -> None:
+            hooktrace.root.indent += 1
+            hooktrace(hook_name, kwargs)
+
+        def after(
+            outcome: Result[object],
+            hook_name: str,
+            methods: Sequence[HookImpl],
+            kwargs: Mapping[str, object],
+        ) -> None:
+            if outcome.exception is None:
+                hooktrace("finish", hook_name, "-->", outcome.get_result())
+            hooktrace.root.indent -= 1
+
+        return self.add_hookcall_monitoring(before, after)
+
+    def subset_hook_caller(
+        self, name: str, remove_plugins: Iterable[_Plugin]
+    ) -> HookCaller:
+        """Return a proxy :class:`~pluggy.HookCaller` instance for the named
+        method which manages calls to all registered plugins except the ones
+        from remove_plugins."""
+        orig: HookCaller = getattr(self.hook, name)
+        plugins_to_remove = {plug for plug in remove_plugins if hasattr(plug, name)}
+        if plugins_to_remove:
+            return _SubsetHookCaller(orig, plugins_to_remove)
+        return orig
+
+
+def _formatdef(func: Callable[..., object]) -> str:
+    return f"{func.__name__}{inspect.signature(func)}"
diff --git a/micromamba_root/Lib/site-packages/pluggy/_result.py b/micromamba_root/Lib/site-packages/pluggy/_result.py
new file mode 100644
index 0000000000000000000000000000000000000000..656a58416cae5d9c9967f0e0b28052252a513704
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy/_result.py
@@ -0,0 +1,107 @@
+"""
+Hook wrapper "result" utilities.
+"""
+
+from __future__ import annotations
+
+from types import TracebackType
+from typing import Callable
+from typing import cast
+from typing import final
+from typing import Generic
+from typing import Optional
+from typing import TypeVar
+
+
+_ExcInfo = tuple[type[BaseException], BaseException, Optional[TracebackType]]
+ResultType = TypeVar("ResultType")
+
+
+class HookCallError(Exception):
+    """Hook was called incorrectly."""
+
+
+@final
+class Result(Generic[ResultType]):
+    """An object used to inspect and set the result in a :ref:`hook wrapper
+    `."""
+
+    __slots__ = ("_result", "_exception", "_traceback")
+
+    def __init__(
+        self,
+        result: ResultType | None,
+        exception: BaseException | None,
+    ) -> None:
+        """:meta private:"""
+        self._result = result
+        self._exception = exception
+        # Exception __traceback__ is mutable, this keeps the original.
+        self._traceback = exception.__traceback__ if exception is not None else None
+
+    @property
+    def excinfo(self) -> _ExcInfo | None:
+        """:meta private:"""
+        exc = self._exception
+        if exc is None:
+            return None
+        else:
+            return (type(exc), exc, self._traceback)
+
+    @property
+    def exception(self) -> BaseException | None:
+        """:meta private:"""
+        return self._exception
+
+    @classmethod
+    def from_call(cls, func: Callable[[], ResultType]) -> Result[ResultType]:
+        """:meta private:"""
+        __tracebackhide__ = True
+        result = exception = None
+        try:
+            result = func()
+        except BaseException as exc:
+            exception = exc
+        return cls(result, exception)
+
+    def force_result(self, result: ResultType) -> None:
+        """Force the result(s) to ``result``.
+
+        If the hook was marked as a ``firstresult`` a single value should
+        be set, otherwise set a (modified) list of results. Any exceptions
+        found during invocation will be deleted.
+
+        This overrides any previous result or exception.
+        """
+        self._result = result
+        self._exception = None
+        self._traceback = None
+
+    def force_exception(self, exception: BaseException) -> None:
+        """Force the result to fail with ``exception``.
+
+        This overrides any previous result or exception.
+
+        .. versionadded:: 1.1.0
+        """
+        self._result = None
+        self._exception = exception
+        self._traceback = exception.__traceback__ if exception is not None else None
+
+    def get_result(self) -> ResultType:
+        """Get the result(s) for this hook call.
+
+        If the hook was marked as a ``firstresult`` only a single value
+        will be returned, otherwise a list of results.
+        """
+        __tracebackhide__ = True
+        exc = self._exception
+        tb = self._traceback
+        if exc is None:
+            return cast(ResultType, self._result)
+        else:
+            raise exc.with_traceback(tb)
+
+
+# Historical name (pluggy<=1.2), kept for backward compatibility.
+_Result = Result
diff --git a/micromamba_root/Lib/site-packages/pluggy/_tracing.py b/micromamba_root/Lib/site-packages/pluggy/_tracing.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0b36db1524ffe1dac4c93561d952ef0a7dbfd8a
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy/_tracing.py
@@ -0,0 +1,72 @@
+"""
+Tracing utils
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import Any
+from typing import Callable
+
+
+_Writer = Callable[[str], object]
+_Processor = Callable[[tuple[str, ...], tuple[Any, ...]], object]
+
+
+class TagTracer:
+    def __init__(self) -> None:
+        self._tags2proc: dict[tuple[str, ...], _Processor] = {}
+        self._writer: _Writer | None = None
+        self.indent = 0
+
+    def get(self, name: str) -> TagTracerSub:
+        return TagTracerSub(self, (name,))
+
+    def _format_message(self, tags: Sequence[str], args: Sequence[object]) -> str:
+        if isinstance(args[-1], dict):
+            extra = args[-1]
+            args = args[:-1]
+        else:
+            extra = {}
+
+        content = " ".join(map(str, args))
+        indent = "  " * self.indent
+
+        lines = ["{}{} [{}]\n".format(indent, content, ":".join(tags))]
+
+        for name, value in extra.items():
+            lines.append(f"{indent}    {name}: {value}\n")
+
+        return "".join(lines)
+
+    def _processmessage(self, tags: tuple[str, ...], args: tuple[object, ...]) -> None:
+        if self._writer is not None and args:
+            self._writer(self._format_message(tags, args))
+        try:
+            processor = self._tags2proc[tags]
+        except KeyError:
+            pass
+        else:
+            processor(tags, args)
+
+    def setwriter(self, writer: _Writer | None) -> None:
+        self._writer = writer
+
+    def setprocessor(self, tags: str | tuple[str, ...], processor: _Processor) -> None:
+        if isinstance(tags, str):
+            tags = tuple(tags.split(":"))
+        else:
+            assert isinstance(tags, tuple)
+        self._tags2proc[tags] = processor
+
+
+class TagTracerSub:
+    def __init__(self, root: TagTracer, tags: tuple[str, ...]) -> None:
+        self.root = root
+        self.tags = tags
+
+    def __call__(self, *args: object) -> None:
+        self.root._processmessage(self.tags, args)
+
+    def get(self, name: str) -> TagTracerSub:
+        return self.__class__(self.root, self.tags + (name,))
diff --git a/micromamba_root/Lib/site-packages/pluggy/_version.py b/micromamba_root/Lib/site-packages/pluggy/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d2b67bc3aab4764437411241b3ec1eeedd970f6
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy/_version.py
@@ -0,0 +1,34 @@
+# file generated by setuptools-scm
+# don't change, don't track in version control
+
+__all__ = [
+    "__version__",
+    "__version_tuple__",
+    "version",
+    "version_tuple",
+    "__commit_id__",
+    "commit_id",
+]
+
+TYPE_CHECKING = False
+if TYPE_CHECKING:
+    from typing import Tuple
+    from typing import Union
+
+    VERSION_TUPLE = Tuple[Union[int, str], ...]
+    COMMIT_ID = Union[str, None]
+else:
+    VERSION_TUPLE = object
+    COMMIT_ID = object
+
+version: str
+__version__: str
+__version_tuple__: VERSION_TUPLE
+version_tuple: VERSION_TUPLE
+commit_id: COMMIT_ID
+__commit_id__: COMMIT_ID
+
+__version__ = version = '1.6.0'
+__version_tuple__ = version_tuple = (1, 6, 0)
+
+__commit_id__ = commit_id = None
diff --git a/micromamba_root/Lib/site-packages/pluggy/_warnings.py b/micromamba_root/Lib/site-packages/pluggy/_warnings.py
new file mode 100644
index 0000000000000000000000000000000000000000..6356c770c7d1f26ef4f90a4781b1386209f8169c
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pluggy/_warnings.py
@@ -0,0 +1,27 @@
+from typing import final
+
+
+class PluggyWarning(UserWarning):
+    """Base class for all warnings emitted by pluggy."""
+
+    __module__ = "pluggy"
+
+
+@final
+class PluggyTeardownRaisedWarning(PluggyWarning):
+    """A plugin raised an exception during an :ref:`old-style hookwrapper
+    ` teardown.
+
+    Such exceptions are not handled by pluggy, and may cause subsequent
+    teardowns to be executed at unexpected times, or be skipped entirely.
+
+    This is an issue in the plugin implementation.
+
+    If the exception is unintended, fix the underlying cause.
+
+    If the exception is intended, switch to :ref:`new-style hook wrappers
+    `, or use :func:`result.force_exception()
+    ` to set the exception instead of raising.
+    """
+
+    __module__ = "pluggy"
diff --git a/micromamba_root/Lib/site-packages/pluggy/py.typed b/micromamba_root/Lib/site-packages/pluggy/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/INSTALLER b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a34a7e56db35cc4c85bfa166244b3d63a6a240d4
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/INSTALLER
@@ -0,0 +1 @@
+conda
diff --git a/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/METADATA b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..8319b3fd872402bdba1f950c0197b40613cdb2b9
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/METADATA
@@ -0,0 +1,555 @@
+Metadata-Version: 2.4
+Name: psutil
+Version: 7.2.2
+Summary: Cross-platform lib for process and system monitoring.
+Home-page: https://github.com/giampaolo/psutil
+Author: Giampaolo Rodola
+Author-email: g.rodola@gmail.com
+License: BSD-3-Clause
+Keywords: ps,top,kill,free,lsof,netstat,nice,tty,ionice,uptime,taskmgr,process,df,iotop,iostat,ifconfig,taskset,who,pidof,pmap,smem,pstree,monitoring,ulimit,prlimit,smem,performance,metrics,agent,observability
+Platform: Platform Independent
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Console
+Classifier: Intended Audience :: Developers
+Classifier: Intended Audience :: Information Technology
+Classifier: Intended Audience :: System Administrators
+Classifier: Operating System :: MacOS :: MacOS X
+Classifier: Operating System :: Microsoft :: Windows :: Windows 10
+Classifier: Operating System :: Microsoft :: Windows :: Windows 11
+Classifier: Operating System :: Microsoft :: Windows :: Windows 7
+Classifier: Operating System :: Microsoft :: Windows :: Windows 8
+Classifier: Operating System :: Microsoft :: Windows :: Windows 8.1
+Classifier: Operating System :: Microsoft :: Windows :: Windows Server 2003
+Classifier: Operating System :: Microsoft :: Windows :: Windows Server 2008
+Classifier: Operating System :: Microsoft :: Windows :: Windows Vista
+Classifier: Operating System :: Microsoft :: Windows
+Classifier: Operating System :: Microsoft
+Classifier: Operating System :: OS Independent
+Classifier: Operating System :: POSIX :: AIX
+Classifier: Operating System :: POSIX :: BSD :: FreeBSD
+Classifier: Operating System :: POSIX :: BSD :: NetBSD
+Classifier: Operating System :: POSIX :: BSD :: OpenBSD
+Classifier: Operating System :: POSIX :: BSD
+Classifier: Operating System :: POSIX :: Linux
+Classifier: Operating System :: POSIX :: SunOS/Solaris
+Classifier: Operating System :: POSIX
+Classifier: Programming Language :: C
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Programming Language :: Python
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Classifier: Topic :: Software Development :: Libraries
+Classifier: Topic :: System :: Benchmark
+Classifier: Topic :: System :: Hardware
+Classifier: Topic :: System :: Monitoring
+Classifier: Topic :: System :: Networking :: Monitoring :: Hardware Watchdog
+Classifier: Topic :: System :: Networking :: Monitoring
+Classifier: Topic :: System :: Networking
+Classifier: Topic :: System :: Operating System
+Classifier: Topic :: System :: Systems Administration
+Classifier: Topic :: Utilities
+Requires-Python: >=3.6
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Provides-Extra: dev
+Requires-Dist: psleak; extra == "dev"
+Requires-Dist: pytest; extra == "dev"
+Requires-Dist: pytest-instafail; extra == "dev"
+Requires-Dist: pytest-xdist; extra == "dev"
+Requires-Dist: setuptools; extra == "dev"
+Requires-Dist: pywin32; (os_name == "nt" and implementation_name != "pypy") and extra == "dev"
+Requires-Dist: wheel; (os_name == "nt" and implementation_name != "pypy") and extra == "dev"
+Requires-Dist: wmi; (os_name == "nt" and implementation_name != "pypy") and extra == "dev"
+Requires-Dist: abi3audit; extra == "dev"
+Requires-Dist: black; extra == "dev"
+Requires-Dist: check-manifest; extra == "dev"
+Requires-Dist: coverage; extra == "dev"
+Requires-Dist: packaging; extra == "dev"
+Requires-Dist: pylint; extra == "dev"
+Requires-Dist: pyperf; extra == "dev"
+Requires-Dist: pypinfo; extra == "dev"
+Requires-Dist: pytest-cov; extra == "dev"
+Requires-Dist: requests; extra == "dev"
+Requires-Dist: rstcheck; extra == "dev"
+Requires-Dist: ruff; extra == "dev"
+Requires-Dist: sphinx; extra == "dev"
+Requires-Dist: sphinx_rtd_theme; extra == "dev"
+Requires-Dist: toml-sort; extra == "dev"
+Requires-Dist: twine; extra == "dev"
+Requires-Dist: validate-pyproject[all]; extra == "dev"
+Requires-Dist: virtualenv; extra == "dev"
+Requires-Dist: vulture; extra == "dev"
+Requires-Dist: wheel; extra == "dev"
+Requires-Dist: colorama; os_name == "nt" and extra == "dev"
+Requires-Dist: pyreadline3; os_name == "nt" and extra == "dev"
+Provides-Extra: test
+Requires-Dist: psleak; extra == "test"
+Requires-Dist: pytest; extra == "test"
+Requires-Dist: pytest-instafail; extra == "test"
+Requires-Dist: pytest-xdist; extra == "test"
+Requires-Dist: setuptools; extra == "test"
+Requires-Dist: pywin32; (os_name == "nt" and implementation_name != "pypy") and extra == "test"
+Requires-Dist: wheel; (os_name == "nt" and implementation_name != "pypy") and extra == "test"
+Requires-Dist: wmi; (os_name == "nt" and implementation_name != "pypy") and extra == "test"
+Dynamic: author
+Dynamic: author-email
+Dynamic: classifier
+Dynamic: description
+Dynamic: description-content-type
+Dynamic: home-page
+Dynamic: keywords
+Dynamic: license
+Dynamic: license-file
+Dynamic: platform
+Dynamic: provides-extra
+Dynamic: requires-python
+Dynamic: summary
+
+|  |downloads| |stars| |forks| |contributors| |packages|
+|  |version| |license| |stackoverflow| |twitter| |tidelift|
+|  |github-actions-wheels| |github-actions-bsd|
+
+.. |downloads| image:: https://img.shields.io/pypi/dm/psutil.svg
+    :target: https://clickpy.clickhouse.com/dashboard/psutil
+    :alt: Downloads
+
+.. |stars| image:: https://img.shields.io/github/stars/giampaolo/psutil.svg
+    :target: https://github.com/giampaolo/psutil/stargazers
+    :alt: Github stars
+
+.. |forks| image:: https://img.shields.io/github/forks/giampaolo/psutil.svg
+    :target: https://github.com/giampaolo/psutil/network/members
+    :alt: Github forks
+
+.. |contributors| image:: https://img.shields.io/github/contributors/giampaolo/psutil.svg
+    :target: https://github.com/giampaolo/psutil/graphs/contributors
+    :alt: Contributors
+
+.. |stackoverflow| image:: https://img.shields.io/badge/stackoverflow-Ask%20questions-blue.svg
+    :target: https://stackoverflow.com/questions/tagged/psutil
+    :alt: Stackoverflow
+
+.. |github-actions-wheels| image:: https://img.shields.io/github/actions/workflow/status/giampaolo/psutil/.github/workflows/build.yml.svg?label=Linux%2C%20macOS%2C%20Windows
+    :target: https://github.com/giampaolo/psutil/actions?query=workflow%3Abuild
+    :alt: Linux, macOS, Windows
+
+.. |github-actions-bsd| image:: https://img.shields.io/github/actions/workflow/status/giampaolo/psutil/.github/workflows/bsd.yml.svg?label=FreeBSD,%20NetBSD,%20OpenBSD
+    :target: https://github.com/giampaolo/psutil/actions?query=workflow%3Absd-tests
+    :alt: FreeBSD, NetBSD, OpenBSD
+
+.. |version| image:: https://img.shields.io/pypi/v/psutil.svg?label=pypi
+    :target: https://pypi.org/project/psutil
+    :alt: Latest version
+
+.. |packages| image:: https://repology.org/badge/tiny-repos/python:psutil.svg
+    :target: https://repology.org/metapackage/python:psutil/versions
+    :alt: Binary packages
+
+.. |license| image:: https://img.shields.io/pypi/l/psutil.svg
+    :target: https://github.com/giampaolo/psutil/blob/master/LICENSE
+    :alt: License
+
+.. |twitter| image:: https://img.shields.io/twitter/follow/grodola?style=flat
+    :target: https://twitter.com/grodola
+    :alt: Twitter Follow
+
+.. |tidelift| image:: https://tidelift.com/badges/github/giampaolo/psutil?style=flat
+    :target: https://tidelift.com/subscription/pkg/pypi-psutil?utm_source=pypi-psutil&utm_medium=referral&utm_campaign=readme
+    :alt: Tidelift
+
+-----
+
+Quick links
+===========
+
+- `Home page `_
+- `Install `_
+- `Documentation `_
+- `Download `_
+- `Forum `_
+- `StackOverflow `_
+- `Blog `_
+- `What's new `_
+
+
+Summary
+=======
+
+psutil (process and system utilities) is a cross-platform library for
+retrieving information on **running processes** and **system utilization**
+(CPU, memory, disks, network, sensors) in Python.
+It is useful mainly for **system monitoring**, **profiling and limiting process
+resources** and **management of running processes**.
+It implements many functionalities offered by classic UNIX command line tools
+such as *ps, top, iotop, lsof, netstat, ifconfig, free* and others.
+psutil currently supports the following platforms:
+
+- **Linux**
+- **Windows**
+- **macOS**
+- **FreeBSD, OpenBSD**, **NetBSD**
+- **Sun Solaris**
+- **AIX**
+
+Supported Python versions are cPython 3.6+ and `PyPy `__.
+Latest psutil version supporting Python 2.7 is
+`psutil 6.1.1 `__.
+
+Example usages
+==============
+
+This represents pretty much the whole psutil API.
+
+CPU
+---
+
+.. code-block:: python
+
+    >>> import psutil
+    >>>
+    >>> psutil.cpu_times()
+    scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=0, guest_nice=0.0)
+    >>>
+    >>> for x in range(3):
+    ...     psutil.cpu_percent(interval=1)
+    ...
+    4.0
+    5.9
+    3.8
+    >>>
+    >>> for x in range(3):
+    ...     psutil.cpu_percent(interval=1, percpu=True)
+    ...
+    [4.0, 6.9, 3.7, 9.2]
+    [7.0, 8.5, 2.4, 2.1]
+    [1.2, 9.0, 9.9, 7.2]
+    >>>
+    >>> for x in range(3):
+    ...     psutil.cpu_times_percent(interval=1, percpu=False)
+    ...
+    scputimes(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
+    scputimes(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
+    scputimes(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
+    >>>
+    >>> psutil.cpu_count()
+    4
+    >>> psutil.cpu_count(logical=False)
+    2
+    >>>
+    >>> psutil.cpu_stats()
+    scpustats(ctx_switches=20455687, interrupts=6598984, soft_interrupts=2134212, syscalls=0)
+    >>>
+    >>> psutil.cpu_freq()
+    scpufreq(current=931.42925, min=800.0, max=3500.0)
+    >>>
+    >>> psutil.getloadavg()  # also on Windows (emulated)
+    (3.14, 3.89, 4.67)
+
+Memory
+------
+
+.. code-block:: python
+
+    >>> psutil.virtual_memory()
+    svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, active=4748992512, inactive=2758115328, buffers=790724608, cached=3500347392, shared=787554304)
+    >>> psutil.swap_memory()
+    sswap(total=2097147904, used=296128512, free=1801019392, percent=14.1, sin=304193536, sout=677842944)
+    >>>
+
+Disks
+-----
+
+.. code-block:: python
+
+    >>> psutil.disk_partitions()
+    [sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid'),
+     sdiskpart(device='/dev/sda2', mountpoint='/home', fstype='ext', opts='rw')]
+    >>>
+    >>> psutil.disk_usage('/')
+    sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
+    >>>
+    >>> psutil.disk_io_counters(perdisk=False)
+    sdiskio(read_count=719566, write_count=1082197, read_bytes=18626220032, write_bytes=24081764352, read_time=5023392, write_time=63199568, read_merged_count=619166, write_merged_count=812396, busy_time=4523412)
+    >>>
+
+Network
+-------
+
+.. code-block:: python
+
+    >>> psutil.net_io_counters(pernic=True)
+    {'eth0': netio(bytes_sent=485291293, bytes_recv=6004858642, packets_sent=3251564, packets_recv=4787798, errin=0, errout=0, dropin=0, dropout=0),
+     'lo': netio(bytes_sent=2838627, bytes_recv=2838627, packets_sent=30567, packets_recv=30567, errin=0, errout=0, dropin=0, dropout=0)}
+    >>>
+    >>> psutil.net_connections(kind='tcp')
+    [sconn(fd=115, family=, type=, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED', pid=1254),
+     sconn(fd=117, family=, type=, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING', pid=2987),
+     ...]
+    >>>
+    >>> psutil.net_if_addrs()
+    {'lo': [snicaddr(family=, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None),
+            snicaddr(family=, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
+            snicaddr(family=, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)],
+     'wlan0': [snicaddr(family=, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),
+               snicaddr(family=, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
+               snicaddr(family=, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
+    >>>
+    >>> psutil.net_if_stats()
+    {'lo': snicstats(isup=True, duplex=, speed=0, mtu=65536, flags='up,loopback,running'),
+     'wlan0': snicstats(isup=True, duplex=, speed=100, mtu=1500, flags='up,broadcast,running,multicast')}
+    >>>
+
+Sensors
+-------
+
+.. code-block:: python
+
+    >>> import psutil
+    >>> psutil.sensors_temperatures()
+    {'acpitz': [shwtemp(label='', current=47.0, high=103.0, critical=103.0)],
+     'asus': [shwtemp(label='', current=47.0, high=None, critical=None)],
+     'coretemp': [shwtemp(label='Physical id 0', current=52.0, high=100.0, critical=100.0),
+                  shwtemp(label='Core 0', current=45.0, high=100.0, critical=100.0)]}
+    >>>
+    >>> psutil.sensors_fans()
+    {'asus': [sfan(label='cpu_fan', current=3200)]}
+    >>>
+    >>> psutil.sensors_battery()
+    sbattery(percent=93, secsleft=16628, power_plugged=False)
+    >>>
+
+Other system info
+-----------------
+
+.. code-block:: python
+
+    >>> import psutil
+    >>> psutil.users()
+    [suser(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0, pid=1352),
+     suser(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0, pid=1788)]
+    >>>
+    >>> psutil.boot_time()
+    1365519115.0
+    >>>
+
+Process management
+------------------
+
+.. code-block:: python
+
+    >>> import psutil
+    >>> psutil.pids()
+    [1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224, 268, 1215,
+     1216, 1220, 1221, 1243, 1244, 1301, 1601, 2237, 2355, 2637, 2774, 3932,
+     4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245, 4263, 4282, 4306, 4311,
+     4312, 4313, 4314, 4337, 4339, 4357, 4358, 4363, 4383, 4395, 4408, 4433,
+     4443, 4445, 4446, 5167, 5234, 5235, 5252, 5318, 5424, 5644, 6987, 7054,
+     7055, 7071]
+    >>>
+    >>> p = psutil.Process(7055)
+    >>> p
+    psutil.Process(pid=7055, name='python3', status='running', started='09:04:44')
+    >>> p.pid
+    7055
+    >>> p.name()
+    'python3'
+    >>> p.exe()
+    '/usr/bin/python3'
+    >>> p.cwd()
+    '/home/giampaolo'
+    >>> p.cmdline()
+    ['/usr/bin/python3', 'main.py']
+    >>>
+    >>> p.ppid()
+    7054
+    >>> p.parent()
+    psutil.Process(pid=4699, name='bash', status='sleeping', started='09:06:44')
+    >>> p.parents()
+    [psutil.Process(pid=4699, name='bash', started='09:06:44'),
+     psutil.Process(pid=4689, name='gnome-terminal-server', status='sleeping', started='0:06:44'),
+     psutil.Process(pid=1, name='systemd', status='sleeping', started='05:56:55')]
+    >>> p.children(recursive=True)
+    [psutil.Process(pid=29835, name='python3', status='sleeping', started='11:45:38'),
+     psutil.Process(pid=29836, name='python3', status='waking', started='11:43:39')]
+    >>>
+    >>> p.status()
+    'running'
+    >>> p.create_time()
+    1267551141.5019531
+    >>> p.terminal()
+    '/dev/pts/0'
+    >>>
+    >>> p.username()
+    'giampaolo'
+    >>> p.uids()
+    puids(real=1000, effective=1000, saved=1000)
+    >>> p.gids()
+    pgids(real=1000, effective=1000, saved=1000)
+    >>>
+    >>> p.cpu_times()
+    pcputimes(user=1.02, system=0.31, children_user=0.32, children_system=0.1, iowait=0.0)
+    >>> p.cpu_percent(interval=1.0)
+    12.1
+    >>> p.cpu_affinity()
+    [0, 1, 2, 3]
+    >>> p.cpu_affinity([0, 1])  # set
+    >>> p.cpu_num()
+    1
+    >>>
+    >>> p.memory_info()
+    pmem(rss=10915840, vms=67608576, shared=3313664, text=2310144, lib=0, data=7262208, dirty=0)
+    >>> p.memory_full_info()  # "real" USS memory usage (Linux, macOS, Win only)
+    pfullmem(rss=10199040, vms=52133888, shared=3887104, text=2867200, lib=0, data=5967872, dirty=0, uss=6545408, pss=6872064, swap=0)
+    >>> p.memory_percent()
+    0.7823
+    >>> p.memory_maps()
+    [pmmap_grouped(path='/lib/x8664-linux-gnu/libutil-2.15.so', rss=32768, size=2125824, pss=32768, shared_clean=0, shared_dirty=0, private_clean=20480, private_dirty=12288, referenced=32768, anonymous=12288, swap=0),
+     pmmap_grouped(path='/lib/x8664-linux-gnu/libc-2.15.so', rss=3821568, size=3842048, pss=3821568, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=3821568, referenced=3575808, anonymous=3821568, swap=0),
+     pmmap_grouped(path='[heap]',  rss=32768, size=139264, pss=32768, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=32768, referenced=32768, anonymous=32768, swap=0),
+     pmmap_grouped(path='[stack]', rss=2465792, size=2494464, pss=2465792, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=2465792, referenced=2277376, anonymous=2465792, swap=0),
+     ...]
+    >>>
+    >>> p.io_counters()
+    pio(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632, read_chars=456232, write_chars=517543)
+    >>>
+    >>> p.open_files()
+    [popenfile(path='/home/giampaolo/monit.py', fd=3, position=0, mode='r', flags=32768),
+     popenfile(path='/var/log/monit.log', fd=4, position=235542, mode='a', flags=33793)]
+    >>>
+    >>> p.net_connections(kind='tcp')
+    [pconn(fd=115, family=, type=, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED'),
+     pconn(fd=117, family=, type=, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING')]
+    >>>
+    >>> p.threads()
+    [pthread(id=5234, user_time=22.5, system_time=9.2891),
+     pthread(id=5237, user_time=0.0707, system_time=1.1)]
+    >>>
+    >>> p.num_threads()
+    4
+    >>> p.num_fds()
+    8
+    >>> p.num_ctx_switches()
+    pctxsw(voluntary=78, involuntary=19)
+    >>>
+    >>> p.nice()
+    0
+    >>> p.nice(10)  # set
+    >>>
+    >>> p.ionice(psutil.IOPRIO_CLASS_IDLE)  # IO priority (Win and Linux only)
+    >>> p.ionice()
+    pionice(ioclass=, value=0)
+    >>>
+    >>> p.rlimit(psutil.RLIMIT_NOFILE, (5, 5))  # set resource limits (Linux only)
+    >>> p.rlimit(psutil.RLIMIT_NOFILE)
+    (5, 5)
+    >>>
+    >>> p.environ()
+    {'LC_PAPER': 'it_IT.UTF-8', 'SHELL': '/bin/bash', 'GREP_OPTIONS': '--color=auto',
+    'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg',
+     ...}
+    >>>
+    >>> p.as_dict()
+    {'status': 'running', 'num_ctx_switches': pctxsw(voluntary=63, involuntary=1), 'pid': 5457, ...}
+    >>> p.is_running()
+    True
+    >>> p.suspend()
+    >>> p.resume()
+    >>>
+    >>> p.terminate()
+    >>> p.kill()
+    >>> p.wait(timeout=3)
+    
+    >>>
+    >>> psutil.test()
+    USER         PID %CPU %MEM     VSZ     RSS TTY        START    TIME  COMMAND
+    root           1  0.0  0.0   24584    2240            Jun17   00:00  init
+    root           2  0.0  0.0       0       0            Jun17   00:00  kthreadd
+    ...
+    giampaolo  31475  0.0  0.0   20760    3024 /dev/pts/0 Jun19   00:00  python2.4
+    giampaolo  31721  0.0  2.2  773060  181896            00:04   10:30  chrome
+    root       31763  0.0  0.0       0       0            00:05   00:00  kworker/0:1
+    >>>
+
+Further process APIs
+--------------------
+
+.. code-block:: python
+
+    >>> import psutil
+    >>> for proc in psutil.process_iter(['pid', 'name']):
+    ...     print(proc.info)
+    ...
+    {'pid': 1, 'name': 'systemd'}
+    {'pid': 2, 'name': 'kthreadd'}
+    {'pid': 3, 'name': 'ksoftirqd/0'}
+    ...
+    >>>
+    >>> psutil.pid_exists(3)
+    True
+    >>>
+    >>> def on_terminate(proc):
+    ...     print("process {} terminated".format(proc))
+    ...
+    >>> # waits for multiple processes to terminate
+    >>> gone, alive = psutil.wait_procs(procs_list, timeout=3, callback=on_terminate)
+    >>>
+
+Heap info
+---------
+
+.. code-block:: python
+
+    >>> import psutil
+    >>> psutil.heap_info()
+    pheap(heap_used=5177792, mmap_used=819200)
+    >>> psutil.heap_trim()
+
+See also `psleak `__
+
+Windows services
+----------------
+
+.. code-block:: python
+
+    >>> list(psutil.win_service_iter())
+    [,
+     ,
+     ,
+     ,
+     ...]
+    >>> s = psutil.win_service_get('alg')
+    >>> s.as_dict()
+    {'binpath': 'C:\\Windows\\System32\\alg.exe',
+     'description': 'Provides support for 3rd party protocol plug-ins for Internet Connection Sharing',
+     'display_name': 'Application Layer Gateway Service',
+     'name': 'alg',
+     'pid': None,
+     'start_type': 'manual',
+     'status': 'stopped',
+     'username': 'NT AUTHORITY\\LocalService'}
+
+Projects using psutil
+=====================
+
+Here's some I find particularly interesting:
+
+- https://github.com/giampaolo/psleak
+- https://github.com/google/grr
+- https://github.com/facebook/osquery/
+- https://github.com/nicolargo/glances
+- https://github.com/aristocratos/bpytop
+- https://github.com/Jahaja/psdash
+- https://github.com/ajenti/ajenti
+- https://github.com/home-assistant/home-assistant/
+
+Portings
+========
+
+- Go: https://github.com/shirou/gopsutil
+- C: https://github.com/hamon-in/cpslib
+- Rust: https://github.com/rust-psutil/rust-psutil
+- Nim: https://github.com/johnscillieri/psutil-nim
+
+
+
diff --git a/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/RECORD b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..b03337dab68251a5e8f6157e973cb52e98b96480
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/RECORD
@@ -0,0 +1,29 @@
+psutil-7.2.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+psutil-7.2.2.dist-info/METADATA,sha256=7sP_UB2h_DIjG_gTmfCkgMCyKaBYDuUpjNuzWrZVIQM,22973
+psutil-7.2.2.dist-info/RECORD,,
+psutil-7.2.2.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+psutil-7.2.2.dist-info/WHEEL,sha256=cMcQWxr0mPhFRPjwRMzQO4N4DwJVdxU9Wjg08Cyz1B4,100
+psutil-7.2.2.dist-info/direct_url.json,sha256=Vh8El1kW6ulSr_Kf4jwWK8y1pqo8nzKTPaeDJEmZSVc,82
+psutil-7.2.2.dist-info/licenses/LICENSE,sha256=uJwGOzeG4o4MCjjxkx22H-015p3SopZvvs_-4PRsjRA,1548
+psutil-7.2.2.dist-info/top_level.txt,sha256=gCNhn57wzksDjSAISmgMJ0aiXzQulk0GJhb2-BAyYgw,7
+psutil/__init__.py,sha256=HLMFt5EXYYZYyAvHGRBSTlNyTKpqC70sweMMivi7ZNk,89857
+psutil/__pycache__/__init__.cpython-314.pyc,,
+psutil/__pycache__/_common.cpython-314.pyc,,
+psutil/__pycache__/_ntuples.cpython-314.pyc,,
+psutil/__pycache__/_psaix.cpython-314.pyc,,
+psutil/__pycache__/_psbsd.cpython-314.pyc,,
+psutil/__pycache__/_pslinux.cpython-314.pyc,,
+psutil/__pycache__/_psosx.cpython-314.pyc,,
+psutil/__pycache__/_psposix.cpython-314.pyc,,
+psutil/__pycache__/_pssunos.cpython-314.pyc,,
+psutil/__pycache__/_pswindows.cpython-314.pyc,,
+psutil/_common.py,sha256=G7zp_Zfm9UOaDThfKEAfUnxanZeNnQYlk9fvb-IV_HU,25254
+psutil/_ntuples.py,sha256=m46Lk4q64nhqUV9ob02BMiGL6Jfra0WbkyTtF9iKMcc,10970
+psutil/_psaix.py,sha256=r-QDjV4UVFWfF9rJ5sLFatjPhz1DiA9lA-hUnMBqGOw,17616
+psutil/_psbsd.py,sha256=wagxSpZAZJyZGX_yYdvuwfAIAXXko_a1yzcKOTMt65Q,29263
+psutil/_pslinux.py,sha256=qKCbq4eEgHW2kcRhErAGknRXhajJ1aLIcDeuEktGl0k,84787
+psutil/_psosx.py,sha256=ifDqDpwf448iS2Enkr8x0HyIgNeSgYBuU3nABRT2s_I,15913
+psutil/_psposix.py,sha256=KIiHtY9ZOeOwDgIfbntJDC9_SFKASjWZGKt9nG-zmDk,11575
+psutil/_pssunos.py,sha256=zDSEQgCKVMtgVCmbLsrg2aEjwHu0uh-OFLMZSH-DzuU,23934
+psutil/_psutil_windows.pyd,sha256=y_KwD7B8sHINE8IdW9sE2IbwTA-Fzizz0EDN6NPSkCk,71680
+psutil/_pswindows.py,sha256=WArTkd5zTBE2giAO6fQkXjRzf14mrwpzpOjJtEWN4iA,35370
diff --git a/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/REQUESTED b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/REQUESTED
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/WHEEL b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..2e01717dd1bb1a01d1e097c506cbb47284ee6933
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (80.10.2)
+Root-Is-Purelib: false
+Tag: cp37-abi3-win_amd64
+
diff --git a/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/direct_url.json b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/direct_url.json
new file mode 100644
index 0000000000000000000000000000000000000000..22a3f8f036548932e5234e40a1a24c76c849491f
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/direct_url.json
@@ -0,0 +1 @@
+{"dir_info": {}, "url": "file:///D:/bld/bld/rattler-build_psutil_1769678167/work"}
\ No newline at end of file
diff --git a/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/top_level.txt b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a4d92cc08db6a0d8bfedbbbd620d1fb11f84677b
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil-7.2.2.dist-info/top_level.txt
@@ -0,0 +1 @@
+psutil
diff --git a/micromamba_root/Lib/site-packages/psutil/__init__.py b/micromamba_root/Lib/site-packages/psutil/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f10598e9bcca7b301782c519a7270ac3c56a8c71
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil/__init__.py
@@ -0,0 +1,2484 @@
+# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""psutil is a cross-platform library for retrieving information on
+running processes and system utilization (CPU, memory, disks, network,
+sensors) in Python. Supported platforms:
+
+ - Linux
+ - Windows
+ - macOS
+ - FreeBSD
+ - OpenBSD
+ - NetBSD
+ - Sun Solaris
+ - AIX
+
+Supported Python versions are cPython 3.6+ and PyPy.
+"""
+
+import collections
+import contextlib
+import datetime
+import functools
+import os
+import signal
+import socket
+import subprocess
+import sys
+import threading
+import time
+
+try:
+    import pwd
+except ImportError:
+    pwd = None
+
+from . import _common
+from . import _ntuples as _ntp
+from ._common import AIX
+from ._common import BSD
+from ._common import CONN_CLOSE
+from ._common import CONN_CLOSE_WAIT
+from ._common import CONN_CLOSING
+from ._common import CONN_ESTABLISHED
+from ._common import CONN_FIN_WAIT1
+from ._common import CONN_FIN_WAIT2
+from ._common import CONN_LAST_ACK
+from ._common import CONN_LISTEN
+from ._common import CONN_NONE
+from ._common import CONN_SYN_RECV
+from ._common import CONN_SYN_SENT
+from ._common import CONN_TIME_WAIT
+from ._common import FREEBSD
+from ._common import LINUX
+from ._common import MACOS
+from ._common import NETBSD
+from ._common import NIC_DUPLEX_FULL
+from ._common import NIC_DUPLEX_HALF
+from ._common import NIC_DUPLEX_UNKNOWN
+from ._common import OPENBSD
+from ._common import OSX  # deprecated alias
+from ._common import POSIX
+from ._common import POWER_TIME_UNKNOWN
+from ._common import POWER_TIME_UNLIMITED
+from ._common import STATUS_DEAD
+from ._common import STATUS_DISK_SLEEP
+from ._common import STATUS_IDLE
+from ._common import STATUS_LOCKED
+from ._common import STATUS_PARKED
+from ._common import STATUS_RUNNING
+from ._common import STATUS_SLEEPING
+from ._common import STATUS_STOPPED
+from ._common import STATUS_TRACING_STOP
+from ._common import STATUS_WAITING
+from ._common import STATUS_WAKING
+from ._common import STATUS_ZOMBIE
+from ._common import SUNOS
+from ._common import WINDOWS
+from ._common import AccessDenied
+from ._common import Error
+from ._common import NoSuchProcess
+from ._common import TimeoutExpired
+from ._common import ZombieProcess
+from ._common import debug
+from ._common import memoize_when_activated
+from ._common import wrap_numbers as _wrap_numbers
+
+if LINUX:
+    # This is public API and it will be retrieved from _pslinux.py
+    # via sys.modules.
+    PROCFS_PATH = "/proc"
+
+    from . import _pslinux as _psplatform
+    from ._pslinux import IOPRIO_CLASS_BE  # noqa: F401
+    from ._pslinux import IOPRIO_CLASS_IDLE  # noqa: F401
+    from ._pslinux import IOPRIO_CLASS_NONE  # noqa: F401
+    from ._pslinux import IOPRIO_CLASS_RT  # noqa: F401
+
+elif WINDOWS:
+    from . import _pswindows as _psplatform
+    from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS  # noqa: F401
+    from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS  # noqa: F401
+    from ._psutil_windows import HIGH_PRIORITY_CLASS  # noqa: F401
+    from ._psutil_windows import IDLE_PRIORITY_CLASS  # noqa: F401
+    from ._psutil_windows import NORMAL_PRIORITY_CLASS  # noqa: F401
+    from ._psutil_windows import REALTIME_PRIORITY_CLASS  # noqa: F401
+    from ._pswindows import CONN_DELETE_TCB  # noqa: F401
+    from ._pswindows import IOPRIO_HIGH  # noqa: F401
+    from ._pswindows import IOPRIO_LOW  # noqa: F401
+    from ._pswindows import IOPRIO_NORMAL  # noqa: F401
+    from ._pswindows import IOPRIO_VERYLOW  # noqa: F401
+
+elif MACOS:
+    from . import _psosx as _psplatform
+
+elif BSD:
+    from . import _psbsd as _psplatform
+
+elif SUNOS:
+    from . import _pssunos as _psplatform
+    from ._pssunos import CONN_BOUND  # noqa: F401
+    from ._pssunos import CONN_IDLE  # noqa: F401
+
+    # This is public writable API which is read from _pslinux.py and
+    # _pssunos.py via sys.modules.
+    PROCFS_PATH = "/proc"
+
+elif AIX:
+    from . import _psaix as _psplatform
+
+    # This is public API and it will be retrieved from _pslinux.py
+    # via sys.modules.
+    PROCFS_PATH = "/proc"
+
+else:  # pragma: no cover
+    msg = f"platform {sys.platform} is not supported"
+    raise NotImplementedError(msg)
+
+
+# fmt: off
+__all__ = [
+    # exceptions
+    "Error", "NoSuchProcess", "ZombieProcess", "AccessDenied",
+    "TimeoutExpired",
+
+    # constants
+    "version_info", "__version__",
+
+    "STATUS_RUNNING", "STATUS_IDLE", "STATUS_SLEEPING", "STATUS_DISK_SLEEP",
+    "STATUS_STOPPED", "STATUS_TRACING_STOP", "STATUS_ZOMBIE", "STATUS_DEAD",
+    "STATUS_WAKING", "STATUS_LOCKED", "STATUS_WAITING", "STATUS_PARKED",
+
+    "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
+    "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
+    "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", "CONN_NONE",
+    # "CONN_IDLE", "CONN_BOUND",
+
+    "AF_LINK",
+
+    "NIC_DUPLEX_FULL", "NIC_DUPLEX_HALF", "NIC_DUPLEX_UNKNOWN",
+
+    "POWER_TIME_UNKNOWN", "POWER_TIME_UNLIMITED",
+
+    "BSD", "FREEBSD", "LINUX", "NETBSD", "OPENBSD", "MACOS", "OSX", "POSIX",
+    "SUNOS", "WINDOWS", "AIX",
+
+    # "RLIM_INFINITY", "RLIMIT_AS", "RLIMIT_CORE", "RLIMIT_CPU", "RLIMIT_DATA",
+    # "RLIMIT_FSIZE", "RLIMIT_LOCKS", "RLIMIT_MEMLOCK", "RLIMIT_NOFILE",
+    # "RLIMIT_NPROC", "RLIMIT_RSS", "RLIMIT_STACK", "RLIMIT_MSGQUEUE",
+    # "RLIMIT_NICE", "RLIMIT_RTPRIO", "RLIMIT_RTTIME", "RLIMIT_SIGPENDING",
+
+    # classes
+    "Process", "Popen",
+
+    # functions
+    "pid_exists", "pids", "process_iter", "wait_procs",             # proc
+    "virtual_memory", "swap_memory",                                # memory
+    "cpu_times", "cpu_percent", "cpu_times_percent", "cpu_count",   # cpu
+    "cpu_stats",  # "cpu_freq", "getloadavg"
+    "net_io_counters", "net_connections", "net_if_addrs",           # network
+    "net_if_stats",
+    "disk_io_counters", "disk_partitions", "disk_usage",            # disk
+    # "sensors_temperatures", "sensors_battery", "sensors_fans"     # sensors
+    "users", "boot_time",                                           # others
+]
+# fmt: on
+
+
+__all__.extend(_psplatform.__extra__all__)
+
+# Linux, FreeBSD
+if hasattr(_psplatform.Process, "rlimit"):
+    # Populate global namespace with RLIM* constants.
+    _globals = globals()
+    _name = None
+    for _name in dir(_psplatform.cext):
+        if _name.startswith('RLIM') and _name.isupper():
+            _globals[_name] = getattr(_psplatform.cext, _name)
+            __all__.append(_name)
+    del _globals, _name
+
+AF_LINK = _psplatform.AF_LINK
+
+__author__ = "Giampaolo Rodola'"
+__version__ = "7.2.2"
+version_info = tuple(int(num) for num in __version__.split('.'))
+
+_timer = getattr(time, 'monotonic', time.time)
+_TOTAL_PHYMEM = None
+_LOWEST_PID = None
+_SENTINEL = object()
+
+# Sanity check in case the user messed up with psutil installation
+# or did something weird with sys.path. In this case we might end
+# up importing a python module using a C extension module which
+# was compiled for a different version of psutil.
+# We want to prevent that by failing sooner rather than later.
+# See: https://github.com/giampaolo/psutil/issues/564
+if int(__version__.replace('.', '')) != getattr(
+    _psplatform.cext, 'version', None
+):
+    msg = f"version conflict: {_psplatform.cext.__file__!r} C extension "
+    msg += "module was built for another version of psutil"
+    if hasattr(_psplatform.cext, 'version'):
+        v = ".".join(list(str(_psplatform.cext.version)))
+        msg += f" ({v} instead of {__version__})"
+    else:
+        msg += f" (different than {__version__})"
+    what = getattr(
+        _psplatform.cext,
+        "__file__",
+        "the existing psutil install directory",
+    )
+    msg += f"; you may try to 'pip uninstall psutil', manually remove {what}"
+    msg += " or clean the virtual env somehow, then reinstall"
+    raise ImportError(msg)
+
+
+# =====================================================================
+# --- Utils
+# =====================================================================
+
+
+if hasattr(_psplatform, 'ppid_map'):
+    # Faster version (Windows and Linux).
+    _ppid_map = _psplatform.ppid_map
+else:  # pragma: no cover
+
+    def _ppid_map():
+        """Return a {pid: ppid, ...} dict for all running processes in
+        one shot. Used to speed up Process.children().
+        """
+        ret = {}
+        for pid in pids():
+            try:
+                ret[pid] = _psplatform.Process(pid).ppid()
+            except (NoSuchProcess, ZombieProcess):
+                pass
+        return ret
+
+
+def _pprint_secs(secs):
+    """Format seconds in a human readable form."""
+    now = time.time()
+    secs_ago = int(now - secs)
+    fmt = "%H:%M:%S" if secs_ago < 60 * 60 * 24 else "%Y-%m-%d %H:%M:%S"
+    return datetime.datetime.fromtimestamp(secs).strftime(fmt)
+
+
+def _check_conn_kind(kind):
+    """Check net_connections()'s `kind` parameter."""
+    kinds = tuple(_common.conn_tmap)
+    if kind not in kinds:
+        msg = f"invalid kind argument {kind!r}; valid ones are: {kinds}"
+        raise ValueError(msg)
+
+
+# =====================================================================
+# --- Process class
+# =====================================================================
+
+
+class Process:
+    """Represents an OS process with the given PID.
+    If PID is omitted current process PID (os.getpid()) is used.
+    Raise NoSuchProcess if PID does not exist.
+
+    Note that most of the methods of this class do not make sure that
+    the PID of the process being queried has been reused. That means
+    that you may end up retrieving information for another process.
+
+    The only exceptions for which process identity is pre-emptively
+    checked and guaranteed are:
+
+     - parent()
+     - children()
+     - nice() (set)
+     - ionice() (set)
+     - rlimit() (set)
+     - cpu_affinity (set)
+     - suspend()
+     - resume()
+     - send_signal()
+     - terminate()
+     - kill()
+
+    To prevent this problem for all other methods you can use
+    is_running() before querying the process.
+    """
+
+    def __init__(self, pid=None):
+        self._init(pid)
+
+    def _init(self, pid, _ignore_nsp=False):
+        if pid is None:
+            pid = os.getpid()
+        else:
+            if pid < 0:
+                msg = f"pid must be a positive integer (got {pid})"
+                raise ValueError(msg)
+            try:
+                _psplatform.cext.check_pid_range(pid)
+            except OverflowError as err:
+                msg = "process PID out of range"
+                raise NoSuchProcess(pid, msg=msg) from err
+
+        self._pid = pid
+        self._name = None
+        self._exe = None
+        self._create_time = None
+        self._gone = False
+        self._pid_reused = False
+        self._hash = None
+        self._lock = threading.RLock()
+        # used for caching on Windows only (on POSIX ppid may change)
+        self._ppid = None
+        # platform-specific modules define an _psplatform.Process
+        # implementation class
+        self._proc = _psplatform.Process(pid)
+        self._last_sys_cpu_times = None
+        self._last_proc_cpu_times = None
+        self._exitcode = _SENTINEL
+        self._ident = (self.pid, None)
+        try:
+            self._ident = self._get_ident()
+        except AccessDenied:
+            # This should happen on Windows only, since we use the fast
+            # create time method. AFAIK, on all other platforms we are
+            # able to get create time for all PIDs.
+            pass
+        except ZombieProcess:
+            # Zombies can still be queried by this class (although
+            # not always) and pids() return them so just go on.
+            pass
+        except NoSuchProcess:
+            if not _ignore_nsp:
+                msg = "process PID not found"
+                raise NoSuchProcess(pid, msg=msg) from None
+            self._gone = True
+
+    def _get_ident(self):
+        """Return a (pid, uid) tuple which is supposed to identify a
+        Process instance univocally over time. The PID alone is not
+        enough, as it can be assigned to a new process after this one
+        terminates, so we add process creation time to the mix. We need
+        this in order to prevent killing the wrong process later on.
+        This is also known as PID reuse or PID recycling problem.
+
+        The reliability of this strategy mostly depends on
+        create_time() precision, which is 0.01 secs on Linux. The
+        assumption is that, after a process terminates, the kernel
+        won't reuse the same PID after such a short period of time
+        (0.01 secs). Technically this is inherently racy, but
+        practically it should be good enough.
+
+        NOTE: unreliable on FreeBSD and OpenBSD as ctime is subject to
+        system clock updates.
+        """
+
+        if WINDOWS:
+            # Use create_time() fast method in order to speedup
+            # `process_iter()`. This means we'll get AccessDenied for
+            # most ADMIN processes, but that's fine since it means
+            # we'll also get AccessDenied on kill().
+            # https://github.com/giampaolo/psutil/issues/2366#issuecomment-2381646555
+            self._create_time = self._proc.create_time(fast_only=True)
+            return (self.pid, self._create_time)
+        elif LINUX or NETBSD or OSX:
+            # Use 'monotonic' process starttime since boot to form unique
+            # process identity, since it is stable over changes to system
+            # time.
+            return (self.pid, self._proc.create_time(monotonic=True))
+        else:
+            return (self.pid, self.create_time())
+
+    def __str__(self):
+        info = collections.OrderedDict()
+        info["pid"] = self.pid
+        if self._name:
+            info['name'] = self._name
+        with self.oneshot():
+            if self._pid_reused:
+                info["status"] = "terminated + PID reused"
+            else:
+                try:
+                    info["name"] = self.name()
+                    info["status"] = self.status()
+                except ZombieProcess:
+                    info["status"] = "zombie"
+                except NoSuchProcess:
+                    info["status"] = "terminated"
+                except AccessDenied:
+                    pass
+
+            if self._exitcode not in {_SENTINEL, None}:
+                info["exitcode"] = self._exitcode
+            if self._create_time is not None:
+                info['started'] = _pprint_secs(self._create_time)
+
+            return "{}.{}({})".format(
+                self.__class__.__module__,
+                self.__class__.__name__,
+                ", ".join([f"{k}={v!r}" for k, v in info.items()]),
+            )
+
+    __repr__ = __str__
+
+    def __eq__(self, other):
+        # Test for equality with another Process object based
+        # on PID and creation time.
+        if not isinstance(other, Process):
+            return NotImplemented
+        if OPENBSD or NETBSD or SUNOS:  # pragma: no cover
+            # Zombie processes on Open/NetBSD/illumos/Solaris have a
+            # creation time of 0.0.  This covers the case when a process
+            # started normally (so it has a ctime), then it turned into a
+            # zombie. It's important to do this because is_running()
+            # depends on __eq__.
+            pid1, ident1 = self._ident
+            pid2, ident2 = other._ident
+            if pid1 == pid2:
+                if ident1 and not ident2:
+                    try:
+                        return self.status() == STATUS_ZOMBIE
+                    except Error:
+                        pass
+        return self._ident == other._ident
+
+    def __ne__(self, other):
+        return not self == other
+
+    def __hash__(self):
+        if self._hash is None:
+            self._hash = hash(self._ident)
+        return self._hash
+
+    def _raise_if_pid_reused(self):
+        """Raises NoSuchProcess in case process PID has been reused."""
+        if self._pid_reused or (not self.is_running() and self._pid_reused):
+            # We may directly raise NSP in here already if PID is just
+            # not running, but I prefer NSP to be raised naturally by
+            # the actual Process API call. This way unit tests will tell
+            # us if the API is broken (aka don't raise NSP when it
+            # should). We also remain consistent with all other "get"
+            # APIs which don't use _raise_if_pid_reused().
+            msg = "process no longer exists and its PID has been reused"
+            raise NoSuchProcess(self.pid, self._name, msg=msg)
+
+    @property
+    def pid(self):
+        """The process PID."""
+        return self._pid
+
+    # --- utility methods
+
+    @contextlib.contextmanager
+    def oneshot(self):
+        """Utility context manager which considerably speeds up the
+        retrieval of multiple process information at the same time.
+
+        Internally different process info (e.g. name, ppid, uids,
+        gids, ...) may be fetched by using the same routine, but
+        only one information is returned and the others are discarded.
+        When using this context manager the internal routine is
+        executed once (in the example below on name()) and the
+        other info are cached.
+
+        The cache is cleared when exiting the context manager block.
+        The advice is to use this every time you retrieve more than
+        one information about the process. If you're lucky, you'll
+        get a hell of a speedup.
+
+        >>> import psutil
+        >>> p = psutil.Process()
+        >>> with p.oneshot():
+        ...     p.name()  # collect multiple info
+        ...     p.cpu_times()  # return cached value
+        ...     p.cpu_percent()  # return cached value
+        ...     p.create_time()  # return cached value
+        ...
+        >>>
+        """
+        with self._lock:
+            if hasattr(self, "_cache"):
+                # NOOP: this covers the use case where the user enters the
+                # context twice:
+                #
+                # >>> with p.oneshot():
+                # ...    with p.oneshot():
+                # ...
+                #
+                # Also, since as_dict() internally uses oneshot()
+                # I expect that the code below will be a pretty common
+                # "mistake" that the user will make, so let's guard
+                # against that:
+                #
+                # >>> with p.oneshot():
+                # ...    p.as_dict()
+                # ...
+                yield
+            else:
+                try:
+                    # cached in case cpu_percent() is used
+                    self.cpu_times.cache_activate(self)
+                    # cached in case memory_percent() is used
+                    self.memory_info.cache_activate(self)
+                    # cached in case parent() is used
+                    self.ppid.cache_activate(self)
+                    # cached in case username() is used
+                    if POSIX:
+                        self.uids.cache_activate(self)
+                    # specific implementation cache
+                    self._proc.oneshot_enter()
+                    yield
+                finally:
+                    self.cpu_times.cache_deactivate(self)
+                    self.memory_info.cache_deactivate(self)
+                    self.ppid.cache_deactivate(self)
+                    if POSIX:
+                        self.uids.cache_deactivate(self)
+                    self._proc.oneshot_exit()
+
+    def as_dict(self, attrs=None, ad_value=None):
+        """Utility method returning process information as a
+        hashable dictionary.
+        If *attrs* is specified it must be a list of strings
+        reflecting available Process class' attribute names
+        (e.g. ['cpu_times', 'name']) else all public (read
+        only) attributes are assumed.
+        *ad_value* is the value which gets assigned in case
+        AccessDenied or ZombieProcess exception is raised when
+        retrieving that particular process information.
+        """
+        valid_names = _as_dict_attrnames
+        if attrs is not None:
+            if not isinstance(attrs, (list, tuple, set, frozenset)):
+                msg = f"invalid attrs type {type(attrs)}"
+                raise TypeError(msg)
+            attrs = set(attrs)
+            invalid_names = attrs - valid_names
+            if invalid_names:
+                msg = "invalid attr name{} {}".format(
+                    "s" if len(invalid_names) > 1 else "",
+                    ", ".join(map(repr, invalid_names)),
+                )
+                raise ValueError(msg)
+
+        retdict = {}
+        ls = attrs or valid_names
+        with self.oneshot():
+            for name in ls:
+                try:
+                    if name == 'pid':
+                        ret = self.pid
+                    else:
+                        meth = getattr(self, name)
+                        ret = meth()
+                except (AccessDenied, ZombieProcess):
+                    ret = ad_value
+                except NotImplementedError:
+                    # in case of not implemented functionality (may happen
+                    # on old or exotic systems) we want to crash only if
+                    # the user explicitly asked for that particular attr
+                    if attrs:
+                        raise
+                    continue
+                retdict[name] = ret
+        return retdict
+
+    def parent(self):
+        """Return the parent process as a Process object pre-emptively
+        checking whether PID has been reused.
+        If no parent is known return None.
+        """
+        lowest_pid = _LOWEST_PID if _LOWEST_PID is not None else pids()[0]
+        if self.pid == lowest_pid:
+            return None
+        ppid = self.ppid()
+        if ppid is not None:
+            # Get a fresh (non-cached) ctime in case the system clock
+            # was updated. TODO: use a monotonic ctime on platforms
+            # where it's supported.
+            proc_ctime = Process(self.pid).create_time()
+            try:
+                parent = Process(ppid)
+                if parent.create_time() <= proc_ctime:
+                    return parent
+                # ...else ppid has been reused by another process
+            except NoSuchProcess:
+                pass
+
+    def parents(self):
+        """Return the parents of this process as a list of Process
+        instances. If no parents are known return an empty list.
+        """
+        parents = []
+        proc = self.parent()
+        while proc is not None:
+            parents.append(proc)
+            proc = proc.parent()
+        return parents
+
+    def is_running(self):
+        """Return whether this process is running.
+
+        It also checks if PID has been reused by another process, in
+        which case it will remove the process from `process_iter()`
+        internal cache and return False.
+        """
+        if self._gone or self._pid_reused:
+            return False
+        try:
+            # Checking if PID is alive is not enough as the PID might
+            # have been reused by another process. Process identity /
+            # uniqueness over time is guaranteed by (PID + creation
+            # time) and that is verified in __eq__.
+            self._pid_reused = self != Process(self.pid)
+            if self._pid_reused:
+                _pids_reused.add(self.pid)
+                raise NoSuchProcess(self.pid)
+            return True
+        except ZombieProcess:
+            # We should never get here as it's already handled in
+            # Process.__init__; here just for extra safety.
+            return True
+        except NoSuchProcess:
+            self._gone = True
+            return False
+
+    # --- actual API
+
+    @memoize_when_activated
+    def ppid(self):
+        """The process parent PID.
+        On Windows the return value is cached after first call.
+        """
+        # On POSIX we don't want to cache the ppid as it may unexpectedly
+        # change to 1 (init) in case this process turns into a zombie:
+        # https://github.com/giampaolo/psutil/issues/321
+        # http://stackoverflow.com/questions/356722/
+
+        # XXX should we check creation time here rather than in
+        # Process.parent()?
+        self._raise_if_pid_reused()
+        if POSIX:
+            return self._proc.ppid()
+        else:  # pragma: no cover
+            self._ppid = self._ppid or self._proc.ppid()
+            return self._ppid
+
+    def name(self):
+        """The process name. The return value is cached after first call."""
+        # Process name is only cached on Windows as on POSIX it may
+        # change, see:
+        # https://github.com/giampaolo/psutil/issues/692
+        if WINDOWS and self._name is not None:
+            return self._name
+        name = self._proc.name()
+        if POSIX and len(name) >= 15:
+            # On UNIX the name gets truncated to the first 15 characters.
+            # If it matches the first part of the cmdline we return that
+            # one instead because it's usually more explicative.
+            # Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon".
+            try:
+                cmdline = self.cmdline()
+            except (AccessDenied, ZombieProcess):
+                # Just pass and return the truncated name: it's better
+                # than nothing. Note: there are actual cases where a
+                # zombie process can return a name() but not a
+                # cmdline(), see:
+                # https://github.com/giampaolo/psutil/issues/2239
+                pass
+            else:
+                if cmdline:
+                    extended_name = os.path.basename(cmdline[0])
+                    if extended_name.startswith(name):
+                        name = extended_name
+        self._name = name
+        self._proc._name = name
+        return name
+
+    def exe(self):
+        """The process executable as an absolute path.
+        May also be an empty string.
+        The return value is cached after first call.
+        """
+
+        def guess_it(fallback):
+            # try to guess exe from cmdline[0] in absence of a native
+            # exe representation
+            cmdline = self.cmdline()
+            if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'):
+                exe = cmdline[0]  # the possible exe
+                # Attempt to guess only in case of an absolute path.
+                # It is not safe otherwise as the process might have
+                # changed cwd.
+                if (
+                    os.path.isabs(exe)
+                    and os.path.isfile(exe)
+                    and os.access(exe, os.X_OK)
+                ):
+                    return exe
+            if isinstance(fallback, AccessDenied):
+                raise fallback
+            return fallback
+
+        if self._exe is None:
+            try:
+                exe = self._proc.exe()
+            except AccessDenied as err:
+                return guess_it(fallback=err)
+            else:
+                if not exe:
+                    # underlying implementation can legitimately return an
+                    # empty string; if that's the case we don't want to
+                    # raise AD while guessing from the cmdline
+                    try:
+                        exe = guess_it(fallback=exe)
+                    except AccessDenied:
+                        pass
+                self._exe = exe
+        return self._exe
+
+    def cmdline(self):
+        """The command line this process has been called with."""
+        return self._proc.cmdline()
+
+    def status(self):
+        """The process current status as a STATUS_* constant."""
+        try:
+            return self._proc.status()
+        except ZombieProcess:
+            return STATUS_ZOMBIE
+
+    def username(self):
+        """The name of the user that owns the process.
+        On UNIX this is calculated by using *real* process uid.
+        """
+        if POSIX:
+            if pwd is None:
+                # might happen if python was installed from sources
+                msg = "requires pwd module shipped with standard python"
+                raise ImportError(msg)
+            real_uid = self.uids().real
+            try:
+                return pwd.getpwuid(real_uid).pw_name
+            except KeyError:
+                # the uid can't be resolved by the system
+                return str(real_uid)
+        else:
+            return self._proc.username()
+
+    def create_time(self):
+        """The process creation time as a floating point number
+        expressed in seconds since the epoch (seconds since January 1,
+        1970, at midnight UTC). The return value, which is cached after
+        first call, is based on the system clock, which means it may be
+        affected by changes such as manual adjustments or time
+        synchronization (e.g. NTP).
+        """
+        if self._create_time is None:
+            self._create_time = self._proc.create_time()
+        return self._create_time
+
+    def cwd(self):
+        """Process current working directory as an absolute path."""
+        return self._proc.cwd()
+
+    def nice(self, value=None):
+        """Get or set process niceness (priority)."""
+        if value is None:
+            return self._proc.nice_get()
+        else:
+            self._raise_if_pid_reused()
+            self._proc.nice_set(value)
+
+    if POSIX:
+
+        @memoize_when_activated
+        def uids(self):
+            """Return process UIDs as a (real, effective, saved)
+            namedtuple.
+            """
+            return self._proc.uids()
+
+        def gids(self):
+            """Return process GIDs as a (real, effective, saved)
+            namedtuple.
+            """
+            return self._proc.gids()
+
+        def terminal(self):
+            """The terminal associated with this process, if any,
+            else None.
+            """
+            return self._proc.terminal()
+
+        def num_fds(self):
+            """Return the number of file descriptors opened by this
+            process (POSIX only).
+            """
+            return self._proc.num_fds()
+
+    # Linux, BSD, AIX and Windows only
+    if hasattr(_psplatform.Process, "io_counters"):
+
+        def io_counters(self):
+            """Return process I/O statistics as a
+            (read_count, write_count, read_bytes, write_bytes)
+            namedtuple.
+            Those are the number of read/write calls performed and the
+            amount of bytes read and written by the process.
+            """
+            return self._proc.io_counters()
+
+    # Linux and Windows
+    if hasattr(_psplatform.Process, "ionice_get"):
+
+        def ionice(self, ioclass=None, value=None):
+            """Get or set process I/O niceness (priority).
+
+            On Linux *ioclass* is one of the IOPRIO_CLASS_* constants.
+            *value* is a number which goes from 0 to 7. The higher the
+            value, the lower the I/O priority of the process.
+
+            On Windows only *ioclass* is used and it can be set to 2
+            (normal), 1 (low) or 0 (very low).
+
+            Available on Linux and Windows > Vista only.
+            """
+            if ioclass is None:
+                if value is not None:
+                    msg = "'ioclass' argument must be specified"
+                    raise ValueError(msg)
+                return self._proc.ionice_get()
+            else:
+                self._raise_if_pid_reused()
+                return self._proc.ionice_set(ioclass, value)
+
+    # Linux / FreeBSD only
+    if hasattr(_psplatform.Process, "rlimit"):
+
+        def rlimit(self, resource, limits=None):
+            """Get or set process resource limits as a (soft, hard)
+            tuple.
+
+            *resource* is one of the RLIMIT_* constants.
+            *limits* is supposed to be a (soft, hard) tuple.
+
+            See "man prlimit" for further info.
+            Available on Linux and FreeBSD only.
+            """
+            if limits is not None:
+                self._raise_if_pid_reused()
+            return self._proc.rlimit(resource, limits)
+
+    # Windows, Linux and FreeBSD only
+    if hasattr(_psplatform.Process, "cpu_affinity_get"):
+
+        def cpu_affinity(self, cpus=None):
+            """Get or set process CPU affinity.
+            If specified, *cpus* must be a list of CPUs for which you
+            want to set the affinity (e.g. [0, 1]).
+            If an empty list is passed, all egible CPUs are assumed
+            (and set).
+            (Windows, Linux and BSD only).
+            """
+            if cpus is None:
+                return sorted(set(self._proc.cpu_affinity_get()))
+            else:
+                self._raise_if_pid_reused()
+                if not cpus:
+                    if hasattr(self._proc, "_get_eligible_cpus"):
+                        cpus = self._proc._get_eligible_cpus()
+                    else:
+                        cpus = tuple(range(len(cpu_times(percpu=True))))
+                self._proc.cpu_affinity_set(list(set(cpus)))
+
+    # Linux, FreeBSD, SunOS
+    if hasattr(_psplatform.Process, "cpu_num"):
+
+        def cpu_num(self):
+            """Return what CPU this process is currently running on.
+            The returned number should be <= psutil.cpu_count()
+            and <= len(psutil.cpu_percent(percpu=True)).
+            It may be used in conjunction with
+            psutil.cpu_percent(percpu=True) to observe the system
+            workload distributed across CPUs.
+            """
+            return self._proc.cpu_num()
+
+    # All platforms has it, but maybe not in the future.
+    if hasattr(_psplatform.Process, "environ"):
+
+        def environ(self):
+            """The environment variables of the process as a dict.  Note: this
+            might not reflect changes made after the process started.
+            """
+            return self._proc.environ()
+
+    if WINDOWS:
+
+        def num_handles(self):
+            """Return the number of handles opened by this process
+            (Windows only).
+            """
+            return self._proc.num_handles()
+
+    def num_ctx_switches(self):
+        """Return the number of voluntary and involuntary context
+        switches performed by this process.
+        """
+        return self._proc.num_ctx_switches()
+
+    def num_threads(self):
+        """Return the number of threads used by this process."""
+        return self._proc.num_threads()
+
+    if hasattr(_psplatform.Process, "threads"):
+
+        def threads(self):
+            """Return threads opened by process as a list of
+            (id, user_time, system_time) namedtuples representing
+            thread id and thread CPU times (user/system).
+            On OpenBSD this method requires root access.
+            """
+            return self._proc.threads()
+
+    def children(self, recursive=False):
+        """Return the children of this process as a list of Process
+        instances, pre-emptively checking whether PID has been reused.
+        If *recursive* is True return all the parent descendants.
+
+        Example (A == this process):
+
+         A ─┐
+            │
+            ├─ B (child) ─┐
+            │             └─ X (grandchild) ─┐
+            │                                └─ Y (great grandchild)
+            ├─ C (child)
+            └─ D (child)
+
+        >>> import psutil
+        >>> p = psutil.Process()
+        >>> p.children()
+        B, C, D
+        >>> p.children(recursive=True)
+        B, X, Y, C, D
+
+        Note that in the example above if process X disappears
+        process Y won't be listed as the reference to process A
+        is lost.
+        """
+        self._raise_if_pid_reused()
+        ppid_map = _ppid_map()
+        # Get a fresh (non-cached) ctime in case the system clock was
+        # updated. TODO: use a monotonic ctime on platforms where it's
+        # supported.
+        proc_ctime = Process(self.pid).create_time()
+        ret = []
+        if not recursive:
+            for pid, ppid in ppid_map.items():
+                if ppid == self.pid:
+                    try:
+                        child = Process(pid)
+                        # if child happens to be older than its parent
+                        # (self) it means child's PID has been reused
+                        if proc_ctime <= child.create_time():
+                            ret.append(child)
+                    except (NoSuchProcess, ZombieProcess):
+                        pass
+        else:
+            # Construct a {pid: [child pids]} dict
+            reverse_ppid_map = collections.defaultdict(list)
+            for pid, ppid in ppid_map.items():
+                reverse_ppid_map[ppid].append(pid)
+            # Recursively traverse that dict, starting from self.pid,
+            # such that we only call Process() on actual children
+            seen = set()
+            stack = [self.pid]
+            while stack:
+                pid = stack.pop()
+                if pid in seen:
+                    # Since pids can be reused while the ppid_map is
+                    # constructed, there may be rare instances where
+                    # there's a cycle in the recorded process "tree".
+                    continue
+                seen.add(pid)
+                for child_pid in reverse_ppid_map[pid]:
+                    try:
+                        child = Process(child_pid)
+                        # if child happens to be older than its parent
+                        # (self) it means child's PID has been reused
+                        intime = proc_ctime <= child.create_time()
+                        if intime:
+                            ret.append(child)
+                            stack.append(child_pid)
+                    except (NoSuchProcess, ZombieProcess):
+                        pass
+        return ret
+
+    def cpu_percent(self, interval=None):
+        """Return a float representing the current process CPU
+        utilization as a percentage.
+
+        When *interval* is 0.0 or None (default) compares process times
+        to system CPU times elapsed since last call, returning
+        immediately (non-blocking). That means that the first time
+        this is called it will return a meaningful 0.0 value.
+
+        When *interval* is > 0.0 compares process times to system CPU
+        times elapsed before and after the interval (blocking).
+
+        In this case is recommended for accuracy that this function
+        be called with at least 0.1 seconds between calls.
+
+        A value > 100.0 can be returned in case of processes running
+        multiple threads on different CPU cores.
+
+        The returned value is explicitly NOT split evenly between
+        all available logical CPUs. This means that a busy loop process
+        running on a system with 2 logical CPUs will be reported as
+        having 100% CPU utilization instead of 50%.
+
+        Examples:
+
+          >>> import psutil
+          >>> p = psutil.Process(os.getpid())
+          >>> # blocking
+          >>> p.cpu_percent(interval=1)
+          2.0
+          >>> # non-blocking (percentage since last call)
+          >>> p.cpu_percent(interval=None)
+          2.9
+          >>>
+        """
+        blocking = interval is not None and interval > 0.0
+        if interval is not None and interval < 0:
+            msg = f"interval is not positive (got {interval!r})"
+            raise ValueError(msg)
+        num_cpus = cpu_count() or 1
+
+        def timer():
+            return _timer() * num_cpus
+
+        if blocking:
+            st1 = timer()
+            pt1 = self._proc.cpu_times()
+            time.sleep(interval)
+            st2 = timer()
+            pt2 = self._proc.cpu_times()
+        else:
+            st1 = self._last_sys_cpu_times
+            pt1 = self._last_proc_cpu_times
+            st2 = timer()
+            pt2 = self._proc.cpu_times()
+            if st1 is None or pt1 is None:
+                self._last_sys_cpu_times = st2
+                self._last_proc_cpu_times = pt2
+                return 0.0
+
+        delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system)
+        delta_time = st2 - st1
+        # reset values for next call in case of interval == None
+        self._last_sys_cpu_times = st2
+        self._last_proc_cpu_times = pt2
+
+        try:
+            # This is the utilization split evenly between all CPUs.
+            # E.g. a busy loop process on a 2-CPU-cores system at this
+            # point is reported as 50% instead of 100%.
+            overall_cpus_percent = (delta_proc / delta_time) * 100
+        except ZeroDivisionError:
+            # interval was too low
+            return 0.0
+        else:
+            # Note 1:
+            # in order to emulate "top" we multiply the value for the num
+            # of CPU cores. This way the busy process will be reported as
+            # having 100% (or more) usage.
+            #
+            # Note 2:
+            # taskmgr.exe on Windows differs in that it will show 50%
+            # instead.
+            #
+            # Note 3:
+            # a percentage > 100 is legitimate as it can result from a
+            # process with multiple threads running on different CPU
+            # cores (top does the same), see:
+            # http://stackoverflow.com/questions/1032357
+            # https://github.com/giampaolo/psutil/issues/474
+            single_cpu_percent = overall_cpus_percent * num_cpus
+            return round(single_cpu_percent, 1)
+
+    @memoize_when_activated
+    def cpu_times(self):
+        """Return a (user, system, children_user, children_system)
+        namedtuple representing the accumulated process time, in
+        seconds.
+        This is similar to os.times() but per-process.
+        On macOS and Windows children_user and children_system are
+        always set to 0.
+        """
+        return self._proc.cpu_times()
+
+    @memoize_when_activated
+    def memory_info(self):
+        """Return a namedtuple with variable fields depending on the
+        platform, representing memory information about the process.
+
+        The "portable" fields available on all platforms are `rss` and `vms`.
+
+        All numbers are expressed in bytes.
+        """
+        return self._proc.memory_info()
+
+    def memory_full_info(self):
+        """This method returns the same information as memory_info(),
+        plus, on some platform (Linux, macOS, Windows), also provides
+        additional metrics (USS, PSS and swap).
+        The additional metrics provide a better representation of actual
+        process memory usage.
+
+        Namely USS is the memory which is unique to a process and which
+        would be freed if the process was terminated right now.
+
+        It does so by passing through the whole process address.
+        As such it usually requires higher user privileges than
+        memory_info() and is considerably slower.
+        """
+        return self._proc.memory_full_info()
+
+    def memory_percent(self, memtype="rss"):
+        """Compare process memory to total physical system memory and
+        calculate process memory utilization as a percentage.
+        *memtype* argument is a string that dictates what type of
+        process memory you want to compare against (defaults to "rss").
+        The list of available strings can be obtained like this:
+
+        >>> psutil.Process().memory_info()._fields
+        ('rss', 'vms', 'shared', 'text', 'lib', 'data', 'dirty', 'uss', 'pss')
+        """
+        valid_types = list(_ntp.pfullmem._fields)
+        if memtype not in valid_types:
+            msg = (
+                f"invalid memtype {memtype!r}; valid types are"
+                f" {tuple(valid_types)!r}"
+            )
+            raise ValueError(msg)
+        fun = (
+            self.memory_info
+            if memtype in _ntp.pmem._fields
+            else self.memory_full_info
+        )
+        metrics = fun()
+        value = getattr(metrics, memtype)
+
+        # use cached value if available
+        total_phymem = _TOTAL_PHYMEM or virtual_memory().total
+        if not total_phymem > 0:
+            # we should never get here
+            msg = (
+                "can't calculate process memory percent because total physical"
+                f" system memory is not positive ({total_phymem!r})"
+            )
+            raise ValueError(msg)
+        return (value / float(total_phymem)) * 100
+
+    if hasattr(_psplatform.Process, "memory_maps"):
+
+        def memory_maps(self, grouped=True):
+            """Return process' mapped memory regions as a list of namedtuples
+            whose fields are variable depending on the platform.
+
+            If *grouped* is True the mapped regions with the same 'path'
+            are grouped together and the different memory fields are summed.
+
+            If *grouped* is False every mapped region is shown as a single
+            entity and the namedtuple will also include the mapped region's
+            address space ('addr') and permission set ('perms').
+            """
+            it = self._proc.memory_maps()
+            if grouped:
+                d = {}
+                for tupl in it:
+                    path = tupl[2]
+                    nums = tupl[3:]
+                    try:
+                        d[path] = list(map(lambda x, y: x + y, d[path], nums))
+                    except KeyError:
+                        d[path] = nums
+                return [_ntp.pmmap_grouped(path, *d[path]) for path in d]
+            else:
+                return [_ntp.pmmap_ext(*x) for x in it]
+
+    def open_files(self):
+        """Return files opened by process as a list of
+        (path, fd) namedtuples including the absolute file name
+        and file descriptor number.
+        """
+        return self._proc.open_files()
+
+    def net_connections(self, kind='inet'):
+        """Return socket connections opened by process as a list of
+        (fd, family, type, laddr, raddr, status) namedtuples.
+        The *kind* parameter filters for connections that match the
+        following criteria:
+
+        +------------+----------------------------------------------------+
+        | Kind Value | Connections using                                  |
+        +------------+----------------------------------------------------+
+        | inet       | IPv4 and IPv6                                      |
+        | inet4      | IPv4                                               |
+        | inet6      | IPv6                                               |
+        | tcp        | TCP                                                |
+        | tcp4       | TCP over IPv4                                      |
+        | tcp6       | TCP over IPv6                                      |
+        | udp        | UDP                                                |
+        | udp4       | UDP over IPv4                                      |
+        | udp6       | UDP over IPv6                                      |
+        | unix       | UNIX socket (both UDP and TCP protocols)           |
+        | all        | the sum of all the possible families and protocols |
+        +------------+----------------------------------------------------+
+        """
+        _check_conn_kind(kind)
+        return self._proc.net_connections(kind)
+
+    @_common.deprecated_method(replacement="net_connections")
+    def connections(self, kind="inet"):
+        return self.net_connections(kind=kind)
+
+    # --- signals
+
+    if POSIX:
+
+        def _send_signal(self, sig):
+            assert not self.pid < 0, self.pid
+            self._raise_if_pid_reused()
+
+            pid, ppid, name = self.pid, self._ppid, self._name
+            if pid == 0:
+                # see "man 2 kill"
+                msg = (
+                    "preventing sending signal to process with PID 0 as it "
+                    "would affect every process in the process group of the "
+                    "calling process (os.getpid()) instead of PID 0"
+                )
+                raise ValueError(msg)
+            try:
+                os.kill(pid, sig)
+            except ProcessLookupError as err:
+                if OPENBSD and pid_exists(pid):
+                    # We do this because os.kill() lies in case of
+                    # zombie processes.
+                    raise ZombieProcess(pid, name, ppid) from err
+                self._gone = True
+                raise NoSuchProcess(pid, name) from err
+            except PermissionError as err:
+                raise AccessDenied(pid, name) from err
+
+    def send_signal(self, sig):
+        """Send a signal *sig* to process pre-emptively checking
+        whether PID has been reused (see signal module constants) .
+        On Windows only SIGTERM is valid and is treated as an alias
+        for kill().
+        """
+        if POSIX:
+            self._send_signal(sig)
+        else:  # pragma: no cover
+            self._raise_if_pid_reused()
+            if sig != signal.SIGTERM and not self.is_running():
+                msg = "process no longer exists"
+                raise NoSuchProcess(self.pid, self._name, msg=msg)
+            self._proc.send_signal(sig)
+
+    def suspend(self):
+        """Suspend process execution with SIGSTOP pre-emptively checking
+        whether PID has been reused.
+        On Windows this has the effect of suspending all process threads.
+        """
+        if POSIX:
+            self._send_signal(signal.SIGSTOP)
+        else:  # pragma: no cover
+            self._raise_if_pid_reused()
+            self._proc.suspend()
+
+    def resume(self):
+        """Resume process execution with SIGCONT pre-emptively checking
+        whether PID has been reused.
+        On Windows this has the effect of resuming all process threads.
+        """
+        if POSIX:
+            self._send_signal(signal.SIGCONT)
+        else:  # pragma: no cover
+            self._raise_if_pid_reused()
+            self._proc.resume()
+
+    def terminate(self):
+        """Terminate the process with SIGTERM pre-emptively checking
+        whether PID has been reused.
+        On Windows this is an alias for kill().
+        """
+        if POSIX:
+            self._send_signal(signal.SIGTERM)
+        else:  # pragma: no cover
+            self._raise_if_pid_reused()
+            self._proc.kill()
+
+    def kill(self):
+        """Kill the current process with SIGKILL pre-emptively checking
+        whether PID has been reused.
+        """
+        if POSIX:
+            self._send_signal(signal.SIGKILL)
+        else:  # pragma: no cover
+            self._raise_if_pid_reused()
+            self._proc.kill()
+
+    def wait(self, timeout=None):
+        """Wait for process to terminate, and if process is a children
+        of os.getpid(), also return its exit code, else None.
+        On Windows there's no such limitation (exit code is always
+        returned).
+
+        If the process is already terminated, immediately return None
+        instead of raising NoSuchProcess.
+
+        If *timeout* (in seconds) is specified and process is still
+        alive, raise TimeoutExpired.
+
+        If *timeout=0* either return immediately or raise
+        TimeoutExpired (non-blocking).
+
+        To wait for multiple Process objects use psutil.wait_procs().
+        """
+        if self.pid == 0:
+            msg = "can't wait for PID 0"
+            raise ValueError(msg)
+        if timeout is not None:
+            if not isinstance(timeout, (int, float)):
+                msg = f"timeout must be an int or float (got {type(timeout)})"
+                raise TypeError(msg)
+            if timeout < 0:
+                msg = f"timeout must be positive or zero (got {timeout})"
+                raise ValueError(msg)
+
+        if self._exitcode is not _SENTINEL:
+            return self._exitcode
+
+        try:
+            self._exitcode = self._proc.wait(timeout)
+        except TimeoutExpired as err:
+            exc = TimeoutExpired(timeout, pid=self.pid, name=self._name)
+            raise exc from err
+
+        return self._exitcode
+
+
+# The valid attr names which can be processed by Process.as_dict().
+# fmt: off
+_as_dict_attrnames = {
+    x for x in dir(Process) if not x.startswith("_") and x not in
+     {'send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait',
+      'is_running', 'as_dict', 'parent', 'parents', 'children', 'rlimit',
+      'connections', 'oneshot'}
+}
+# fmt: on
+
+
+# =====================================================================
+# --- Popen class
+# =====================================================================
+
+
+class Popen(Process):
+    """Same as subprocess.Popen, but in addition it provides all
+    psutil.Process methods in a single class.
+    For the following methods which are common to both classes, psutil
+    implementation takes precedence:
+
+    * send_signal()
+    * terminate()
+    * kill()
+
+    This is done in order to avoid killing another process in case its
+    PID has been reused, fixing BPO-6973.
+
+      >>> import psutil
+      >>> from subprocess import PIPE
+      >>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE)
+      >>> p.name()
+      'python'
+      >>> p.uids()
+      user(real=1000, effective=1000, saved=1000)
+      >>> p.username()
+      'giampaolo'
+      >>> p.communicate()
+      ('hi', None)
+      >>> p.terminate()
+      >>> p.wait(timeout=2)
+      0
+      >>>
+    """
+
+    def __init__(self, *args, **kwargs):
+        # Explicitly avoid to raise NoSuchProcess in case the process
+        # spawned by subprocess.Popen terminates too quickly, see:
+        # https://github.com/giampaolo/psutil/issues/193
+        self.__subproc = subprocess.Popen(*args, **kwargs)
+        self._init(self.__subproc.pid, _ignore_nsp=True)
+
+    def __dir__(self):
+        return sorted(set(dir(Popen) + dir(subprocess.Popen)))
+
+    def __enter__(self):
+        if hasattr(self.__subproc, '__enter__'):
+            self.__subproc.__enter__()
+        return self
+
+    def __exit__(self, *args, **kwargs):
+        if hasattr(self.__subproc, '__exit__'):
+            return self.__subproc.__exit__(*args, **kwargs)
+        else:
+            if self.stdout:
+                self.stdout.close()
+            if self.stderr:
+                self.stderr.close()
+            try:
+                # Flushing a BufferedWriter may raise an error.
+                if self.stdin:
+                    self.stdin.close()
+            finally:
+                # Wait for the process to terminate, to avoid zombies.
+                self.wait()
+
+    def __getattribute__(self, name):
+        try:
+            return object.__getattribute__(self, name)
+        except AttributeError:
+            try:
+                return object.__getattribute__(self.__subproc, name)
+            except AttributeError:
+                msg = f"{self.__class__!r} has no attribute {name!r}"
+                raise AttributeError(msg) from None
+
+    def wait(self, timeout=None):
+        if self.__subproc.returncode is not None:
+            return self.__subproc.returncode
+        ret = super().wait(timeout)
+        self.__subproc.returncode = ret
+        return ret
+
+
+# =====================================================================
+# --- system processes related functions
+# =====================================================================
+
+
+def pids():
+    """Return a list of current running PIDs."""
+    global _LOWEST_PID
+    ret = sorted(_psplatform.pids())
+    _LOWEST_PID = ret[0]
+    return ret
+
+
+def pid_exists(pid):
+    """Return True if given PID exists in the current process list.
+    This is faster than doing "pid in psutil.pids()" and
+    should be preferred.
+    """
+    if pid < 0:
+        return False
+    elif pid == 0 and POSIX:
+        # On POSIX we use os.kill() to determine PID existence.
+        # According to "man 2 kill" PID 0 has a special meaning
+        # though: it refers to <> and that is not we want
+        # to do here.
+        return pid in pids()
+    else:
+        return _psplatform.pid_exists(pid)
+
+
+_pmap = {}
+_pids_reused = set()
+
+
+def process_iter(attrs=None, ad_value=None):
+    """Return a generator yielding a Process instance for all
+    running processes.
+
+    Every new Process instance is only created once and then cached
+    into an internal table which is updated every time this is used.
+    Cache can optionally be cleared via `process_iter.cache_clear()`.
+
+    The sorting order in which processes are yielded is based on
+    their PIDs.
+
+    *attrs* and *ad_value* have the same meaning as in
+    Process.as_dict(). If *attrs* is specified as_dict() is called
+    and the resulting dict is stored as a 'info' attribute attached
+    to returned Process instance.
+    If *attrs* is an empty list it will retrieve all process info
+    (slow).
+    """
+    global _pmap
+
+    def add(pid):
+        proc = Process(pid)
+        pmap[proc.pid] = proc
+        return proc
+
+    def remove(pid):
+        pmap.pop(pid, None)
+
+    pmap = _pmap.copy()
+    a = set(pids())
+    b = set(pmap.keys())
+    new_pids = a - b
+    gone_pids = b - a
+    for pid in gone_pids:
+        remove(pid)
+    while _pids_reused:
+        pid = _pids_reused.pop()
+        debug(f"refreshing Process instance for reused PID {pid}")
+        remove(pid)
+    try:
+        ls = sorted(list(pmap.items()) + list(dict.fromkeys(new_pids).items()))
+        for pid, proc in ls:
+            try:
+                if proc is None:  # new process
+                    proc = add(pid)
+                if attrs is not None:
+                    proc.info = proc.as_dict(attrs=attrs, ad_value=ad_value)
+                yield proc
+            except NoSuchProcess:
+                remove(pid)
+    finally:
+        _pmap = pmap
+
+
+process_iter.cache_clear = lambda: _pmap.clear()  # noqa: PLW0108
+process_iter.cache_clear.__doc__ = "Clear process_iter() internal cache."
+
+
+def wait_procs(procs, timeout=None, callback=None):
+    """Convenience function which waits for a list of processes to
+    terminate.
+
+    Return a (gone, alive) tuple indicating which processes
+    are gone and which ones are still alive.
+
+    The gone ones will have a new *returncode* attribute indicating
+    process exit status (may be None).
+
+    *callback* is a function which gets called every time a process
+    terminates (a Process instance is passed as callback argument).
+
+    Function will return as soon as all processes terminate or when
+    *timeout* occurs.
+    Differently from Process.wait() it will not raise TimeoutExpired if
+    *timeout* occurs.
+
+    Typical use case is:
+
+     - send SIGTERM to a list of processes
+     - give them some time to terminate
+     - send SIGKILL to those ones which are still alive
+
+    Example:
+
+    >>> def on_terminate(proc):
+    ...     print("process {} terminated".format(proc))
+    ...
+    >>> for p in procs:
+    ...    p.terminate()
+    ...
+    >>> gone, alive = wait_procs(procs, timeout=3, callback=on_terminate)
+    >>> for p in alive:
+    ...     p.kill()
+    """
+
+    def check_gone(proc, timeout):
+        try:
+            returncode = proc.wait(timeout=timeout)
+        except (TimeoutExpired, subprocess.TimeoutExpired):
+            pass
+        else:
+            if returncode is not None or not proc.is_running():
+                # Set new Process instance attribute.
+                proc.returncode = returncode
+                gone.add(proc)
+                if callback is not None:
+                    callback(proc)
+
+    if timeout is not None and not timeout >= 0:
+        msg = f"timeout must be a positive integer, got {timeout}"
+        raise ValueError(msg)
+    if callback is not None and not callable(callback):
+        msg = f"callback {callback!r} is not a callable"
+        raise TypeError(msg)
+
+    gone = set()
+    alive = set(procs)
+    if timeout is not None:
+        deadline = _timer() + timeout
+
+    while alive:
+        if timeout is not None and timeout <= 0:
+            break
+        for proc in alive:
+            # Make sure that every complete iteration (all processes)
+            # will last max 1 sec.
+            # We do this because we don't want to wait too long on a
+            # single process: in case it terminates too late other
+            # processes may disappear in the meantime and their PID
+            # reused.
+            max_timeout = 1.0 / len(alive)
+            if timeout is not None:
+                timeout = min((deadline - _timer()), max_timeout)
+                if timeout <= 0:
+                    break
+                check_gone(proc, timeout)
+            else:
+                check_gone(proc, max_timeout)
+        alive = alive - gone  # noqa: PLR6104
+
+    if alive:
+        # Last attempt over processes survived so far.
+        # timeout == 0 won't make this function wait any further.
+        for proc in alive:
+            check_gone(proc, 0)
+        alive = alive - gone  # noqa: PLR6104
+
+    return (list(gone), list(alive))
+
+
+# =====================================================================
+# --- CPU related functions
+# =====================================================================
+
+
+def cpu_count(logical=True):
+    """Return the number of logical CPUs in the system (same as
+    os.cpu_count()).
+
+    If *logical* is False return the number of physical cores only
+    (e.g. hyper thread CPUs are excluded).
+
+    Return None if undetermined.
+
+    The return value is cached after first call.
+    If desired cache can be cleared like this:
+
+    >>> psutil.cpu_count.cache_clear()
+    """
+    if logical:
+        ret = _psplatform.cpu_count_logical()
+    else:
+        ret = _psplatform.cpu_count_cores()
+    if ret is not None and ret < 1:
+        ret = None
+    return ret
+
+
+def cpu_times(percpu=False):
+    """Return system-wide CPU times as a namedtuple.
+    Every CPU time represents the seconds the CPU has spent in the
+    given mode. The namedtuple's fields availability varies depending on the
+    platform:
+
+     - user
+     - system
+     - idle
+     - nice (UNIX)
+     - iowait (Linux)
+     - irq (Linux, FreeBSD)
+     - softirq (Linux)
+     - steal (Linux >= 2.6.11)
+     - guest (Linux >= 2.6.24)
+     - guest_nice (Linux >= 3.2.0)
+
+    When *percpu* is True return a list of namedtuples for each CPU.
+    First element of the list refers to first CPU, second element
+    to second CPU and so on.
+    The order of the list is consistent across calls.
+    """
+    if not percpu:
+        return _psplatform.cpu_times()
+    else:
+        return _psplatform.per_cpu_times()
+
+
+try:
+    _last_cpu_times = {threading.current_thread().ident: cpu_times()}
+except Exception:  # noqa: BLE001
+    # Don't want to crash at import time.
+    _last_cpu_times = {}
+
+try:
+    _last_per_cpu_times = {
+        threading.current_thread().ident: cpu_times(percpu=True)
+    }
+except Exception:  # noqa: BLE001
+    # Don't want to crash at import time.
+    _last_per_cpu_times = {}
+
+
+def _cpu_tot_time(times):
+    """Given a cpu_time() ntuple calculates the total CPU time
+    (including idle time).
+    """
+    tot = sum(times)
+    if LINUX:
+        # On Linux guest times are already accounted in "user" or
+        # "nice" times, so we subtract them from total.
+        # Htop does the same. References:
+        # https://github.com/giampaolo/psutil/pull/940
+        # http://unix.stackexchange.com/questions/178045
+        # https://github.com/torvalds/linux/blob/
+        #     447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/
+        #     cputime.c#L158
+        tot -= getattr(times, "guest", 0)  # Linux 2.6.24+
+        tot -= getattr(times, "guest_nice", 0)  # Linux 3.2.0+
+    return tot
+
+
+def _cpu_busy_time(times):
+    """Given a cpu_time() ntuple calculates the busy CPU time.
+    We do so by subtracting all idle CPU times.
+    """
+    busy = _cpu_tot_time(times)
+    busy -= times.idle
+    # Linux: "iowait" is time during which the CPU does not do anything
+    # (waits for IO to complete). On Linux IO wait is *not* accounted
+    # in "idle" time so we subtract it. Htop does the same.
+    # References:
+    # https://github.com/torvalds/linux/blob/
+    #     447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/cputime.c#L244
+    busy -= getattr(times, "iowait", 0)
+    return busy
+
+
+def _cpu_times_deltas(t1, t2):
+    assert t1._fields == t2._fields, (t1, t2)
+    field_deltas = []
+    for field in _ntp.scputimes._fields:
+        field_delta = getattr(t2, field) - getattr(t1, field)
+        # CPU times are always supposed to increase over time
+        # or at least remain the same and that's because time
+        # cannot go backwards.
+        # Surprisingly sometimes this might not be the case (at
+        # least on Windows and Linux), see:
+        # https://github.com/giampaolo/psutil/issues/392
+        # https://github.com/giampaolo/psutil/issues/645
+        # https://github.com/giampaolo/psutil/issues/1210
+        # Trim negative deltas to zero to ignore decreasing fields.
+        # top does the same. Reference:
+        # https://gitlab.com/procps-ng/procps/blob/v3.3.12/top/top.c#L5063
+        field_delta = max(0, field_delta)
+        field_deltas.append(field_delta)
+    return _ntp.scputimes(*field_deltas)
+
+
+def cpu_percent(interval=None, percpu=False):
+    """Return a float representing the current system-wide CPU
+    utilization as a percentage.
+
+    When *interval* is > 0.0 compares system CPU times elapsed before
+    and after the interval (blocking).
+
+    When *interval* is 0.0 or None compares system CPU times elapsed
+    since last call or module import, returning immediately (non
+    blocking). That means the first time this is called it will
+    return a meaningless 0.0 value which you should ignore.
+    In this case is recommended for accuracy that this function be
+    called with at least 0.1 seconds between calls.
+
+    When *percpu* is True returns a list of floats representing the
+    utilization as a percentage for each CPU.
+    First element of the list refers to first CPU, second element
+    to second CPU and so on.
+    The order of the list is consistent across calls.
+
+    Examples:
+
+      >>> # blocking, system-wide
+      >>> psutil.cpu_percent(interval=1)
+      2.0
+      >>>
+      >>> # blocking, per-cpu
+      >>> psutil.cpu_percent(interval=1, percpu=True)
+      [2.0, 1.0]
+      >>>
+      >>> # non-blocking (percentage since last call)
+      >>> psutil.cpu_percent(interval=None)
+      2.9
+      >>>
+    """
+    tid = threading.current_thread().ident
+    blocking = interval is not None and interval > 0.0
+    if interval is not None and interval < 0:
+        msg = f"interval is not positive (got {interval})"
+        raise ValueError(msg)
+
+    def calculate(t1, t2):
+        times_delta = _cpu_times_deltas(t1, t2)
+        all_delta = _cpu_tot_time(times_delta)
+        busy_delta = _cpu_busy_time(times_delta)
+
+        try:
+            busy_perc = (busy_delta / all_delta) * 100
+        except ZeroDivisionError:
+            return 0.0
+        else:
+            return round(busy_perc, 1)
+
+    # system-wide usage
+    if not percpu:
+        if blocking:
+            t1 = cpu_times()
+            time.sleep(interval)
+        else:
+            t1 = _last_cpu_times.get(tid) or cpu_times()
+        _last_cpu_times[tid] = cpu_times()
+        return calculate(t1, _last_cpu_times[tid])
+    # per-cpu usage
+    else:
+        ret = []
+        if blocking:
+            tot1 = cpu_times(percpu=True)
+            time.sleep(interval)
+        else:
+            tot1 = _last_per_cpu_times.get(tid) or cpu_times(percpu=True)
+        _last_per_cpu_times[tid] = cpu_times(percpu=True)
+        for t1, t2 in zip(tot1, _last_per_cpu_times[tid]):
+            ret.append(calculate(t1, t2))
+        return ret
+
+
+# Use a separate dict for cpu_times_percent(), so it's independent from
+# cpu_percent() and they can both be used within the same program.
+_last_cpu_times_2 = _last_cpu_times.copy()
+_last_per_cpu_times_2 = _last_per_cpu_times.copy()
+
+
+def cpu_times_percent(interval=None, percpu=False):
+    """Same as cpu_percent() but provides utilization percentages
+    for each specific CPU time as is returned by cpu_times().
+    For instance, on Linux we'll get:
+
+      >>> cpu_times_percent()
+      cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0,
+                 irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
+      >>>
+
+    *interval* and *percpu* arguments have the same meaning as in
+    cpu_percent().
+    """
+    tid = threading.current_thread().ident
+    blocking = interval is not None and interval > 0.0
+    if interval is not None and interval < 0:
+        msg = f"interval is not positive (got {interval!r})"
+        raise ValueError(msg)
+
+    def calculate(t1, t2):
+        nums = []
+        times_delta = _cpu_times_deltas(t1, t2)
+        all_delta = _cpu_tot_time(times_delta)
+        # "scale" is the value to multiply each delta with to get percentages.
+        # We use "max" to avoid division by zero (if all_delta is 0, then all
+        # fields are 0 so percentages will be 0 too. all_delta cannot be a
+        # fraction because cpu times are integers)
+        scale = 100.0 / max(1, all_delta)
+        for field_delta in times_delta:
+            field_perc = field_delta * scale
+            field_perc = round(field_perc, 1)
+            # make sure we don't return negative values or values over 100%
+            field_perc = min(max(0.0, field_perc), 100.0)
+            nums.append(field_perc)
+        return _ntp.scputimes(*nums)
+
+    # system-wide usage
+    if not percpu:
+        if blocking:
+            t1 = cpu_times()
+            time.sleep(interval)
+        else:
+            t1 = _last_cpu_times_2.get(tid) or cpu_times()
+        _last_cpu_times_2[tid] = cpu_times()
+        return calculate(t1, _last_cpu_times_2[tid])
+    # per-cpu usage
+    else:
+        ret = []
+        if blocking:
+            tot1 = cpu_times(percpu=True)
+            time.sleep(interval)
+        else:
+            tot1 = _last_per_cpu_times_2.get(tid) or cpu_times(percpu=True)
+        _last_per_cpu_times_2[tid] = cpu_times(percpu=True)
+        for t1, t2 in zip(tot1, _last_per_cpu_times_2[tid]):
+            ret.append(calculate(t1, t2))
+        return ret
+
+
+def cpu_stats():
+    """Return CPU statistics."""
+    return _psplatform.cpu_stats()
+
+
+if hasattr(_psplatform, "cpu_freq"):
+
+    def cpu_freq(percpu=False):
+        """Return CPU frequency as a namedtuple including current,
+        min and max frequency expressed in Mhz.
+
+        If *percpu* is True and the system supports per-cpu frequency
+        retrieval (Linux only) a list of frequencies is returned for
+        each CPU. If not a list with one element is returned.
+        """
+        ret = _psplatform.cpu_freq()
+        if percpu:
+            return ret
+        else:
+            num_cpus = float(len(ret))
+            if num_cpus == 0:
+                return None
+            elif num_cpus == 1:
+                return ret[0]
+            else:
+                currs, mins, maxs = 0.0, 0.0, 0.0
+                set_none = False
+                for cpu in ret:
+                    currs += cpu.current
+                    # On Linux if /proc/cpuinfo is used min/max are set
+                    # to None.
+                    if LINUX and cpu.min is None:
+                        set_none = True
+                        continue
+                    mins += cpu.min
+                    maxs += cpu.max
+
+                current = currs / num_cpus
+
+                if set_none:
+                    min_ = max_ = None
+                else:
+                    min_ = mins / num_cpus
+                    max_ = maxs / num_cpus
+
+                return _ntp.scpufreq(current, min_, max_)
+
+    __all__.append("cpu_freq")
+
+
+if hasattr(os, "getloadavg") or hasattr(_psplatform, "getloadavg"):
+    # Perform this hasattr check once on import time to either use the
+    # platform based code or proxy straight from the os module.
+    if hasattr(os, "getloadavg"):
+        getloadavg = os.getloadavg
+    else:
+        getloadavg = _psplatform.getloadavg
+
+    __all__.append("getloadavg")
+
+
+# =====================================================================
+# --- system memory related functions
+# =====================================================================
+
+
+def virtual_memory():
+    """Return statistics about system memory usage as a namedtuple
+    including the following fields, expressed in bytes:
+
+     - total:
+       total physical memory available.
+
+     - available:
+       the memory that can be given instantly to processes without the
+       system going into swap.
+       This is calculated by summing different memory values depending
+       on the platform and it is supposed to be used to monitor actual
+       memory usage in a cross platform fashion.
+
+     - percent:
+       the percentage usage calculated as (total - available) / total * 100
+
+     - used:
+        memory used, calculated differently depending on the platform and
+        designed for informational purposes only:
+        macOS: active + wired
+        BSD: active + wired + cached
+        Linux: total - free
+
+     - free:
+       memory not being used at all (zeroed) that is readily available;
+       note that this doesn't reflect the actual memory available
+       (use 'available' instead)
+
+    Platform-specific fields:
+
+     - active (UNIX):
+       memory currently in use or very recently used, and so it is in RAM.
+
+     - inactive (UNIX):
+       memory that is marked as not used.
+
+     - buffers (BSD, Linux):
+       cache for things like file system metadata.
+
+     - cached (BSD, macOS):
+       cache for various things.
+
+     - wired (macOS, BSD):
+       memory that is marked to always stay in RAM. It is never moved to disk.
+
+     - shared (BSD):
+       memory that may be simultaneously accessed by multiple processes.
+
+    The sum of 'used' and 'available' does not necessarily equal total.
+    On Windows 'available' and 'free' are the same.
+    """
+    global _TOTAL_PHYMEM
+    ret = _psplatform.virtual_memory()
+    # cached for later use in Process.memory_percent()
+    _TOTAL_PHYMEM = ret.total
+    return ret
+
+
+def swap_memory():
+    """Return system swap memory statistics as a namedtuple including
+    the following fields:
+
+     - total:   total swap memory in bytes
+     - used:    used swap memory in bytes
+     - free:    free swap memory in bytes
+     - percent: the percentage usage
+     - sin:     no. of bytes the system has swapped in from disk (cumulative)
+     - sout:    no. of bytes the system has swapped out from disk (cumulative)
+
+    'sin' and 'sout' on Windows are meaningless and always set to 0.
+    """
+    return _psplatform.swap_memory()
+
+
+# =====================================================================
+# --- disks/partitions related functions
+# =====================================================================
+
+
+def disk_usage(path):
+    """Return disk usage statistics about the given *path* as a
+    namedtuple including total, used and free space expressed in bytes
+    plus the percentage usage.
+    """
+    return _psplatform.disk_usage(path)
+
+
+def disk_partitions(all=False):
+    """Return mounted partitions as a list of
+    (device, mountpoint, fstype, opts) namedtuple.
+    'opts' field is a raw string separated by commas indicating mount
+    options which may vary depending on the platform.
+
+    If *all* parameter is False return physical devices only and ignore
+    all others.
+    """
+    return _psplatform.disk_partitions(all)
+
+
+def disk_io_counters(perdisk=False, nowrap=True):
+    """Return system disk I/O statistics as a namedtuple including
+    the following fields:
+
+     - read_count:  number of reads
+     - write_count: number of writes
+     - read_bytes:  number of bytes read
+     - write_bytes: number of bytes written
+     - read_time:   time spent reading from disk (in ms)
+     - write_time:  time spent writing to disk (in ms)
+
+    Platform specific:
+
+     - busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in ms)
+     - read_merged_count (Linux): number of merged reads
+     - write_merged_count (Linux): number of merged writes
+
+    If *perdisk* is True return the same information for every
+    physical disk installed on the system as a dictionary
+    with partition names as the keys and the namedtuple
+    described above as the values.
+
+    If *nowrap* is True it detects and adjust the numbers which overflow
+    and wrap (restart from 0) and add "old value" to "new value" so that
+    the returned numbers will always be increasing or remain the same,
+    but never decrease.
+    "disk_io_counters.cache_clear()" can be used to invalidate the
+    cache.
+
+    On recent Windows versions 'diskperf -y' command may need to be
+    executed first otherwise this function won't find any disk.
+    """
+    kwargs = dict(perdisk=perdisk) if LINUX else {}
+    rawdict = _psplatform.disk_io_counters(**kwargs)
+    if not rawdict:
+        return {} if perdisk else None
+    if nowrap:
+        rawdict = _wrap_numbers(rawdict, 'psutil.disk_io_counters')
+    if perdisk:
+        for disk, fields in rawdict.items():
+            rawdict[disk] = _ntp.sdiskio(*fields)
+        return rawdict
+    else:
+        return _ntp.sdiskio(*(sum(x) for x in zip(*rawdict.values())))
+
+
+disk_io_counters.cache_clear = functools.partial(
+    _wrap_numbers.cache_clear, 'psutil.disk_io_counters'
+)
+disk_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache"
+
+
+# =====================================================================
+# --- network related functions
+# =====================================================================
+
+
+def net_io_counters(pernic=False, nowrap=True):
+    """Return network I/O statistics as a namedtuple including
+    the following fields:
+
+     - bytes_sent:   number of bytes sent
+     - bytes_recv:   number of bytes received
+     - packets_sent: number of packets sent
+     - packets_recv: number of packets received
+     - errin:        total number of errors while receiving
+     - errout:       total number of errors while sending
+     - dropin:       total number of incoming packets which were dropped
+     - dropout:      total number of outgoing packets which were dropped
+                     (always 0 on macOS and BSD)
+
+    If *pernic* is True return the same information for every
+    network interface installed on the system as a dictionary
+    with network interface names as the keys and the namedtuple
+    described above as the values.
+
+    If *nowrap* is True it detects and adjust the numbers which overflow
+    and wrap (restart from 0) and add "old value" to "new value" so that
+    the returned numbers will always be increasing or remain the same,
+    but never decrease.
+    "net_io_counters.cache_clear()" can be used to invalidate the
+    cache.
+    """
+    rawdict = _psplatform.net_io_counters()
+    if not rawdict:
+        return {} if pernic else None
+    if nowrap:
+        rawdict = _wrap_numbers(rawdict, 'psutil.net_io_counters')
+    if pernic:
+        for nic, fields in rawdict.items():
+            rawdict[nic] = _ntp.snetio(*fields)
+        return rawdict
+    else:
+        return _ntp.snetio(*[sum(x) for x in zip(*rawdict.values())])
+
+
+net_io_counters.cache_clear = functools.partial(
+    _wrap_numbers.cache_clear, 'psutil.net_io_counters'
+)
+net_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache"
+
+
+def net_connections(kind='inet'):
+    """Return system-wide socket connections as a list of
+    (fd, family, type, laddr, raddr, status, pid) namedtuples.
+    In case of limited privileges 'fd' and 'pid' may be set to -1
+    and None respectively.
+    The *kind* parameter filters for connections that fit the
+    following criteria:
+
+    +------------+----------------------------------------------------+
+    | Kind Value | Connections using                                  |
+    +------------+----------------------------------------------------+
+    | inet       | IPv4 and IPv6                                      |
+    | inet4      | IPv4                                               |
+    | inet6      | IPv6                                               |
+    | tcp        | TCP                                                |
+    | tcp4       | TCP over IPv4                                      |
+    | tcp6       | TCP over IPv6                                      |
+    | udp        | UDP                                                |
+    | udp4       | UDP over IPv4                                      |
+    | udp6       | UDP over IPv6                                      |
+    | unix       | UNIX socket (both UDP and TCP protocols)           |
+    | all        | the sum of all the possible families and protocols |
+    +------------+----------------------------------------------------+
+
+    On macOS this function requires root privileges.
+    """
+    _check_conn_kind(kind)
+    return _psplatform.net_connections(kind)
+
+
+def net_if_addrs():
+    """Return the addresses associated to each NIC (network interface
+    card) installed on the system as a dictionary whose keys are the
+    NIC names and value is a list of namedtuples for each address
+    assigned to the NIC. Each namedtuple includes 5 fields:
+
+     - family: can be either socket.AF_INET, socket.AF_INET6 or
+               psutil.AF_LINK, which refers to a MAC address.
+     - address: is the primary address and it is always set.
+     - netmask: and 'broadcast' and 'ptp' may be None.
+     - ptp: stands for "point to point" and references the
+            destination address on a point to point interface
+            (typically a VPN).
+     - broadcast: and *ptp* are mutually exclusive.
+
+    Note: you can have more than one address of the same family
+    associated with each interface.
+    """
+    rawlist = _psplatform.net_if_addrs()
+    rawlist.sort(key=lambda x: x[1])  # sort by family
+    ret = collections.defaultdict(list)
+    for name, fam, addr, mask, broadcast, ptp in rawlist:
+        try:
+            fam = socket.AddressFamily(fam)
+        except ValueError:
+            if WINDOWS and fam == -1:
+                fam = _psplatform.AF_LINK
+            elif (
+                hasattr(_psplatform, "AF_LINK") and fam == _psplatform.AF_LINK
+            ):
+                # Linux defines AF_LINK as an alias for AF_PACKET.
+                # We re-set the family here so that repr(family)
+                # will show AF_LINK rather than AF_PACKET
+                fam = _psplatform.AF_LINK
+
+        if fam == _psplatform.AF_LINK:
+            # The underlying C function may return an incomplete MAC
+            # address in which case we fill it with null bytes, see:
+            # https://github.com/giampaolo/psutil/issues/786
+            separator = ":" if POSIX else "-"
+            while addr.count(separator) < 5:
+                addr += f"{separator}00"
+
+        nt = _ntp.snicaddr(fam, addr, mask, broadcast, ptp)
+
+        # On Windows broadcast is None, so we determine it via
+        # ipaddress module.
+        if WINDOWS and fam in {socket.AF_INET, socket.AF_INET6}:
+            try:
+                broadcast = _common.broadcast_addr(nt)
+            except Exception as err:  # noqa: BLE001
+                debug(err)
+            else:
+                if broadcast is not None:
+                    nt._replace(broadcast=broadcast)
+
+        ret[name].append(nt)
+
+    return dict(ret)
+
+
+def net_if_stats():
+    """Return information about each NIC (network interface card)
+    installed on the system as a dictionary whose keys are the
+    NIC names and value is a namedtuple with the following fields:
+
+     - isup: whether the interface is up (bool)
+     - duplex: can be either NIC_DUPLEX_FULL, NIC_DUPLEX_HALF or
+               NIC_DUPLEX_UNKNOWN
+     - speed: the NIC speed expressed in mega bits (MB); if it can't
+              be determined (e.g. 'localhost') it will be set to 0.
+     - mtu: the maximum transmission unit expressed in bytes.
+    """
+    return _psplatform.net_if_stats()
+
+
+# =====================================================================
+# --- sensors
+# =====================================================================
+
+
+# Linux, macOS
+if hasattr(_psplatform, "sensors_temperatures"):
+
+    def sensors_temperatures(fahrenheit=False):
+        """Return hardware temperatures. Each entry is a namedtuple
+        representing a certain hardware sensor (it may be a CPU, an
+        hard disk or something else, depending on the OS and its
+        configuration).
+        All temperatures are expressed in celsius unless *fahrenheit*
+        is set to True.
+        """
+
+        def convert(n):
+            if n is not None:
+                return (float(n) * 9 / 5) + 32 if fahrenheit else n
+
+        ret = collections.defaultdict(list)
+        rawdict = _psplatform.sensors_temperatures()
+
+        for name, values in rawdict.items():
+            while values:
+                label, current, high, critical = values.pop(0)
+                current = convert(current)
+                high = convert(high)
+                critical = convert(critical)
+
+                if high and not critical:
+                    critical = high
+                elif critical and not high:
+                    high = critical
+
+                ret[name].append(_ntp.shwtemp(label, current, high, critical))
+
+        return dict(ret)
+
+    __all__.append("sensors_temperatures")
+
+
+# Linux
+if hasattr(_psplatform, "sensors_fans"):
+
+    def sensors_fans():
+        """Return fans speed. Each entry is a namedtuple
+        representing a certain hardware sensor.
+        All speed are expressed in RPM (rounds per minute).
+        """
+        return _psplatform.sensors_fans()
+
+    __all__.append("sensors_fans")
+
+
+# Linux, Windows, FreeBSD, macOS
+if hasattr(_psplatform, "sensors_battery"):
+
+    def sensors_battery():
+        """Return battery information. If no battery is installed
+        returns None.
+
+         - percent: battery power left as a percentage.
+         - secsleft: a rough approximation of how many seconds are left
+                     before the battery runs out of power. May be
+                     POWER_TIME_UNLIMITED or POWER_TIME_UNLIMITED.
+         - power_plugged: True if the AC power cable is connected.
+        """
+        return _psplatform.sensors_battery()
+
+    __all__.append("sensors_battery")
+
+
+# =====================================================================
+# --- other system related functions
+# =====================================================================
+
+
+def boot_time():
+    """Return the system boot time expressed in seconds since the epoch
+    (seconds since January 1, 1970, at midnight UTC). The returned
+    value is based on the system clock, which means it may be affected
+    by changes such as manual adjustments or time synchronization (e.g.
+    NTP).
+    """
+    return _psplatform.boot_time()
+
+
+def users():
+    """Return users currently connected on the system as a list of
+    namedtuples including the following fields.
+
+     - user: the name of the user
+     - terminal: the tty or pseudo-tty associated with the user, if any.
+     - host: the host name associated with the entry, if any.
+     - started: the creation time as a floating point number expressed in
+       seconds since the epoch.
+    """
+    return _psplatform.users()
+
+
+# =====================================================================
+# --- Windows services
+# =====================================================================
+
+
+if WINDOWS:
+
+    def win_service_iter():
+        """Return a generator yielding a WindowsService instance for all
+        Windows services installed.
+        """
+        return _psplatform.win_service_iter()
+
+    def win_service_get(name):
+        """Get a Windows service by *name*.
+        Raise NoSuchProcess if no service with such name exists.
+        """
+        return _psplatform.win_service_get(name)
+
+
+# =====================================================================
+# --- malloc / heap
+# =====================================================================
+
+
+# Linux + glibc, Windows, macOS, FreeBSD, NetBSD
+if hasattr(_psplatform, "heap_info"):
+
+    def heap_info():
+        """Return low-level heap statistics from the C heap allocator
+        (glibc).
+
+        - `heap_used`: the total number of bytes allocated via
+          malloc/free. These are typically allocations smaller than
+          MMAP_THRESHOLD.
+
+        - `mmap_used`: the total number of bytes allocated via `mmap()`
+          or via large ``malloc()`` allocations.
+
+        - `heap_count` (Windows only): number of private heaps created
+          via `HeapCreate()`.
+        """
+        return _ntp.pheap(*_psplatform.heap_info())
+
+    def heap_trim():
+        """Request that the underlying allocator free any unused memory
+        it's holding in the heap (typically small `malloc()`
+        allocations).
+
+        In practice, modern allocators rarely comply, so this is not a
+        general-purpose memory-reduction tool and won't meaningfully
+        shrink RSS in real programs. Its primary value is in **leak
+        detection tools**.
+
+        Calling `heap_trim()` before taking measurements helps reduce
+        allocator noise, giving you a cleaner baseline so that changes
+        in `heap_used` come from the code you're testing, not from
+        internal allocator caching or fragmentation. Its effectiveness
+        depends on allocator behavior and fragmentation patterns.
+        """
+        _psplatform.heap_trim()
+
+    __all__.append("heap_info")
+    __all__.append("heap_trim")
+
+
+# =====================================================================
+
+
+def _set_debug(value):
+    """Enable or disable PSUTIL_DEBUG option, which prints debugging
+    messages to stderr.
+    """
+    import psutil._common
+
+    psutil._common.PSUTIL_DEBUG = bool(value)
+    _psplatform.cext.set_debug(bool(value))
+
+
+del memoize_when_activated
diff --git a/micromamba_root/Lib/site-packages/psutil/_common.py b/micromamba_root/Lib/site-packages/psutil/_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..33b6282253ac3321193fdd882aaf38185dee9d49
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil/_common.py
@@ -0,0 +1,861 @@
+# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""Common objects shared by __init__.py and _ps*.py modules.
+
+Note: this module is imported by setup.py, so it should not import
+psutil or third-party modules.
+"""
+
+import collections
+import enum
+import functools
+import os
+import socket
+import stat
+import sys
+import threading
+import warnings
+from socket import AF_INET
+from socket import SOCK_DGRAM
+from socket import SOCK_STREAM
+
+try:
+    from socket import AF_INET6
+except ImportError:
+    AF_INET6 = None
+try:
+    from socket import AF_UNIX
+except ImportError:
+    AF_UNIX = None
+
+
+PSUTIL_DEBUG = bool(os.getenv('PSUTIL_DEBUG'))
+_DEFAULT = object()
+
+# fmt: off
+__all__ = [
+    # OS constants
+    'FREEBSD', 'BSD', 'LINUX', 'NETBSD', 'OPENBSD', 'MACOS', 'OSX', 'POSIX',
+    'SUNOS', 'WINDOWS',
+    # connection constants
+    'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_CLOSING', 'CONN_ESTABLISHED',
+    'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_LAST_ACK', 'CONN_LISTEN',
+    'CONN_NONE', 'CONN_SYN_RECV', 'CONN_SYN_SENT', 'CONN_TIME_WAIT',
+    # net constants
+    'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN',  # noqa: F822
+    # process status constants
+    'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED',
+    'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 'STATUS_SUSPENDED',
+    'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKE_KILL',
+    'STATUS_WAKING', 'STATUS_ZOMBIE', 'STATUS_PARKED',
+    # other constants
+    'ENCODING', 'ENCODING_ERRS', 'AF_INET6',
+    # utility functions
+    'conn_tmap', 'deprecated_method', 'isfile_strict', 'memoize',
+    'parse_environ_block', 'path_exists_strict', 'usage_percent',
+    'supports_ipv6', 'sockfam_to_enum', 'socktype_to_enum', "wrap_numbers",
+    'open_text', 'open_binary', 'cat', 'bcat',
+    'bytes2human', 'conn_to_ntuple', 'debug',
+    # shell utils
+    'hilite', 'term_supports_colors', 'print_color',
+]
+# fmt: on
+
+
+# ===================================================================
+# --- OS constants
+# ===================================================================
+
+
+POSIX = os.name == "posix"
+WINDOWS = os.name == "nt"
+LINUX = sys.platform.startswith("linux")
+MACOS = sys.platform.startswith("darwin")
+OSX = MACOS  # deprecated alias
+FREEBSD = sys.platform.startswith(("freebsd", "midnightbsd"))
+OPENBSD = sys.platform.startswith("openbsd")
+NETBSD = sys.platform.startswith("netbsd")
+BSD = FREEBSD or OPENBSD or NETBSD
+SUNOS = sys.platform.startswith(("sunos", "solaris"))
+AIX = sys.platform.startswith("aix")
+
+
+# ===================================================================
+# --- API constants
+# ===================================================================
+
+
+# Process.status()
+STATUS_RUNNING = "running"
+STATUS_SLEEPING = "sleeping"
+STATUS_DISK_SLEEP = "disk-sleep"
+STATUS_STOPPED = "stopped"
+STATUS_TRACING_STOP = "tracing-stop"
+STATUS_ZOMBIE = "zombie"
+STATUS_DEAD = "dead"
+STATUS_WAKE_KILL = "wake-kill"
+STATUS_WAKING = "waking"
+STATUS_IDLE = "idle"  # Linux, macOS, FreeBSD
+STATUS_LOCKED = "locked"  # FreeBSD
+STATUS_WAITING = "waiting"  # FreeBSD
+STATUS_SUSPENDED = "suspended"  # NetBSD
+STATUS_PARKED = "parked"  # Linux
+
+# Process.net_connections() and psutil.net_connections()
+CONN_ESTABLISHED = "ESTABLISHED"
+CONN_SYN_SENT = "SYN_SENT"
+CONN_SYN_RECV = "SYN_RECV"
+CONN_FIN_WAIT1 = "FIN_WAIT1"
+CONN_FIN_WAIT2 = "FIN_WAIT2"
+CONN_TIME_WAIT = "TIME_WAIT"
+CONN_CLOSE = "CLOSE"
+CONN_CLOSE_WAIT = "CLOSE_WAIT"
+CONN_LAST_ACK = "LAST_ACK"
+CONN_LISTEN = "LISTEN"
+CONN_CLOSING = "CLOSING"
+CONN_NONE = "NONE"
+
+
+# net_if_stats()
+class NicDuplex(enum.IntEnum):
+    NIC_DUPLEX_FULL = 2
+    NIC_DUPLEX_HALF = 1
+    NIC_DUPLEX_UNKNOWN = 0
+
+
+globals().update(NicDuplex.__members__)
+
+
+# sensors_battery()
+class BatteryTime(enum.IntEnum):
+    POWER_TIME_UNKNOWN = -1
+    POWER_TIME_UNLIMITED = -2
+
+
+globals().update(BatteryTime.__members__)
+
+# --- others
+
+ENCODING = sys.getfilesystemencoding()
+ENCODING_ERRS = sys.getfilesystemencodeerrors()
+
+
+# ===================================================================
+# --- Process.net_connections() 'kind' parameter mapping
+# ===================================================================
+
+
+conn_tmap = {
+    "all": ([AF_INET, AF_INET6, AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]),
+    "tcp": ([AF_INET, AF_INET6], [SOCK_STREAM]),
+    "tcp4": ([AF_INET], [SOCK_STREAM]),
+    "udp": ([AF_INET, AF_INET6], [SOCK_DGRAM]),
+    "udp4": ([AF_INET], [SOCK_DGRAM]),
+    "inet": ([AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
+    "inet4": ([AF_INET], [SOCK_STREAM, SOCK_DGRAM]),
+    "inet6": ([AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
+}
+
+if AF_INET6 is not None:
+    conn_tmap.update({
+        "tcp6": ([AF_INET6], [SOCK_STREAM]),
+        "udp6": ([AF_INET6], [SOCK_DGRAM]),
+    })
+
+if AF_UNIX is not None and not SUNOS:
+    conn_tmap.update({"unix": ([AF_UNIX], [SOCK_STREAM, SOCK_DGRAM])})
+
+
+# =====================================================================
+# --- Exceptions
+# =====================================================================
+
+
+class Error(Exception):
+    """Base exception class. All other psutil exceptions inherit
+    from this one.
+    """
+
+    __module__ = 'psutil'
+
+    def _infodict(self, attrs):
+        info = collections.OrderedDict()
+        for name in attrs:
+            value = getattr(self, name, None)
+            if value or (name == "pid" and value == 0):
+                info[name] = value
+        return info
+
+    def __str__(self):
+        # invoked on `raise Error`
+        info = self._infodict(("pid", "ppid", "name"))
+        if info:
+            details = "({})".format(
+                ", ".join([f"{k}={v!r}" for k, v in info.items()])
+            )
+        else:
+            details = None
+        return " ".join([x for x in (getattr(self, "msg", ""), details) if x])
+
+    def __repr__(self):
+        # invoked on `repr(Error)`
+        info = self._infodict(("pid", "ppid", "name", "seconds", "msg"))
+        details = ", ".join([f"{k}={v!r}" for k, v in info.items()])
+        return f"psutil.{self.__class__.__name__}({details})"
+
+
+class NoSuchProcess(Error):
+    """Exception raised when a process with a certain PID doesn't
+    or no longer exists.
+    """
+
+    __module__ = 'psutil'
+
+    def __init__(self, pid, name=None, msg=None):
+        Error.__init__(self)
+        self.pid = pid
+        self.name = name
+        self.msg = msg or "process no longer exists"
+
+    def __reduce__(self):
+        return (self.__class__, (self.pid, self.name, self.msg))
+
+
+class ZombieProcess(NoSuchProcess):
+    """Exception raised when querying a zombie process. This is
+    raised on macOS, BSD and Solaris only, and not always: depending
+    on the query the OS may be able to succeed anyway.
+    On Linux all zombie processes are querable (hence this is never
+    raised). Windows doesn't have zombie processes.
+    """
+
+    __module__ = 'psutil'
+
+    def __init__(self, pid, name=None, ppid=None, msg=None):
+        NoSuchProcess.__init__(self, pid, name, msg)
+        self.ppid = ppid
+        self.msg = msg or "PID still exists but it's a zombie"
+
+    def __reduce__(self):
+        return (self.__class__, (self.pid, self.name, self.ppid, self.msg))
+
+
+class AccessDenied(Error):
+    """Exception raised when permission to perform an action is denied."""
+
+    __module__ = 'psutil'
+
+    def __init__(self, pid=None, name=None, msg=None):
+        Error.__init__(self)
+        self.pid = pid
+        self.name = name
+        self.msg = msg or ""
+
+    def __reduce__(self):
+        return (self.__class__, (self.pid, self.name, self.msg))
+
+
+class TimeoutExpired(Error):
+    """Raised on Process.wait(timeout) if timeout expires and process
+    is still alive.
+    """
+
+    __module__ = 'psutil'
+
+    def __init__(self, seconds, pid=None, name=None):
+        Error.__init__(self)
+        self.seconds = seconds
+        self.pid = pid
+        self.name = name
+        self.msg = f"timeout after {seconds} seconds"
+
+    def __reduce__(self):
+        return (self.__class__, (self.seconds, self.pid, self.name))
+
+
+# ===================================================================
+# --- utils
+# ===================================================================
+
+
+def usage_percent(used, total, round_=None):
+    """Calculate percentage usage of 'used' against 'total'."""
+    try:
+        ret = (float(used) / total) * 100
+    except ZeroDivisionError:
+        return 0.0
+    else:
+        if round_ is not None:
+            ret = round(ret, round_)
+        return ret
+
+
+def memoize(fun):
+    """A simple memoize decorator for functions supporting (hashable)
+    positional arguments.
+    It also provides a cache_clear() function for clearing the cache:
+
+    >>> @memoize
+    ... def foo()
+    ...     return 1
+        ...
+    >>> foo()
+    1
+    >>> foo.cache_clear()
+    >>>
+
+    It supports:
+     - functions
+     - classes (acts as a @singleton)
+     - staticmethods
+     - classmethods
+
+    It does NOT support:
+     - methods
+    """
+
+    @functools.wraps(fun)
+    def wrapper(*args, **kwargs):
+        key = (args, frozenset(sorted(kwargs.items())))
+        try:
+            return cache[key]
+        except KeyError:
+            try:
+                ret = cache[key] = fun(*args, **kwargs)
+            except Exception as err:
+                raise err from None
+            return ret
+
+    def cache_clear():
+        """Clear cache."""
+        cache.clear()
+
+    cache = {}
+    wrapper.cache_clear = cache_clear
+    return wrapper
+
+
+def memoize_when_activated(fun):
+    """A memoize decorator which is disabled by default. It can be
+    activated and deactivated on request.
+    For efficiency reasons it can be used only against class methods
+    accepting no arguments.
+
+    >>> class Foo:
+    ...     @memoize
+    ...     def foo()
+    ...         print(1)
+    ...
+    >>> f = Foo()
+    >>> # deactivated (default)
+    >>> foo()
+    1
+    >>> foo()
+    1
+    >>>
+    >>> # activated
+    >>> foo.cache_activate(self)
+    >>> foo()
+    1
+    >>> foo()
+    >>> foo()
+    >>>
+    """
+
+    @functools.wraps(fun)
+    def wrapper(self):
+        try:
+            # case 1: we previously entered oneshot() ctx
+            ret = self._cache[fun]
+        except AttributeError:
+            # case 2: we never entered oneshot() ctx
+            try:
+                return fun(self)
+            except Exception as err:
+                raise err from None
+        except KeyError:
+            # case 3: we entered oneshot() ctx but there's no cache
+            # for this entry yet
+            try:
+                ret = fun(self)
+            except Exception as err:
+                raise err from None
+            try:
+                self._cache[fun] = ret
+            except AttributeError:
+                # multi-threading race condition, see:
+                # https://github.com/giampaolo/psutil/issues/1948
+                pass
+        return ret
+
+    def cache_activate(proc):
+        """Activate cache. Expects a Process instance. Cache will be
+        stored as a "_cache" instance attribute.
+        """
+        proc._cache = {}
+
+    def cache_deactivate(proc):
+        """Deactivate and clear cache."""
+        try:
+            del proc._cache
+        except AttributeError:
+            pass
+
+    wrapper.cache_activate = cache_activate
+    wrapper.cache_deactivate = cache_deactivate
+    return wrapper
+
+
+def isfile_strict(path):
+    """Same as os.path.isfile() but does not swallow EACCES / EPERM
+    exceptions, see:
+    http://mail.python.org/pipermail/python-dev/2012-June/120787.html.
+    """
+    try:
+        st = os.stat(path)
+    except PermissionError:
+        raise
+    except OSError:
+        return False
+    else:
+        return stat.S_ISREG(st.st_mode)
+
+
+def path_exists_strict(path):
+    """Same as os.path.exists() but does not swallow EACCES / EPERM
+    exceptions. See:
+    http://mail.python.org/pipermail/python-dev/2012-June/120787.html.
+    """
+    try:
+        os.stat(path)
+    except PermissionError:
+        raise
+    except OSError:
+        return False
+    else:
+        return True
+
+
+def supports_ipv6():
+    """Return True if IPv6 is supported on this platform."""
+    if not socket.has_ipv6 or AF_INET6 is None:
+        return False
+    try:
+        with socket.socket(AF_INET6, socket.SOCK_STREAM) as sock:
+            sock.bind(("::1", 0))
+        return True
+    except OSError:
+        return False
+
+
+def parse_environ_block(data):
+    """Parse a C environ block of environment variables into a dictionary."""
+    # The block is usually raw data from the target process.  It might contain
+    # trailing garbage and lines that do not look like assignments.
+    ret = {}
+    pos = 0
+
+    # localize global variable to speed up access.
+    WINDOWS_ = WINDOWS
+    while True:
+        next_pos = data.find("\0", pos)
+        # nul byte at the beginning or double nul byte means finish
+        if next_pos <= pos:
+            break
+        # there might not be an equals sign
+        equal_pos = data.find("=", pos, next_pos)
+        if equal_pos > pos:
+            key = data[pos:equal_pos]
+            value = data[equal_pos + 1 : next_pos]
+            # Windows expects environment variables to be uppercase only
+            if WINDOWS_:
+                key = key.upper()
+            ret[key] = value
+        pos = next_pos + 1
+
+    return ret
+
+
+def sockfam_to_enum(num):
+    """Convert a numeric socket family value to an IntEnum member.
+    If it's not a known member, return the numeric value itself.
+    """
+    try:
+        return socket.AddressFamily(num)
+    except ValueError:
+        return num
+
+
+def socktype_to_enum(num):
+    """Convert a numeric socket type value to an IntEnum member.
+    If it's not a known member, return the numeric value itself.
+    """
+    try:
+        return socket.SocketKind(num)
+    except ValueError:
+        return num
+
+
+def conn_to_ntuple(fd, fam, type_, laddr, raddr, status, status_map, pid=None):
+    """Convert a raw connection tuple to a proper ntuple."""
+    from . import _ntuples as ntp
+
+    if fam in {socket.AF_INET, AF_INET6}:
+        if laddr:
+            laddr = ntp.addr(*laddr)
+        if raddr:
+            raddr = ntp.addr(*raddr)
+    if type_ == socket.SOCK_STREAM and fam in {AF_INET, AF_INET6}:
+        status = status_map.get(status, CONN_NONE)
+    else:
+        status = CONN_NONE  # ignore whatever C returned to us
+    fam = sockfam_to_enum(fam)
+    type_ = socktype_to_enum(type_)
+    if pid is None:
+        return ntp.pconn(fd, fam, type_, laddr, raddr, status)
+    else:
+        return ntp.sconn(fd, fam, type_, laddr, raddr, status, pid)
+
+
+def broadcast_addr(addr):
+    """Given the address ntuple returned by ``net_if_addrs()``
+    calculates the broadcast address.
+    """
+    import ipaddress
+
+    if not addr.address or not addr.netmask:
+        return None
+    if addr.family == socket.AF_INET:
+        return str(
+            ipaddress.IPv4Network(
+                f"{addr.address}/{addr.netmask}", strict=False
+            ).broadcast_address
+        )
+    if addr.family == socket.AF_INET6:
+        return str(
+            ipaddress.IPv6Network(
+                f"{addr.address}/{addr.netmask}", strict=False
+            ).broadcast_address
+        )
+
+
+def deprecated_method(replacement):
+    """A decorator which can be used to mark a method as deprecated
+    'replcement' is the method name which will be called instead.
+    """
+
+    def outer(fun):
+        msg = (
+            f"{fun.__name__}() is deprecated and will be removed; use"
+            f" {replacement}() instead"
+        )
+        if fun.__doc__ is None:
+            fun.__doc__ = msg
+
+        @functools.wraps(fun)
+        def inner(self, *args, **kwargs):
+            warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
+            return getattr(self, replacement)(*args, **kwargs)
+
+        return inner
+
+    return outer
+
+
+class _WrapNumbers:
+    """Watches numbers so that they don't overflow and wrap
+    (reset to zero).
+    """
+
+    def __init__(self):
+        self.lock = threading.Lock()
+        self.cache = {}
+        self.reminders = {}
+        self.reminder_keys = {}
+
+    def _add_dict(self, input_dict, name):
+        assert name not in self.cache
+        assert name not in self.reminders
+        assert name not in self.reminder_keys
+        self.cache[name] = input_dict
+        self.reminders[name] = collections.defaultdict(int)
+        self.reminder_keys[name] = collections.defaultdict(set)
+
+    def _remove_dead_reminders(self, input_dict, name):
+        """In case the number of keys changed between calls (e.g. a
+        disk disappears) this removes the entry from self.reminders.
+        """
+        old_dict = self.cache[name]
+        gone_keys = set(old_dict.keys()) - set(input_dict.keys())
+        for gone_key in gone_keys:
+            for remkey in self.reminder_keys[name][gone_key]:
+                del self.reminders[name][remkey]
+            del self.reminder_keys[name][gone_key]
+
+    def run(self, input_dict, name):
+        """Cache dict and sum numbers which overflow and wrap.
+        Return an updated copy of `input_dict`.
+        """
+        if name not in self.cache:
+            # This was the first call.
+            self._add_dict(input_dict, name)
+            return input_dict
+
+        self._remove_dead_reminders(input_dict, name)
+
+        old_dict = self.cache[name]
+        new_dict = {}
+        for key in input_dict:
+            input_tuple = input_dict[key]
+            try:
+                old_tuple = old_dict[key]
+            except KeyError:
+                # The input dict has a new key (e.g. a new disk or NIC)
+                # which didn't exist in the previous call.
+                new_dict[key] = input_tuple
+                continue
+
+            bits = []
+            for i in range(len(input_tuple)):
+                input_value = input_tuple[i]
+                old_value = old_tuple[i]
+                remkey = (key, i)
+                if input_value < old_value:
+                    # it wrapped!
+                    self.reminders[name][remkey] += old_value
+                    self.reminder_keys[name][key].add(remkey)
+                bits.append(input_value + self.reminders[name][remkey])
+
+            new_dict[key] = tuple(bits)
+
+        self.cache[name] = input_dict
+        return new_dict
+
+    def cache_clear(self, name=None):
+        """Clear the internal cache, optionally only for function 'name'."""
+        with self.lock:
+            if name is None:
+                self.cache.clear()
+                self.reminders.clear()
+                self.reminder_keys.clear()
+            else:
+                self.cache.pop(name, None)
+                self.reminders.pop(name, None)
+                self.reminder_keys.pop(name, None)
+
+    def cache_info(self):
+        """Return internal cache dicts as a tuple of 3 elements."""
+        with self.lock:
+            return (self.cache, self.reminders, self.reminder_keys)
+
+
+def wrap_numbers(input_dict, name):
+    """Given an `input_dict` and a function `name`, adjust the numbers
+    which "wrap" (restart from zero) across different calls by adding
+    "old value" to "new value" and return an updated dict.
+    """
+    with _wn.lock:
+        return _wn.run(input_dict, name)
+
+
+_wn = _WrapNumbers()
+wrap_numbers.cache_clear = _wn.cache_clear
+wrap_numbers.cache_info = _wn.cache_info
+
+
+# The read buffer size for open() builtin. This (also) dictates how
+# much data we read(2) when iterating over file lines as in:
+#   >>> with open(file) as f:
+#   ...    for line in f:
+#   ...        ...
+# Default per-line buffer size for binary files is 1K. For text files
+# is 8K. We use a bigger buffer (32K) in order to have more consistent
+# results when reading /proc pseudo files on Linux, see:
+# https://github.com/giampaolo/psutil/issues/2050
+# https://github.com/giampaolo/psutil/issues/708
+FILE_READ_BUFFER_SIZE = 32 * 1024
+
+
+def open_binary(fname):
+    return open(fname, "rb", buffering=FILE_READ_BUFFER_SIZE)
+
+
+def open_text(fname):
+    """Open a file in text mode by using the proper FS encoding and
+    en/decoding error handlers.
+    """
+    # See:
+    # https://github.com/giampaolo/psutil/issues/675
+    # https://github.com/giampaolo/psutil/pull/733
+    fobj = open(  # noqa: SIM115
+        fname,
+        buffering=FILE_READ_BUFFER_SIZE,
+        encoding=ENCODING,
+        errors=ENCODING_ERRS,
+    )
+    try:
+        # Dictates per-line read(2) buffer size. Defaults is 8k. See:
+        # https://github.com/giampaolo/psutil/issues/2050#issuecomment-1013387546
+        fobj._CHUNK_SIZE = FILE_READ_BUFFER_SIZE
+    except AttributeError:
+        pass
+    except Exception:
+        fobj.close()
+        raise
+
+    return fobj
+
+
+def cat(fname, fallback=_DEFAULT, _open=open_text):
+    """Read entire file content and return it as a string. File is
+    opened in text mode. If specified, `fallback` is the value
+    returned in case of error, either if the file does not exist or
+    it can't be read().
+    """
+    if fallback is _DEFAULT:
+        with _open(fname) as f:
+            return f.read()
+    else:
+        try:
+            with _open(fname) as f:
+                return f.read()
+        except OSError:
+            return fallback
+
+
+def bcat(fname, fallback=_DEFAULT):
+    """Same as above but opens file in binary mode."""
+    return cat(fname, fallback=fallback, _open=open_binary)
+
+
+def bytes2human(n, format="%(value).1f%(symbol)s"):
+    """Used by various scripts. See: https://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/?in=user-4178764.
+
+    >>> bytes2human(10000)
+    '9.8K'
+    >>> bytes2human(100001221)
+    '95.4M'
+    """
+    symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
+    prefix = {}
+    for i, s in enumerate(symbols[1:]):
+        prefix[s] = 1 << (i + 1) * 10
+    for symbol in reversed(symbols[1:]):
+        if abs(n) >= prefix[symbol]:
+            value = float(n) / prefix[symbol]
+            return format % locals()
+    return format % dict(symbol=symbols[0], value=n)
+
+
+def get_procfs_path():
+    """Return updated psutil.PROCFS_PATH constant."""
+    return sys.modules['psutil'].PROCFS_PATH
+
+
+def decode(s):
+    return s.decode(encoding=ENCODING, errors=ENCODING_ERRS)
+
+
+# =====================================================================
+# --- shell utils
+# =====================================================================
+
+
+@memoize
+def term_supports_colors(file=sys.stdout):  # pragma: no cover
+    if not hasattr(file, "isatty") or not file.isatty():
+        return False
+    try:
+        file.fileno()
+    except Exception:  # noqa: BLE001
+        return False
+    return True
+
+
+def hilite(s, color=None, bold=False):  # pragma: no cover
+    """Return an highlighted version of 'string'."""
+    if not term_supports_colors():
+        return s
+    attr = []
+    colors = dict(
+        blue='34',
+        brown='33',
+        darkgrey='30',
+        green='32',
+        grey='37',
+        lightblue='36',
+        red='91',
+        violet='35',
+        yellow='93',
+    )
+    colors[None] = '29'
+    try:
+        color = colors[color]
+    except KeyError:
+        msg = f"invalid color {color!r}; choose amongst {list(colors.keys())}"
+        raise ValueError(msg) from None
+    attr.append(color)
+    if bold:
+        attr.append('1')
+    return f"\x1b[{';'.join(attr)}m{s}\x1b[0m"
+
+
+def print_color(
+    s, color=None, bold=False, file=sys.stdout
+):  # pragma: no cover
+    """Print a colorized version of string."""
+    if not term_supports_colors():
+        print(s, file=file)
+    elif POSIX:
+        print(hilite(s, color, bold), file=file)
+    else:
+        import ctypes
+
+        DEFAULT_COLOR = 7
+        GetStdHandle = ctypes.windll.Kernel32.GetStdHandle
+        SetConsoleTextAttribute = (
+            ctypes.windll.Kernel32.SetConsoleTextAttribute
+        )
+
+        colors = dict(green=2, red=4, brown=6, yellow=6)
+        colors[None] = DEFAULT_COLOR
+        try:
+            color = colors[color]
+        except KeyError:
+            msg = (
+                f"invalid color {color!r}; choose between"
+                f" {list(colors.keys())!r}"
+            )
+            raise ValueError(msg) from None
+        if bold and color <= 7:
+            color += 8
+
+        handle_id = -12 if file is sys.stderr else -11
+        GetStdHandle.restype = ctypes.c_ulong
+        handle = GetStdHandle(handle_id)
+        SetConsoleTextAttribute(handle, color)
+        try:
+            print(s, file=file)
+        finally:
+            SetConsoleTextAttribute(handle, DEFAULT_COLOR)
+
+
+def debug(msg):
+    """If PSUTIL_DEBUG env var is set, print a debug message to stderr."""
+    if PSUTIL_DEBUG:
+        import inspect
+
+        fname, lineno, _, _lines, _index = inspect.getframeinfo(
+            inspect.currentframe().f_back
+        )
+        if isinstance(msg, Exception):
+            if isinstance(msg, OSError):
+                # ...because str(exc) may contain info about the file name
+                msg = f"ignoring {msg}"
+            else:
+                msg = f"ignoring {msg!r}"
+        print(  # noqa: T201
+            f"psutil-debug [{fname}:{lineno}]> {msg}", file=sys.stderr
+        )
diff --git a/micromamba_root/Lib/site-packages/psutil/_ntuples.py b/micromamba_root/Lib/site-packages/psutil/_ntuples.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0ab0393763f0969d2f4b4302fa638771c6c0bdb
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil/_ntuples.py
@@ -0,0 +1,429 @@
+# Copyright (c) 2009, Giampaolo Rodola". All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+from collections import namedtuple as nt
+
+from ._common import AIX
+from ._common import BSD
+from ._common import FREEBSD
+from ._common import LINUX
+from ._common import MACOS
+from ._common import SUNOS
+from ._common import WINDOWS
+
+# ===================================================================
+# --- system functions
+# ===================================================================
+
+# psutil.swap_memory()
+sswap = nt("sswap", ("total", "used", "free", "percent", "sin", "sout"))
+
+# psutil.disk_usage()
+sdiskusage = nt("sdiskusage", ("total", "used", "free", "percent"))
+
+# psutil.disk_io_counters()
+sdiskio = nt(
+    "sdiskio",
+    (
+        "read_count",
+        "write_count",
+        "read_bytes",
+        "write_bytes",
+        "read_time",
+        "write_time",
+    ),
+)
+
+# psutil.disk_partitions()
+sdiskpart = nt("sdiskpart", ("device", "mountpoint", "fstype", "opts"))
+
+# psutil.net_io_counters()
+snetio = nt(
+    "snetio",
+    (
+        "bytes_sent",
+        "bytes_recv",
+        "packets_sent",
+        "packets_recv",
+        "errin",
+        "errout",
+        "dropin",
+        "dropout",
+    ),
+)
+
+# psutil.users()
+suser = nt("suser", ("name", "terminal", "host", "started", "pid"))
+
+# psutil.net_connections()
+sconn = nt(
+    "sconn", ("fd", "family", "type", "laddr", "raddr", "status", "pid")
+)
+
+# psutil.net_if_addrs()
+snicaddr = nt("snicaddr", ("family", "address", "netmask", "broadcast", "ptp"))
+
+# psutil.net_if_stats()
+snicstats = nt("snicstats", ("isup", "duplex", "speed", "mtu", "flags"))
+
+# psutil.cpu_stats()
+scpustats = nt(
+    "scpustats", ("ctx_switches", "interrupts", "soft_interrupts", "syscalls")
+)
+
+# psutil.cpu_freq()
+scpufreq = nt("scpufreq", ("current", "min", "max"))
+
+# psutil.sensors_temperatures()
+shwtemp = nt("shwtemp", ("label", "current", "high", "critical"))
+
+# psutil.sensors_battery()
+sbattery = nt("sbattery", ("percent", "secsleft", "power_plugged"))
+
+# psutil.sensors_fans()
+sfan = nt("sfan", ("label", "current"))
+
+# psutil.heap_info() (mallinfo2 Linux struct)
+if LINUX or WINDOWS or MACOS or BSD:
+    pheap = nt(
+        "pheap",
+        [
+            "heap_used",  # uordblks, memory allocated via malloc()
+            "mmap_used",  # hblkhd, memory allocated via mmap() (large blocks)
+        ],
+    )
+    if WINDOWS:
+        pheap = nt("pheap", pheap._fields + ("heap_count",))
+
+# ===================================================================
+# --- Process class
+# ===================================================================
+
+# psutil.Process.cpu_times()
+pcputimes = nt(
+    "pcputimes", ("user", "system", "children_user", "children_system")
+)
+
+# psutil.Process.open_files()
+popenfile = nt("popenfile", ("path", "fd"))
+
+# psutil.Process.threads()
+pthread = nt("pthread", ("id", "user_time", "system_time"))
+
+# psutil.Process.uids()
+puids = nt("puids", ("real", "effective", "saved"))
+
+# psutil.Process.gids()
+pgids = nt("pgids", ("real", "effective", "saved"))
+
+# psutil.Process.io_counters()
+pio = nt("pio", ("read_count", "write_count", "read_bytes", "write_bytes"))
+
+# psutil.Process.ionice()
+pionice = nt("pionice", ("ioclass", "value"))
+
+# psutil.Process.ctx_switches()
+pctxsw = nt("pctxsw", ("voluntary", "involuntary"))
+
+# psutil.Process.net_connections()
+pconn = nt("pconn", ("fd", "family", "type", "laddr", "raddr", "status"))
+
+# psutil.net_connections() and psutil.Process.net_connections()
+addr = nt("addr", ("ip", "port"))
+
+# ===================================================================
+# --- Linux
+# ===================================================================
+
+if LINUX:
+
+    # This gets set from _pslinux.py
+    scputimes = None
+
+    # psutil.virtual_memory()
+    svmem = nt(
+        "svmem",
+        (
+            "total",
+            "available",
+            "percent",
+            "used",
+            "free",
+            "active",
+            "inactive",
+            "buffers",
+            "cached",
+            "shared",
+            "slab",
+        ),
+    )
+
+    # psutil.disk_io_counters()
+    sdiskio = nt(
+        "sdiskio",
+        (
+            "read_count",
+            "write_count",
+            "read_bytes",
+            "write_bytes",
+            "read_time",
+            "write_time",
+            "read_merged_count",
+            "write_merged_count",
+            "busy_time",
+        ),
+    )
+
+    # psutil.Process().open_files()
+    popenfile = nt("popenfile", ("path", "fd", "position", "mode", "flags"))
+
+    # psutil.Process().memory_info()
+    pmem = nt("pmem", ("rss", "vms", "shared", "text", "lib", "data", "dirty"))
+
+    # psutil.Process().memory_full_info()
+    pfullmem = nt("pfullmem", pmem._fields + ("uss", "pss", "swap"))
+
+    # psutil.Process().memory_maps(grouped=True)
+    pmmap_grouped = nt(
+        "pmmap_grouped",
+        (
+            "path",
+            "rss",
+            "size",
+            "pss",
+            "shared_clean",
+            "shared_dirty",
+            "private_clean",
+            "private_dirty",
+            "referenced",
+            "anonymous",
+            "swap",
+        ),
+    )
+
+    # psutil.Process().memory_maps(grouped=False)
+    pmmap_ext = nt(
+        "pmmap_ext", "addr perms " + " ".join(pmmap_grouped._fields)
+    )
+
+    # psutil.Process.io_counters()
+    pio = nt(
+        "pio",
+        (
+            "read_count",
+            "write_count",
+            "read_bytes",
+            "write_bytes",
+            "read_chars",
+            "write_chars",
+        ),
+    )
+
+    # psutil.Process.cpu_times()
+    pcputimes = nt(
+        "pcputimes",
+        ("user", "system", "children_user", "children_system", "iowait"),
+    )
+
+# ===================================================================
+# --- Windows
+# ===================================================================
+
+elif WINDOWS:
+
+    # psutil.cpu_times()
+    scputimes = nt("scputimes", ("user", "system", "idle", "interrupt", "dpc"))
+
+    # psutil.virtual_memory()
+    svmem = nt("svmem", ("total", "available", "percent", "used", "free"))
+
+    # psutil.Process.memory_info()
+    pmem = nt(
+        "pmem",
+        (
+            "rss",
+            "vms",
+            "num_page_faults",
+            "peak_wset",
+            "wset",
+            "peak_paged_pool",
+            "paged_pool",
+            "peak_nonpaged_pool",
+            "nonpaged_pool",
+            "pagefile",
+            "peak_pagefile",
+            "private",
+        ),
+    )
+
+    # psutil.Process.memory_full_info()
+    pfullmem = nt("pfullmem", pmem._fields + ("uss",))
+
+    # psutil.Process.memory_maps(grouped=True)
+    pmmap_grouped = nt("pmmap_grouped", ("path", "rss"))
+
+    # psutil.Process.memory_maps(grouped=False)
+    pmmap_ext = nt(
+        "pmmap_ext", "addr perms " + " ".join(pmmap_grouped._fields)
+    )
+
+    # psutil.Process.io_counters()
+    pio = nt(
+        "pio",
+        (
+            "read_count",
+            "write_count",
+            "read_bytes",
+            "write_bytes",
+            "other_count",
+            "other_bytes",
+        ),
+    )
+
+# ===================================================================
+# --- macOS
+# ===================================================================
+
+elif MACOS:
+
+    # psutil.cpu_times()
+    scputimes = nt("scputimes", ("user", "nice", "system", "idle"))
+
+    # psutil.virtual_memory()
+    svmem = nt(
+        "svmem",
+        (
+            "total",
+            "available",
+            "percent",
+            "used",
+            "free",
+            "active",
+            "inactive",
+            "wired",
+        ),
+    )
+
+    # psutil.Process.memory_info()
+    pmem = nt("pmem", ("rss", "vms", "pfaults", "pageins"))
+
+    # psutil.Process.memory_full_info()
+    pfullmem = nt("pfullmem", pmem._fields + ("uss",))
+
+# ===================================================================
+# --- BSD
+# ===================================================================
+
+elif BSD:
+
+    # psutil.virtual_memory()
+    svmem = nt(
+        "svmem",
+        (
+            "total",
+            "available",
+            "percent",
+            "used",
+            "free",
+            "active",
+            "inactive",
+            "buffers",
+            "cached",
+            "shared",
+            "wired",
+        ),
+    )
+
+    # psutil.cpu_times()
+    scputimes = nt("scputimes", ("user", "nice", "system", "idle", "irq"))
+
+    # psutil.Process.memory_info()
+    pmem = nt("pmem", ("rss", "vms", "text", "data", "stack"))
+
+    # psutil.Process.memory_full_info()
+    pfullmem = pmem
+
+    # psutil.Process.cpu_times()
+    pcputimes = nt(
+        "pcputimes", ("user", "system", "children_user", "children_system")
+    )
+
+    # psutil.Process.memory_maps(grouped=True)
+    pmmap_grouped = nt(
+        "pmmap_grouped", "path rss, private, ref_count, shadow_count"
+    )
+
+    # psutil.Process.memory_maps(grouped=False)
+    pmmap_ext = nt(
+        "pmmap_ext", "addr, perms path rss, private, ref_count, shadow_count"
+    )
+
+    # psutil.disk_io_counters()
+    if FREEBSD:
+        sdiskio = nt(
+            "sdiskio",
+            (
+                "read_count",
+                "write_count",
+                "read_bytes",
+                "write_bytes",
+                "read_time",
+                "write_time",
+                "busy_time",
+            ),
+        )
+    else:
+        sdiskio = nt(
+            "sdiskio",
+            ("read_count", "write_count", "read_bytes", "write_bytes"),
+        )
+
+# ===================================================================
+# --- SunOS
+# ===================================================================
+
+elif SUNOS:
+
+    # psutil.cpu_times()
+    scputimes = nt("scputimes", ("user", "system", "idle", "iowait"))
+
+    # psutil.cpu_times(percpu=True)
+    pcputimes = nt(
+        "pcputimes", ("user", "system", "children_user", "children_system")
+    )
+
+    # psutil.virtual_memory()
+    svmem = nt("svmem", ("total", "available", "percent", "used", "free"))
+
+    # psutil.Process.memory_info()
+    pmem = nt("pmem", ("rss", "vms"))
+
+    # psutil.Process.memory_full_info()
+    pfullmem = pmem
+
+    # psutil.Process.memory_maps(grouped=True)
+    pmmap_grouped = nt("pmmap_grouped", ("path", "rss", "anonymous", "locked"))
+
+    # psutil.Process.memory_maps(grouped=False)
+    pmmap_ext = nt(
+        "pmmap_ext", "addr perms " + " ".join(pmmap_grouped._fields)
+    )
+
+# ===================================================================
+# --- AIX
+# ===================================================================
+
+elif AIX:
+
+    # psutil.Process.memory_info()
+    pmem = nt("pmem", ("rss", "vms"))
+
+    # psutil.Process.memory_full_info()
+    pfullmem = pmem
+
+    # psutil.Process.cpu_times()
+    scputimes = nt("scputimes", ("user", "system", "idle", "iowait"))
+
+    # psutil.virtual_memory()
+    svmem = nt("svmem", ("total", "available", "percent", "used", "free"))
diff --git a/micromamba_root/Lib/site-packages/psutil/_psaix.py b/micromamba_root/Lib/site-packages/psutil/_psaix.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f628ad93c1b1464b16d63daee79fe161204730e
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil/_psaix.py
@@ -0,0 +1,546 @@
+# Copyright (c) 2009, Giampaolo Rodola'
+# Copyright (c) 2017, Arnon Yaari
+# All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""AIX platform implementation."""
+
+import functools
+import glob
+import os
+import re
+import subprocess
+import sys
+
+from . import _common
+from . import _ntuples as ntp
+from . import _psposix
+from . import _psutil_aix as cext
+from ._common import NIC_DUPLEX_FULL
+from ._common import NIC_DUPLEX_HALF
+from ._common import NIC_DUPLEX_UNKNOWN
+from ._common import AccessDenied
+from ._common import NoSuchProcess
+from ._common import ZombieProcess
+from ._common import conn_to_ntuple
+from ._common import get_procfs_path
+from ._common import memoize_when_activated
+from ._common import usage_percent
+
+__extra__all__ = ["PROCFS_PATH"]
+
+
+# =====================================================================
+# --- globals
+# =====================================================================
+
+
+HAS_THREADS = hasattr(cext, "proc_threads")
+HAS_NET_IO_COUNTERS = hasattr(cext, "net_io_counters")
+HAS_PROC_IO_COUNTERS = hasattr(cext, "proc_io_counters")
+
+PAGE_SIZE = cext.getpagesize()
+AF_LINK = cext.AF_LINK
+
+PROC_STATUSES = {
+    cext.SIDL: _common.STATUS_IDLE,
+    cext.SZOMB: _common.STATUS_ZOMBIE,
+    cext.SACTIVE: _common.STATUS_RUNNING,
+    cext.SSWAP: _common.STATUS_RUNNING,  # TODO what status is this?
+    cext.SSTOP: _common.STATUS_STOPPED,
+}
+
+TCP_STATUSES = {
+    cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
+    cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
+    cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV,
+    cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
+    cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
+    cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
+    cext.TCPS_CLOSED: _common.CONN_CLOSE,
+    cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
+    cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
+    cext.TCPS_LISTEN: _common.CONN_LISTEN,
+    cext.TCPS_CLOSING: _common.CONN_CLOSING,
+    cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
+}
+
+proc_info_map = dict(
+    ppid=0,
+    rss=1,
+    vms=2,
+    create_time=3,
+    nice=4,
+    num_threads=5,
+    status=6,
+    ttynr=7,
+)
+
+
+# =====================================================================
+# --- memory
+# =====================================================================
+
+
+def virtual_memory():
+    total, avail, free, _pinned, inuse = cext.virtual_mem()
+    percent = usage_percent((total - avail), total, round_=1)
+    return ntp.svmem(total, avail, percent, inuse, free)
+
+
+def swap_memory():
+    """Swap system memory as a (total, used, free, sin, sout) tuple."""
+    total, free, sin, sout = cext.swap_mem()
+    used = total - free
+    percent = usage_percent(used, total, round_=1)
+    return ntp.sswap(total, used, free, percent, sin, sout)
+
+
+# =====================================================================
+# --- CPU
+# =====================================================================
+
+
+def cpu_times():
+    """Return system-wide CPU times as a named tuple."""
+    ret = cext.per_cpu_times()
+    return ntp.scputimes(*[sum(x) for x in zip(*ret)])
+
+
+def per_cpu_times():
+    """Return system per-CPU times as a list of named tuples."""
+    ret = cext.per_cpu_times()
+    return [ntp.scputimes(*x) for x in ret]
+
+
+def cpu_count_logical():
+    """Return the number of logical CPUs in the system."""
+    try:
+        return os.sysconf("SC_NPROCESSORS_ONLN")
+    except ValueError:
+        # mimic os.cpu_count() behavior
+        return None
+
+
+def cpu_count_cores():
+    cmd = ["lsdev", "-Cc", "processor"]
+    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    stdout, stderr = p.communicate()
+    stdout, stderr = (x.decode(sys.stdout.encoding) for x in (stdout, stderr))
+    if p.returncode != 0:
+        msg = f"{cmd!r} command error\n{stderr}"
+        raise RuntimeError(msg)
+    processors = stdout.strip().splitlines()
+    return len(processors) or None
+
+
+def cpu_stats():
+    """Return various CPU stats as a named tuple."""
+    ctx_switches, interrupts, soft_interrupts, syscalls = cext.cpu_stats()
+    return ntp.scpustats(ctx_switches, interrupts, soft_interrupts, syscalls)
+
+
+# =====================================================================
+# --- disks
+# =====================================================================
+
+
+disk_io_counters = cext.disk_io_counters
+disk_usage = _psposix.disk_usage
+
+
+def disk_partitions(all=False):
+    """Return system disk partitions."""
+    # TODO - the filtering logic should be better checked so that
+    # it tries to reflect 'df' as much as possible
+    retlist = []
+    partitions = cext.disk_partitions()
+    for partition in partitions:
+        device, mountpoint, fstype, opts = partition
+        if device == 'none':
+            device = ''
+        if not all:
+            # Differently from, say, Linux, we don't have a list of
+            # common fs types so the best we can do, AFAIK, is to
+            # filter by filesystem having a total size > 0.
+            if not disk_usage(mountpoint).total:
+                continue
+        ntuple = ntp.sdiskpart(device, mountpoint, fstype, opts)
+        retlist.append(ntuple)
+    return retlist
+
+
+# =====================================================================
+# --- network
+# =====================================================================
+
+
+net_if_addrs = cext.net_if_addrs
+
+if HAS_NET_IO_COUNTERS:
+    net_io_counters = cext.net_io_counters
+
+
+def net_connections(kind, _pid=-1):
+    """Return socket connections.  If pid == -1 return system-wide
+    connections (as opposed to connections opened by one process only).
+    """
+    families, types = _common.conn_tmap[kind]
+    rawlist = cext.net_connections(_pid)
+    ret = []
+    for item in rawlist:
+        fd, fam, type_, laddr, raddr, status, pid = item
+        if fam not in families:
+            continue
+        if type_ not in types:
+            continue
+        nt = conn_to_ntuple(
+            fd,
+            fam,
+            type_,
+            laddr,
+            raddr,
+            status,
+            TCP_STATUSES,
+            pid=pid if _pid == -1 else None,
+        )
+        ret.append(nt)
+    return ret
+
+
+def net_if_stats():
+    """Get NIC stats (isup, duplex, speed, mtu)."""
+    duplex_map = {"Full": NIC_DUPLEX_FULL, "Half": NIC_DUPLEX_HALF}
+    names = {x[0] for x in net_if_addrs()}
+    ret = {}
+    for name in names:
+        mtu = cext.net_if_mtu(name)
+        flags = cext.net_if_flags(name)
+
+        # try to get speed and duplex
+        # TODO: rewrite this in C (entstat forks, so use truss -f to follow.
+        # looks like it is using an undocumented ioctl?)
+        duplex = ""
+        speed = 0
+        p = subprocess.Popen(
+            ["/usr/bin/entstat", "-d", name],
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+        )
+        stdout, stderr = p.communicate()
+        stdout, stderr = (
+            x.decode(sys.stdout.encoding) for x in (stdout, stderr)
+        )
+        if p.returncode == 0:
+            re_result = re.search(
+                r"Running: (\d+) Mbps.*?(\w+) Duplex", stdout
+            )
+            if re_result is not None:
+                speed = int(re_result.group(1))
+                duplex = re_result.group(2)
+
+        output_flags = ','.join(flags)
+        isup = 'running' in flags
+        duplex = duplex_map.get(duplex, NIC_DUPLEX_UNKNOWN)
+        ret[name] = ntp.snicstats(isup, duplex, speed, mtu, output_flags)
+    return ret
+
+
+# =====================================================================
+# --- other system functions
+# =====================================================================
+
+
+def boot_time():
+    """The system boot time expressed in seconds since the epoch."""
+    return cext.boot_time()
+
+
+def users():
+    """Return currently connected users as a list of namedtuples."""
+    retlist = []
+    rawlist = cext.users()
+    localhost = (':0.0', ':0')
+    for item in rawlist:
+        user, tty, hostname, tstamp, user_process, pid = item
+        # note: the underlying C function includes entries about
+        # system boot, run level and others.  We might want
+        # to use them in the future.
+        if not user_process:
+            continue
+        if hostname in localhost:
+            hostname = 'localhost'
+        nt = ntp.suser(user, tty, hostname, tstamp, pid)
+        retlist.append(nt)
+    return retlist
+
+
+# =====================================================================
+# --- processes
+# =====================================================================
+
+
+def pids():
+    """Returns a list of PIDs currently running on the system."""
+    return [int(x) for x in os.listdir(get_procfs_path()) if x.isdigit()]
+
+
+def pid_exists(pid):
+    """Check for the existence of a unix pid."""
+    return os.path.exists(os.path.join(get_procfs_path(), str(pid), "psinfo"))
+
+
+def wrap_exceptions(fun):
+    """Call callable into a try/except clause and translate ENOENT,
+    EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
+    """
+
+    @functools.wraps(fun)
+    def wrapper(self, *args, **kwargs):
+        pid, ppid, name = self.pid, self._ppid, self._name
+        try:
+            return fun(self, *args, **kwargs)
+        except (FileNotFoundError, ProcessLookupError) as err:
+            # ENOENT (no such file or directory) gets raised on open().
+            # ESRCH (no such process) can get raised on read() if
+            # process is gone in meantime.
+            if not pid_exists(pid):
+                raise NoSuchProcess(pid, name) from err
+            raise ZombieProcess(pid, name, ppid) from err
+        except PermissionError as err:
+            raise AccessDenied(pid, name) from err
+
+    return wrapper
+
+
+class Process:
+    """Wrapper class around underlying C implementation."""
+
+    __slots__ = ["_cache", "_name", "_ppid", "_procfs_path", "pid"]
+
+    def __init__(self, pid):
+        self.pid = pid
+        self._name = None
+        self._ppid = None
+        self._procfs_path = get_procfs_path()
+
+    def oneshot_enter(self):
+        self._proc_basic_info.cache_activate(self)
+        self._proc_cred.cache_activate(self)
+
+    def oneshot_exit(self):
+        self._proc_basic_info.cache_deactivate(self)
+        self._proc_cred.cache_deactivate(self)
+
+    @wrap_exceptions
+    @memoize_when_activated
+    def _proc_basic_info(self):
+        return cext.proc_basic_info(self.pid, self._procfs_path)
+
+    @wrap_exceptions
+    @memoize_when_activated
+    def _proc_cred(self):
+        return cext.proc_cred(self.pid, self._procfs_path)
+
+    @wrap_exceptions
+    def name(self):
+        if self.pid == 0:
+            return "swapper"
+        # note: max 16 characters
+        return cext.proc_name(self.pid, self._procfs_path).rstrip("\x00")
+
+    @wrap_exceptions
+    def exe(self):
+        # there is no way to get executable path in AIX other than to guess,
+        # and guessing is more complex than what's in the wrapping class
+        cmdline = self.cmdline()
+        if not cmdline:
+            return ''
+        exe = cmdline[0]
+        if os.path.sep in exe:
+            # relative or absolute path
+            if not os.path.isabs(exe):
+                # if cwd has changed, we're out of luck - this may be wrong!
+                exe = os.path.abspath(os.path.join(self.cwd(), exe))
+            if (
+                os.path.isabs(exe)
+                and os.path.isfile(exe)
+                and os.access(exe, os.X_OK)
+            ):
+                return exe
+            # not found, move to search in PATH using basename only
+            exe = os.path.basename(exe)
+        # search for exe name PATH
+        for path in os.environ["PATH"].split(":"):
+            possible_exe = os.path.abspath(os.path.join(path, exe))
+            if os.path.isfile(possible_exe) and os.access(
+                possible_exe, os.X_OK
+            ):
+                return possible_exe
+        return ''
+
+    @wrap_exceptions
+    def cmdline(self):
+        return cext.proc_args(self.pid)
+
+    @wrap_exceptions
+    def environ(self):
+        return cext.proc_environ(self.pid)
+
+    @wrap_exceptions
+    def create_time(self):
+        return self._proc_basic_info()[proc_info_map['create_time']]
+
+    @wrap_exceptions
+    def num_threads(self):
+        return self._proc_basic_info()[proc_info_map['num_threads']]
+
+    if HAS_THREADS:
+
+        @wrap_exceptions
+        def threads(self):
+            rawlist = cext.proc_threads(self.pid)
+            retlist = []
+            for thread_id, utime, stime in rawlist:
+                ntuple = ntp.pthread(thread_id, utime, stime)
+                retlist.append(ntuple)
+            # The underlying C implementation retrieves all OS threads
+            # and filters them by PID.  At this point we can't tell whether
+            # an empty list means there were no connections for process or
+            # process is no longer active so we force NSP in case the PID
+            # is no longer there.
+            if not retlist:
+                # will raise NSP if process is gone
+                os.stat(f"{self._procfs_path}/{self.pid}")
+            return retlist
+
+    @wrap_exceptions
+    def net_connections(self, kind='inet'):
+        ret = net_connections(kind, _pid=self.pid)
+        # The underlying C implementation retrieves all OS connections
+        # and filters them by PID.  At this point we can't tell whether
+        # an empty list means there were no connections for process or
+        # process is no longer active so we force NSP in case the PID
+        # is no longer there.
+        if not ret:
+            # will raise NSP if process is gone
+            os.stat(f"{self._procfs_path}/{self.pid}")
+        return ret
+
+    @wrap_exceptions
+    def nice_get(self):
+        return cext.proc_priority_get(self.pid)
+
+    @wrap_exceptions
+    def nice_set(self, value):
+        return cext.proc_priority_set(self.pid, value)
+
+    @wrap_exceptions
+    def ppid(self):
+        self._ppid = self._proc_basic_info()[proc_info_map['ppid']]
+        return self._ppid
+
+    @wrap_exceptions
+    def uids(self):
+        real, effective, saved, _, _, _ = self._proc_cred()
+        return ntp.puids(real, effective, saved)
+
+    @wrap_exceptions
+    def gids(self):
+        _, _, _, real, effective, saved = self._proc_cred()
+        return ntp.puids(real, effective, saved)
+
+    @wrap_exceptions
+    def cpu_times(self):
+        t = cext.proc_cpu_times(self.pid, self._procfs_path)
+        return ntp.pcputimes(*t)
+
+    @wrap_exceptions
+    def terminal(self):
+        ttydev = self._proc_basic_info()[proc_info_map['ttynr']]
+        # convert from 64-bit dev_t to 32-bit dev_t and then map the device
+        ttydev = ((ttydev & 0x0000FFFF00000000) >> 16) | (ttydev & 0xFFFF)
+        # try to match rdev of /dev/pts/* files ttydev
+        for dev in glob.glob("/dev/**/*"):
+            if os.stat(dev).st_rdev == ttydev:
+                return dev
+        return None
+
+    @wrap_exceptions
+    def cwd(self):
+        procfs_path = self._procfs_path
+        try:
+            result = os.readlink(f"{procfs_path}/{self.pid}/cwd")
+            return result.rstrip('/')
+        except FileNotFoundError:
+            os.stat(f"{procfs_path}/{self.pid}")  # raise NSP or AD
+            return ""
+
+    @wrap_exceptions
+    def memory_info(self):
+        ret = self._proc_basic_info()
+        rss = ret[proc_info_map['rss']] * 1024
+        vms = ret[proc_info_map['vms']] * 1024
+        return ntp.pmem(rss, vms)
+
+    memory_full_info = memory_info
+
+    @wrap_exceptions
+    def status(self):
+        code = self._proc_basic_info()[proc_info_map['status']]
+        # XXX is '?' legit? (we're not supposed to return it anyway)
+        return PROC_STATUSES.get(code, '?')
+
+    def open_files(self):
+        # TODO rewrite without using procfiles (stat /proc/pid/fd/* and then
+        # find matching name of the inode)
+        p = subprocess.Popen(
+            ["/usr/bin/procfiles", "-n", str(self.pid)],
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+        )
+        stdout, stderr = p.communicate()
+        stdout, stderr = (
+            x.decode(sys.stdout.encoding) for x in (stdout, stderr)
+        )
+        if "no such process" in stderr.lower():
+            raise NoSuchProcess(self.pid, self._name)
+        procfiles = re.findall(r"(\d+): S_IFREG.*name:(.*)\n", stdout)
+        retlist = []
+        for fd, path in procfiles:
+            path = path.strip()
+            if path.startswith("//"):
+                path = path[1:]
+            if path.lower() == "cannot be retrieved":
+                continue
+            retlist.append(ntp.popenfile(path, int(fd)))
+        return retlist
+
+    @wrap_exceptions
+    def num_fds(self):
+        if self.pid == 0:  # no /proc/0/fd
+            return 0
+        return len(os.listdir(f"{self._procfs_path}/{self.pid}/fd"))
+
+    @wrap_exceptions
+    def num_ctx_switches(self):
+        return ntp.pctxsw(*cext.proc_num_ctx_switches(self.pid))
+
+    @wrap_exceptions
+    def wait(self, timeout=None):
+        return _psposix.wait_pid(self.pid, timeout)
+
+    if HAS_PROC_IO_COUNTERS:
+
+        @wrap_exceptions
+        def io_counters(self):
+            try:
+                rc, wc, rb, wb = cext.proc_io_counters(self.pid)
+            except OSError as err:
+                # if process is terminated, proc_io_counters returns OSError
+                # instead of NSP
+                if not pid_exists(self.pid):
+                    raise NoSuchProcess(self.pid, self._name) from err
+                raise
+            return ntp.pio(rc, wc, rb, wb)
diff --git a/micromamba_root/Lib/site-packages/psutil/_psbsd.py b/micromamba_root/Lib/site-packages/psutil/_psbsd.py
new file mode 100644
index 0000000000000000000000000000000000000000..a75cd1af131973c0f78caa65a22c0a7e91645959
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil/_psbsd.py
@@ -0,0 +1,904 @@
+# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""FreeBSD, OpenBSD and NetBSD platforms implementation."""
+
+import contextlib
+import errno
+import functools
+import os
+from collections import defaultdict
+from collections import namedtuple
+from xml.etree import ElementTree  # noqa: ICN001
+
+from . import _common
+from . import _ntuples as ntp
+from . import _psposix
+from . import _psutil_bsd as cext
+from ._common import FREEBSD
+from ._common import NETBSD
+from ._common import OPENBSD
+from ._common import AccessDenied
+from ._common import NoSuchProcess
+from ._common import ZombieProcess
+from ._common import conn_tmap
+from ._common import conn_to_ntuple
+from ._common import debug
+from ._common import memoize
+from ._common import memoize_when_activated
+from ._common import usage_percent
+
+__extra__all__ = []
+
+
+# =====================================================================
+# --- globals
+# =====================================================================
+
+
+if FREEBSD:
+    PROC_STATUSES = {
+        cext.SIDL: _common.STATUS_IDLE,
+        cext.SRUN: _common.STATUS_RUNNING,
+        cext.SSLEEP: _common.STATUS_SLEEPING,
+        cext.SSTOP: _common.STATUS_STOPPED,
+        cext.SZOMB: _common.STATUS_ZOMBIE,
+        cext.SWAIT: _common.STATUS_WAITING,
+        cext.SLOCK: _common.STATUS_LOCKED,
+    }
+elif OPENBSD:
+    PROC_STATUSES = {
+        cext.SIDL: _common.STATUS_IDLE,
+        cext.SSLEEP: _common.STATUS_SLEEPING,
+        cext.SSTOP: _common.STATUS_STOPPED,
+        # According to /usr/include/sys/proc.h SZOMB is unused.
+        # test_zombie_process() shows that SDEAD is the right
+        # equivalent. Also it appears there's no equivalent of
+        # psutil.STATUS_DEAD. SDEAD really means STATUS_ZOMBIE.
+        # cext.SZOMB: _common.STATUS_ZOMBIE,
+        cext.SDEAD: _common.STATUS_ZOMBIE,
+        cext.SZOMB: _common.STATUS_ZOMBIE,
+        # From http://www.eecs.harvard.edu/~margo/cs161/videos/proc.h.txt
+        # OpenBSD has SRUN and SONPROC: SRUN indicates that a process
+        # is runnable but *not* yet running, i.e. is on a run queue.
+        # SONPROC indicates that the process is actually executing on
+        # a CPU, i.e. it is no longer on a run queue.
+        # As such we'll map SRUN to STATUS_WAKING and SONPROC to
+        # STATUS_RUNNING
+        cext.SRUN: _common.STATUS_WAKING,
+        cext.SONPROC: _common.STATUS_RUNNING,
+    }
+elif NETBSD:
+    PROC_STATUSES = {
+        cext.SIDL: _common.STATUS_IDLE,
+        cext.SSLEEP: _common.STATUS_SLEEPING,
+        cext.SSTOP: _common.STATUS_STOPPED,
+        cext.SZOMB: _common.STATUS_ZOMBIE,
+        cext.SRUN: _common.STATUS_WAKING,
+        cext.SONPROC: _common.STATUS_RUNNING,
+    }
+
+TCP_STATUSES = {
+    cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
+    cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
+    cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
+    cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
+    cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
+    cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
+    cext.TCPS_CLOSED: _common.CONN_CLOSE,
+    cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
+    cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
+    cext.TCPS_LISTEN: _common.CONN_LISTEN,
+    cext.TCPS_CLOSING: _common.CONN_CLOSING,
+    cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
+}
+
+PAGESIZE = cext.getpagesize()
+AF_LINK = cext.AF_LINK
+
+HAS_PROC_NUM_THREADS = hasattr(cext, "proc_num_threads")
+
+kinfo_proc_map = dict(
+    ppid=0,
+    status=1,
+    real_uid=2,
+    effective_uid=3,
+    saved_uid=4,
+    real_gid=5,
+    effective_gid=6,
+    saved_gid=7,
+    ttynr=8,
+    create_time=9,
+    ctx_switches_vol=10,
+    ctx_switches_unvol=11,
+    read_io_count=12,
+    write_io_count=13,
+    user_time=14,
+    sys_time=15,
+    ch_user_time=16,
+    ch_sys_time=17,
+    rss=18,
+    vms=19,
+    memtext=20,
+    memdata=21,
+    memstack=22,
+    cpunum=23,
+    name=24,
+)
+
+
+# =====================================================================
+# --- memory
+# =====================================================================
+
+
+def virtual_memory():
+    mem = cext.virtual_mem()
+    if NETBSD:
+        total, free, active, inactive, wired, cached = mem
+        # On NetBSD buffers and shared mem is determined via /proc.
+        # The C ext set them to 0.
+        with open('/proc/meminfo', 'rb') as f:
+            for line in f:
+                if line.startswith(b'Buffers:'):
+                    buffers = int(line.split()[1]) * 1024
+                elif line.startswith(b'MemShared:'):
+                    shared = int(line.split()[1]) * 1024
+        # Before avail was calculated as (inactive + cached + free),
+        # same as zabbix, but it turned out it could exceed total (see
+        # #2233), so zabbix seems to be wrong. Htop calculates it
+        # differently, and the used value seem more realistic, so let's
+        # match htop.
+        # https://github.com/htop-dev/htop/blob/e7f447b/netbsd/NetBSDProcessList.c#L162
+        # https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/netbsd/memory.c#L135
+        used = active + wired
+        avail = total - used
+    else:
+        total, free, active, inactive, wired, cached, buffers, shared = mem
+        # matches freebsd-memory CLI:
+        # * https://people.freebsd.org/~rse/dist/freebsd-memory
+        # * https://www.cyberciti.biz/files/scripts/freebsd-memory.pl.txt
+        # matches zabbix:
+        # * https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/freebsd/memory.c#L143
+        avail = inactive + cached + free
+        used = active + wired + cached
+
+    percent = usage_percent((total - avail), total, round_=1)
+    return ntp.svmem(
+        total,
+        avail,
+        percent,
+        used,
+        free,
+        active,
+        inactive,
+        buffers,
+        cached,
+        shared,
+        wired,
+    )
+
+
+def swap_memory():
+    """System swap memory as (total, used, free, sin, sout) namedtuple."""
+    total, used, free, sin, sout = cext.swap_mem()
+    percent = usage_percent(used, total, round_=1)
+    return ntp.sswap(total, used, free, percent, sin, sout)
+
+
+# malloc / heap functions (FreeBSD / NetBSD)
+if hasattr(cext, "heap_info"):
+    heap_info = cext.heap_info
+    heap_trim = cext.heap_trim
+
+
+# =====================================================================
+# --- CPU
+# =====================================================================
+
+
+def cpu_times():
+    """Return system per-CPU times as a namedtuple."""
+    user, nice, system, idle, irq = cext.cpu_times()
+    return ntp.scputimes(user, nice, system, idle, irq)
+
+
+def per_cpu_times():
+    """Return system CPU times as a namedtuple."""
+    ret = []
+    for cpu_t in cext.per_cpu_times():
+        user, nice, system, idle, irq = cpu_t
+        item = ntp.scputimes(user, nice, system, idle, irq)
+        ret.append(item)
+    return ret
+
+
+def cpu_count_logical():
+    """Return the number of logical CPUs in the system."""
+    return cext.cpu_count_logical()
+
+
+if OPENBSD or NETBSD:
+
+    def cpu_count_cores():
+        # OpenBSD and NetBSD do not implement this.
+        return 1 if cpu_count_logical() == 1 else None
+
+else:
+
+    def cpu_count_cores():
+        """Return the number of CPU cores in the system."""
+        # From the C module we'll get an XML string similar to this:
+        # http://manpages.ubuntu.com/manpages/precise/man4/smp.4freebsd.html
+        # We may get None in case "sysctl kern.sched.topology_spec"
+        # is not supported on this BSD version, in which case we'll mimic
+        # os.cpu_count() and return None.
+        ret = None
+        s = cext.cpu_topology()
+        if s is not None:
+            # get rid of padding chars appended at the end of the string
+            index = s.rfind("")
+            if index != -1:
+                s = s[: index + 9]
+                root = ElementTree.fromstring(s)
+                try:
+                    ret = len(root.findall('group/children/group/cpu')) or None
+                finally:
+                    # needed otherwise it will memleak
+                    root.clear()
+        if not ret:
+            # If logical CPUs == 1 it's obvious we' have only 1 core.
+            if cpu_count_logical() == 1:
+                return 1
+        return ret
+
+
+def cpu_stats():
+    """Return various CPU stats as a named tuple."""
+    if FREEBSD:
+        # Note: the C ext is returning some metrics we are not exposing:
+        # traps.
+        ctxsw, intrs, soft_intrs, syscalls, _traps = cext.cpu_stats()
+    elif NETBSD:
+        # XXX
+        # Note about intrs: the C extension returns 0. intrs
+        # can be determined via /proc/stat; it has the same value as
+        # soft_intrs thought so the kernel is faking it (?).
+        #
+        # Note about syscalls: the C extension always sets it to 0 (?).
+        #
+        # Note: the C ext is returning some metrics we are not exposing:
+        # traps, faults and forks.
+        ctxsw, intrs, soft_intrs, syscalls, _traps, _faults, _forks = (
+            cext.cpu_stats()
+        )
+        with open('/proc/stat', 'rb') as f:
+            for line in f:
+                if line.startswith(b'intr'):
+                    intrs = int(line.split()[1])
+    elif OPENBSD:
+        # Note: the C ext is returning some metrics we are not exposing:
+        # traps, faults and forks.
+        ctxsw, intrs, soft_intrs, syscalls, _traps, _faults, _forks = (
+            cext.cpu_stats()
+        )
+    return ntp.scpustats(ctxsw, intrs, soft_intrs, syscalls)
+
+
+if FREEBSD:
+
+    def cpu_freq():
+        """Return frequency metrics for CPUs. As of Dec 2018 only
+        CPU 0 appears to be supported by FreeBSD and all other cores
+        match the frequency of CPU 0.
+        """
+        ret = []
+        num_cpus = cpu_count_logical()
+        for cpu in range(num_cpus):
+            try:
+                current, available_freq = cext.cpu_freq(cpu)
+            except NotImplementedError:
+                continue
+            if available_freq:
+                try:
+                    min_freq = int(available_freq.split(" ")[-1].split("/")[0])
+                except (IndexError, ValueError):
+                    min_freq = None
+                try:
+                    max_freq = int(available_freq.split(" ")[0].split("/")[0])
+                except (IndexError, ValueError):
+                    max_freq = None
+            ret.append(ntp.scpufreq(current, min_freq, max_freq))
+        return ret
+
+elif OPENBSD:
+
+    def cpu_freq():
+        curr = float(cext.cpu_freq())
+        return [ntp.scpufreq(curr, 0.0, 0.0)]
+
+
+# =====================================================================
+# --- disks
+# =====================================================================
+
+
+def disk_partitions(all=False):
+    """Return mounted disk partitions as a list of namedtuples.
+    'all' argument is ignored, see:
+    https://github.com/giampaolo/psutil/issues/906.
+    """
+    retlist = []
+    partitions = cext.disk_partitions()
+    for partition in partitions:
+        device, mountpoint, fstype, opts = partition
+        ntuple = ntp.sdiskpart(device, mountpoint, fstype, opts)
+        retlist.append(ntuple)
+    return retlist
+
+
+disk_usage = _psposix.disk_usage
+disk_io_counters = cext.disk_io_counters
+
+
+# =====================================================================
+# --- network
+# =====================================================================
+
+
+net_io_counters = cext.net_io_counters
+net_if_addrs = cext.net_if_addrs
+
+
+def net_if_stats():
+    """Get NIC stats (isup, duplex, speed, mtu)."""
+    names = net_io_counters().keys()
+    ret = {}
+    for name in names:
+        try:
+            mtu = cext.net_if_mtu(name)
+            flags = cext.net_if_flags(name)
+            duplex, speed = cext.net_if_duplex_speed(name)
+        except OSError as err:
+            # https://github.com/giampaolo/psutil/issues/1279
+            if err.errno != errno.ENODEV:
+                raise
+        else:
+            if hasattr(_common, 'NicDuplex'):
+                duplex = _common.NicDuplex(duplex)
+            output_flags = ','.join(flags)
+            isup = 'running' in flags
+            ret[name] = ntp.snicstats(isup, duplex, speed, mtu, output_flags)
+    return ret
+
+
+def net_connections(kind):
+    """System-wide network connections."""
+    families, types = conn_tmap[kind]
+    ret = set()
+    if OPENBSD:
+        rawlist = cext.net_connections(-1, families, types)
+    elif NETBSD:
+        rawlist = cext.net_connections(-1, kind)
+    else:  # FreeBSD
+        rawlist = cext.net_connections(families, types)
+
+    for item in rawlist:
+        fd, fam, type, laddr, raddr, status, pid = item
+        nt = conn_to_ntuple(
+            fd, fam, type, laddr, raddr, status, TCP_STATUSES, pid
+        )
+        ret.add(nt)
+    return list(ret)
+
+
+# =====================================================================
+#  --- sensors
+# =====================================================================
+
+
+if FREEBSD:
+
+    def sensors_battery():
+        """Return battery info."""
+        try:
+            percent, minsleft, power_plugged = cext.sensors_battery()
+        except NotImplementedError:
+            # See: https://github.com/giampaolo/psutil/issues/1074
+            return None
+        power_plugged = power_plugged == 1
+        if power_plugged:
+            secsleft = _common.POWER_TIME_UNLIMITED
+        elif minsleft == -1:
+            secsleft = _common.POWER_TIME_UNKNOWN
+        else:
+            secsleft = minsleft * 60
+        return ntp.sbattery(percent, secsleft, power_plugged)
+
+    def sensors_temperatures():
+        """Return CPU cores temperatures if available, else an empty dict."""
+        ret = defaultdict(list)
+        num_cpus = cpu_count_logical()
+        for cpu in range(num_cpus):
+            try:
+                current, high = cext.sensors_cpu_temperature(cpu)
+                if high <= 0:
+                    high = None
+                name = f"Core {cpu}"
+                ret["coretemp"].append(ntp.shwtemp(name, current, high, high))
+            except NotImplementedError:
+                pass
+
+        return ret
+
+
+# =====================================================================
+#  --- other system functions
+# =====================================================================
+
+
+def boot_time():
+    """The system boot time expressed in seconds since the epoch."""
+    return cext.boot_time()
+
+
+if NETBSD:
+
+    try:
+        INIT_BOOT_TIME = boot_time()
+    except Exception as err:  # noqa: BLE001
+        # Don't want to crash at import time.
+        debug(f"ignoring exception on import: {err!r}")
+        INIT_BOOT_TIME = 0
+
+    def adjust_proc_create_time(ctime):
+        """Account for system clock updates."""
+        if INIT_BOOT_TIME == 0:
+            return ctime
+
+        diff = INIT_BOOT_TIME - boot_time()
+        if diff == 0 or abs(diff) < 1:
+            return ctime
+
+        debug("system clock was updated; adjusting process create_time()")
+        if diff < 0:
+            return ctime - diff
+        return ctime + diff
+
+
+def users():
+    """Return currently connected users as a list of namedtuples."""
+    retlist = []
+    rawlist = cext.users()
+    for item in rawlist:
+        user, tty, hostname, tstamp, pid = item
+        if tty == '~':
+            continue  # reboot or shutdown
+        nt = ntp.suser(user, tty or None, hostname, tstamp, pid)
+        retlist.append(nt)
+    return retlist
+
+
+# =====================================================================
+# --- processes
+# =====================================================================
+
+
+@memoize
+def _pid_0_exists():
+    try:
+        Process(0).name()
+    except NoSuchProcess:
+        return False
+    except AccessDenied:
+        return True
+    else:
+        return True
+
+
+def pids():
+    """Returns a list of PIDs currently running on the system."""
+    ret = cext.pids()
+    if OPENBSD and (0 not in ret) and _pid_0_exists():
+        # On OpenBSD the kernel does not return PID 0 (neither does
+        # ps) but it's actually querable (Process(0) will succeed).
+        ret.insert(0, 0)
+    return ret
+
+
+if NETBSD:
+
+    def pid_exists(pid):
+        exists = _psposix.pid_exists(pid)
+        if not exists:
+            # We do this because _psposix.pid_exists() lies in case of
+            # zombie processes.
+            return pid in pids()
+        else:
+            return True
+
+elif OPENBSD:
+
+    def pid_exists(pid):
+        exists = _psposix.pid_exists(pid)
+        if not exists:
+            return False
+        else:
+            # OpenBSD seems to be the only BSD platform where
+            # _psposix.pid_exists() returns True for thread IDs (tids),
+            # so we can't use it.
+            return pid in pids()
+
+else:  # FreeBSD
+    pid_exists = _psposix.pid_exists
+
+
+def wrap_exceptions(fun):
+    """Decorator which translates bare OSError exceptions into
+    NoSuchProcess and AccessDenied.
+    """
+
+    @functools.wraps(fun)
+    def wrapper(self, *args, **kwargs):
+        pid, ppid, name = self.pid, self._ppid, self._name
+        try:
+            return fun(self, *args, **kwargs)
+        except ProcessLookupError as err:
+            if cext.proc_is_zombie(pid):
+                raise ZombieProcess(pid, name, ppid) from err
+            raise NoSuchProcess(pid, name) from err
+        except PermissionError as err:
+            raise AccessDenied(pid, name) from err
+        except cext.ZombieProcessError as err:
+            raise ZombieProcess(pid, name, ppid) from err
+        except OSError as err:
+            if pid == 0 and 0 in pids():
+                raise AccessDenied(pid, name) from err
+            raise err from None
+
+    return wrapper
+
+
+@contextlib.contextmanager
+def wrap_exceptions_procfs(inst):
+    """Same as above, for routines relying on reading /proc fs."""
+    pid, name, ppid = inst.pid, inst._name, inst._ppid
+    try:
+        yield
+    except (ProcessLookupError, FileNotFoundError) as err:
+        # ENOENT (no such file or directory) gets raised on open().
+        # ESRCH (no such process) can get raised on read() if
+        # process is gone in meantime.
+        if cext.proc_is_zombie(inst.pid):
+            raise ZombieProcess(pid, name, ppid) from err
+        else:
+            raise NoSuchProcess(pid, name) from err
+    except PermissionError as err:
+        raise AccessDenied(pid, name) from err
+
+
+class Process:
+    """Wrapper class around underlying C implementation."""
+
+    __slots__ = ["_cache", "_name", "_ppid", "pid"]
+
+    def __init__(self, pid):
+        self.pid = pid
+        self._name = None
+        self._ppid = None
+
+    def _assert_alive(self):
+        """Raise NSP if the process disappeared on us."""
+        # For those C function who do not raise NSP, possibly returning
+        # incorrect or incomplete result.
+        cext.proc_name(self.pid)
+
+    @wrap_exceptions
+    @memoize_when_activated
+    def oneshot(self):
+        """Retrieves multiple process info in one shot as a raw tuple."""
+        ret = cext.proc_oneshot_info(self.pid)
+        assert len(ret) == len(kinfo_proc_map)
+        return ret
+
+    def oneshot_enter(self):
+        self.oneshot.cache_activate(self)
+
+    def oneshot_exit(self):
+        self.oneshot.cache_deactivate(self)
+
+    @wrap_exceptions
+    def name(self):
+        name = self.oneshot()[kinfo_proc_map['name']]
+        return name if name is not None else cext.proc_name(self.pid)
+
+    @wrap_exceptions
+    def exe(self):
+        if FREEBSD:
+            if self.pid == 0:
+                return ''  # else NSP
+            return cext.proc_exe(self.pid)
+        elif NETBSD:
+            if self.pid == 0:
+                # /proc/0 dir exists but /proc/0/exe doesn't
+                return ""
+            with wrap_exceptions_procfs(self):
+                return os.readlink(f"/proc/{self.pid}/exe")
+        else:
+            # OpenBSD: exe cannot be determined; references:
+            # https://chromium.googlesource.com/chromium/src/base/+/
+            #     master/base_paths_posix.cc
+            # We try our best guess by using which against the first
+            # cmdline arg (may return None).
+            import shutil
+
+            cmdline = self.cmdline()
+            if cmdline:
+                return shutil.which(cmdline[0]) or ""
+            else:
+                return ""
+
+    @wrap_exceptions
+    def cmdline(self):
+        if OPENBSD and self.pid == 0:
+            return []  # ...else it crashes
+        elif NETBSD:
+            # XXX - most of the times the underlying sysctl() call on
+            # NetBSD and OpenBSD returns a truncated string. Also
+            # /proc/pid/cmdline behaves the same so it looks like this
+            # is a kernel bug.
+            try:
+                return cext.proc_cmdline(self.pid)
+            except OSError as err:
+                if err.errno == errno.EINVAL:
+                    pid, name, ppid = self.pid, self._name, self._ppid
+                    if cext.proc_is_zombie(self.pid):
+                        raise ZombieProcess(pid, name, ppid) from err
+                    if not pid_exists(self.pid):
+                        raise NoSuchProcess(pid, name, ppid) from err
+                    # XXX: this happens with unicode tests. It means the C
+                    # routine is unable to decode invalid unicode chars.
+                    debug(f"ignoring {err!r} and returning an empty list")
+                    return []
+                else:
+                    raise
+        else:
+            return cext.proc_cmdline(self.pid)
+
+    @wrap_exceptions
+    def environ(self):
+        return cext.proc_environ(self.pid)
+
+    @wrap_exceptions
+    def terminal(self):
+        tty_nr = self.oneshot()[kinfo_proc_map['ttynr']]
+        tmap = _psposix.get_terminal_map()
+        try:
+            return tmap[tty_nr]
+        except KeyError:
+            return None
+
+    @wrap_exceptions
+    def ppid(self):
+        self._ppid = self.oneshot()[kinfo_proc_map['ppid']]
+        return self._ppid
+
+    @wrap_exceptions
+    def uids(self):
+        rawtuple = self.oneshot()
+        return ntp.puids(
+            rawtuple[kinfo_proc_map['real_uid']],
+            rawtuple[kinfo_proc_map['effective_uid']],
+            rawtuple[kinfo_proc_map['saved_uid']],
+        )
+
+    @wrap_exceptions
+    def gids(self):
+        rawtuple = self.oneshot()
+        return ntp.pgids(
+            rawtuple[kinfo_proc_map['real_gid']],
+            rawtuple[kinfo_proc_map['effective_gid']],
+            rawtuple[kinfo_proc_map['saved_gid']],
+        )
+
+    @wrap_exceptions
+    def cpu_times(self):
+        rawtuple = self.oneshot()
+        return ntp.pcputimes(
+            rawtuple[kinfo_proc_map['user_time']],
+            rawtuple[kinfo_proc_map['sys_time']],
+            rawtuple[kinfo_proc_map['ch_user_time']],
+            rawtuple[kinfo_proc_map['ch_sys_time']],
+        )
+
+    if FREEBSD:
+
+        @wrap_exceptions
+        def cpu_num(self):
+            return self.oneshot()[kinfo_proc_map['cpunum']]
+
+    @wrap_exceptions
+    def memory_info(self):
+        rawtuple = self.oneshot()
+        return ntp.pmem(
+            rawtuple[kinfo_proc_map['rss']],
+            rawtuple[kinfo_proc_map['vms']],
+            rawtuple[kinfo_proc_map['memtext']],
+            rawtuple[kinfo_proc_map['memdata']],
+            rawtuple[kinfo_proc_map['memstack']],
+        )
+
+    memory_full_info = memory_info
+
+    @wrap_exceptions
+    def create_time(self, monotonic=False):
+        ctime = self.oneshot()[kinfo_proc_map['create_time']]
+        if NETBSD and not monotonic:
+            # NetBSD: ctime subject to system clock updates.
+            ctime = adjust_proc_create_time(ctime)
+        return ctime
+
+    @wrap_exceptions
+    def num_threads(self):
+        if HAS_PROC_NUM_THREADS:
+            # FreeBSD / NetBSD
+            return cext.proc_num_threads(self.pid)
+        else:
+            return len(self.threads())
+
+    @wrap_exceptions
+    def num_ctx_switches(self):
+        rawtuple = self.oneshot()
+        return ntp.pctxsw(
+            rawtuple[kinfo_proc_map['ctx_switches_vol']],
+            rawtuple[kinfo_proc_map['ctx_switches_unvol']],
+        )
+
+    @wrap_exceptions
+    def threads(self):
+        # Note: on OpenSBD this (/dev/mem) requires root access.
+        rawlist = cext.proc_threads(self.pid)
+        retlist = []
+        for thread_id, utime, stime in rawlist:
+            ntuple = ntp.pthread(thread_id, utime, stime)
+            retlist.append(ntuple)
+        if OPENBSD:
+            self._assert_alive()
+        return retlist
+
+    @wrap_exceptions
+    def net_connections(self, kind='inet'):
+        families, types = conn_tmap[kind]
+        ret = []
+
+        if NETBSD:
+            rawlist = cext.net_connections(self.pid, kind)
+        elif OPENBSD:
+            rawlist = cext.net_connections(self.pid, families, types)
+        else:
+            rawlist = cext.proc_net_connections(self.pid, families, types)
+
+        for item in rawlist:
+            fd, fam, type, laddr, raddr, status = item[:6]
+            if FREEBSD:
+                if (fam not in families) or (type not in types):
+                    continue
+            nt = conn_to_ntuple(
+                fd, fam, type, laddr, raddr, status, TCP_STATUSES
+            )
+            ret.append(nt)
+
+        self._assert_alive()
+        return ret
+
+    @wrap_exceptions
+    def wait(self, timeout=None):
+        return _psposix.wait_pid(self.pid, timeout)
+
+    @wrap_exceptions
+    def nice_get(self):
+        return cext.proc_priority_get(self.pid)
+
+    @wrap_exceptions
+    def nice_set(self, value):
+        return cext.proc_priority_set(self.pid, value)
+
+    @wrap_exceptions
+    def status(self):
+        code = self.oneshot()[kinfo_proc_map['status']]
+        # XXX is '?' legit? (we're not supposed to return it anyway)
+        return PROC_STATUSES.get(code, '?')
+
+    @wrap_exceptions
+    def io_counters(self):
+        rawtuple = self.oneshot()
+        return ntp.pio(
+            rawtuple[kinfo_proc_map['read_io_count']],
+            rawtuple[kinfo_proc_map['write_io_count']],
+            -1,
+            -1,
+        )
+
+    @wrap_exceptions
+    def cwd(self):
+        """Return process current working directory."""
+        # sometimes we get an empty string, in which case we turn
+        # it into None
+        if OPENBSD and self.pid == 0:
+            return ""  # ...else it would raise EINVAL
+        return cext.proc_cwd(self.pid)
+
+    nt_mmap_grouped = namedtuple(
+        'mmap', 'path rss, private, ref_count, shadow_count'
+    )
+    nt_mmap_ext = namedtuple(
+        'mmap', 'addr, perms path rss, private, ref_count, shadow_count'
+    )
+
+    @wrap_exceptions
+    def open_files(self):
+        """Return files opened by process as a list of namedtuples."""
+        rawlist = cext.proc_open_files(self.pid)
+        return [ntp.popenfile(path, fd) for path, fd in rawlist]
+
+    @wrap_exceptions
+    def num_fds(self):
+        """Return the number of file descriptors opened by this process."""
+        ret = cext.proc_num_fds(self.pid)
+        if NETBSD:
+            self._assert_alive()
+        return ret
+
+    # --- FreeBSD only APIs
+
+    if FREEBSD:
+
+        @wrap_exceptions
+        def cpu_affinity_get(self):
+            return cext.proc_cpu_affinity_get(self.pid)
+
+        @wrap_exceptions
+        def cpu_affinity_set(self, cpus):
+            # Pre-emptively check if CPUs are valid because the C
+            # function has a weird behavior in case of invalid CPUs,
+            # see: https://github.com/giampaolo/psutil/issues/586
+            allcpus = set(range(len(per_cpu_times())))
+            for cpu in cpus:
+                if cpu not in allcpus:
+                    msg = f"invalid CPU {cpu!r} (choose between {allcpus})"
+                    raise ValueError(msg)
+            try:
+                cext.proc_cpu_affinity_set(self.pid, cpus)
+            except OSError as err:
+                # 'man cpuset_setaffinity' about EDEADLK:
+                # <>
+                if err.errno in {errno.EINVAL, errno.EDEADLK}:
+                    for cpu in cpus:
+                        if cpu not in allcpus:
+                            msg = (
+                                f"invalid CPU {cpu!r} (choose between"
+                                f" {allcpus})"
+                            )
+                            raise ValueError(msg) from err
+                raise
+
+        @wrap_exceptions
+        def memory_maps(self):
+            return cext.proc_memory_maps(self.pid)
+
+        @wrap_exceptions
+        def rlimit(self, resource, limits=None):
+            if limits is None:
+                return cext.proc_getrlimit(self.pid, resource)
+            else:
+                if len(limits) != 2:
+                    msg = (
+                        "second argument must be a (soft, hard) tuple, got"
+                        f" {limits!r}"
+                    )
+                    raise ValueError(msg)
+                soft, hard = limits
+                return cext.proc_setrlimit(self.pid, resource, soft, hard)
diff --git a/micromamba_root/Lib/site-packages/psutil/_pslinux.py b/micromamba_root/Lib/site-packages/psutil/_pslinux.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc305b59559e9b97f96eacf2a2002d2b02e3fe41
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil/_pslinux.py
@@ -0,0 +1,2269 @@
+# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""Linux platform implementation."""
+
+import base64
+import collections
+import enum
+import errno
+import functools
+import glob
+import os
+import re
+import resource
+import socket
+import struct
+import sys
+import warnings
+from collections import defaultdict
+from collections import namedtuple
+
+from . import _common
+from . import _ntuples as ntp
+from . import _psposix
+from . import _psutil_linux as cext
+from ._common import ENCODING
+from ._common import NIC_DUPLEX_FULL
+from ._common import NIC_DUPLEX_HALF
+from ._common import NIC_DUPLEX_UNKNOWN
+from ._common import AccessDenied
+from ._common import NoSuchProcess
+from ._common import ZombieProcess
+from ._common import bcat
+from ._common import cat
+from ._common import debug
+from ._common import decode
+from ._common import get_procfs_path
+from ._common import isfile_strict
+from ._common import memoize
+from ._common import memoize_when_activated
+from ._common import open_binary
+from ._common import open_text
+from ._common import parse_environ_block
+from ._common import path_exists_strict
+from ._common import supports_ipv6
+from ._common import usage_percent
+
+# fmt: off
+__extra__all__ = [
+    'PROCFS_PATH',
+    # io prio constants
+    "IOPRIO_CLASS_NONE", "IOPRIO_CLASS_RT", "IOPRIO_CLASS_BE",
+    "IOPRIO_CLASS_IDLE",
+    # connection status constants
+    "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
+    "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
+    "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING",
+]
+# fmt: on
+
+
+# =====================================================================
+# --- globals
+# =====================================================================
+
+
+POWER_SUPPLY_PATH = "/sys/class/power_supply"
+HAS_PROC_SMAPS = os.path.exists(f"/proc/{os.getpid()}/smaps")
+HAS_PROC_SMAPS_ROLLUP = os.path.exists(f"/proc/{os.getpid()}/smaps_rollup")
+HAS_PROC_IO_PRIORITY = hasattr(cext, "proc_ioprio_get")
+HAS_CPU_AFFINITY = hasattr(cext, "proc_cpu_affinity_get")
+
+# Number of clock ticks per second
+CLOCK_TICKS = os.sysconf("SC_CLK_TCK")
+PAGESIZE = cext.getpagesize()
+LITTLE_ENDIAN = sys.byteorder == 'little'
+UNSET = object()
+
+# "man iostat" states that sectors are equivalent with blocks and have
+# a size of 512 bytes. Despite this value can be queried at runtime
+# via /sys/block/{DISK}/queue/hw_sector_size and results may vary
+# between 1k, 2k, or 4k... 512 appears to be a magic constant used
+# throughout Linux source code:
+# * https://stackoverflow.com/a/38136179/376587
+# * https://lists.gt.net/linux/kernel/2241060
+# * https://github.com/giampaolo/psutil/issues/1305
+# * https://github.com/torvalds/linux/blob/
+#     4f671fe2f9523a1ea206f63fe60a7c7b3a56d5c7/include/linux/bio.h#L99
+# * https://lkml.org/lkml/2015/8/17/234
+DISK_SECTOR_SIZE = 512
+
+AddressFamily = enum.IntEnum(
+    'AddressFamily', {'AF_LINK': int(socket.AF_PACKET)}
+)
+AF_LINK = AddressFamily.AF_LINK
+
+
+# ioprio_* constants http://linux.die.net/man/2/ioprio_get
+class IOPriority(enum.IntEnum):
+    IOPRIO_CLASS_NONE = 0
+    IOPRIO_CLASS_RT = 1
+    IOPRIO_CLASS_BE = 2
+    IOPRIO_CLASS_IDLE = 3
+
+
+globals().update(IOPriority.__members__)
+
+# See:
+# https://github.com/torvalds/linux/blame/master/fs/proc/array.c
+# ...and (TASK_* constants):
+# https://github.com/torvalds/linux/blob/master/include/linux/sched.h
+PROC_STATUSES = {
+    "R": _common.STATUS_RUNNING,
+    "S": _common.STATUS_SLEEPING,
+    "D": _common.STATUS_DISK_SLEEP,
+    "T": _common.STATUS_STOPPED,
+    "t": _common.STATUS_TRACING_STOP,
+    "Z": _common.STATUS_ZOMBIE,
+    "X": _common.STATUS_DEAD,
+    "x": _common.STATUS_DEAD,
+    "K": _common.STATUS_WAKE_KILL,
+    "W": _common.STATUS_WAKING,
+    "I": _common.STATUS_IDLE,
+    "P": _common.STATUS_PARKED,
+}
+
+# https://github.com/torvalds/linux/blob/master/include/net/tcp_states.h
+TCP_STATUSES = {
+    "01": _common.CONN_ESTABLISHED,
+    "02": _common.CONN_SYN_SENT,
+    "03": _common.CONN_SYN_RECV,
+    "04": _common.CONN_FIN_WAIT1,
+    "05": _common.CONN_FIN_WAIT2,
+    "06": _common.CONN_TIME_WAIT,
+    "07": _common.CONN_CLOSE,
+    "08": _common.CONN_CLOSE_WAIT,
+    "09": _common.CONN_LAST_ACK,
+    "0A": _common.CONN_LISTEN,
+    "0B": _common.CONN_CLOSING,
+}
+
+
+# =====================================================================
+# --- utils
+# =====================================================================
+
+
+def readlink(path):
+    """Wrapper around os.readlink()."""
+    assert isinstance(path, str), path
+    path = os.readlink(path)
+    # readlink() might return paths containing null bytes ('\x00')
+    # resulting in "TypeError: must be encoded string without NULL
+    # bytes, not str" errors when the string is passed to other
+    # fs-related functions (os.*, open(), ...).
+    # Apparently everything after '\x00' is garbage (we can have
+    # ' (deleted)', 'new' and possibly others), see:
+    # https://github.com/giampaolo/psutil/issues/717
+    path = path.split('\x00')[0]
+    # Certain paths have ' (deleted)' appended. Usually this is
+    # bogus as the file actually exists. Even if it doesn't we
+    # don't care.
+    if path.endswith(' (deleted)') and not path_exists_strict(path):
+        path = path[:-10]
+    return path
+
+
+def file_flags_to_mode(flags):
+    """Convert file's open() flags into a readable string.
+    Used by Process.open_files().
+    """
+    modes_map = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'}
+    mode = modes_map[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)]
+    if flags & os.O_APPEND:
+        mode = mode.replace('w', 'a', 1)
+    mode = mode.replace('w+', 'r+')
+    # possible values: r, w, a, r+, a+
+    return mode
+
+
+def is_storage_device(name):
+    """Return True if the given name refers to a root device (e.g.
+    "sda", "nvme0n1") as opposed to a logical partition (e.g.  "sda1",
+    "nvme0n1p1"). If name is a virtual device (e.g. "loop1", "ram")
+    return True.
+    """
+    # Re-adapted from iostat source code, see:
+    # https://github.com/sysstat/sysstat/blob/
+    #     97912938cd476645b267280069e83b1c8dc0e1c7/common.c#L208
+    # Some devices may have a slash in their name (e.g. cciss/c0d0...).
+    name = name.replace('/', '!')
+    including_virtual = True
+    if including_virtual:
+        path = f"/sys/block/{name}"
+    else:
+        path = f"/sys/block/{name}/device"
+    return os.access(path, os.F_OK)
+
+
+@memoize
+def _scputimes_ntuple(procfs_path):
+    """Return a namedtuple of variable fields depending on the CPU times
+    available on this Linux kernel version which may be:
+    (user, nice, system, idle, iowait, irq, softirq, [steal, [guest,
+     [guest_nice]]])
+    Used by cpu_times() function.
+    """
+    with open_binary(f"{procfs_path}/stat") as f:
+        values = f.readline().split()[1:]
+    fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq']
+    vlen = len(values)
+    if vlen >= 8:
+        # Linux >= 2.6.11
+        fields.append('steal')
+    if vlen >= 9:
+        # Linux >= 2.6.24
+        fields.append('guest')
+    if vlen >= 10:
+        # Linux >= 3.2.0
+        fields.append('guest_nice')
+    return namedtuple('scputimes', fields)
+
+
+# Set it into _ntuples.py namespace.
+try:
+    ntp.scputimes = _scputimes_ntuple("/proc")
+except Exception as err:  # noqa: BLE001
+    # Don't want to crash at import time.
+    debug(f"ignoring exception on import: {err!r}")
+    ntp.scputimes = namedtuple('scputimes', 'user system idle')(0.0, 0.0, 0.0)
+
+# XXX: must be available also at this module level in order to be
+# serialized (tests/test_misc.py::TestMisc::test_serialization).
+scputimes = ntp.scputimes
+
+
+# =====================================================================
+# --- system memory
+# =====================================================================
+
+
+def calculate_avail_vmem(mems):
+    """Fallback for kernels < 3.14 where /proc/meminfo does not provide
+    "MemAvailable", see:
+    https://blog.famzah.net/2014/09/24/.
+
+    This code reimplements the algorithm outlined here:
+    https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
+        commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
+
+    We use this function also when "MemAvailable" returns 0 (possibly a
+    kernel bug, see: https://github.com/giampaolo/psutil/issues/1915).
+    In that case this routine matches "free" CLI tool result ("available"
+    column).
+
+    XXX: on recent kernels this calculation may differ by ~1.5% compared
+    to "MemAvailable:", as it's calculated slightly differently.
+    It is still way more realistic than doing (free + cached) though.
+    See:
+    * https://gitlab.com/procps-ng/procps/issues/42
+    * https://github.com/famzah/linux-memavailable-procfs/issues/2
+    """
+    # Note about "fallback" value. According to:
+    # https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
+    #     commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
+    # ...long ago "available" memory was calculated as (free + cached),
+    # We use fallback when one of these is missing from /proc/meminfo:
+    # "Active(file)": introduced in 2.6.28 / Dec 2008
+    # "Inactive(file)": introduced in 2.6.28 / Dec 2008
+    # "SReclaimable": introduced in 2.6.19 / Nov 2006
+    # /proc/zoneinfo: introduced in 2.6.13 / Aug 2005
+    free = mems[b'MemFree:']
+    fallback = free + mems.get(b"Cached:", 0)
+    try:
+        lru_active_file = mems[b'Active(file):']
+        lru_inactive_file = mems[b'Inactive(file):']
+        slab_reclaimable = mems[b'SReclaimable:']
+    except KeyError as err:
+        debug(
+            f"{err.args[0]} is missing from /proc/meminfo; using an"
+            " approximation for calculating available memory"
+        )
+        return fallback
+    try:
+        f = open_binary(f"{get_procfs_path()}/zoneinfo")
+    except OSError:
+        return fallback  # kernel 2.6.13
+
+    watermark_low = 0
+    with f:
+        for line in f:
+            line = line.strip()
+            if line.startswith(b'low'):
+                watermark_low += int(line.split()[1])
+    watermark_low *= PAGESIZE
+
+    avail = free - watermark_low
+    pagecache = lru_active_file + lru_inactive_file
+    pagecache -= min(pagecache / 2, watermark_low)
+    avail += pagecache
+    avail += slab_reclaimable - min(slab_reclaimable / 2.0, watermark_low)
+    return int(avail)
+
+
+def virtual_memory():
+    """Report virtual memory stats.
+    This implementation mimics procps-ng-3.3.12, aka "free" CLI tool:
+    https://gitlab.com/procps-ng/procps/blob/
+        24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L778-791
+    The returned values are supposed to match both "free" and "vmstat -s"
+    CLI tools.
+    """
+    missing_fields = []
+    mems = {}
+    with open_binary(f"{get_procfs_path()}/meminfo") as f:
+        for line in f:
+            fields = line.split()
+            mems[fields[0]] = int(fields[1]) * 1024
+
+    # /proc doc states that the available fields in /proc/meminfo vary
+    # by architecture and compile options, but these 3 values are also
+    # returned by sysinfo(2); as such we assume they are always there.
+    total = mems[b'MemTotal:']
+    free = mems[b'MemFree:']
+    try:
+        buffers = mems[b'Buffers:']
+    except KeyError:
+        # https://github.com/giampaolo/psutil/issues/1010
+        buffers = 0
+        missing_fields.append('buffers')
+    try:
+        cached = mems[b"Cached:"]
+    except KeyError:
+        cached = 0
+        missing_fields.append('cached')
+    else:
+        # "free" cmdline utility sums reclaimable to cached.
+        # Older versions of procps used to add slab memory instead.
+        # This got changed in:
+        # https://gitlab.com/procps-ng/procps/commit/
+        #     05d751c4f076a2f0118b914c5e51cfbb4762ad8e
+        cached += mems.get(b"SReclaimable:", 0)  # since kernel 2.6.19
+
+    try:
+        shared = mems[b'Shmem:']  # since kernel 2.6.32
+    except KeyError:
+        try:
+            shared = mems[b'MemShared:']  # kernels 2.4
+        except KeyError:
+            shared = 0
+            missing_fields.append('shared')
+
+    try:
+        active = mems[b"Active:"]
+    except KeyError:
+        active = 0
+        missing_fields.append('active')
+
+    try:
+        inactive = mems[b"Inactive:"]
+    except KeyError:
+        try:
+            inactive = (
+                mems[b"Inact_dirty:"]
+                + mems[b"Inact_clean:"]
+                + mems[b"Inact_laundry:"]
+            )
+        except KeyError:
+            inactive = 0
+            missing_fields.append('inactive')
+
+    try:
+        slab = mems[b"Slab:"]
+    except KeyError:
+        slab = 0
+
+    # - starting from 4.4.0 we match free's "available" column.
+    #   Before 4.4.0 we calculated it as (free + buffers + cached)
+    #   which matched htop.
+    # - free and htop available memory differs as per:
+    #   http://askubuntu.com/a/369589
+    #   http://unix.stackexchange.com/a/65852/168884
+    # - MemAvailable has been introduced in kernel 3.14
+    try:
+        avail = mems[b'MemAvailable:']
+    except KeyError:
+        avail = calculate_avail_vmem(mems)
+    else:
+        if avail == 0:
+            # Yes, it can happen (probably a kernel bug):
+            # https://github.com/giampaolo/psutil/issues/1915
+            # In this case "free" CLI tool makes an estimate. We do the same,
+            # and it matches "free" CLI tool.
+            avail = calculate_avail_vmem(mems)
+
+    if avail < 0:
+        avail = 0
+        missing_fields.append('available')
+    elif avail > total:
+        # If avail is greater than total or our calculation overflows,
+        # that's symptomatic of running within a LCX container where such
+        # values will be dramatically distorted over those of the host.
+        # https://gitlab.com/procps-ng/procps/blob/
+        #     24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L764
+        avail = free
+
+    used = total - avail
+
+    percent = usage_percent((total - avail), total, round_=1)
+
+    # Warn about missing metrics which are set to 0.
+    if missing_fields:
+        msg = "{} memory stats couldn't be determined and {} set to 0".format(
+            ", ".join(missing_fields),
+            "was" if len(missing_fields) == 1 else "were",
+        )
+        warnings.warn(msg, RuntimeWarning, stacklevel=2)
+
+    return ntp.svmem(
+        total,
+        avail,
+        percent,
+        used,
+        free,
+        active,
+        inactive,
+        buffers,
+        cached,
+        shared,
+        slab,
+    )
+
+
+def swap_memory():
+    """Return swap memory metrics."""
+    mems = {}
+    with open_binary(f"{get_procfs_path()}/meminfo") as f:
+        for line in f:
+            fields = line.split()
+            mems[fields[0]] = int(fields[1]) * 1024
+    # We prefer /proc/meminfo over sysinfo() syscall so that
+    # psutil.PROCFS_PATH can be used in order to allow retrieval
+    # for linux containers, see:
+    # https://github.com/giampaolo/psutil/issues/1015
+    try:
+        total = mems[b'SwapTotal:']
+        free = mems[b'SwapFree:']
+    except KeyError:
+        _, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo()
+        total *= unit_multiplier
+        free *= unit_multiplier
+
+    used = total - free
+    percent = usage_percent(used, total, round_=1)
+    # get pgin/pgouts
+    try:
+        f = open_binary(f"{get_procfs_path()}/vmstat")
+    except OSError as err:
+        # see https://github.com/giampaolo/psutil/issues/722
+        msg = (
+            "'sin' and 'sout' swap memory stats couldn't "
+            f"be determined and were set to 0 ({err})"
+        )
+        warnings.warn(msg, RuntimeWarning, stacklevel=2)
+        sin = sout = 0
+    else:
+        with f:
+            sin = sout = None
+            for line in f:
+                # values are expressed in 4 kilo bytes, we want
+                # bytes instead
+                if line.startswith(b'pswpin'):
+                    sin = int(line.split(b' ')[1]) * 4 * 1024
+                elif line.startswith(b'pswpout'):
+                    sout = int(line.split(b' ')[1]) * 4 * 1024
+                if sin is not None and sout is not None:
+                    break
+            else:
+                # we might get here when dealing with exotic Linux
+                # flavors, see:
+                # https://github.com/giampaolo/psutil/issues/313
+                msg = "'sin' and 'sout' swap memory stats couldn't "
+                msg += "be determined and were set to 0"
+                warnings.warn(msg, RuntimeWarning, stacklevel=2)
+                sin = sout = 0
+    return ntp.sswap(total, used, free, percent, sin, sout)
+
+
+# malloc / heap functions; require glibc
+if hasattr(cext, "heap_info"):
+    heap_info = cext.heap_info
+    heap_trim = cext.heap_trim
+
+
+# =====================================================================
+# --- CPU
+# =====================================================================
+
+
+def cpu_times():
+    """Return a named tuple representing the following system-wide
+    CPU times:
+    (user, nice, system, idle, iowait, irq, softirq [steal, [guest,
+     [guest_nice]]])
+    Last 3 fields may not be available on all Linux kernel versions.
+    """
+    procfs_path = get_procfs_path()
+    with open_binary(f"{procfs_path}/stat") as f:
+        values = f.readline().split()
+    fields = values[1 : len(ntp.scputimes._fields) + 1]
+    fields = [float(x) / CLOCK_TICKS for x in fields]
+    return ntp.scputimes(*fields)
+
+
+def per_cpu_times():
+    """Return a list of namedtuple representing the CPU times
+    for every CPU available on the system.
+    """
+    procfs_path = get_procfs_path()
+    cpus = []
+    with open_binary(f"{procfs_path}/stat") as f:
+        # get rid of the first line which refers to system wide CPU stats
+        f.readline()
+        for line in f:
+            if line.startswith(b'cpu'):
+                values = line.split()
+                fields = values[1 : len(ntp.scputimes._fields) + 1]
+                fields = [float(x) / CLOCK_TICKS for x in fields]
+                entry = ntp.scputimes(*fields)
+                cpus.append(entry)
+        return cpus
+
+
+def cpu_count_logical():
+    """Return the number of logical CPUs in the system."""
+    try:
+        return os.sysconf("SC_NPROCESSORS_ONLN")
+    except ValueError:
+        # as a second fallback we try to parse /proc/cpuinfo
+        num = 0
+        with open_binary(f"{get_procfs_path()}/cpuinfo") as f:
+            for line in f:
+                if line.lower().startswith(b'processor'):
+                    num += 1
+
+        # unknown format (e.g. amrel/sparc architectures), see:
+        # https://github.com/giampaolo/psutil/issues/200
+        # try to parse /proc/stat as a last resort
+        if num == 0:
+            search = re.compile(r'cpu\d')
+            with open_text(f"{get_procfs_path()}/stat") as f:
+                for line in f:
+                    line = line.split(' ')[0]
+                    if search.match(line):
+                        num += 1
+
+        if num == 0:
+            # mimic os.cpu_count()
+            return None
+        return num
+
+
+def cpu_count_cores():
+    """Return the number of CPU cores in the system."""
+    # Method #1
+    ls = set()
+    # These 2 files are the same but */core_cpus_list is newer while
+    # */thread_siblings_list is deprecated and may disappear in the future.
+    # https://www.kernel.org/doc/Documentation/admin-guide/cputopology.rst
+    # https://github.com/giampaolo/psutil/pull/1727#issuecomment-707624964
+    # https://lkml.org/lkml/2019/2/26/41
+    p1 = "/sys/devices/system/cpu/cpu[0-9]*/topology/core_cpus_list"
+    p2 = "/sys/devices/system/cpu/cpu[0-9]*/topology/thread_siblings_list"
+    for path in glob.glob(p1) or glob.glob(p2):
+        with open_binary(path) as f:
+            ls.add(f.read().strip())
+    result = len(ls)
+    if result != 0:
+        return result
+
+    # Method #2
+    mapping = {}
+    current_info = {}
+    with open_binary(f"{get_procfs_path()}/cpuinfo") as f:
+        for line in f:
+            line = line.strip().lower()
+            if not line:
+                # new section
+                try:
+                    mapping[current_info[b'physical id']] = current_info[
+                        b'cpu cores'
+                    ]
+                except KeyError:
+                    pass
+                current_info = {}
+            elif line.startswith((b'physical id', b'cpu cores')):
+                # ongoing section
+                key, value = line.split(b'\t:', 1)
+                current_info[key] = int(value)
+
+    result = sum(mapping.values())
+    return result or None  # mimic os.cpu_count()
+
+
+def cpu_stats():
+    """Return various CPU stats as a named tuple."""
+    with open_binary(f"{get_procfs_path()}/stat") as f:
+        ctx_switches = None
+        interrupts = None
+        soft_interrupts = None
+        for line in f:
+            if line.startswith(b'ctxt'):
+                ctx_switches = int(line.split()[1])
+            elif line.startswith(b'intr'):
+                interrupts = int(line.split()[1])
+            elif line.startswith(b'softirq'):
+                soft_interrupts = int(line.split()[1])
+            if (
+                ctx_switches is not None
+                and soft_interrupts is not None
+                and interrupts is not None
+            ):
+                break
+    syscalls = 0
+    return ntp.scpustats(ctx_switches, interrupts, soft_interrupts, syscalls)
+
+
+def _cpu_get_cpuinfo_freq():
+    """Return current CPU frequency from cpuinfo if available."""
+    with open_binary(f"{get_procfs_path()}/cpuinfo") as f:
+        return [
+            float(line.split(b':', 1)[1])
+            for line in f
+            if line.lower().startswith(b'cpu mhz')
+        ]
+
+
+if os.path.exists("/sys/devices/system/cpu/cpufreq/policy0") or os.path.exists(
+    "/sys/devices/system/cpu/cpu0/cpufreq"
+):
+
+    def cpu_freq():
+        """Return frequency metrics for all CPUs.
+        Contrarily to other OSes, Linux updates these values in
+        real-time.
+        """
+        cpuinfo_freqs = _cpu_get_cpuinfo_freq()
+        paths = glob.glob(
+            "/sys/devices/system/cpu/cpufreq/policy[0-9]*"
+        ) or glob.glob("/sys/devices/system/cpu/cpu[0-9]*/cpufreq")
+        paths.sort(key=lambda x: int(re.search(r"[0-9]+", x).group()))
+        ret = []
+        pjoin = os.path.join
+        for i, path in enumerate(paths):
+            if len(paths) == len(cpuinfo_freqs):
+                # take cached value from cpuinfo if available, see:
+                # https://github.com/giampaolo/psutil/issues/1851
+                curr = cpuinfo_freqs[i] * 1000
+            else:
+                curr = bcat(pjoin(path, "scaling_cur_freq"), fallback=None)
+            if curr is None:
+                # Likely an old RedHat, see:
+                # https://github.com/giampaolo/psutil/issues/1071
+                curr = bcat(pjoin(path, "cpuinfo_cur_freq"), fallback=None)
+                if curr is None:
+                    online_path = f"/sys/devices/system/cpu/cpu{i}/online"
+                    # if cpu core is offline, set to all zeroes
+                    if cat(online_path, fallback=None) == "0\n":
+                        ret.append(ntp.scpufreq(0.0, 0.0, 0.0))
+                        continue
+                    msg = "can't find current frequency file"
+                    raise NotImplementedError(msg)
+            curr = int(curr) / 1000
+            max_ = int(bcat(pjoin(path, "scaling_max_freq"))) / 1000
+            min_ = int(bcat(pjoin(path, "scaling_min_freq"))) / 1000
+            ret.append(ntp.scpufreq(curr, min_, max_))
+        return ret
+
+else:
+
+    def cpu_freq():
+        """Alternate implementation using /proc/cpuinfo.
+        min and max frequencies are not available and are set to None.
+        """
+        return [ntp.scpufreq(x, 0.0, 0.0) for x in _cpu_get_cpuinfo_freq()]
+
+
+# =====================================================================
+# --- network
+# =====================================================================
+
+
+net_if_addrs = cext.net_if_addrs
+
+
+class _Ipv6UnsupportedError(Exception):
+    pass
+
+
+class NetConnections:
+    """A wrapper on top of /proc/net/* files, retrieving per-process
+    and system-wide open connections (TCP, UDP, UNIX) similarly to
+    "netstat -an".
+
+    Note: in case of UNIX sockets we're only able to determine the
+    local endpoint/path, not the one it's connected to.
+    According to [1] it would be possible but not easily.
+
+    [1] http://serverfault.com/a/417946
+    """
+
+    def __init__(self):
+        # The string represents the basename of the corresponding
+        # /proc/net/{proto_name} file.
+        tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM)
+        tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
+        udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM)
+        udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
+        unix = ("unix", socket.AF_UNIX, None)
+        self.tmap = {
+            "all": (tcp4, tcp6, udp4, udp6, unix),
+            "tcp": (tcp4, tcp6),
+            "tcp4": (tcp4,),
+            "tcp6": (tcp6,),
+            "udp": (udp4, udp6),
+            "udp4": (udp4,),
+            "udp6": (udp6,),
+            "unix": (unix,),
+            "inet": (tcp4, tcp6, udp4, udp6),
+            "inet4": (tcp4, udp4),
+            "inet6": (tcp6, udp6),
+        }
+        self._procfs_path = None
+
+    def get_proc_inodes(self, pid):
+        inodes = defaultdict(list)
+        for fd in os.listdir(f"{self._procfs_path}/{pid}/fd"):
+            try:
+                inode = readlink(f"{self._procfs_path}/{pid}/fd/{fd}")
+            except (FileNotFoundError, ProcessLookupError):
+                # ENOENT == file which is gone in the meantime;
+                # os.stat(f"/proc/{self.pid}") will be done later
+                # to force NSP (if it's the case)
+                continue
+            except OSError as err:
+                if err.errno == errno.EINVAL:
+                    # not a link
+                    continue
+                if err.errno == errno.ENAMETOOLONG:
+                    # file name too long
+                    debug(err)
+                    continue
+                raise
+            else:
+                if inode.startswith('socket:['):
+                    # the process is using a socket
+                    inode = inode[8:][:-1]
+                    inodes[inode].append((pid, int(fd)))
+        return inodes
+
+    def get_all_inodes(self):
+        inodes = {}
+        for pid in pids():
+            try:
+                inodes.update(self.get_proc_inodes(pid))
+            except (FileNotFoundError, ProcessLookupError, PermissionError):
+                # os.listdir() is gonna raise a lot of access denied
+                # exceptions in case of unprivileged user; that's fine
+                # as we'll just end up returning a connection with PID
+                # and fd set to None anyway.
+                # Both netstat -an and lsof does the same so it's
+                # unlikely we can do any better.
+                # ENOENT just means a PID disappeared on us.
+                continue
+        return inodes
+
+    @staticmethod
+    def decode_address(addr, family):
+        """Accept an "ip:port" address as displayed in /proc/net/*
+        and convert it into a human readable form, like:
+
+        "0500000A:0016" -> ("10.0.0.5", 22)
+        "0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)
+
+        The IP address portion is a little or big endian four-byte
+        hexadecimal number; that is, the least significant byte is listed
+        first, so we need to reverse the order of the bytes to convert it
+        to an IP address.
+        The port is represented as a two-byte hexadecimal number.
+
+        Reference:
+        http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
+        """
+        ip, port = addr.split(':')
+        port = int(port, 16)
+        # this usually refers to a local socket in listen mode with
+        # no end-points connected
+        if not port:
+            return ()
+        ip = ip.encode('ascii')
+        if family == socket.AF_INET:
+            # see: https://github.com/giampaolo/psutil/issues/201
+            if LITTLE_ENDIAN:
+                ip = socket.inet_ntop(family, base64.b16decode(ip)[::-1])
+            else:
+                ip = socket.inet_ntop(family, base64.b16decode(ip))
+        else:  # IPv6
+            ip = base64.b16decode(ip)
+            try:
+                # see: https://github.com/giampaolo/psutil/issues/201
+                if LITTLE_ENDIAN:
+                    ip = socket.inet_ntop(
+                        socket.AF_INET6,
+                        struct.pack('>4I', *struct.unpack('<4I', ip)),
+                    )
+                else:
+                    ip = socket.inet_ntop(
+                        socket.AF_INET6,
+                        struct.pack('<4I', *struct.unpack('<4I', ip)),
+                    )
+            except ValueError:
+                # see: https://github.com/giampaolo/psutil/issues/623
+                if not supports_ipv6():
+                    raise _Ipv6UnsupportedError from None
+                raise
+        return ntp.addr(ip, port)
+
+    @staticmethod
+    def process_inet(file, family, type_, inodes, filter_pid=None):
+        """Parse /proc/net/tcp* and /proc/net/udp* files."""
+        if file.endswith('6') and not os.path.exists(file):
+            # IPv6 not supported
+            return
+        with open_text(file) as f:
+            f.readline()  # skip the first line
+            for lineno, line in enumerate(f, 1):
+                try:
+                    _, laddr, raddr, status, _, _, _, _, _, inode = (
+                        line.split()[:10]
+                    )
+                except ValueError:
+                    msg = (
+                        f"error while parsing {file}; malformed line"
+                        f" {lineno} {line!r}"
+                    )
+                    raise RuntimeError(msg) from None
+                if inode in inodes:
+                    # # We assume inet sockets are unique, so we error
+                    # # out if there are multiple references to the
+                    # # same inode. We won't do this for UNIX sockets.
+                    # if len(inodes[inode]) > 1 and family != socket.AF_UNIX:
+                    #     raise ValueError("ambiguous inode with multiple "
+                    #                      "PIDs references")
+                    pid, fd = inodes[inode][0]
+                else:
+                    pid, fd = None, -1
+                if filter_pid is not None and filter_pid != pid:
+                    continue
+                else:
+                    if type_ == socket.SOCK_STREAM:
+                        status = TCP_STATUSES[status]
+                    else:
+                        status = _common.CONN_NONE
+                    try:
+                        laddr = NetConnections.decode_address(laddr, family)
+                        raddr = NetConnections.decode_address(raddr, family)
+                    except _Ipv6UnsupportedError:
+                        continue
+                    yield (fd, family, type_, laddr, raddr, status, pid)
+
+    @staticmethod
+    def process_unix(file, family, inodes, filter_pid=None):
+        """Parse /proc/net/unix files."""
+        with open_text(file) as f:
+            f.readline()  # skip the first line
+            for line in f:
+                tokens = line.split()
+                try:
+                    _, _, _, _, type_, _, inode = tokens[0:7]
+                except ValueError:
+                    if ' ' not in line:
+                        # see: https://github.com/giampaolo/psutil/issues/766
+                        continue
+                    msg = (
+                        f"error while parsing {file}; malformed line {line!r}"
+                    )
+                    raise RuntimeError(msg)  # noqa: B904
+                if inode in inodes:  # noqa: SIM108
+                    # With UNIX sockets we can have a single inode
+                    # referencing many file descriptors.
+                    pairs = inodes[inode]
+                else:
+                    pairs = [(None, -1)]
+                for pid, fd in pairs:
+                    if filter_pid is not None and filter_pid != pid:
+                        continue
+                    else:
+                        path = tokens[-1] if len(tokens) == 8 else ''
+                        type_ = _common.socktype_to_enum(int(type_))
+                        # XXX: determining the remote endpoint of a
+                        # UNIX socket on Linux is not possible, see:
+                        # https://serverfault.com/questions/252723/
+                        raddr = ""
+                        status = _common.CONN_NONE
+                        yield (fd, family, type_, path, raddr, status, pid)
+
+    def retrieve(self, kind, pid=None):
+        self._procfs_path = get_procfs_path()
+        if pid is not None:
+            inodes = self.get_proc_inodes(pid)
+            if not inodes:
+                # no connections for this process
+                return []
+        else:
+            inodes = self.get_all_inodes()
+        ret = set()
+        for proto_name, family, type_ in self.tmap[kind]:
+            path = f"{self._procfs_path}/net/{proto_name}"
+            if family in {socket.AF_INET, socket.AF_INET6}:
+                ls = self.process_inet(
+                    path, family, type_, inodes, filter_pid=pid
+                )
+            else:
+                ls = self.process_unix(path, family, inodes, filter_pid=pid)
+            for fd, family, type_, laddr, raddr, status, bound_pid in ls:
+                if pid:
+                    conn = ntp.pconn(fd, family, type_, laddr, raddr, status)
+                else:
+                    conn = ntp.sconn(
+                        fd, family, type_, laddr, raddr, status, bound_pid
+                    )
+                ret.add(conn)
+        return list(ret)
+
+
+_net_connections = NetConnections()
+
+
+def net_connections(kind='inet'):
+    """Return system-wide open connections."""
+    return _net_connections.retrieve(kind)
+
+
+def net_io_counters():
+    """Return network I/O statistics for every network interface
+    installed on the system as a dict of raw tuples.
+    """
+    with open_text(f"{get_procfs_path()}/net/dev") as f:
+        lines = f.readlines()
+    retdict = {}
+    for line in lines[2:]:
+        colon = line.rfind(':')
+        assert colon > 0, repr(line)
+        name = line[:colon].strip()
+        fields = line[colon + 1 :].strip().split()
+
+        (
+            # in
+            bytes_recv,
+            packets_recv,
+            errin,
+            dropin,
+            _fifoin,  # unused
+            _framein,  # unused
+            _compressedin,  # unused
+            _multicastin,  # unused
+            # out
+            bytes_sent,
+            packets_sent,
+            errout,
+            dropout,
+            _fifoout,  # unused
+            _collisionsout,  # unused
+            _carrierout,  # unused
+            _compressedout,  # unused
+        ) = map(int, fields)
+
+        retdict[name] = (
+            bytes_sent,
+            bytes_recv,
+            packets_sent,
+            packets_recv,
+            errin,
+            errout,
+            dropin,
+            dropout,
+        )
+    return retdict
+
+
+def net_if_stats():
+    """Get NIC stats (isup, duplex, speed, mtu)."""
+    duplex_map = {
+        cext.DUPLEX_FULL: NIC_DUPLEX_FULL,
+        cext.DUPLEX_HALF: NIC_DUPLEX_HALF,
+        cext.DUPLEX_UNKNOWN: NIC_DUPLEX_UNKNOWN,
+    }
+    names = net_io_counters().keys()
+    ret = {}
+    for name in names:
+        try:
+            mtu = cext.net_if_mtu(name)
+            flags = cext.net_if_flags(name)
+            duplex, speed = cext.net_if_duplex_speed(name)
+        except OSError as err:
+            # https://github.com/giampaolo/psutil/issues/1279
+            if err.errno != errno.ENODEV:
+                raise
+            debug(err)
+        else:
+            output_flags = ','.join(flags)
+            isup = 'running' in flags
+            ret[name] = ntp.snicstats(
+                isup, duplex_map[duplex], speed, mtu, output_flags
+            )
+    return ret
+
+
+# =====================================================================
+# --- disks
+# =====================================================================
+
+
+disk_usage = _psposix.disk_usage
+
+
+def disk_io_counters(perdisk=False):
+    """Return disk I/O statistics for every disk installed on the
+    system as a dict of raw tuples.
+    """
+
+    def read_procfs():
+        # OK, this is a bit confusing. The format of /proc/diskstats can
+        # have 3 variations.
+        # On Linux 2.4 each line has always 15 fields, e.g.:
+        # "3     0   8 hda 8 8 8 8 8 8 8 8 8 8 8"
+        # On Linux 2.6+ each line *usually* has 14 fields, and the disk
+        # name is in another position, like this:
+        # "3    0   hda 8 8 8 8 8 8 8 8 8 8 8"
+        # ...unless (Linux 2.6) the line refers to a partition instead
+        # of a disk, in which case the line has less fields (7):
+        # "3    1   hda1 8 8 8 8"
+        # 4.18+ has 4 fields added:
+        # "3    0   hda 8 8 8 8 8 8 8 8 8 8 8 0 0 0 0"
+        # 5.5 has 2 more fields.
+        # See:
+        # https://www.kernel.org/doc/Documentation/iostats.txt
+        # https://www.kernel.org/doc/Documentation/ABI/testing/procfs-diskstats
+        with open_text(f"{get_procfs_path()}/diskstats") as f:
+            lines = f.readlines()
+        for line in lines:
+            fields = line.split()
+            flen = len(fields)
+            # fmt: off
+            if flen == 15:
+                # Linux 2.4
+                name = fields[3]
+                reads = int(fields[2])
+                (reads_merged, rbytes, rtime, writes, writes_merged,
+                    wbytes, wtime, _, busy_time, _) = map(int, fields[4:14])
+            elif flen == 14 or flen >= 18:
+                # Linux 2.6+, line referring to a disk
+                name = fields[2]
+                (reads, reads_merged, rbytes, rtime, writes, writes_merged,
+                    wbytes, wtime, _, busy_time, _) = map(int, fields[3:14])
+            elif flen == 7:
+                # Linux 2.6+, line referring to a partition
+                name = fields[2]
+                reads, rbytes, writes, wbytes = map(int, fields[3:])
+                rtime = wtime = reads_merged = writes_merged = busy_time = 0
+            else:
+                msg = f"not sure how to interpret line {line!r}"
+                raise ValueError(msg)
+            yield (name, reads, writes, rbytes, wbytes, rtime, wtime,
+                   reads_merged, writes_merged, busy_time)
+            # fmt: on
+
+    def read_sysfs():
+        for block in os.listdir('/sys/block'):
+            for root, _, files in os.walk(os.path.join('/sys/block', block)):
+                if 'stat' not in files:
+                    continue
+                with open_text(os.path.join(root, 'stat')) as f:
+                    fields = f.read().strip().split()
+                name = os.path.basename(root)
+                # fmt: off
+                (reads, reads_merged, rbytes, rtime, writes, writes_merged,
+                    wbytes, wtime, _, busy_time) = map(int, fields[:10])
+                yield (name, reads, writes, rbytes, wbytes, rtime,
+                       wtime, reads_merged, writes_merged, busy_time)
+                # fmt: on
+
+    if os.path.exists(f"{get_procfs_path()}/diskstats"):
+        gen = read_procfs()
+    elif os.path.exists('/sys/block'):
+        gen = read_sysfs()
+    else:
+        msg = (
+            f"{get_procfs_path()}/diskstats nor /sys/block are available on"
+            " this system"
+        )
+        raise NotImplementedError(msg)
+
+    retdict = {}
+    for entry in gen:
+        # fmt: off
+        (name, reads, writes, rbytes, wbytes, rtime, wtime, reads_merged,
+            writes_merged, busy_time) = entry
+        if not perdisk and not is_storage_device(name):
+            # perdisk=False means we want to calculate totals so we skip
+            # partitions (e.g. 'sda1', 'nvme0n1p1') and only include
+            # base disk devices (e.g. 'sda', 'nvme0n1'). Base disks
+            # include a total of all their partitions + some extra size
+            # of their own:
+            #     $ cat /proc/diskstats
+            #     259       0 sda 10485760 ...
+            #     259       1 sda1 5186039 ...
+            #     259       1 sda2 5082039 ...
+            # See:
+            # https://github.com/giampaolo/psutil/pull/1313
+            continue
+
+        rbytes *= DISK_SECTOR_SIZE
+        wbytes *= DISK_SECTOR_SIZE
+        retdict[name] = (reads, writes, rbytes, wbytes, rtime, wtime,
+                         reads_merged, writes_merged, busy_time)
+        # fmt: on
+
+    return retdict
+
+
+class RootFsDeviceFinder:
+    """disk_partitions() may return partitions with device == "/dev/root"
+    or "rootfs". This container class uses different strategies to try to
+    obtain the real device path. Resources:
+    https://bootlin.com/blog/find-root-device/
+    https://www.systutorials.com/how-to-find-the-disk-where-root-is-on-in-bash-on-linux/.
+    """
+
+    __slots__ = ['major', 'minor']
+
+    def __init__(self):
+        dev = os.stat("/").st_dev
+        self.major = os.major(dev)
+        self.minor = os.minor(dev)
+
+    def ask_proc_partitions(self):
+        with open_text(f"{get_procfs_path()}/partitions") as f:
+            for line in f.readlines()[2:]:
+                fields = line.split()
+                if len(fields) < 4:  # just for extra safety
+                    continue
+                major = int(fields[0]) if fields[0].isdigit() else None
+                minor = int(fields[1]) if fields[1].isdigit() else None
+                name = fields[3]
+                if major == self.major and minor == self.minor:
+                    if name:  # just for extra safety
+                        return f"/dev/{name}"
+
+    def ask_sys_dev_block(self):
+        path = f"/sys/dev/block/{self.major}:{self.minor}/uevent"
+        with open_text(path) as f:
+            for line in f:
+                if line.startswith("DEVNAME="):
+                    name = line.strip().rpartition("DEVNAME=")[2]
+                    if name:  # just for extra safety
+                        return f"/dev/{name}"
+
+    def ask_sys_class_block(self):
+        needle = f"{self.major}:{self.minor}"
+        files = glob.iglob("/sys/class/block/*/dev")
+        for file in files:
+            try:
+                f = open_text(file)
+            except FileNotFoundError:  # race condition
+                continue
+            else:
+                with f:
+                    data = f.read().strip()
+                    if data == needle:
+                        name = os.path.basename(os.path.dirname(file))
+                        return f"/dev/{name}"
+
+    def find(self):
+        path = None
+        if path is None:
+            try:
+                path = self.ask_proc_partitions()
+            except OSError as err:
+                debug(err)
+        if path is None:
+            try:
+                path = self.ask_sys_dev_block()
+            except OSError as err:
+                debug(err)
+        if path is None:
+            try:
+                path = self.ask_sys_class_block()
+            except OSError as err:
+                debug(err)
+        # We use exists() because the "/dev/*" part of the path is hard
+        # coded, so we want to be sure.
+        if path is not None and os.path.exists(path):
+            return path
+
+
+def disk_partitions(all=False):
+    """Return mounted disk partitions as a list of namedtuples."""
+    fstypes = set()
+    procfs_path = get_procfs_path()
+    if not all:
+        with open_text(f"{procfs_path}/filesystems") as f:
+            for line in f:
+                line = line.strip()
+                if not line.startswith("nodev"):
+                    fstypes.add(line.strip())
+                else:
+                    # ignore all lines starting with "nodev" except "nodev zfs"
+                    fstype = line.split("\t")[1]
+                    if fstype == "zfs":
+                        fstypes.add("zfs")
+
+    # See: https://github.com/giampaolo/psutil/issues/1307
+    if procfs_path == "/proc" and os.path.isfile('/etc/mtab'):
+        mounts_path = os.path.realpath("/etc/mtab")
+    else:
+        mounts_path = os.path.realpath(f"{procfs_path}/self/mounts")
+
+    retlist = []
+    partitions = cext.disk_partitions(mounts_path)
+    for partition in partitions:
+        device, mountpoint, fstype, opts = partition
+        if device == 'none':
+            device = ''
+        if device in {"/dev/root", "rootfs"}:
+            device = RootFsDeviceFinder().find() or device
+        if not all:
+            if not device or fstype not in fstypes:
+                continue
+        ntuple = ntp.sdiskpart(device, mountpoint, fstype, opts)
+        retlist.append(ntuple)
+
+    return retlist
+
+
+# =====================================================================
+# --- sensors
+# =====================================================================
+
+
+def sensors_temperatures():
+    """Return hardware (CPU and others) temperatures as a dict
+    including hardware name, label, current, max and critical
+    temperatures.
+
+    Implementation notes:
+    - /sys/class/hwmon looks like the most recent interface to
+      retrieve this info, and this implementation relies on it
+      only (old distros will probably use something else)
+    - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
+    - /sys/class/thermal/thermal_zone* is another one but it's more
+      difficult to parse
+    """
+    ret = collections.defaultdict(list)
+    basenames = glob.glob('/sys/class/hwmon/hwmon*/temp*_*')
+    # CentOS has an intermediate /device directory:
+    # https://github.com/giampaolo/psutil/issues/971
+    # https://github.com/nicolargo/glances/issues/1060
+    basenames.extend(glob.glob('/sys/class/hwmon/hwmon*/device/temp*_*'))
+    basenames = sorted({x.split('_')[0] for x in basenames})
+
+    # Only add the coretemp hwmon entries if they're not already in
+    # /sys/class/hwmon/
+    # https://github.com/giampaolo/psutil/issues/1708
+    # https://github.com/giampaolo/psutil/pull/1648
+    basenames2 = glob.glob(
+        '/sys/devices/platform/coretemp.*/hwmon/hwmon*/temp*_*'
+    )
+    repl = re.compile(r"/sys/devices/platform/coretemp.*/hwmon/")
+    for name in basenames2:
+        altname = repl.sub('/sys/class/hwmon/', name)
+        if altname not in basenames:
+            basenames.append(name)
+
+    for base in basenames:
+        try:
+            path = base + '_input'
+            current = float(bcat(path)) / 1000.0
+            path = os.path.join(os.path.dirname(base), 'name')
+            unit_name = cat(path).strip()
+        except (OSError, ValueError):
+            # A lot of things can go wrong here, so let's just skip the
+            # whole entry. Sure thing is Linux's /sys/class/hwmon really
+            # is a stinky broken mess.
+            # https://github.com/giampaolo/psutil/issues/1009
+            # https://github.com/giampaolo/psutil/issues/1101
+            # https://github.com/giampaolo/psutil/issues/1129
+            # https://github.com/giampaolo/psutil/issues/1245
+            # https://github.com/giampaolo/psutil/issues/1323
+            continue
+
+        high = bcat(base + '_max', fallback=None)
+        critical = bcat(base + '_crit', fallback=None)
+        label = cat(base + '_label', fallback='').strip()
+
+        if high is not None:
+            try:
+                high = float(high) / 1000.0
+            except ValueError:
+                high = None
+        if critical is not None:
+            try:
+                critical = float(critical) / 1000.0
+            except ValueError:
+                critical = None
+
+        ret[unit_name].append((label, current, high, critical))
+
+    # Indication that no sensors were detected in /sys/class/hwmon/
+    if not basenames:
+        basenames = glob.glob('/sys/class/thermal/thermal_zone*')
+        basenames = sorted(set(basenames))
+
+        for base in basenames:
+            try:
+                path = os.path.join(base, 'temp')
+                current = float(bcat(path)) / 1000.0
+                path = os.path.join(base, 'type')
+                unit_name = cat(path).strip()
+            except (OSError, ValueError) as err:
+                debug(err)
+                continue
+
+            trip_paths = glob.glob(base + '/trip_point*')
+            trip_points = {
+                '_'.join(os.path.basename(p).split('_')[0:3])
+                for p in trip_paths
+            }
+            critical = None
+            high = None
+            for trip_point in trip_points:
+                path = os.path.join(base, trip_point + "_type")
+                trip_type = cat(path, fallback='').strip()
+                if trip_type == 'critical':
+                    critical = bcat(
+                        os.path.join(base, trip_point + "_temp"), fallback=None
+                    )
+                elif trip_type == 'high':
+                    high = bcat(
+                        os.path.join(base, trip_point + "_temp"), fallback=None
+                    )
+
+                if high is not None:
+                    try:
+                        high = float(high) / 1000.0
+                    except ValueError:
+                        high = None
+                if critical is not None:
+                    try:
+                        critical = float(critical) / 1000.0
+                    except ValueError:
+                        critical = None
+
+            ret[unit_name].append(('', current, high, critical))
+
+    return dict(ret)
+
+
+def sensors_fans():
+    """Return hardware fans info (for CPU and other peripherals) as a
+    dict including hardware label and current speed.
+
+    Implementation notes:
+    - /sys/class/hwmon looks like the most recent interface to
+      retrieve this info, and this implementation relies on it
+      only (old distros will probably use something else)
+    - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
+    """
+    ret = collections.defaultdict(list)
+    basenames = glob.glob('/sys/class/hwmon/hwmon*/fan*_*')
+    if not basenames:
+        # CentOS has an intermediate /device directory:
+        # https://github.com/giampaolo/psutil/issues/971
+        basenames = glob.glob('/sys/class/hwmon/hwmon*/device/fan*_*')
+
+    basenames = sorted({x.split("_")[0] for x in basenames})
+    for base in basenames:
+        try:
+            current = int(bcat(base + '_input'))
+        except OSError as err:
+            debug(err)
+            continue
+        unit_name = cat(os.path.join(os.path.dirname(base), 'name')).strip()
+        label = cat(base + '_label', fallback='').strip()
+        ret[unit_name].append(ntp.sfan(label, current))
+
+    return dict(ret)
+
+
+def sensors_battery():
+    """Return battery information.
+    Implementation note: it appears /sys/class/power_supply/BAT0/
+    directory structure may vary and provide files with the same
+    meaning but under different names, see:
+    https://github.com/giampaolo/psutil/issues/966.
+    """
+    null = object()
+
+    def multi_bcat(*paths):
+        """Attempt to read the content of multiple files which may
+        not exist. If none of them exist return None.
+        """
+        for path in paths:
+            ret = bcat(path, fallback=null)
+            if ret != null:
+                try:
+                    return int(ret)
+                except ValueError:
+                    return ret.strip()
+        return None
+
+    bats = [
+        x
+        for x in os.listdir(POWER_SUPPLY_PATH)
+        if x.startswith('BAT') or 'battery' in x.lower()
+    ]
+    if not bats:
+        return None
+    # Get the first available battery. Usually this is "BAT0", except
+    # some rare exceptions:
+    # https://github.com/giampaolo/psutil/issues/1238
+    root = os.path.join(POWER_SUPPLY_PATH, min(bats))
+
+    # Base metrics.
+    energy_now = multi_bcat(root + "/energy_now", root + "/charge_now")
+    power_now = multi_bcat(root + "/power_now", root + "/current_now")
+    energy_full = multi_bcat(root + "/energy_full", root + "/charge_full")
+    time_to_empty = multi_bcat(root + "/time_to_empty_now")
+
+    # Percent. If we have energy_full the percentage will be more
+    # accurate compared to reading /capacity file (float vs. int).
+    if energy_full is not None and energy_now is not None:
+        try:
+            percent = 100.0 * energy_now / energy_full
+        except ZeroDivisionError:
+            percent = 0.0
+    else:
+        percent = int(cat(root + "/capacity", fallback=-1))
+        if percent == -1:
+            return None
+
+    # Is AC power cable plugged in?
+    # Note: AC0 is not always available and sometimes (e.g. CentOS7)
+    # it's called "AC".
+    power_plugged = None
+    online = multi_bcat(
+        os.path.join(POWER_SUPPLY_PATH, "AC0/online"),
+        os.path.join(POWER_SUPPLY_PATH, "AC/online"),
+    )
+    if online is not None:
+        power_plugged = online == 1
+    else:
+        status = cat(root + "/status", fallback="").strip().lower()
+        if status == "discharging":
+            power_plugged = False
+        elif status in {"charging", "full"}:
+            power_plugged = True
+
+    # Seconds left.
+    # Note to self: we may also calculate the charging ETA as per:
+    # https://github.com/thialfihar/dotfiles/blob/
+    #     013937745fd9050c30146290e8f963d65c0179e6/bin/battery.py#L55
+    if power_plugged:
+        secsleft = _common.POWER_TIME_UNLIMITED
+    elif energy_now is not None and power_now is not None:
+        try:
+            secsleft = int(energy_now / abs(power_now) * 3600)
+        except ZeroDivisionError:
+            secsleft = _common.POWER_TIME_UNKNOWN
+    elif time_to_empty is not None:
+        secsleft = int(time_to_empty * 60)
+        if secsleft < 0:
+            secsleft = _common.POWER_TIME_UNKNOWN
+    else:
+        secsleft = _common.POWER_TIME_UNKNOWN
+
+    return ntp.sbattery(percent, secsleft, power_plugged)
+
+
+# =====================================================================
+# --- other system functions
+# =====================================================================
+
+
+def users():
+    """Return currently connected users as a list of namedtuples."""
+    retlist = []
+    rawlist = cext.users()
+    for item in rawlist:
+        user, tty, hostname, tstamp, pid = item
+        nt = ntp.suser(user, tty or None, hostname, tstamp, pid)
+        retlist.append(nt)
+    return retlist
+
+
+def boot_time():
+    """Return the system boot time expressed in seconds since the epoch."""
+    path = f"{get_procfs_path()}/stat"
+    with open_binary(path) as f:
+        for line in f:
+            if line.startswith(b'btime'):
+                return float(line.strip().split()[1])
+        msg = f"line 'btime' not found in {path}"
+        raise RuntimeError(msg)
+
+
+# =====================================================================
+# --- processes
+# =====================================================================
+
+
+def pids():
+    """Returns a list of PIDs currently running on the system."""
+    path = get_procfs_path().encode(ENCODING)
+    return [int(x) for x in os.listdir(path) if x.isdigit()]
+
+
+def pid_exists(pid):
+    """Check for the existence of a unix PID. Linux TIDs are not
+    supported (always return False).
+    """
+    if not _psposix.pid_exists(pid):
+        return False
+    else:
+        # Linux's apparently does not distinguish between PIDs and TIDs
+        # (thread IDs).
+        # listdir("/proc") won't show any TID (only PIDs) but
+        # os.stat("/proc/{tid}") will succeed if {tid} exists.
+        # os.kill() can also be passed a TID. This is quite confusing.
+        # In here we want to enforce this distinction and support PIDs
+        # only, see:
+        # https://github.com/giampaolo/psutil/issues/687
+        try:
+            # Note: already checked that this is faster than using a
+            # regular expr. Also (a lot) faster than doing
+            # 'return pid in pids()'
+            path = f"{get_procfs_path()}/{pid}/status"
+            with open_binary(path) as f:
+                for line in f:
+                    if line.startswith(b"Tgid:"):
+                        tgid = int(line.split()[1])
+                        # If tgid and pid are the same then we're
+                        # dealing with a process PID.
+                        return tgid == pid
+                msg = f"'Tgid' line not found in {path}"
+                raise ValueError(msg)
+        except (OSError, ValueError):
+            return pid in pids()
+
+
+def ppid_map():
+    """Obtain a {pid: ppid, ...} dict for all running processes in
+    one shot. Used to speed up Process.children().
+    """
+    ret = {}
+    procfs_path = get_procfs_path()
+    for pid in pids():
+        try:
+            with open_binary(f"{procfs_path}/{pid}/stat") as f:
+                data = f.read()
+        except (FileNotFoundError, ProcessLookupError):
+            pass
+        except PermissionError as err:
+            raise AccessDenied(pid) from err
+        else:
+            rpar = data.rfind(b')')
+            dset = data[rpar + 2 :].split()
+            ppid = int(dset[1])
+            ret[pid] = ppid
+    return ret
+
+
+def wrap_exceptions(fun):
+    """Decorator which translates bare OSError exceptions into
+    NoSuchProcess and AccessDenied.
+    """
+
+    @functools.wraps(fun)
+    def wrapper(self, *args, **kwargs):
+        pid, name = self.pid, self._name
+        try:
+            return fun(self, *args, **kwargs)
+        except PermissionError as err:
+            raise AccessDenied(pid, name) from err
+        except ProcessLookupError as err:
+            self._raise_if_zombie()
+            raise NoSuchProcess(pid, name) from err
+        except FileNotFoundError as err:
+            self._raise_if_zombie()
+            # /proc/PID directory may still exist, but the files within
+            # it may not, indicating the process is gone, see:
+            # https://github.com/giampaolo/psutil/issues/2418
+            if not os.path.exists(f"{self._procfs_path}/{pid}/stat"):
+                raise NoSuchProcess(pid, name) from err
+            raise
+
+    return wrapper
+
+
+class Process:
+    """Linux process implementation."""
+
+    __slots__ = [
+        "_cache",
+        "_ctime",
+        "_name",
+        "_ppid",
+        "_procfs_path",
+        "pid",
+    ]
+
+    def __init__(self, pid):
+        self.pid = pid
+        self._name = None
+        self._ppid = None
+        self._ctime = None
+        self._procfs_path = get_procfs_path()
+
+    def _is_zombie(self):
+        # Note: most of the times Linux is able to return info about the
+        # process even if it's a zombie, and /proc/{pid} will exist.
+        # There are some exceptions though, like exe(), cmdline() and
+        # memory_maps(). In these cases /proc/{pid}/{file} exists but
+        # it's empty. Instead of returning a "null" value we'll raise an
+        # exception.
+        try:
+            data = bcat(f"{self._procfs_path}/{self.pid}/stat")
+        except OSError:
+            return False
+        else:
+            rpar = data.rfind(b')')
+            status = data[rpar + 2 : rpar + 3]
+            return status == b"Z"
+
+    def _raise_if_zombie(self):
+        if self._is_zombie():
+            raise ZombieProcess(self.pid, self._name, self._ppid)
+
+    def _raise_if_not_alive(self):
+        """Raise NSP if the process disappeared on us."""
+        # For those C function who do not raise NSP, possibly returning
+        # incorrect or incomplete result.
+        os.stat(f"{self._procfs_path}/{self.pid}")
+
+    def _readlink(self, path, fallback=UNSET):
+        # * https://github.com/giampaolo/psutil/issues/503
+        #   os.readlink('/proc/pid/exe') may raise ESRCH (ProcessLookupError)
+        #   instead of ENOENT (FileNotFoundError) when it races.
+        # * ENOENT may occur also if the path actually exists if PID is
+        #   a low PID (~0-20 range).
+        # * https://github.com/giampaolo/psutil/issues/2514
+        try:
+            return readlink(path)
+        except (FileNotFoundError, ProcessLookupError):
+            if os.path.lexists(f"{self._procfs_path}/{self.pid}"):
+                self._raise_if_zombie()
+                if fallback is not UNSET:
+                    return fallback
+            raise
+
+    @wrap_exceptions
+    @memoize_when_activated
+    def _parse_stat_file(self):
+        """Parse /proc/{pid}/stat file and return a dict with various
+        process info.
+        Using "man proc" as a reference: where "man proc" refers to
+        position N always subtract 3 (e.g ppid position 4 in
+        'man proc' == position 1 in here).
+        The return value is cached in case oneshot() ctx manager is
+        in use.
+        """
+        data = bcat(f"{self._procfs_path}/{self.pid}/stat")
+        # Process name is between parentheses. It can contain spaces and
+        # other parentheses. This is taken into account by looking for
+        # the first occurrence of "(" and the last occurrence of ")".
+        rpar = data.rfind(b')')
+        name = data[data.find(b'(') + 1 : rpar]
+        fields = data[rpar + 2 :].split()
+
+        ret = {}
+        ret['name'] = name
+        ret['status'] = fields[0]
+        ret['ppid'] = fields[1]
+        ret['ttynr'] = fields[4]
+        ret['utime'] = fields[11]
+        ret['stime'] = fields[12]
+        ret['children_utime'] = fields[13]
+        ret['children_stime'] = fields[14]
+        ret['create_time'] = fields[19]
+        ret['cpu_num'] = fields[36]
+        try:
+            ret['blkio_ticks'] = fields[39]  # aka 'delayacct_blkio_ticks'
+        except IndexError:
+            # https://github.com/giampaolo/psutil/issues/2455
+            debug("can't get blkio_ticks, set iowait to 0")
+            ret['blkio_ticks'] = 0
+
+        return ret
+
+    @wrap_exceptions
+    @memoize_when_activated
+    def _read_status_file(self):
+        """Read /proc/{pid}/stat file and return its content.
+        The return value is cached in case oneshot() ctx manager is
+        in use.
+        """
+        with open_binary(f"{self._procfs_path}/{self.pid}/status") as f:
+            return f.read()
+
+    @wrap_exceptions
+    @memoize_when_activated
+    def _read_smaps_file(self):
+        with open_binary(f"{self._procfs_path}/{self.pid}/smaps") as f:
+            return f.read().strip()
+
+    def oneshot_enter(self):
+        self._parse_stat_file.cache_activate(self)
+        self._read_status_file.cache_activate(self)
+        self._read_smaps_file.cache_activate(self)
+
+    def oneshot_exit(self):
+        self._parse_stat_file.cache_deactivate(self)
+        self._read_status_file.cache_deactivate(self)
+        self._read_smaps_file.cache_deactivate(self)
+
+    @wrap_exceptions
+    def name(self):
+        # XXX - gets changed later and probably needs refactoring
+        return decode(self._parse_stat_file()['name'])
+
+    @wrap_exceptions
+    def exe(self):
+        return self._readlink(
+            f"{self._procfs_path}/{self.pid}/exe", fallback=""
+        )
+
+    @wrap_exceptions
+    def cmdline(self):
+        with open_text(f"{self._procfs_path}/{self.pid}/cmdline") as f:
+            data = f.read()
+        if not data:
+            # may happen in case of zombie process
+            self._raise_if_zombie()
+            return []
+        # 'man proc' states that args are separated by null bytes '\0'
+        # and last char is supposed to be a null byte. Nevertheless
+        # some processes may change their cmdline after being started
+        # (via setproctitle() or similar), they are usually not
+        # compliant with this rule and use spaces instead. Google
+        # Chrome process is an example. See:
+        # https://github.com/giampaolo/psutil/issues/1179
+        sep = '\x00' if data.endswith('\x00') else ' '
+        if data.endswith(sep):
+            data = data[:-1]
+        cmdline = data.split(sep)
+        # Sometimes last char is a null byte '\0' but the args are
+        # separated by spaces, see: https://github.com/giampaolo/psutil/
+        # issues/1179#issuecomment-552984549
+        if sep == '\x00' and len(cmdline) == 1 and ' ' in data:
+            cmdline = data.split(' ')
+        return cmdline
+
+    @wrap_exceptions
+    def environ(self):
+        with open_text(f"{self._procfs_path}/{self.pid}/environ") as f:
+            data = f.read()
+        return parse_environ_block(data)
+
+    @wrap_exceptions
+    def terminal(self):
+        tty_nr = int(self._parse_stat_file()['ttynr'])
+        tmap = _psposix.get_terminal_map()
+        try:
+            return tmap[tty_nr]
+        except KeyError:
+            return None
+
+    # May not be available on old kernels.
+    if os.path.exists(f"/proc/{os.getpid()}/io"):
+
+        @wrap_exceptions
+        def io_counters(self):
+            fname = f"{self._procfs_path}/{self.pid}/io"
+            fields = {}
+            with open_binary(fname) as f:
+                for line in f:
+                    # https://github.com/giampaolo/psutil/issues/1004
+                    line = line.strip()
+                    if line:
+                        try:
+                            name, value = line.split(b': ')
+                        except ValueError:
+                            # https://github.com/giampaolo/psutil/issues/1004
+                            continue
+                        else:
+                            fields[name] = int(value)
+            if not fields:
+                msg = f"{fname} file was empty"
+                raise RuntimeError(msg)
+            try:
+                return ntp.pio(
+                    fields[b'syscr'],  # read syscalls
+                    fields[b'syscw'],  # write syscalls
+                    fields[b'read_bytes'],  # read bytes
+                    fields[b'write_bytes'],  # write bytes
+                    fields[b'rchar'],  # read chars
+                    fields[b'wchar'],  # write chars
+                )
+            except KeyError as err:
+                msg = (
+                    f"{err.args[0]!r} field was not found in {fname}; found"
+                    f" fields are {fields!r}"
+                )
+                raise ValueError(msg) from None
+
+    @wrap_exceptions
+    def cpu_times(self):
+        values = self._parse_stat_file()
+        utime = float(values['utime']) / CLOCK_TICKS
+        stime = float(values['stime']) / CLOCK_TICKS
+        children_utime = float(values['children_utime']) / CLOCK_TICKS
+        children_stime = float(values['children_stime']) / CLOCK_TICKS
+        iowait = float(values['blkio_ticks']) / CLOCK_TICKS
+        return ntp.pcputimes(
+            utime, stime, children_utime, children_stime, iowait
+        )
+
+    @wrap_exceptions
+    def cpu_num(self):
+        """What CPU the process is on."""
+        return int(self._parse_stat_file()['cpu_num'])
+
+    @wrap_exceptions
+    def wait(self, timeout=None):
+        return _psposix.wait_pid(self.pid, timeout)
+
+    @wrap_exceptions
+    def create_time(self, monotonic=False):
+        # The 'starttime' field in /proc/[pid]/stat is expressed in
+        # jiffies (clock ticks per second), a relative value which
+        # represents the number of clock ticks that have passed since
+        # the system booted until the process was created. It never
+        # changes and is unaffected by system clock updates.
+        if self._ctime is None:
+            self._ctime = (
+                float(self._parse_stat_file()['create_time']) / CLOCK_TICKS
+            )
+        if monotonic:
+            return self._ctime
+        # Add the boot time, returning time expressed in seconds since
+        # the epoch. This is subject to system clock updates.
+        return self._ctime + boot_time()
+
+    @wrap_exceptions
+    def memory_info(self):
+        #  ============================================================
+        # | FIELD  | DESCRIPTION                         | AKA  | TOP  |
+        #  ============================================================
+        # | rss    | resident set size                   |      | RES  |
+        # | vms    | total program size                  | size | VIRT |
+        # | shared | shared pages (from shared mappings) |      | SHR  |
+        # | text   | text ('code')                       | trs  | CODE |
+        # | lib    | library (unused in Linux 2.6)       | lrs  |      |
+        # | data   | data + stack                        | drs  | DATA |
+        # | dirty  | dirty pages (unused in Linux 2.6)   | dt   |      |
+        #  ============================================================
+        with open_binary(f"{self._procfs_path}/{self.pid}/statm") as f:
+            vms, rss, shared, text, lib, data, dirty = (
+                int(x) * PAGESIZE for x in f.readline().split()[:7]
+            )
+        return ntp.pmem(rss, vms, shared, text, lib, data, dirty)
+
+    if HAS_PROC_SMAPS_ROLLUP or HAS_PROC_SMAPS:
+
+        def _parse_smaps_rollup(self):
+            # /proc/pid/smaps_rollup was added to Linux in 2017. Faster
+            # than /proc/pid/smaps. It reports higher PSS than */smaps
+            # (from 1k up to 200k higher; tested against all processes).
+            # IMPORTANT: /proc/pid/smaps_rollup is weird, because it
+            # raises ESRCH / ENOENT for many PIDs, even if they're alive
+            # (also as root). In that case we'll use /proc/pid/smaps as
+            # fallback, which is slower but has a +50% success rate
+            # compared to /proc/pid/smaps_rollup.
+            uss = pss = swap = 0
+            with open_binary(
+                f"{self._procfs_path}/{self.pid}/smaps_rollup"
+            ) as f:
+                for line in f:
+                    if line.startswith(b"Private_"):
+                        # Private_Clean, Private_Dirty, Private_Hugetlb
+                        uss += int(line.split()[1]) * 1024
+                    elif line.startswith(b"Pss:"):
+                        pss = int(line.split()[1]) * 1024
+                    elif line.startswith(b"Swap:"):
+                        swap = int(line.split()[1]) * 1024
+            return (uss, pss, swap)
+
+        @wrap_exceptions
+        def _parse_smaps(
+            self,
+            # Gets Private_Clean, Private_Dirty, Private_Hugetlb.
+            _private_re=re.compile(br"\nPrivate.*:\s+(\d+)"),
+            _pss_re=re.compile(br"\nPss\:\s+(\d+)"),
+            _swap_re=re.compile(br"\nSwap\:\s+(\d+)"),
+        ):
+            # /proc/pid/smaps does not exist on kernels < 2.6.14 or if
+            # CONFIG_MMU kernel configuration option is not enabled.
+
+            # Note: using 3 regexes is faster than reading the file
+            # line by line.
+            #
+            # You might be tempted to calculate USS by subtracting
+            # the "shared" value from the "resident" value in
+            # /proc//statm. But at least on Linux, statm's "shared"
+            # value actually counts pages backed by files, which has
+            # little to do with whether the pages are actually shared.
+            # /proc/self/smaps on the other hand appears to give us the
+            # correct information.
+            smaps_data = self._read_smaps_file()
+            # Note: smaps file can be empty for certain processes.
+            # The code below will not crash though and will result to 0.
+            uss = sum(map(int, _private_re.findall(smaps_data))) * 1024
+            pss = sum(map(int, _pss_re.findall(smaps_data))) * 1024
+            swap = sum(map(int, _swap_re.findall(smaps_data))) * 1024
+            return (uss, pss, swap)
+
+        @wrap_exceptions
+        def memory_full_info(self):
+            if HAS_PROC_SMAPS_ROLLUP:  # faster
+                try:
+                    uss, pss, swap = self._parse_smaps_rollup()
+                except (ProcessLookupError, FileNotFoundError):
+                    uss, pss, swap = self._parse_smaps()
+            else:
+                uss, pss, swap = self._parse_smaps()
+            basic_mem = self.memory_info()
+            return ntp.pfullmem(*basic_mem + (uss, pss, swap))
+
+    else:
+        memory_full_info = memory_info
+
+    if HAS_PROC_SMAPS:
+
+        @wrap_exceptions
+        def memory_maps(self):
+            """Return process's mapped memory regions as a list of named
+            tuples. Fields are explained in 'man proc'; here is an updated
+            (Apr 2012) version: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/filesystems/proc.txt?id=b76437579d1344b612cf1851ae610c636cec7db0.
+
+            /proc/{PID}/smaps does not exist on kernels < 2.6.14 or if
+            CONFIG_MMU kernel configuration option is not enabled.
+            """
+
+            def get_blocks(lines, current_block):
+                data = {}
+                for line in lines:
+                    fields = line.split(None, 5)
+                    if not fields[0].endswith(b':'):
+                        # new block section
+                        yield (current_block.pop(), data)
+                        current_block.append(line)
+                    else:
+                        try:
+                            data[fields[0]] = int(fields[1]) * 1024
+                        except (ValueError, IndexError):
+                            if fields[0].startswith(b'VmFlags:'):
+                                # see issue #369
+                                continue
+                            msg = f"don't know how to interpret line {line!r}"
+                            raise ValueError(msg) from None
+                yield (current_block.pop(), data)
+
+            data = self._read_smaps_file()
+            # Note: smaps file can be empty for certain processes or for
+            # zombies.
+            if not data:
+                self._raise_if_zombie()
+                return []
+            lines = data.split(b'\n')
+            ls = []
+            first_line = lines.pop(0)
+            current_block = [first_line]
+            for header, data in get_blocks(lines, current_block):
+                hfields = header.split(None, 5)
+                try:
+                    addr, perms, _offset, _dev, _inode, path = hfields
+                except ValueError:
+                    addr, perms, _offset, _dev, _inode, path = hfields + ['']
+                if not path:
+                    path = '[anon]'
+                else:
+                    path = decode(path)
+                    path = path.strip()
+                    if path.endswith(' (deleted)') and not path_exists_strict(
+                        path
+                    ):
+                        path = path[:-10]
+                item = (
+                    decode(addr),
+                    decode(perms),
+                    path,
+                    data.get(b'Rss:', 0),
+                    data.get(b'Size:', 0),
+                    data.get(b'Pss:', 0),
+                    data.get(b'Shared_Clean:', 0),
+                    data.get(b'Shared_Dirty:', 0),
+                    data.get(b'Private_Clean:', 0),
+                    data.get(b'Private_Dirty:', 0),
+                    data.get(b'Referenced:', 0),
+                    data.get(b'Anonymous:', 0),
+                    data.get(b'Swap:', 0),
+                )
+                ls.append(item)
+            return ls
+
+    @wrap_exceptions
+    def cwd(self):
+        return self._readlink(
+            f"{self._procfs_path}/{self.pid}/cwd", fallback=""
+        )
+
+    @wrap_exceptions
+    def num_ctx_switches(
+        self, _ctxsw_re=re.compile(br'ctxt_switches:\t(\d+)')
+    ):
+        data = self._read_status_file()
+        ctxsw = _ctxsw_re.findall(data)
+        if not ctxsw:
+            msg = (
+                "'voluntary_ctxt_switches' and"
+                " 'nonvoluntary_ctxt_switches'lines were not found in"
+                f" {self._procfs_path}/{self.pid}/status; the kernel is"
+                " probably older than 2.6.23"
+            )
+            raise NotImplementedError(msg)
+        return ntp.pctxsw(int(ctxsw[0]), int(ctxsw[1]))
+
+    @wrap_exceptions
+    def num_threads(self, _num_threads_re=re.compile(br'Threads:\t(\d+)')):
+        # Using a re is faster than iterating over file line by line.
+        data = self._read_status_file()
+        return int(_num_threads_re.findall(data)[0])
+
+    @wrap_exceptions
+    def threads(self):
+        thread_ids = os.listdir(f"{self._procfs_path}/{self.pid}/task")
+        thread_ids.sort()
+        retlist = []
+        hit_enoent = False
+        for thread_id in thread_ids:
+            fname = f"{self._procfs_path}/{self.pid}/task/{thread_id}/stat"
+            try:
+                with open_binary(fname) as f:
+                    st = f.read().strip()
+            except (FileNotFoundError, ProcessLookupError):
+                # no such file or directory or no such process;
+                # it means thread disappeared on us
+                hit_enoent = True
+                continue
+            # ignore the first two values ("pid (exe)")
+            st = st[st.find(b')') + 2 :]
+            values = st.split(b' ')
+            utime = float(values[11]) / CLOCK_TICKS
+            stime = float(values[12]) / CLOCK_TICKS
+            ntuple = ntp.pthread(int(thread_id), utime, stime)
+            retlist.append(ntuple)
+        if hit_enoent:
+            self._raise_if_not_alive()
+        return retlist
+
+    @wrap_exceptions
+    def nice_get(self):
+        # with open_text(f"{self._procfs_path}/{self.pid}/stat") as f:
+        #   data = f.read()
+        #   return int(data.split()[18])
+
+        # Use C implementation
+        return cext.proc_priority_get(self.pid)
+
+    @wrap_exceptions
+    def nice_set(self, value):
+        return cext.proc_priority_set(self.pid, value)
+
+    # starting from CentOS 6.
+    if HAS_CPU_AFFINITY:
+
+        @wrap_exceptions
+        def cpu_affinity_get(self):
+            return cext.proc_cpu_affinity_get(self.pid)
+
+        def _get_eligible_cpus(
+            self, _re=re.compile(br"Cpus_allowed_list:\t(\d+)-(\d+)")
+        ):
+            # See: https://github.com/giampaolo/psutil/issues/956
+            data = self._read_status_file()
+            match = _re.findall(data)
+            if match:
+                return list(range(int(match[0][0]), int(match[0][1]) + 1))
+            else:
+                return list(range(len(per_cpu_times())))
+
+        @wrap_exceptions
+        def cpu_affinity_set(self, cpus):
+            try:
+                cext.proc_cpu_affinity_set(self.pid, cpus)
+            except (OSError, ValueError) as err:
+                if isinstance(err, ValueError) or err.errno == errno.EINVAL:
+                    eligible_cpus = self._get_eligible_cpus()
+                    all_cpus = tuple(range(len(per_cpu_times())))
+                    for cpu in cpus:
+                        if cpu not in all_cpus:
+                            msg = (
+                                f"invalid CPU {cpu!r}; choose between"
+                                f" {eligible_cpus!r}"
+                            )
+                            raise ValueError(msg) from None
+                        if cpu not in eligible_cpus:
+                            msg = (
+                                f"CPU number {cpu} is not eligible; choose"
+                                f" between {eligible_cpus}"
+                            )
+                            raise ValueError(msg) from err
+                raise
+
+    # only starting from kernel 2.6.13
+    if HAS_PROC_IO_PRIORITY:
+
+        @wrap_exceptions
+        def ionice_get(self):
+            ioclass, value = cext.proc_ioprio_get(self.pid)
+            ioclass = IOPriority(ioclass)
+            return ntp.pionice(ioclass, value)
+
+        @wrap_exceptions
+        def ionice_set(self, ioclass, value):
+            if value is None:
+                value = 0
+            if value and ioclass in {
+                IOPriority.IOPRIO_CLASS_IDLE,
+                IOPriority.IOPRIO_CLASS_NONE,
+            }:
+                msg = f"{ioclass!r} ioclass accepts no value"
+                raise ValueError(msg)
+            if value < 0 or value > 7:
+                msg = "value not in 0-7 range"
+                raise ValueError(msg)
+            return cext.proc_ioprio_set(self.pid, ioclass, value)
+
+    if hasattr(resource, "prlimit"):
+
+        @wrap_exceptions
+        def rlimit(self, resource_, limits=None):
+            # If pid is 0 prlimit() applies to the calling process and
+            # we don't want that. We should never get here though as
+            # PID 0 is not supported on Linux.
+            if self.pid == 0:
+                msg = "can't use prlimit() against PID 0 process"
+                raise ValueError(msg)
+            try:
+                if limits is None:
+                    # get
+                    return resource.prlimit(self.pid, resource_)
+                else:
+                    # set
+                    if len(limits) != 2:
+                        msg = (
+                            "second argument must be a (soft, hard) "
+                            f"tuple, got {limits!r}"
+                        )
+                        raise ValueError(msg)
+                    resource.prlimit(self.pid, resource_, limits)
+            except OSError as err:
+                if err.errno == errno.ENOSYS:
+                    # I saw this happening on Travis:
+                    # https://travis-ci.org/giampaolo/psutil/jobs/51368273
+                    self._raise_if_zombie()
+                raise
+
+    @wrap_exceptions
+    def status(self):
+        letter = self._parse_stat_file()['status']
+        letter = letter.decode()
+        # XXX is '?' legit? (we're not supposed to return it anyway)
+        return PROC_STATUSES.get(letter, '?')
+
+    @wrap_exceptions
+    def open_files(self):
+        retlist = []
+        files = os.listdir(f"{self._procfs_path}/{self.pid}/fd")
+        hit_enoent = False
+        for fd in files:
+            file = f"{self._procfs_path}/{self.pid}/fd/{fd}"
+            try:
+                path = readlink(file)
+            except (FileNotFoundError, ProcessLookupError):
+                # ENOENT == file which is gone in the meantime
+                hit_enoent = True
+                continue
+            except OSError as err:
+                if err.errno == errno.EINVAL:
+                    # not a link
+                    continue
+                if err.errno == errno.ENAMETOOLONG:
+                    # file name too long
+                    debug(err)
+                    continue
+                raise
+            else:
+                # If path is not an absolute there's no way to tell
+                # whether it's a regular file or not, so we skip it.
+                # A regular file is always supposed to be have an
+                # absolute path though.
+                if path.startswith('/') and isfile_strict(path):
+                    # Get file position and flags.
+                    file = f"{self._procfs_path}/{self.pid}/fdinfo/{fd}"
+                    try:
+                        with open_binary(file) as f:
+                            pos = int(f.readline().split()[1])
+                            flags = int(f.readline().split()[1], 8)
+                    except (FileNotFoundError, ProcessLookupError):
+                        # fd gone in the meantime; process may
+                        # still be alive
+                        hit_enoent = True
+                    else:
+                        mode = file_flags_to_mode(flags)
+                        ntuple = ntp.popenfile(
+                            path, int(fd), int(pos), mode, flags
+                        )
+                        retlist.append(ntuple)
+        if hit_enoent:
+            self._raise_if_not_alive()
+        return retlist
+
+    @wrap_exceptions
+    def net_connections(self, kind='inet'):
+        ret = _net_connections.retrieve(kind, self.pid)
+        self._raise_if_not_alive()
+        return ret
+
+    @wrap_exceptions
+    def num_fds(self):
+        return len(os.listdir(f"{self._procfs_path}/{self.pid}/fd"))
+
+    @wrap_exceptions
+    def ppid(self):
+        return int(self._parse_stat_file()['ppid'])
+
+    @wrap_exceptions
+    def uids(self, _uids_re=re.compile(br'Uid:\t(\d+)\t(\d+)\t(\d+)')):
+        data = self._read_status_file()
+        real, effective, saved = _uids_re.findall(data)[0]
+        return ntp.puids(int(real), int(effective), int(saved))
+
+    @wrap_exceptions
+    def gids(self, _gids_re=re.compile(br'Gid:\t(\d+)\t(\d+)\t(\d+)')):
+        data = self._read_status_file()
+        real, effective, saved = _gids_re.findall(data)[0]
+        return ntp.pgids(int(real), int(effective), int(saved))
diff --git a/micromamba_root/Lib/site-packages/psutil/_psosx.py b/micromamba_root/Lib/site-packages/psutil/_psosx.py
new file mode 100644
index 0000000000000000000000000000000000000000..b14d5e023bec1f9cb5cb06b4caf7170489f3d4c7
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil/_psosx.py
@@ -0,0 +1,549 @@
+# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""macOS platform implementation."""
+
+import errno
+import functools
+import os
+
+from . import _common
+from . import _ntuples as ntp
+from . import _psposix
+from . import _psutil_osx as cext
+from ._common import AccessDenied
+from ._common import NoSuchProcess
+from ._common import ZombieProcess
+from ._common import conn_tmap
+from ._common import conn_to_ntuple
+from ._common import debug
+from ._common import isfile_strict
+from ._common import memoize_when_activated
+from ._common import parse_environ_block
+from ._common import usage_percent
+
+__extra__all__ = []
+
+
+# =====================================================================
+# --- globals
+# =====================================================================
+
+
+PAGESIZE = cext.getpagesize()
+AF_LINK = cext.AF_LINK
+
+TCP_STATUSES = {
+    cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
+    cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
+    cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
+    cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
+    cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
+    cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
+    cext.TCPS_CLOSED: _common.CONN_CLOSE,
+    cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
+    cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
+    cext.TCPS_LISTEN: _common.CONN_LISTEN,
+    cext.TCPS_CLOSING: _common.CONN_CLOSING,
+    cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
+}
+
+PROC_STATUSES = {
+    cext.SIDL: _common.STATUS_IDLE,
+    cext.SRUN: _common.STATUS_RUNNING,
+    cext.SSLEEP: _common.STATUS_SLEEPING,
+    cext.SSTOP: _common.STATUS_STOPPED,
+    cext.SZOMB: _common.STATUS_ZOMBIE,
+}
+
+kinfo_proc_map = dict(
+    ppid=0,
+    ruid=1,
+    euid=2,
+    suid=3,
+    rgid=4,
+    egid=5,
+    sgid=6,
+    ttynr=7,
+    ctime=8,
+    status=9,
+    name=10,
+)
+
+pidtaskinfo_map = dict(
+    cpuutime=0,
+    cpustime=1,
+    rss=2,
+    vms=3,
+    pfaults=4,
+    pageins=5,
+    numthreads=6,
+    volctxsw=7,
+)
+
+
+# =====================================================================
+# --- memory
+# =====================================================================
+
+
+def virtual_memory():
+    """System virtual memory as a namedtuple."""
+    total, active, inactive, wired, free, speculative = cext.virtual_mem()
+    # This is how Zabbix calculate avail and used mem:
+    # https://github.com/zabbix/zabbix/blob/master/src/libs/zbxsysinfo/osx/memory.c
+    # Also see: https://github.com/giampaolo/psutil/issues/1277
+    avail = inactive + free
+    used = active + wired
+    # This is NOT how Zabbix calculates free mem but it matches "free"
+    # cmdline utility.
+    free -= speculative
+    percent = usage_percent((total - avail), total, round_=1)
+    return ntp.svmem(
+        total, avail, percent, used, free, active, inactive, wired
+    )
+
+
+def swap_memory():
+    """Swap system memory as a (total, used, free, sin, sout) tuple."""
+    total, used, free, sin, sout = cext.swap_mem()
+    percent = usage_percent(used, total, round_=1)
+    return ntp.sswap(total, used, free, percent, sin, sout)
+
+
+# malloc / heap functions
+heap_info = cext.heap_info
+heap_trim = cext.heap_trim
+
+
+# =====================================================================
+# --- CPU
+# =====================================================================
+
+
+def cpu_times():
+    """Return system CPU times as a namedtuple."""
+    user, nice, system, idle = cext.cpu_times()
+    return ntp.scputimes(user, nice, system, idle)
+
+
+def per_cpu_times():
+    """Return system CPU times as a named tuple."""
+    ret = []
+    for cpu_t in cext.per_cpu_times():
+        user, nice, system, idle = cpu_t
+        item = ntp.scputimes(user, nice, system, idle)
+        ret.append(item)
+    return ret
+
+
+def cpu_count_logical():
+    """Return the number of logical CPUs in the system."""
+    return cext.cpu_count_logical()
+
+
+def cpu_count_cores():
+    """Return the number of CPU cores in the system."""
+    return cext.cpu_count_cores()
+
+
+def cpu_stats():
+    ctx_switches, interrupts, soft_interrupts, syscalls, _traps = (
+        cext.cpu_stats()
+    )
+    return ntp.scpustats(ctx_switches, interrupts, soft_interrupts, syscalls)
+
+
+if cext.has_cpu_freq():  # not always available on ARM64
+
+    def cpu_freq():
+        """Return CPU frequency.
+        On macOS per-cpu frequency is not supported.
+        Also, the returned frequency never changes, see:
+        https://arstechnica.com/civis/viewtopic.php?f=19&t=465002.
+        """
+        curr, min_, max_ = cext.cpu_freq()
+        return [ntp.scpufreq(curr, min_, max_)]
+
+
+# =====================================================================
+# --- disks
+# =====================================================================
+
+
+disk_usage = _psposix.disk_usage
+disk_io_counters = cext.disk_io_counters
+
+
+def disk_partitions(all=False):
+    """Return mounted disk partitions as a list of namedtuples."""
+    retlist = []
+    partitions = cext.disk_partitions()
+    for partition in partitions:
+        device, mountpoint, fstype, opts = partition
+        if device == 'none':
+            device = ''
+        if not all:
+            if not os.path.isabs(device) or not os.path.exists(device):
+                continue
+        ntuple = ntp.sdiskpart(device, mountpoint, fstype, opts)
+        retlist.append(ntuple)
+    return retlist
+
+
+# =====================================================================
+# --- sensors
+# =====================================================================
+
+
+def sensors_battery():
+    """Return battery information."""
+    try:
+        percent, minsleft, power_plugged = cext.sensors_battery()
+    except NotImplementedError:
+        # no power source - return None according to interface
+        return None
+    power_plugged = power_plugged == 1
+    if power_plugged:
+        secsleft = _common.POWER_TIME_UNLIMITED
+    elif minsleft == -1:
+        secsleft = _common.POWER_TIME_UNKNOWN
+    else:
+        secsleft = minsleft * 60
+    return ntp.sbattery(percent, secsleft, power_plugged)
+
+
+# =====================================================================
+# --- network
+# =====================================================================
+
+
+net_io_counters = cext.net_io_counters
+net_if_addrs = cext.net_if_addrs
+
+
+def net_connections(kind='inet'):
+    """System-wide network connections."""
+    # Note: on macOS this will fail with AccessDenied unless
+    # the process is owned by root.
+    ret = []
+    for pid in pids():
+        try:
+            cons = Process(pid).net_connections(kind)
+        except NoSuchProcess:
+            continue
+        else:
+            if cons:
+                for c in cons:
+                    c = list(c) + [pid]
+                    ret.append(ntp.sconn(*c))
+    return ret
+
+
+def net_if_stats():
+    """Get NIC stats (isup, duplex, speed, mtu)."""
+    names = net_io_counters().keys()
+    ret = {}
+    for name in names:
+        try:
+            mtu = cext.net_if_mtu(name)
+            flags = cext.net_if_flags(name)
+            duplex, speed = cext.net_if_duplex_speed(name)
+        except OSError as err:
+            # https://github.com/giampaolo/psutil/issues/1279
+            if err.errno != errno.ENODEV:
+                raise
+        else:
+            if hasattr(_common, 'NicDuplex'):
+                duplex = _common.NicDuplex(duplex)
+            output_flags = ','.join(flags)
+            isup = 'running' in flags
+            ret[name] = ntp.snicstats(isup, duplex, speed, mtu, output_flags)
+    return ret
+
+
+# =====================================================================
+# --- other system functions
+# =====================================================================
+
+
+def boot_time():
+    """The system boot time expressed in seconds since the epoch."""
+    return cext.boot_time()
+
+
+try:
+    INIT_BOOT_TIME = boot_time()
+except Exception as err:  # noqa: BLE001
+    # Don't want to crash at import time.
+    debug(f"ignoring exception on import: {err!r}")
+    INIT_BOOT_TIME = 0
+
+
+def adjust_proc_create_time(ctime):
+    """Account for system clock updates."""
+    if INIT_BOOT_TIME == 0:
+        return ctime
+
+    diff = INIT_BOOT_TIME - boot_time()
+    if diff == 0 or abs(diff) < 1:
+        return ctime
+
+    debug("system clock was updated; adjusting process create_time()")
+    if diff < 0:
+        return ctime - diff
+    return ctime + diff
+
+
+def users():
+    """Return currently connected users as a list of namedtuples."""
+    retlist = []
+    rawlist = cext.users()
+    for item in rawlist:
+        user, tty, hostname, tstamp, pid = item
+        if tty == '~':
+            continue  # reboot or shutdown
+        if not tstamp:
+            continue
+        nt = ntp.suser(user, tty or None, hostname or None, tstamp, pid)
+        retlist.append(nt)
+    return retlist
+
+
+# =====================================================================
+# --- processes
+# =====================================================================
+
+
+def pids():
+    ls = cext.pids()
+    if 0 not in ls:
+        # On certain macOS versions pids() C doesn't return PID 0 but
+        # "ps" does and the process is querable via sysctl():
+        # https://travis-ci.org/giampaolo/psutil/jobs/309619941
+        try:
+            Process(0).create_time()
+            ls.insert(0, 0)
+        except NoSuchProcess:
+            pass
+        except AccessDenied:
+            ls.insert(0, 0)
+    return ls
+
+
+pid_exists = _psposix.pid_exists
+
+
+def wrap_exceptions(fun):
+    """Decorator which translates bare OSError exceptions into
+    NoSuchProcess and AccessDenied.
+    """
+
+    @functools.wraps(fun)
+    def wrapper(self, *args, **kwargs):
+        pid, ppid, name = self.pid, self._ppid, self._name
+        try:
+            return fun(self, *args, **kwargs)
+        except ProcessLookupError as err:
+            if cext.proc_is_zombie(pid):
+                raise ZombieProcess(pid, name, ppid) from err
+            raise NoSuchProcess(pid, name) from err
+        except PermissionError as err:
+            raise AccessDenied(pid, name) from err
+        except cext.ZombieProcessError as err:
+            raise ZombieProcess(pid, name, ppid) from err
+
+    return wrapper
+
+
+class Process:
+    """Wrapper class around underlying C implementation."""
+
+    __slots__ = ["_cache", "_name", "_ppid", "pid"]
+
+    def __init__(self, pid):
+        self.pid = pid
+        self._name = None
+        self._ppid = None
+
+    @wrap_exceptions
+    @memoize_when_activated
+    def _get_kinfo_proc(self):
+        # Note: should work with all PIDs without permission issues.
+        ret = cext.proc_kinfo_oneshot(self.pid)
+        assert len(ret) == len(kinfo_proc_map)
+        return ret
+
+    @wrap_exceptions
+    @memoize_when_activated
+    def _get_pidtaskinfo(self):
+        # Note: should work for PIDs owned by user only.
+        ret = cext.proc_pidtaskinfo_oneshot(self.pid)
+        assert len(ret) == len(pidtaskinfo_map)
+        return ret
+
+    def oneshot_enter(self):
+        self._get_kinfo_proc.cache_activate(self)
+        self._get_pidtaskinfo.cache_activate(self)
+
+    def oneshot_exit(self):
+        self._get_kinfo_proc.cache_deactivate(self)
+        self._get_pidtaskinfo.cache_deactivate(self)
+
+    @wrap_exceptions
+    def name(self):
+        name = self._get_kinfo_proc()[kinfo_proc_map['name']]
+        return name if name is not None else cext.proc_name(self.pid)
+
+    @wrap_exceptions
+    def exe(self):
+        return cext.proc_exe(self.pid)
+
+    @wrap_exceptions
+    def cmdline(self):
+        return cext.proc_cmdline(self.pid)
+
+    @wrap_exceptions
+    def environ(self):
+        return parse_environ_block(cext.proc_environ(self.pid))
+
+    @wrap_exceptions
+    def ppid(self):
+        self._ppid = self._get_kinfo_proc()[kinfo_proc_map['ppid']]
+        return self._ppid
+
+    @wrap_exceptions
+    def cwd(self):
+        return cext.proc_cwd(self.pid)
+
+    @wrap_exceptions
+    def uids(self):
+        rawtuple = self._get_kinfo_proc()
+        return ntp.puids(
+            rawtuple[kinfo_proc_map['ruid']],
+            rawtuple[kinfo_proc_map['euid']],
+            rawtuple[kinfo_proc_map['suid']],
+        )
+
+    @wrap_exceptions
+    def gids(self):
+        rawtuple = self._get_kinfo_proc()
+        return ntp.puids(
+            rawtuple[kinfo_proc_map['rgid']],
+            rawtuple[kinfo_proc_map['egid']],
+            rawtuple[kinfo_proc_map['sgid']],
+        )
+
+    @wrap_exceptions
+    def terminal(self):
+        tty_nr = self._get_kinfo_proc()[kinfo_proc_map['ttynr']]
+        tmap = _psposix.get_terminal_map()
+        try:
+            return tmap[tty_nr]
+        except KeyError:
+            return None
+
+    @wrap_exceptions
+    def memory_info(self):
+        rawtuple = self._get_pidtaskinfo()
+        return ntp.pmem(
+            rawtuple[pidtaskinfo_map['rss']],
+            rawtuple[pidtaskinfo_map['vms']],
+            rawtuple[pidtaskinfo_map['pfaults']],
+            rawtuple[pidtaskinfo_map['pageins']],
+        )
+
+    @wrap_exceptions
+    def memory_full_info(self):
+        basic_mem = self.memory_info()
+        uss = cext.proc_memory_uss(self.pid)
+        return ntp.pfullmem(*basic_mem + (uss,))
+
+    @wrap_exceptions
+    def cpu_times(self):
+        rawtuple = self._get_pidtaskinfo()
+        return ntp.pcputimes(
+            rawtuple[pidtaskinfo_map['cpuutime']],
+            rawtuple[pidtaskinfo_map['cpustime']],
+            # children user / system times are not retrievable (set to 0)
+            0.0,
+            0.0,
+        )
+
+    @wrap_exceptions
+    def create_time(self, monotonic=False):
+        ctime = self._get_kinfo_proc()[kinfo_proc_map['ctime']]
+        if not monotonic:
+            ctime = adjust_proc_create_time(ctime)
+        return ctime
+
+    @wrap_exceptions
+    def num_ctx_switches(self):
+        # Unvoluntary value seems not to be available;
+        # getrusage() numbers seems to confirm this theory.
+        # We set it to 0.
+        vol = self._get_pidtaskinfo()[pidtaskinfo_map['volctxsw']]
+        return ntp.pctxsw(vol, 0)
+
+    @wrap_exceptions
+    def num_threads(self):
+        return self._get_pidtaskinfo()[pidtaskinfo_map['numthreads']]
+
+    @wrap_exceptions
+    def open_files(self):
+        if self.pid == 0:
+            return []
+        files = []
+        rawlist = cext.proc_open_files(self.pid)
+        for path, fd in rawlist:
+            if isfile_strict(path):
+                ntuple = ntp.popenfile(path, fd)
+                files.append(ntuple)
+        return files
+
+    @wrap_exceptions
+    def net_connections(self, kind='inet'):
+        families, types = conn_tmap[kind]
+        rawlist = cext.proc_net_connections(self.pid, families, types)
+        ret = []
+        for item in rawlist:
+            fd, fam, type, laddr, raddr, status = item
+            nt = conn_to_ntuple(
+                fd, fam, type, laddr, raddr, status, TCP_STATUSES
+            )
+            ret.append(nt)
+        return ret
+
+    @wrap_exceptions
+    def num_fds(self):
+        if self.pid == 0:
+            return 0
+        return cext.proc_num_fds(self.pid)
+
+    @wrap_exceptions
+    def wait(self, timeout=None):
+        return _psposix.wait_pid(self.pid, timeout)
+
+    @wrap_exceptions
+    def nice_get(self):
+        return cext.proc_priority_get(self.pid)
+
+    @wrap_exceptions
+    def nice_set(self, value):
+        return cext.proc_priority_set(self.pid, value)
+
+    @wrap_exceptions
+    def status(self):
+        code = self._get_kinfo_proc()[kinfo_proc_map['status']]
+        # XXX is '?' legit? (we're not supposed to return it anyway)
+        return PROC_STATUSES.get(code, '?')
+
+    @wrap_exceptions
+    def threads(self):
+        rawlist = cext.proc_threads(self.pid)
+        retlist = []
+        for thread_id, utime, stime in rawlist:
+            ntuple = ntp.pthread(thread_id, utime, stime)
+            retlist.append(ntuple)
+        return retlist
diff --git a/micromamba_root/Lib/site-packages/psutil/_psposix.py b/micromamba_root/Lib/site-packages/psutil/_psposix.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7ad2fdabd30ee585642b49e38db9afc489b6ede
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil/_psposix.py
@@ -0,0 +1,363 @@
+# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""Routines common to all posix systems."""
+
+import enum
+import errno
+import glob
+import os
+import select
+import signal
+import time
+
+from . import _ntuples as ntp
+from ._common import MACOS
+from ._common import TimeoutExpired
+from ._common import debug
+from ._common import memoize
+from ._common import usage_percent
+
+if MACOS:
+    from . import _psutil_osx
+
+
+__all__ = ['pid_exists', 'wait_pid', 'disk_usage', 'get_terminal_map']
+
+
+def pid_exists(pid):
+    """Check whether pid exists in the current process table."""
+    if pid == 0:
+        # According to "man 2 kill" PID 0 has a special meaning:
+        # it refers to <> so we don't want to go any further.
+        # If we get here it means this UNIX platform *does* have
+        # a process with id 0.
+        return True
+    try:
+        os.kill(pid, 0)
+    except ProcessLookupError:
+        return False
+    except PermissionError:
+        # EPERM clearly means there's a process to deny access to
+        return True
+    # According to "man 2 kill" possible error values are
+    # (EINVAL, EPERM, ESRCH)
+    else:
+        return True
+
+
+Negsignal = enum.IntEnum(
+    'Negsignal', {x.name: -x.value for x in signal.Signals}
+)
+
+
+def negsig_to_enum(num):
+    """Convert a negative signal value to an enum."""
+    try:
+        return Negsignal(num)
+    except ValueError:
+        return num
+
+
+def convert_exit_code(status):
+    """Convert a os.waitpid() status to an exit code."""
+    if os.WIFEXITED(status):
+        # Process terminated normally by calling exit(3) or _exit(2),
+        # or by returning from main(). The return value is the
+        # positive integer passed to *exit().
+        return os.WEXITSTATUS(status)
+    if os.WIFSIGNALED(status):
+        # Process exited due to a signal. Return the negative value
+        # of that signal.
+        return negsig_to_enum(-os.WTERMSIG(status))
+    # if os.WIFSTOPPED(status):
+    #     # Process was stopped via SIGSTOP or is being traced, and
+    #     # waitpid() was called with WUNTRACED flag. PID is still
+    #     # alive. From now on waitpid() will keep returning (0, 0)
+    #     # until the process state doesn't change.
+    #     # It may make sense to catch/enable this since stopped PIDs
+    #     # ignore SIGTERM.
+    #     interval = sleep(interval)
+    #     continue
+    # if os.WIFCONTINUED(status):
+    #     # Process was resumed via SIGCONT and waitpid() was called
+    #     # with WCONTINUED flag.
+    #     interval = sleep(interval)
+    #     continue
+
+    # Should never happen.
+    msg = f"unknown process exit status {status!r}"
+    raise ValueError(msg)
+
+
+def wait_pid_posix(
+    pid,
+    timeout=None,
+    _waitpid=os.waitpid,
+    _timer=getattr(time, 'monotonic', time.time),  # noqa: B008
+    _min=min,
+    _sleep=time.sleep,
+    _pid_exists=pid_exists,
+):
+    """Wait for a process PID to terminate.
+
+    If the process terminated normally by calling exit(3) or _exit(2),
+    or by returning from main(), the return value is the positive integer
+    passed to *exit().
+
+    If it was terminated by a signal it returns the negated value of the
+    signal which caused the termination (e.g. -SIGTERM).
+
+    If PID is not a children of os.getpid() (current process) just
+    wait until the process disappears and return None.
+
+    If PID does not exist at all return None immediately.
+
+    If timeout is specified and process is still alive raise
+    TimeoutExpired.
+
+    If timeout=0 either return immediately or raise TimeoutExpired
+    (non-blocking).
+    """
+    interval = 0.0001
+    max_interval = 0.04
+    flags = 0
+    stop_at = None
+
+    if timeout is not None:
+        flags |= os.WNOHANG
+        if timeout != 0:
+            stop_at = _timer() + timeout
+
+    def sleep_or_timeout(interval):
+        # Sleep for some time and return a new increased interval.
+        if timeout == 0 or (stop_at is not None and _timer() >= stop_at):
+            raise TimeoutExpired(timeout)
+        _sleep(interval)
+        return _min(interval * 2, max_interval)
+
+    # See: https://linux.die.net/man/2/waitpid
+    while True:
+        try:
+            retpid, status = os.waitpid(pid, flags)
+        except ChildProcessError:
+            # This has two meanings:
+            # - PID is not a child of os.getpid() in which case
+            #   we keep polling until it's gone
+            # - PID never existed in the first place
+            # In both cases we'll eventually return None as we
+            # can't determine its exit status code.
+            while _pid_exists(pid):
+                interval = sleep_or_timeout(interval)
+            return None
+        else:
+            if retpid == 0:
+                # WNOHANG flag was used and PID is still running.
+                interval = sleep_or_timeout(interval)
+            else:
+                return convert_exit_code(status)
+
+
+def _waitpid(pid, timeout):
+    """Wrapper around os.waitpid(). PID is supposed to be gone already,
+    it just returns the exit code.
+    """
+    try:
+        retpid, status = os.waitpid(pid, 0)
+    except ChildProcessError:
+        # PID is not a child of os.getpid().
+        return wait_pid_posix(pid, timeout)
+    else:
+        assert retpid != 0
+        return convert_exit_code(status)
+
+
+def wait_pid_pidfd_open(pid, timeout=None):
+    """Wait for PID to terminate using pidfd_open() + poll(). Linux >=
+    5.3 + Python >= 3.9 only.
+    """
+    try:
+        pidfd = os.pidfd_open(pid, 0)
+    except OSError as err:
+        if err.errno == errno.ESRCH:
+            # No such process. os.waitpid() may still be able to return
+            # the status code.
+            return wait_pid_posix(pid, timeout)
+        if err.errno in {errno.EMFILE, errno.ENFILE, errno.ENODEV}:
+            # EMFILE, ENFILE: too many open files
+            # ENODEV: anonymous inode filesystem not supported
+            debug(f"pidfd_open() failed ({err!r}); use fallback")
+            return wait_pid_posix(pid, timeout)
+        raise
+
+    try:
+        # poll() / select() have the advantage of not requiring any
+        # extra file descriptor, contrary to epoll() / kqueue().
+        # select() crashes if process opens > 1024 FDs, so we use
+        # poll().
+        poller = select.poll()
+        poller.register(pidfd, select.POLLIN)
+        timeout_ms = None if timeout is None else int(timeout * 1000)
+        events = poller.poll(timeout_ms)  # wait
+
+        if not events:
+            raise TimeoutExpired(timeout)
+        return _waitpid(pid, timeout)
+    finally:
+        os.close(pidfd)
+
+
+def wait_pid_kqueue(pid, timeout=None):
+    """Wait for PID to terminate using kqueue(). macOS and BSD only."""
+    try:
+        kq = select.kqueue()
+    except OSError as err:
+        if err.errno in {errno.EMFILE, errno.ENFILE}:  # too many open files
+            debug(f"kqueue() failed ({err!r}); use fallback")
+            return wait_pid_posix(pid, timeout)
+        raise
+
+    try:
+        kev = select.kevent(
+            pid,
+            filter=select.KQ_FILTER_PROC,
+            flags=select.KQ_EV_ADD | select.KQ_EV_ONESHOT,
+            fflags=select.KQ_NOTE_EXIT,
+        )
+        try:
+            events = kq.control([kev], 1, timeout)  # wait
+        except OSError as err:
+            if err.errno in {errno.EACCES, errno.EPERM, errno.ESRCH}:
+                debug(f"kqueue.control() failed ({err!r}); use fallback")
+                return wait_pid_posix(pid, timeout)
+            raise
+        else:
+            if not events:
+                raise TimeoutExpired(timeout)
+            return _waitpid(pid, timeout)
+    finally:
+        kq.close()
+
+
+@memoize
+def can_use_pidfd_open():
+    # Availability: Linux >= 5.3, Python >= 3.9
+    if not hasattr(os, "pidfd_open"):
+        return False
+    try:
+        pidfd = os.pidfd_open(os.getpid(), 0)
+    except OSError as err:
+        if err.errno in {errno.EMFILE, errno.ENFILE}:  # noqa: SIM103
+            # transitory 'too many open files'
+            return True
+        # likely blocked by security policy like SECCOMP (EPERM,
+        # EACCES, ENOSYS)
+        return False
+    else:
+        os.close(pidfd)
+        return True
+
+
+@memoize
+def can_use_kqueue():
+    # Availability: macOS, BSD
+    names = (
+        "kqueue",
+        "KQ_EV_ADD",
+        "KQ_EV_ONESHOT",
+        "KQ_FILTER_PROC",
+        "KQ_NOTE_EXIT",
+    )
+    if not all(hasattr(select, x) for x in names):
+        return False
+    kq = None
+    try:
+        kq = select.kqueue()
+        kev = select.kevent(
+            os.getpid(),
+            filter=select.KQ_FILTER_PROC,
+            flags=select.KQ_EV_ADD | select.KQ_EV_ONESHOT,
+            fflags=select.KQ_NOTE_EXIT,
+        )
+        kq.control([kev], 1, 0)
+        return True
+    except OSError as err:
+        if err.errno in {errno.EMFILE, errno.ENFILE}:  # noqa: SIM103
+            # transitory 'too many open files'
+            return True
+        return False
+    finally:
+        if kq is not None:
+            kq.close()
+
+
+def wait_pid(pid, timeout=None):
+    # PID 0 passed to waitpid() waits for any child of the current
+    # process to change state.
+    assert pid > 0
+    if timeout is not None:
+        assert timeout >= 0
+
+    if can_use_pidfd_open():
+        return wait_pid_pidfd_open(pid, timeout)
+    elif can_use_kqueue():
+        return wait_pid_kqueue(pid, timeout)
+    else:
+        return wait_pid_posix(pid, timeout)
+
+
+wait_pid.__doc__ = wait_pid_posix.__doc__
+
+
+def disk_usage(path):
+    """Return disk usage associated with path.
+    Note: UNIX usually reserves 5% disk space which is not accessible
+    by user. In this function "total" and "used" values reflect the
+    total and used disk space whereas "free" and "percent" represent
+    the "free" and "used percent" user disk space.
+    """
+    st = os.statvfs(path)
+    # Total space which is only available to root (unless changed
+    # at system level).
+    total = st.f_blocks * st.f_frsize
+    # Remaining free space usable by root.
+    avail_to_root = st.f_bfree * st.f_frsize
+    # Remaining free space usable by user.
+    avail_to_user = st.f_bavail * st.f_frsize
+    # Total space being used in general.
+    used = total - avail_to_root
+    if MACOS:
+        # see: https://github.com/giampaolo/psutil/pull/2152
+        used = _psutil_osx.disk_usage_used(path, used)
+    # Total space which is available to user (same as 'total' but
+    # for the user).
+    total_user = used + avail_to_user
+    # User usage percent compared to the total amount of space
+    # the user can use. This number would be higher if compared
+    # to root's because the user has less space (usually -5%).
+    usage_percent_user = usage_percent(used, total_user, round_=1)
+
+    # NB: the percentage is -5% than what shown by df due to
+    # reserved blocks that we are currently not considering:
+    # https://github.com/giampaolo/psutil/issues/829#issuecomment-223750462
+    return ntp.sdiskusage(
+        total=total, used=used, free=avail_to_user, percent=usage_percent_user
+    )
+
+
+@memoize
+def get_terminal_map():
+    """Get a map of device-id -> path as a dict.
+    Used by Process.terminal().
+    """
+    ret = {}
+    ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*')
+    for name in ls:
+        assert name not in ret, name
+        try:
+            ret[os.stat(name).st_rdev] = name
+        except FileNotFoundError:
+            pass
+    return ret
diff --git a/micromamba_root/Lib/site-packages/psutil/_pssunos.py b/micromamba_root/Lib/site-packages/psutil/_pssunos.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0e70581f5a02dfbc8e61a9d26e105ee6160a8aa
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil/_pssunos.py
@@ -0,0 +1,704 @@
+# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""Sun OS Solaris platform implementation."""
+
+import errno
+import functools
+import os
+import socket
+import subprocess
+import sys
+from collections import namedtuple
+from socket import AF_INET
+
+from . import _common
+from . import _ntuples as ntp
+from . import _psposix
+from . import _psutil_sunos as cext
+from ._common import AF_INET6
+from ._common import ENCODING
+from ._common import AccessDenied
+from ._common import NoSuchProcess
+from ._common import ZombieProcess
+from ._common import debug
+from ._common import get_procfs_path
+from ._common import isfile_strict
+from ._common import memoize_when_activated
+from ._common import sockfam_to_enum
+from ._common import socktype_to_enum
+from ._common import usage_percent
+
+__extra__all__ = ["CONN_IDLE", "CONN_BOUND", "PROCFS_PATH"]
+
+
+# =====================================================================
+# --- globals
+# =====================================================================
+
+
+PAGE_SIZE = cext.getpagesize()
+AF_LINK = cext.AF_LINK
+IS_64_BIT = sys.maxsize > 2**32
+
+CONN_IDLE = "IDLE"
+CONN_BOUND = "BOUND"
+
+PROC_STATUSES = {
+    cext.SSLEEP: _common.STATUS_SLEEPING,
+    cext.SRUN: _common.STATUS_RUNNING,
+    cext.SZOMB: _common.STATUS_ZOMBIE,
+    cext.SSTOP: _common.STATUS_STOPPED,
+    cext.SIDL: _common.STATUS_IDLE,
+    cext.SONPROC: _common.STATUS_RUNNING,  # same as run
+    cext.SWAIT: _common.STATUS_WAITING,
+}
+
+TCP_STATUSES = {
+    cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
+    cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
+    cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV,
+    cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
+    cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
+    cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
+    cext.TCPS_CLOSED: _common.CONN_CLOSE,
+    cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
+    cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
+    cext.TCPS_LISTEN: _common.CONN_LISTEN,
+    cext.TCPS_CLOSING: _common.CONN_CLOSING,
+    cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
+    cext.TCPS_IDLE: CONN_IDLE,  # sunos specific
+    cext.TCPS_BOUND: CONN_BOUND,  # sunos specific
+}
+
+proc_info_map = dict(
+    ppid=0,
+    rss=1,
+    vms=2,
+    create_time=3,
+    nice=4,
+    num_threads=5,
+    status=6,
+    ttynr=7,
+    uid=8,
+    euid=9,
+    gid=10,
+    egid=11,
+)
+
+
+# =====================================================================
+# --- memory
+# =====================================================================
+
+
+def virtual_memory():
+    """Report virtual memory metrics."""
+    # we could have done this with kstat, but IMHO this is good enough
+    total = os.sysconf('SC_PHYS_PAGES') * PAGE_SIZE
+    # note: there's no difference on Solaris
+    free = avail = os.sysconf('SC_AVPHYS_PAGES') * PAGE_SIZE
+    used = total - free
+    percent = usage_percent(used, total, round_=1)
+    return ntp.svmem(total, avail, percent, used, free)
+
+
+def swap_memory():
+    """Report swap memory metrics."""
+    sin, sout = cext.swap_mem()
+    # XXX
+    # we are supposed to get total/free by doing so:
+    # http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/
+    #     usr/src/cmd/swap/swap.c
+    # ...nevertheless I can't manage to obtain the same numbers as 'swap'
+    # cmdline utility, so let's parse its output (sigh!)
+    p = subprocess.Popen(
+        [
+            '/usr/bin/env',
+            f"PATH=/usr/sbin:/sbin:{os.environ['PATH']}",
+            'swap',
+            '-l',
+        ],
+        stdout=subprocess.PIPE,
+    )
+    stdout, _ = p.communicate()
+    stdout = stdout.decode(sys.stdout.encoding)
+    if p.returncode != 0:
+        msg = f"'swap -l' failed (retcode={p.returncode})"
+        raise RuntimeError(msg)
+
+    lines = stdout.strip().split('\n')[1:]
+    if not lines:
+        msg = 'no swap device(s) configured'
+        raise RuntimeError(msg)
+    total = free = 0
+    for line in lines:
+        line = line.split()
+        t, f = line[3:5]
+        total += int(int(t) * 512)
+        free += int(int(f) * 512)
+    used = total - free
+    percent = usage_percent(used, total, round_=1)
+    return ntp.sswap(
+        total, used, free, percent, sin * PAGE_SIZE, sout * PAGE_SIZE
+    )
+
+
+# =====================================================================
+# --- CPU
+# =====================================================================
+
+
+def cpu_times():
+    """Return system-wide CPU times as a named tuple."""
+    ret = cext.per_cpu_times()
+    return ntp.scputimes(*[sum(x) for x in zip(*ret)])
+
+
+def per_cpu_times():
+    """Return system per-CPU times as a list of named tuples."""
+    ret = cext.per_cpu_times()
+    return [ntp.scputimes(*x) for x in ret]
+
+
+def cpu_count_logical():
+    """Return the number of logical CPUs in the system."""
+    try:
+        return os.sysconf("SC_NPROCESSORS_ONLN")
+    except ValueError:
+        # mimic os.cpu_count() behavior
+        return None
+
+
+def cpu_count_cores():
+    """Return the number of CPU cores in the system."""
+    return cext.cpu_count_cores()
+
+
+def cpu_stats():
+    """Return various CPU stats as a named tuple."""
+    ctx_switches, interrupts, syscalls, _traps = cext.cpu_stats()
+    soft_interrupts = 0
+    return ntp.scpustats(ctx_switches, interrupts, soft_interrupts, syscalls)
+
+
+# =====================================================================
+# --- disks
+# =====================================================================
+
+
+disk_io_counters = cext.disk_io_counters
+disk_usage = _psposix.disk_usage
+
+
+def disk_partitions(all=False):
+    """Return system disk partitions."""
+    # TODO - the filtering logic should be better checked so that
+    # it tries to reflect 'df' as much as possible
+    retlist = []
+    partitions = cext.disk_partitions()
+    for partition in partitions:
+        device, mountpoint, fstype, opts = partition
+        if device == 'none':
+            device = ''
+        if not all:
+            # Differently from, say, Linux, we don't have a list of
+            # common fs types so the best we can do, AFAIK, is to
+            # filter by filesystem having a total size > 0.
+            try:
+                if not disk_usage(mountpoint).total:
+                    continue
+            except OSError as err:
+                # https://github.com/giampaolo/psutil/issues/1674
+                debug(f"skipping {mountpoint!r}: {err}")
+                continue
+        ntuple = ntp.sdiskpart(device, mountpoint, fstype, opts)
+        retlist.append(ntuple)
+    return retlist
+
+
+# =====================================================================
+# --- network
+# =====================================================================
+
+
+net_io_counters = cext.net_io_counters
+net_if_addrs = cext.net_if_addrs
+
+
+def net_connections(kind, _pid=-1):
+    """Return socket connections.  If pid == -1 return system-wide
+    connections (as opposed to connections opened by one process only).
+    Only INET sockets are returned (UNIX are not).
+    """
+    families, types = _common.conn_tmap[kind]
+    rawlist = cext.net_connections(_pid)
+    ret = set()
+    for item in rawlist:
+        fd, fam, type_, laddr, raddr, status, pid = item
+        if fam not in families:
+            continue
+        if type_ not in types:
+            continue
+        # TODO: refactor and use _common.conn_to_ntuple.
+        if fam in {AF_INET, AF_INET6}:
+            if laddr:
+                laddr = ntp.addr(*laddr)
+            if raddr:
+                raddr = ntp.addr(*raddr)
+        status = TCP_STATUSES[status]
+        fam = sockfam_to_enum(fam)
+        type_ = socktype_to_enum(type_)
+        if _pid == -1:
+            nt = ntp.sconn(fd, fam, type_, laddr, raddr, status, pid)
+        else:
+            nt = ntp.pconn(fd, fam, type_, laddr, raddr, status)
+        ret.add(nt)
+    return list(ret)
+
+
+def net_if_stats():
+    """Get NIC stats (isup, duplex, speed, mtu)."""
+    ret = cext.net_if_stats()
+    for name, items in ret.items():
+        isup, duplex, speed, mtu = items
+        if hasattr(_common, 'NicDuplex'):
+            duplex = _common.NicDuplex(duplex)
+        ret[name] = ntp.snicstats(isup, duplex, speed, mtu, '')
+    return ret
+
+
+# =====================================================================
+# --- other system functions
+# =====================================================================
+
+
+def boot_time():
+    """The system boot time expressed in seconds since the epoch."""
+    return cext.boot_time()
+
+
+def users():
+    """Return currently connected users as a list of namedtuples."""
+    retlist = []
+    rawlist = cext.users()
+    localhost = (':0.0', ':0')
+    for item in rawlist:
+        user, tty, hostname, tstamp, user_process, pid = item
+        # note: the underlying C function includes entries about
+        # system boot, run level and others.  We might want
+        # to use them in the future.
+        if not user_process:
+            continue
+        if hostname in localhost:
+            hostname = 'localhost'
+        nt = ntp.suser(user, tty, hostname, tstamp, pid)
+        retlist.append(nt)
+    return retlist
+
+
+# =====================================================================
+# --- processes
+# =====================================================================
+
+
+def pids():
+    """Returns a list of PIDs currently running on the system."""
+    path = get_procfs_path().encode(ENCODING)
+    return [int(x) for x in os.listdir(path) if x.isdigit()]
+
+
+def pid_exists(pid):
+    """Check for the existence of a unix pid."""
+    return _psposix.pid_exists(pid)
+
+
+def wrap_exceptions(fun):
+    """Call callable into a try/except clause and translate ENOENT,
+    EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
+    """
+
+    @functools.wraps(fun)
+    def wrapper(self, *args, **kwargs):
+        pid, ppid, name = self.pid, self._ppid, self._name
+        try:
+            return fun(self, *args, **kwargs)
+        except (FileNotFoundError, ProcessLookupError) as err:
+            # ENOENT (no such file or directory) gets raised on open().
+            # ESRCH (no such process) can get raised on read() if
+            # process is gone in meantime.
+            if not pid_exists(pid):
+                raise NoSuchProcess(pid, name) from err
+            raise ZombieProcess(pid, name, ppid) from err
+        except PermissionError as err:
+            raise AccessDenied(pid, name) from err
+        except OSError as err:
+            if pid == 0:
+                if 0 in pids():
+                    raise AccessDenied(pid, name) from err
+                raise
+            raise
+
+    return wrapper
+
+
+class Process:
+    """Wrapper class around underlying C implementation."""
+
+    __slots__ = ["_cache", "_name", "_ppid", "_procfs_path", "pid"]
+
+    def __init__(self, pid):
+        self.pid = pid
+        self._name = None
+        self._ppid = None
+        self._procfs_path = get_procfs_path()
+
+    def _assert_alive(self):
+        """Raise NSP if the process disappeared on us."""
+        # For those C function who do not raise NSP, possibly returning
+        # incorrect or incomplete result.
+        os.stat(f"{self._procfs_path}/{self.pid}")
+
+    def oneshot_enter(self):
+        self._proc_name_and_args.cache_activate(self)
+        self._proc_basic_info.cache_activate(self)
+        self._proc_cred.cache_activate(self)
+
+    def oneshot_exit(self):
+        self._proc_name_and_args.cache_deactivate(self)
+        self._proc_basic_info.cache_deactivate(self)
+        self._proc_cred.cache_deactivate(self)
+
+    @wrap_exceptions
+    @memoize_when_activated
+    def _proc_name_and_args(self):
+        return cext.proc_name_and_args(self.pid, self._procfs_path)
+
+    @wrap_exceptions
+    @memoize_when_activated
+    def _proc_basic_info(self):
+        if self.pid == 0 and not os.path.exists(
+            f"{self._procfs_path}/{self.pid}/psinfo"
+        ):
+            raise AccessDenied(self.pid)
+        ret = cext.proc_basic_info(self.pid, self._procfs_path)
+        assert len(ret) == len(proc_info_map)
+        return ret
+
+    @wrap_exceptions
+    @memoize_when_activated
+    def _proc_cred(self):
+        return cext.proc_cred(self.pid, self._procfs_path)
+
+    @wrap_exceptions
+    def name(self):
+        # note: max len == 15
+        return self._proc_name_and_args()[0]
+
+    @wrap_exceptions
+    def exe(self):
+        try:
+            return os.readlink(f"{self._procfs_path}/{self.pid}/path/a.out")
+        except OSError:
+            pass  # continue and guess the exe name from the cmdline
+        # Will be guessed later from cmdline but we want to explicitly
+        # invoke cmdline here in order to get an AccessDenied
+        # exception if the user has not enough privileges.
+        self.cmdline()
+        return ""
+
+    @wrap_exceptions
+    def cmdline(self):
+        return self._proc_name_and_args()[1]
+
+    @wrap_exceptions
+    def environ(self):
+        return cext.proc_environ(self.pid, self._procfs_path)
+
+    @wrap_exceptions
+    def create_time(self):
+        return self._proc_basic_info()[proc_info_map['create_time']]
+
+    @wrap_exceptions
+    def num_threads(self):
+        return self._proc_basic_info()[proc_info_map['num_threads']]
+
+    @wrap_exceptions
+    def nice_get(self):
+        # Note #1: getpriority(3) doesn't work for realtime processes.
+        # Psinfo is what ps uses, see:
+        # https://github.com/giampaolo/psutil/issues/1194
+        return self._proc_basic_info()[proc_info_map['nice']]
+
+    @wrap_exceptions
+    def nice_set(self, value):
+        if self.pid in {2, 3}:
+            # Special case PIDs: internally setpriority(3) return ESRCH
+            # (no such process), no matter what.
+            # The process actually exists though, as it has a name,
+            # creation time, etc.
+            raise AccessDenied(self.pid, self._name)
+        return cext.proc_priority_set(self.pid, value)
+
+    @wrap_exceptions
+    def ppid(self):
+        self._ppid = self._proc_basic_info()[proc_info_map['ppid']]
+        return self._ppid
+
+    @wrap_exceptions
+    def uids(self):
+        try:
+            real, effective, saved, _, _, _ = self._proc_cred()
+        except AccessDenied:
+            real = self._proc_basic_info()[proc_info_map['uid']]
+            effective = self._proc_basic_info()[proc_info_map['euid']]
+            saved = None
+        return ntp.puids(real, effective, saved)
+
+    @wrap_exceptions
+    def gids(self):
+        try:
+            _, _, _, real, effective, saved = self._proc_cred()
+        except AccessDenied:
+            real = self._proc_basic_info()[proc_info_map['gid']]
+            effective = self._proc_basic_info()[proc_info_map['egid']]
+            saved = None
+        return ntp.puids(real, effective, saved)
+
+    @wrap_exceptions
+    def cpu_times(self):
+        try:
+            times = cext.proc_cpu_times(self.pid, self._procfs_path)
+        except OSError as err:
+            if err.errno == errno.EOVERFLOW and not IS_64_BIT:
+                # We may get here if we attempt to query a 64bit process
+                # with a 32bit python.
+                # Error originates from read() and also tools like "cat"
+                # fail in the same way (!).
+                # Since there simply is no way to determine CPU times we
+                # return 0.0 as a fallback. See:
+                # https://github.com/giampaolo/psutil/issues/857
+                times = (0.0, 0.0, 0.0, 0.0)
+            else:
+                raise
+        return ntp.pcputimes(*times)
+
+    @wrap_exceptions
+    def cpu_num(self):
+        return cext.proc_cpu_num(self.pid, self._procfs_path)
+
+    @wrap_exceptions
+    def terminal(self):
+        procfs_path = self._procfs_path
+        hit_enoent = False
+        tty = wrap_exceptions(self._proc_basic_info()[proc_info_map['ttynr']])
+        if tty != cext.PRNODEV:
+            for x in (0, 1, 2, 255):
+                try:
+                    return os.readlink(f"{procfs_path}/{self.pid}/path/{x}")
+                except FileNotFoundError:
+                    hit_enoent = True
+                    continue
+        if hit_enoent:
+            self._assert_alive()
+
+    @wrap_exceptions
+    def cwd(self):
+        # /proc/PID/path/cwd may not be resolved by readlink() even if
+        # it exists (ls shows it). If that's the case and the process
+        # is still alive return None (we can return None also on BSD).
+        # Reference: https://groups.google.com/g/comp.unix.solaris/c/tcqvhTNFCAs
+        procfs_path = self._procfs_path
+        try:
+            return os.readlink(f"{procfs_path}/{self.pid}/path/cwd")
+        except FileNotFoundError:
+            os.stat(f"{procfs_path}/{self.pid}")  # raise NSP or AD
+            return ""
+
+    @wrap_exceptions
+    def memory_info(self):
+        ret = self._proc_basic_info()
+        rss = ret[proc_info_map['rss']] * 1024
+        vms = ret[proc_info_map['vms']] * 1024
+        return ntp.pmem(rss, vms)
+
+    memory_full_info = memory_info
+
+    @wrap_exceptions
+    def status(self):
+        code = self._proc_basic_info()[proc_info_map['status']]
+        # XXX is '?' legit? (we're not supposed to return it anyway)
+        return PROC_STATUSES.get(code, '?')
+
+    @wrap_exceptions
+    def threads(self):
+        procfs_path = self._procfs_path
+        ret = []
+        tids = os.listdir(f"{procfs_path}/{self.pid}/lwp")
+        hit_enoent = False
+        for tid in tids:
+            tid = int(tid)
+            try:
+                utime, stime = cext.query_process_thread(
+                    self.pid, tid, procfs_path
+                )
+            except OSError as err:
+                if err.errno == errno.EOVERFLOW and not IS_64_BIT:
+                    # We may get here if we attempt to query a 64bit process
+                    # with a 32bit python.
+                    # Error originates from read() and also tools like "cat"
+                    # fail in the same way (!).
+                    # Since there simply is no way to determine CPU times we
+                    # return 0.0 as a fallback. See:
+                    # https://github.com/giampaolo/psutil/issues/857
+                    continue
+                # ENOENT == thread gone in meantime
+                if err.errno == errno.ENOENT:
+                    hit_enoent = True
+                    continue
+                raise
+            else:
+                nt = ntp.pthread(tid, utime, stime)
+                ret.append(nt)
+        if hit_enoent:
+            self._assert_alive()
+        return ret
+
+    @wrap_exceptions
+    def open_files(self):
+        retlist = []
+        hit_enoent = False
+        procfs_path = self._procfs_path
+        pathdir = f"{procfs_path}/{self.pid}/path"
+        for fd in os.listdir(f"{procfs_path}/{self.pid}/fd"):
+            path = os.path.join(pathdir, fd)
+            if os.path.islink(path):
+                try:
+                    file = os.readlink(path)
+                except FileNotFoundError:
+                    hit_enoent = True
+                    continue
+                else:
+                    if isfile_strict(file):
+                        retlist.append(ntp.popenfile(file, int(fd)))
+        if hit_enoent:
+            self._assert_alive()
+        return retlist
+
+    def _get_unix_sockets(self, pid):
+        """Get UNIX sockets used by process by parsing 'pfiles' output."""
+        # TODO: rewrite this in C (...but the damn netstat source code
+        # does not include this part! Argh!!)
+        cmd = ["pfiles", str(pid)]
+        p = subprocess.Popen(
+            cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
+        )
+        stdout, stderr = p.communicate()
+        stdout, stderr = (
+            x.decode(sys.stdout.encoding) for x in (stdout, stderr)
+        )
+        if p.returncode != 0:
+            if 'permission denied' in stderr.lower():
+                raise AccessDenied(self.pid, self._name)
+            if 'no such process' in stderr.lower():
+                raise NoSuchProcess(self.pid, self._name)
+            msg = f"{cmd!r} command error\n{stderr}"
+            raise RuntimeError(msg)
+
+        lines = stdout.split('\n')[2:]
+        for i, line in enumerate(lines):
+            line = line.lstrip()
+            if line.startswith('sockname: AF_UNIX'):
+                path = line.split(' ', 2)[2]
+                type = lines[i - 2].strip()
+                if type == 'SOCK_STREAM':
+                    type = socket.SOCK_STREAM
+                elif type == 'SOCK_DGRAM':
+                    type = socket.SOCK_DGRAM
+                else:
+                    type = -1
+                yield (-1, socket.AF_UNIX, type, path, "", _common.CONN_NONE)
+
+    @wrap_exceptions
+    def net_connections(self, kind='inet'):
+        ret = net_connections(kind, _pid=self.pid)
+        # The underlying C implementation retrieves all OS connections
+        # and filters them by PID.  At this point we can't tell whether
+        # an empty list means there were no connections for process or
+        # process is no longer active so we force NSP in case the PID
+        # is no longer there.
+        if not ret:
+            # will raise NSP if process is gone
+            os.stat(f"{self._procfs_path}/{self.pid}")
+
+        # UNIX sockets
+        if kind in {'all', 'unix'}:
+            ret.extend(
+                [ntp.pconn(*conn) for conn in self._get_unix_sockets(self.pid)]
+            )
+        return ret
+
+    nt_mmap_grouped = namedtuple('mmap', 'path rss anon locked')
+    nt_mmap_ext = namedtuple('mmap', 'addr perms path rss anon locked')
+
+    @wrap_exceptions
+    def memory_maps(self):
+        def toaddr(start, end):
+            return "{}-{}".format(
+                hex(start)[2:].strip('L'), hex(end)[2:].strip('L')
+            )
+
+        procfs_path = self._procfs_path
+        retlist = []
+        try:
+            rawlist = cext.proc_memory_maps(self.pid, procfs_path)
+        except OSError as err:
+            if err.errno == errno.EOVERFLOW and not IS_64_BIT:
+                # We may get here if we attempt to query a 64bit process
+                # with a 32bit python.
+                # Error originates from read() and also tools like "cat"
+                # fail in the same way (!).
+                # Since there simply is no way to determine CPU times we
+                # return 0.0 as a fallback. See:
+                # https://github.com/giampaolo/psutil/issues/857
+                return []
+            else:
+                raise
+        hit_enoent = False
+        for item in rawlist:
+            addr, addrsize, perm, name, rss, anon, locked = item
+            addr = toaddr(addr, addrsize)
+            if not name.startswith('['):
+                try:
+                    name = os.readlink(f"{procfs_path}/{self.pid}/path/{name}")
+                except OSError as err:
+                    if err.errno == errno.ENOENT:
+                        # sometimes the link may not be resolved by
+                        # readlink() even if it exists (ls shows it).
+                        # If that's the case we just return the
+                        # unresolved link path.
+                        # This seems an inconsistency with /proc similar
+                        # to: http://goo.gl/55XgO
+                        name = f"{procfs_path}/{self.pid}/path/{name}"
+                        hit_enoent = True
+                    else:
+                        raise
+            retlist.append((addr, perm, name, rss, anon, locked))
+        if hit_enoent:
+            self._assert_alive()
+        return retlist
+
+    @wrap_exceptions
+    def num_fds(self):
+        return len(os.listdir(f"{self._procfs_path}/{self.pid}/fd"))
+
+    @wrap_exceptions
+    def num_ctx_switches(self):
+        return ntp.pctxsw(
+            *cext.proc_num_ctx_switches(self.pid, self._procfs_path)
+        )
+
+    @wrap_exceptions
+    def wait(self, timeout=None):
+        return _psposix.wait_pid(self.pid, timeout)
diff --git a/micromamba_root/Lib/site-packages/psutil/_psutil_windows.pyd b/micromamba_root/Lib/site-packages/psutil/_psutil_windows.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..3fbc872ec3daa24e65b135c17e7939f9d2ba5a72
Binary files /dev/null and b/micromamba_root/Lib/site-packages/psutil/_psutil_windows.pyd differ
diff --git a/micromamba_root/Lib/site-packages/psutil/_pswindows.py b/micromamba_root/Lib/site-packages/psutil/_pswindows.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ee1eafce0bb08f86df6d08d30a66bb2058c6f7c
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/psutil/_pswindows.py
@@ -0,0 +1,1096 @@
+# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""Windows platform implementation."""
+
+import contextlib
+import enum
+import functools
+import os
+import signal
+import sys
+import threading
+import time
+
+from . import _common
+from . import _ntuples as ntp
+from ._common import ENCODING
+from ._common import AccessDenied
+from ._common import NoSuchProcess
+from ._common import TimeoutExpired
+from ._common import conn_tmap
+from ._common import conn_to_ntuple
+from ._common import debug
+from ._common import isfile_strict
+from ._common import memoize
+from ._common import memoize_when_activated
+from ._common import parse_environ_block
+from ._common import usage_percent
+from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS
+from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS
+from ._psutil_windows import HIGH_PRIORITY_CLASS
+from ._psutil_windows import IDLE_PRIORITY_CLASS
+from ._psutil_windows import NORMAL_PRIORITY_CLASS
+from ._psutil_windows import REALTIME_PRIORITY_CLASS
+
+try:
+    from . import _psutil_windows as cext
+except ImportError as err:
+    if (
+        str(err).lower().startswith("dll load failed")
+        and sys.getwindowsversion()[0] < 6
+    ):
+        # We may get here if:
+        # 1) we are on an old Windows version
+        # 2) psutil was installed via pip + wheel
+        # See: https://github.com/giampaolo/psutil/issues/811
+        msg = "this Windows version is too old (< Windows Vista); "
+        msg += "psutil 3.4.2 is the latest version which supports Windows "
+        msg += "2000, XP and 2003 server"
+        raise RuntimeError(msg) from err
+    else:
+        raise
+
+
+# process priority constants, import from __init__.py:
+# http://msdn.microsoft.com/en-us/library/ms686219(v=vs.85).aspx
+# fmt: off
+__extra__all__ = [
+    "win_service_iter", "win_service_get",
+    # Process priority
+    "ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS",
+    "HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS", "NORMAL_PRIORITY_CLASS",
+    "REALTIME_PRIORITY_CLASS",
+    # IO priority
+    "IOPRIO_VERYLOW", "IOPRIO_LOW", "IOPRIO_NORMAL", "IOPRIO_HIGH",
+    # others
+    "CONN_DELETE_TCB", "AF_LINK",
+]
+# fmt: on
+
+
+# =====================================================================
+# --- globals
+# =====================================================================
+
+CONN_DELETE_TCB = "DELETE_TCB"
+ERROR_PARTIAL_COPY = 299
+PYPY = '__pypy__' in sys.builtin_module_names
+
+AddressFamily = enum.IntEnum('AddressFamily', {'AF_LINK': -1})
+AF_LINK = AddressFamily.AF_LINK
+
+TCP_STATUSES = {
+    cext.MIB_TCP_STATE_ESTAB: _common.CONN_ESTABLISHED,
+    cext.MIB_TCP_STATE_SYN_SENT: _common.CONN_SYN_SENT,
+    cext.MIB_TCP_STATE_SYN_RCVD: _common.CONN_SYN_RECV,
+    cext.MIB_TCP_STATE_FIN_WAIT1: _common.CONN_FIN_WAIT1,
+    cext.MIB_TCP_STATE_FIN_WAIT2: _common.CONN_FIN_WAIT2,
+    cext.MIB_TCP_STATE_TIME_WAIT: _common.CONN_TIME_WAIT,
+    cext.MIB_TCP_STATE_CLOSED: _common.CONN_CLOSE,
+    cext.MIB_TCP_STATE_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
+    cext.MIB_TCP_STATE_LAST_ACK: _common.CONN_LAST_ACK,
+    cext.MIB_TCP_STATE_LISTEN: _common.CONN_LISTEN,
+    cext.MIB_TCP_STATE_CLOSING: _common.CONN_CLOSING,
+    cext.MIB_TCP_STATE_DELETE_TCB: CONN_DELETE_TCB,
+    cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
+}
+
+
+class Priority(enum.IntEnum):
+    ABOVE_NORMAL_PRIORITY_CLASS = ABOVE_NORMAL_PRIORITY_CLASS
+    BELOW_NORMAL_PRIORITY_CLASS = BELOW_NORMAL_PRIORITY_CLASS
+    HIGH_PRIORITY_CLASS = HIGH_PRIORITY_CLASS
+    IDLE_PRIORITY_CLASS = IDLE_PRIORITY_CLASS
+    NORMAL_PRIORITY_CLASS = NORMAL_PRIORITY_CLASS
+    REALTIME_PRIORITY_CLASS = REALTIME_PRIORITY_CLASS
+
+
+globals().update(Priority.__members__)
+
+
+class IOPriority(enum.IntEnum):
+    IOPRIO_VERYLOW = 0
+    IOPRIO_LOW = 1
+    IOPRIO_NORMAL = 2
+    IOPRIO_HIGH = 3
+
+
+globals().update(IOPriority.__members__)
+
+pinfo_map = dict(
+    num_handles=0,
+    ctx_switches=1,
+    user_time=2,
+    kernel_time=3,
+    create_time=4,
+    num_threads=5,
+    io_rcount=6,
+    io_wcount=7,
+    io_rbytes=8,
+    io_wbytes=9,
+    io_count_others=10,
+    io_bytes_others=11,
+    num_page_faults=12,
+    peak_wset=13,
+    wset=14,
+    peak_paged_pool=15,
+    paged_pool=16,
+    peak_non_paged_pool=17,
+    non_paged_pool=18,
+    pagefile=19,
+    peak_pagefile=20,
+    mem_private=21,
+)
+
+
+# =====================================================================
+# --- utils
+# =====================================================================
+
+
+@functools.lru_cache(maxsize=512)
+def convert_dos_path(s):
+    r"""Convert paths using native DOS format like:
+        "\Device\HarddiskVolume1\Windows\systemew\file.txt" or
+        "\??\C:\Windows\systemew\file.txt"
+    into:
+        "C:\Windows\systemew\file.txt".
+    """
+    if s.startswith('\\\\'):
+        return s
+    rawdrive = '\\'.join(s.split('\\')[:3])
+    if rawdrive in {"\\??\\UNC", "\\Device\\Mup"}:
+        rawdrive = '\\'.join(s.split('\\')[:5])
+        driveletter = '\\\\' + '\\'.join(s.split('\\')[3:5])
+    elif rawdrive.startswith('\\??\\'):
+        driveletter = s.split('\\')[2]
+    else:
+        driveletter = cext.QueryDosDevice(rawdrive)
+    remainder = s[len(rawdrive) :]
+    return os.path.join(driveletter, remainder)
+
+
+@memoize
+def getpagesize():
+    return cext.getpagesize()
+
+
+# =====================================================================
+# --- memory
+# =====================================================================
+
+
+def virtual_memory():
+    """System virtual memory as a namedtuple."""
+    mem = cext.virtual_mem()
+    totphys, availphys, _totsys, _availsys = mem
+    total = totphys
+    avail = availphys
+    free = availphys
+    used = total - avail
+    percent = usage_percent((total - avail), total, round_=1)
+    return ntp.svmem(total, avail, percent, used, free)
+
+
+def swap_memory():
+    """Swap system memory as a (total, used, free, sin, sout) tuple."""
+    mem = cext.virtual_mem()
+
+    total_phys = mem[0]
+    total_system = mem[2]
+
+    # system memory (commit total/limit) is the sum of physical and swap
+    # thus physical memory values need to be subtracted to get swap values
+    total = total_system - total_phys
+    # commit total is incremented immediately (decrementing free_system)
+    # while the corresponding free physical value is not decremented until
+    # pages are accessed, so we can't use free system memory for swap.
+    # instead, we calculate page file usage based on performance counter
+    if total > 0:
+        percentswap = cext.swap_percent()
+        used = int(0.01 * percentswap * total)
+    else:
+        percentswap = 0.0
+        used = 0
+
+    free = total - used
+    percent = round(percentswap, 1)
+    return ntp.sswap(total, used, free, percent, 0, 0)
+
+
+# malloc / heap functions
+heap_info = cext.heap_info
+heap_trim = cext.heap_trim
+
+
+# =====================================================================
+# --- disk
+# =====================================================================
+
+
+disk_io_counters = cext.disk_io_counters
+
+
+def disk_usage(path):
+    """Return disk usage associated with path."""
+    if isinstance(path, bytes):
+        # XXX: do we want to use "strict"? Probably yes, in order
+        # to fail immediately. After all we are accepting input here...
+        path = path.decode(ENCODING, errors="strict")
+    total, used, free = cext.disk_usage(path)
+    percent = usage_percent(used, total, round_=1)
+    return ntp.sdiskusage(total, used, free, percent)
+
+
+def disk_partitions(all):
+    """Return disk partitions."""
+    rawlist = cext.disk_partitions(all)
+    return [ntp.sdiskpart(*x) for x in rawlist]
+
+
+# =====================================================================
+# --- CPU
+# =====================================================================
+
+
+def cpu_times():
+    """Return system CPU times as a named tuple."""
+    user, system, idle = cext.cpu_times()
+    # Internally, GetSystemTimes() is used, and it doesn't return
+    # interrupt and dpc times. cext.per_cpu_times() does, so we
+    # rely on it to get those only.
+    percpu_summed = ntp.scputimes(
+        *[sum(n) for n in zip(*cext.per_cpu_times())]
+    )
+    return ntp.scputimes(
+        user, system, idle, percpu_summed.interrupt, percpu_summed.dpc
+    )
+
+
+def per_cpu_times():
+    """Return system per-CPU times as a list of named tuples."""
+    ret = []
+    for user, system, idle, interrupt, dpc in cext.per_cpu_times():
+        item = ntp.scputimes(user, system, idle, interrupt, dpc)
+        ret.append(item)
+    return ret
+
+
+def cpu_count_logical():
+    """Return the number of logical CPUs in the system."""
+    return cext.cpu_count_logical()
+
+
+def cpu_count_cores():
+    """Return the number of CPU cores in the system."""
+    return cext.cpu_count_cores()
+
+
+def cpu_stats():
+    """Return CPU statistics."""
+    ctx_switches, interrupts, _dpcs, syscalls = cext.cpu_stats()
+    soft_interrupts = 0
+    return ntp.scpustats(ctx_switches, interrupts, soft_interrupts, syscalls)
+
+
+def cpu_freq():
+    """Return CPU frequency.
+    On Windows per-cpu frequency is not supported.
+    """
+    curr, max_ = cext.cpu_freq()
+    min_ = 0.0
+    return [ntp.scpufreq(float(curr), min_, float(max_))]
+
+
+_loadavg_initialized = False
+_lock = threading.Lock()
+
+
+def _getloadavg_impl():
+    # Drop to 2 decimal points which is what Linux does
+    raw_loads = cext.getloadavg()
+    return tuple(round(load, 2) for load in raw_loads)
+
+
+def getloadavg():
+    """Return the number of processes in the system run queue averaged
+    over the last 1, 5, and 15 minutes respectively as a tuple.
+    """
+    global _loadavg_initialized
+
+    if _loadavg_initialized:
+        return _getloadavg_impl()
+
+    with _lock:
+        if not _loadavg_initialized:
+            cext.init_loadavg_counter()
+            _loadavg_initialized = True
+
+    return _getloadavg_impl()
+
+
+# =====================================================================
+# --- network
+# =====================================================================
+
+
+def net_connections(kind, _pid=-1):
+    """Return socket connections.  If pid == -1 return system-wide
+    connections (as opposed to connections opened by one process only).
+    """
+    families, types = conn_tmap[kind]
+    rawlist = cext.net_connections(_pid, families, types)
+    ret = set()
+    for item in rawlist:
+        fd, fam, type, laddr, raddr, status, pid = item
+        nt = conn_to_ntuple(
+            fd,
+            fam,
+            type,
+            laddr,
+            raddr,
+            status,
+            TCP_STATUSES,
+            pid=pid if _pid == -1 else None,
+        )
+        ret.add(nt)
+    return list(ret)
+
+
+def net_if_stats():
+    """Get NIC stats (isup, duplex, speed, mtu)."""
+    ret = {}
+    rawdict = cext.net_if_stats()
+    for name, items in rawdict.items():
+        isup, duplex, speed, mtu = items
+        if hasattr(_common, 'NicDuplex'):
+            duplex = _common.NicDuplex(duplex)
+        ret[name] = ntp.snicstats(isup, duplex, speed, mtu, '')
+    return ret
+
+
+def net_io_counters():
+    """Return network I/O statistics for every network interface
+    installed on the system as a dict of raw tuples.
+    """
+    return cext.net_io_counters()
+
+
+def net_if_addrs():
+    """Return the addresses associated to each NIC."""
+    return cext.net_if_addrs()
+
+
+# =====================================================================
+# --- sensors
+# =====================================================================
+
+
+def sensors_battery():
+    """Return battery information."""
+    # For constants meaning see:
+    # https://msdn.microsoft.com/en-us/library/windows/desktop/
+    #     aa373232(v=vs.85).aspx
+    acline_status, flags, percent, secsleft = cext.sensors_battery()
+    power_plugged = acline_status == 1
+    no_battery = bool(flags & 128)
+    charging = bool(flags & 8)
+
+    if no_battery:
+        return None
+    if power_plugged or charging:
+        secsleft = _common.POWER_TIME_UNLIMITED
+    elif secsleft == -1:
+        secsleft = _common.POWER_TIME_UNKNOWN
+
+    return ntp.sbattery(percent, secsleft, power_plugged)
+
+
+# =====================================================================
+# --- other system functions
+# =====================================================================
+
+
+_last_btime = 0
+
+
+def boot_time():
+    """The system boot time expressed in seconds since the epoch. This
+    also includes the time spent during hybernate / suspend.
+    """
+    # This dirty hack is to adjust the precision of the returned
+    # value which may have a 1 second fluctuation, see:
+    # https://github.com/giampaolo/psutil/issues/1007
+    global _last_btime
+    ret = time.time() - cext.uptime()
+    if abs(ret - _last_btime) <= 1:
+        return _last_btime
+    else:
+        _last_btime = ret
+        return ret
+
+
+def users():
+    """Return currently connected users as a list of namedtuples."""
+    retlist = []
+    rawlist = cext.users()
+    for item in rawlist:
+        user, hostname, tstamp = item
+        nt = ntp.suser(user, None, hostname, tstamp, None)
+        retlist.append(nt)
+    return retlist
+
+
+# =====================================================================
+# --- Windows services
+# =====================================================================
+
+
+def win_service_iter():
+    """Yields a list of WindowsService instances."""
+    for name, display_name in cext.winservice_enumerate():
+        yield WindowsService(name, display_name)
+
+
+def win_service_get(name):
+    """Open a Windows service and return it as a WindowsService instance."""
+    service = WindowsService(name, None)
+    service._display_name = service._query_config()['display_name']
+    return service
+
+
+class WindowsService:  # noqa: PLW1641
+    """Represents an installed Windows service."""
+
+    def __init__(self, name, display_name):
+        self._name = name
+        self._display_name = display_name
+
+    def __str__(self):
+        details = f"(name={self._name!r}, display_name={self._display_name!r})"
+        return f"{self.__class__.__name__}{details}"
+
+    def __repr__(self):
+        return f"<{self.__str__()} at {id(self)}>"
+
+    def __eq__(self, other):
+        # Test for equality with another WindosService object based
+        # on name.
+        if not isinstance(other, WindowsService):
+            return NotImplemented
+        return self._name == other._name
+
+    def __ne__(self, other):
+        return not self == other
+
+    def _query_config(self):
+        with self._wrap_exceptions():
+            display_name, binpath, username, start_type = (
+                cext.winservice_query_config(self._name)
+            )
+        # XXX - update _self.display_name?
+        return dict(
+            display_name=display_name,
+            binpath=binpath,
+            username=username,
+            start_type=start_type,
+        )
+
+    def _query_status(self):
+        with self._wrap_exceptions():
+            status, pid = cext.winservice_query_status(self._name)
+        if pid == 0:
+            pid = None
+        return dict(status=status, pid=pid)
+
+    @contextlib.contextmanager
+    def _wrap_exceptions(self):
+        """Ctx manager which translates bare OSError and WindowsError
+        exceptions into NoSuchProcess and AccessDenied.
+        """
+        try:
+            yield
+        except OSError as err:
+            name = self._name
+            if is_permission_err(err):
+                msg = (
+                    f"service {name!r} is not querable (not enough privileges)"
+                )
+                raise AccessDenied(pid=None, name=name, msg=msg) from err
+            elif err.winerror in {
+                cext.ERROR_INVALID_NAME,
+                cext.ERROR_SERVICE_DOES_NOT_EXIST,
+            }:
+                msg = f"service {name!r} does not exist"
+                raise NoSuchProcess(pid=None, name=name, msg=msg) from err
+            else:
+                raise
+
+    # config query
+
+    def name(self):
+        """The service name. This string is how a service is referenced
+        and can be passed to win_service_get() to get a new
+        WindowsService instance.
+        """
+        return self._name
+
+    def display_name(self):
+        """The service display name. The value is cached when this class
+        is instantiated.
+        """
+        return self._display_name
+
+    def binpath(self):
+        """The fully qualified path to the service binary/exe file as
+        a string, including command line arguments.
+        """
+        return self._query_config()['binpath']
+
+    def username(self):
+        """The name of the user that owns this service."""
+        return self._query_config()['username']
+
+    def start_type(self):
+        """A string which can either be "automatic", "manual" or
+        "disabled".
+        """
+        return self._query_config()['start_type']
+
+    # status query
+
+    def pid(self):
+        """The process PID, if any, else None. This can be passed
+        to Process class to control the service's process.
+        """
+        return self._query_status()['pid']
+
+    def status(self):
+        """Service status as a string."""
+        return self._query_status()['status']
+
+    def description(self):
+        """Service long description."""
+        return cext.winservice_query_descr(self.name())
+
+    # utils
+
+    def as_dict(self):
+        """Utility method retrieving all the information above as a
+        dictionary.
+        """
+        d = self._query_config()
+        d.update(self._query_status())
+        d['name'] = self.name()
+        d['display_name'] = self.display_name()
+        d['description'] = self.description()
+        return d
+
+    # actions
+    # XXX: the necessary C bindings for start() and stop() are
+    # implemented but for now I prefer not to expose them.
+    # I may change my mind in the future. Reasons:
+    # - they require Administrator privileges
+    # - can't implement a timeout for stop() (unless by using a thread,
+    #   which sucks)
+    # - would require adding ServiceAlreadyStarted and
+    #   ServiceAlreadyStopped exceptions, adding two new APIs.
+    # - we might also want to have modify(), which would basically mean
+    #   rewriting win32serviceutil.ChangeServiceConfig, which involves a
+    #   lot of stuff (and API constants which would pollute the API), see:
+    #   http://pyxr.sourceforge.net/PyXR/c/python24/lib/site-packages/
+    #       win32/lib/win32serviceutil.py.html#0175
+    # - psutil is typically about "read only" monitoring stuff;
+    #   win_service_* APIs should only be used to retrieve a service and
+    #   check whether it's running
+
+    # def start(self, timeout=None):
+    #     with self._wrap_exceptions():
+    #         cext.winservice_start(self.name())
+    #         if timeout:
+    #             giveup_at = time.time() + timeout
+    #             while True:
+    #                 if self.status() == "running":
+    #                     return
+    #                 else:
+    #                     if time.time() > giveup_at:
+    #                         raise TimeoutExpired(timeout)
+    #                     else:
+    #                         time.sleep(.1)
+
+    # def stop(self):
+    #     # Note: timeout is not implemented because it's just not
+    #     # possible, see:
+    #     # http://stackoverflow.com/questions/11973228/
+    #     with self._wrap_exceptions():
+    #         return cext.winservice_stop(self.name())
+
+
+# =====================================================================
+# --- processes
+# =====================================================================
+
+
+pids = cext.pids
+pid_exists = cext.pid_exists
+ppid_map = cext.ppid_map  # used internally by Process.children()
+
+
+def is_permission_err(exc):
+    """Return True if this is a permission error."""
+    assert isinstance(exc, OSError), exc
+    return isinstance(exc, PermissionError) or exc.winerror in {
+        cext.ERROR_ACCESS_DENIED,
+        cext.ERROR_PRIVILEGE_NOT_HELD,
+    }
+
+
+def convert_oserror(exc, pid=None, name=None):
+    """Convert OSError into NoSuchProcess or AccessDenied."""
+    assert isinstance(exc, OSError), exc
+    if is_permission_err(exc):
+        return AccessDenied(pid=pid, name=name)
+    if isinstance(exc, ProcessLookupError):
+        return NoSuchProcess(pid=pid, name=name)
+    raise exc
+
+
+def wrap_exceptions(fun):
+    """Decorator which converts OSError into NoSuchProcess or AccessDenied."""
+
+    @functools.wraps(fun)
+    def wrapper(self, *args, **kwargs):
+        try:
+            return fun(self, *args, **kwargs)
+        except OSError as err:
+            raise convert_oserror(err, pid=self.pid, name=self._name) from err
+
+    return wrapper
+
+
+def retry_error_partial_copy(fun):
+    """Workaround for https://github.com/giampaolo/psutil/issues/875.
+    See: https://stackoverflow.com/questions/4457745#4457745.
+    """
+
+    @functools.wraps(fun)
+    def wrapper(self, *args, **kwargs):
+        delay = 0.0001
+        times = 33
+        for _ in range(times):  # retries for roughly 1 second
+            try:
+                return fun(self, *args, **kwargs)
+            except OSError as _:
+                err = _
+                if err.winerror == ERROR_PARTIAL_COPY:
+                    time.sleep(delay)
+                    delay = min(delay * 2, 0.04)
+                    continue
+                raise
+        msg = (
+            f"{fun} retried {times} times, converted to AccessDenied as it's "
+            f"still returning {err}"
+        )
+        raise AccessDenied(pid=self.pid, name=self._name, msg=msg)
+
+    return wrapper
+
+
+class Process:
+    """Wrapper class around underlying C implementation."""
+
+    __slots__ = ["_cache", "_name", "_ppid", "pid"]
+
+    def __init__(self, pid):
+        self.pid = pid
+        self._name = None
+        self._ppid = None
+
+    # --- oneshot() stuff
+
+    def oneshot_enter(self):
+        self._proc_info.cache_activate(self)
+        self.exe.cache_activate(self)
+
+    def oneshot_exit(self):
+        self._proc_info.cache_deactivate(self)
+        self.exe.cache_deactivate(self)
+
+    @memoize_when_activated
+    def _proc_info(self):
+        """Return multiple information about this process as a
+        raw tuple.
+        """
+        ret = cext.proc_info(self.pid)
+        assert len(ret) == len(pinfo_map)
+        return ret
+
+    def name(self):
+        """Return process name, which on Windows is always the final
+        part of the executable.
+        """
+        # This is how PIDs 0 and 4 are always represented in taskmgr
+        # and process-hacker.
+        if self.pid == 0:
+            return "System Idle Process"
+        if self.pid == 4:
+            return "System"
+        return os.path.basename(self.exe())
+
+    @wrap_exceptions
+    @memoize_when_activated
+    def exe(self):
+        if PYPY:
+            try:
+                exe = cext.proc_exe(self.pid)
+            except OSError as err:
+                # 24 = ERROR_TOO_MANY_OPEN_FILES. Not sure why this happens
+                # (perhaps PyPy's JIT delaying garbage collection of files?).
+                if err.errno == 24:
+                    debug(f"{err!r} translated into AccessDenied")
+                    raise AccessDenied(self.pid, self._name) from err
+                raise
+        else:
+            exe = cext.proc_exe(self.pid)
+        if exe.startswith('\\'):
+            return convert_dos_path(exe)
+        return exe  # May be "Registry", "MemCompression", ...
+
+    @wrap_exceptions
+    @retry_error_partial_copy
+    def cmdline(self):
+        if cext.WINVER >= cext.WINDOWS_8_1:
+            # PEB method detects cmdline changes but requires more
+            # privileges: https://github.com/giampaolo/psutil/pull/1398
+            try:
+                return cext.proc_cmdline(self.pid, use_peb=True)
+            except OSError as err:
+                if is_permission_err(err):
+                    return cext.proc_cmdline(self.pid, use_peb=False)
+                else:
+                    raise
+        else:
+            return cext.proc_cmdline(self.pid, use_peb=True)
+
+    @wrap_exceptions
+    @retry_error_partial_copy
+    def environ(self):
+        s = cext.proc_environ(self.pid)
+        return parse_environ_block(s)
+
+    def ppid(self):
+        try:
+            return ppid_map()[self.pid]
+        except KeyError:
+            raise NoSuchProcess(self.pid, self._name) from None
+
+    def _get_raw_meminfo(self):
+        try:
+            return cext.proc_memory_info(self.pid)
+        except OSError as err:
+            if is_permission_err(err):
+                # TODO: the C ext can probably be refactored in order
+                # to get this from cext.proc_info()
+                debug("attempting memory_info() fallback (slower)")
+                info = self._proc_info()
+                return (
+                    info[pinfo_map['num_page_faults']],
+                    info[pinfo_map['peak_wset']],
+                    info[pinfo_map['wset']],
+                    info[pinfo_map['peak_paged_pool']],
+                    info[pinfo_map['paged_pool']],
+                    info[pinfo_map['peak_non_paged_pool']],
+                    info[pinfo_map['non_paged_pool']],
+                    info[pinfo_map['pagefile']],
+                    info[pinfo_map['peak_pagefile']],
+                    info[pinfo_map['mem_private']],
+                )
+            raise
+
+    @wrap_exceptions
+    def memory_info(self):
+        # on Windows RSS == WorkingSetSize and VSM == PagefileUsage.
+        # Underlying C function returns fields of PROCESS_MEMORY_COUNTERS
+        # struct.
+        t = self._get_raw_meminfo()
+        rss = t[2]  # wset
+        vms = t[7]  # pagefile
+        return ntp.pmem(*(rss, vms) + t)
+
+    @wrap_exceptions
+    def memory_full_info(self):
+        basic_mem = self.memory_info()
+        uss = cext.proc_memory_uss(self.pid)
+        uss *= getpagesize()
+        return ntp.pfullmem(*basic_mem + (uss,))
+
+    def memory_maps(self):
+        try:
+            raw = cext.proc_memory_maps(self.pid)
+        except OSError as err:
+            # XXX - can't use wrap_exceptions decorator as we're
+            # returning a generator; probably needs refactoring.
+            raise convert_oserror(err, self.pid, self._name) from err
+        else:
+            for addr, perm, path, rss in raw:
+                path = convert_dos_path(path)
+                addr = hex(addr)
+                yield (addr, perm, path, rss)
+
+    @wrap_exceptions
+    def kill(self):
+        return cext.proc_kill(self.pid)
+
+    @wrap_exceptions
+    def send_signal(self, sig):
+        if sig == signal.SIGTERM:
+            cext.proc_kill(self.pid)
+        elif sig in {signal.CTRL_C_EVENT, signal.CTRL_BREAK_EVENT}:
+            os.kill(self.pid, sig)
+        else:
+            msg = (
+                "only SIGTERM, CTRL_C_EVENT and CTRL_BREAK_EVENT signals "
+                "are supported on Windows"
+            )
+            raise ValueError(msg)
+
+    @wrap_exceptions
+    def wait(self, timeout=None):
+        if timeout is None:
+            cext_timeout = cext.INFINITE
+        else:
+            # WaitForSingleObject() expects time in milliseconds.
+            cext_timeout = int(timeout * 1000)
+
+        timer = getattr(time, 'monotonic', time.time)
+        stop_at = timer() + timeout if timeout is not None else None
+
+        try:
+            # Exit code is supposed to come from GetExitCodeProcess().
+            # May also be None if OpenProcess() failed with
+            # ERROR_INVALID_PARAMETER, meaning PID is already gone.
+            exit_code = cext.proc_wait(self.pid, cext_timeout)
+        except cext.TimeoutExpired as err:
+            # WaitForSingleObject() returned WAIT_TIMEOUT. Just raise.
+            raise TimeoutExpired(timeout, self.pid, self._name) from err
+        except cext.TimeoutAbandoned:
+            # WaitForSingleObject() returned WAIT_ABANDONED, see:
+            # https://github.com/giampaolo/psutil/issues/1224
+            # We'll just rely on the internal polling and return None
+            # when the PID disappears. Subprocess module does the same
+            # (return None):
+            # https://github.com/python/cpython/blob/
+            #     be50a7b627d0aa37e08fa8e2d5568891f19903ce/
+            #     Lib/subprocess.py#L1193-L1194
+            exit_code = None
+
+        # At this point WaitForSingleObject() returned WAIT_OBJECT_0,
+        # meaning the process is gone. Stupidly there are cases where
+        # its PID may still stick around so we do a further internal
+        # polling.
+        delay = 0.0001
+        while True:
+            if not pid_exists(self.pid):
+                return exit_code
+            if stop_at and timer() >= stop_at:
+                raise TimeoutExpired(timeout, pid=self.pid, name=self._name)
+            time.sleep(delay)
+            delay = min(delay * 2, 0.04)  # incremental delay
+
+    @wrap_exceptions
+    def username(self):
+        if self.pid in {0, 4}:
+            return 'NT AUTHORITY\\SYSTEM'
+        domain, user = cext.proc_username(self.pid)
+        return f"{domain}\\{user}"
+
+    @wrap_exceptions
+    def create_time(self, fast_only=False):
+        # Note: proc_times() not put under oneshot() 'cause create_time()
+        # is already cached by the main Process class.
+        try:
+            _user, _system, created = cext.proc_times(self.pid)
+            return created
+        except OSError as err:
+            if is_permission_err(err):
+                if fast_only:
+                    raise
+                debug("attempting create_time() fallback (slower)")
+                return self._proc_info()[pinfo_map['create_time']]
+            raise
+
+    @wrap_exceptions
+    def num_threads(self):
+        return self._proc_info()[pinfo_map['num_threads']]
+
+    @wrap_exceptions
+    def threads(self):
+        rawlist = cext.proc_threads(self.pid)
+        retlist = []
+        for thread_id, utime, stime in rawlist:
+            ntuple = ntp.pthread(thread_id, utime, stime)
+            retlist.append(ntuple)
+        return retlist
+
+    @wrap_exceptions
+    def cpu_times(self):
+        try:
+            user, system, _created = cext.proc_times(self.pid)
+        except OSError as err:
+            if not is_permission_err(err):
+                raise
+            debug("attempting cpu_times() fallback (slower)")
+            info = self._proc_info()
+            user = info[pinfo_map['user_time']]
+            system = info[pinfo_map['kernel_time']]
+        # Children user/system times are not retrievable (set to 0).
+        return ntp.pcputimes(user, system, 0.0, 0.0)
+
+    @wrap_exceptions
+    def suspend(self):
+        cext.proc_suspend_or_resume(self.pid, True)
+
+    @wrap_exceptions
+    def resume(self):
+        cext.proc_suspend_or_resume(self.pid, False)
+
+    @wrap_exceptions
+    @retry_error_partial_copy
+    def cwd(self):
+        if self.pid in {0, 4}:
+            raise AccessDenied(self.pid, self._name)
+        # return a normalized pathname since the native C function appends
+        # "\\" at the and of the path
+        path = cext.proc_cwd(self.pid)
+        return os.path.normpath(path)
+
+    @wrap_exceptions
+    def open_files(self):
+        if self.pid in {0, 4}:
+            return []
+        ret = set()
+        # Filenames come in in native format like:
+        # "\Device\HarddiskVolume1\Windows\systemew\file.txt"
+        # Convert the first part in the corresponding drive letter
+        # (e.g. "C:\") by using Windows's QueryDosDevice()
+        raw_file_names = cext.proc_open_files(self.pid)
+        for file in raw_file_names:
+            file = convert_dos_path(file)
+            if isfile_strict(file):
+                ntuple = ntp.popenfile(file, -1)
+                ret.add(ntuple)
+        return list(ret)
+
+    @wrap_exceptions
+    def net_connections(self, kind='inet'):
+        return net_connections(kind, _pid=self.pid)
+
+    @wrap_exceptions
+    def nice_get(self):
+        value = cext.proc_priority_get(self.pid)
+        value = Priority(value)
+        return value
+
+    @wrap_exceptions
+    def nice_set(self, value):
+        return cext.proc_priority_set(self.pid, value)
+
+    @wrap_exceptions
+    def ionice_get(self):
+        ret = cext.proc_io_priority_get(self.pid)
+        ret = IOPriority(ret)
+        return ret
+
+    @wrap_exceptions
+    def ionice_set(self, ioclass, value):
+        if value:
+            msg = "value argument not accepted on Windows"
+            raise TypeError(msg)
+        if ioclass not in {
+            IOPriority.IOPRIO_VERYLOW,
+            IOPriority.IOPRIO_LOW,
+            IOPriority.IOPRIO_NORMAL,
+            IOPriority.IOPRIO_HIGH,
+        }:
+            msg = f"{ioclass} is not a valid priority"
+            raise ValueError(msg)
+        cext.proc_io_priority_set(self.pid, ioclass)
+
+    @wrap_exceptions
+    def io_counters(self):
+        try:
+            ret = cext.proc_io_counters(self.pid)
+        except OSError as err:
+            if not is_permission_err(err):
+                raise
+            debug("attempting io_counters() fallback (slower)")
+            info = self._proc_info()
+            ret = (
+                info[pinfo_map['io_rcount']],
+                info[pinfo_map['io_wcount']],
+                info[pinfo_map['io_rbytes']],
+                info[pinfo_map['io_wbytes']],
+                info[pinfo_map['io_count_others']],
+                info[pinfo_map['io_bytes_others']],
+            )
+        return ntp.pio(*ret)
+
+    @wrap_exceptions
+    def status(self):
+        suspended = cext.proc_is_suspended(self.pid)
+        if suspended:
+            return _common.STATUS_STOPPED
+        else:
+            return _common.STATUS_RUNNING
+
+    @wrap_exceptions
+    def cpu_affinity_get(self):
+        def from_bitmask(x):
+            return [i for i in range(64) if (1 << i) & x]
+
+        bitmask = cext.proc_cpu_affinity_get(self.pid)
+        return from_bitmask(bitmask)
+
+    @wrap_exceptions
+    def cpu_affinity_set(self, value):
+        def to_bitmask(ls):
+            if not ls:
+                msg = f"invalid argument {ls!r}"
+                raise ValueError(msg)
+            out = 0
+            for b in ls:
+                out |= 2**b
+            return out
+
+        # SetProcessAffinityMask() states that ERROR_INVALID_PARAMETER
+        # is returned for an invalid CPU but this seems not to be true,
+        # therefore we check CPUs validy beforehand.
+        allcpus = list(range(len(per_cpu_times())))
+        for cpu in value:
+            if cpu not in allcpus:
+                if not isinstance(cpu, int):
+                    msg = f"invalid CPU {cpu!r}; an integer is required"
+                    raise TypeError(msg)
+                msg = f"invalid CPU {cpu!r}"
+                raise ValueError(msg)
+
+        bitmask = to_bitmask(value)
+        cext.proc_cpu_affinity_set(self.pid, bitmask)
+
+    @wrap_exceptions
+    def num_handles(self):
+        try:
+            return cext.proc_num_handles(self.pid)
+        except OSError as err:
+            if is_permission_err(err):
+                debug("attempting num_handles() fallback (slower)")
+                return self._proc_info()[pinfo_map['num_handles']]
+            raise
+
+    @wrap_exceptions
+    def num_ctx_switches(self):
+        ctx_switches = self._proc_info()[pinfo_map['ctx_switches']]
+        # only voluntary ctx switches are supported
+        return ntp.pctxsw(ctx_switches, 0)
diff --git a/micromamba_root/Lib/site-packages/pygments/cmdline.py b/micromamba_root/Lib/site-packages/pygments/cmdline.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd4a1fb43926b7f7bdd7ef5028dbe19a9137515a
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pygments/cmdline.py
@@ -0,0 +1,668 @@
+"""
+    pygments.cmdline
+    ~~~~~~~~~~~~~~~~
+
+    Command line interface.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import os
+import sys
+import shutil
+import argparse
+from textwrap import dedent
+
+from pygments import __version__, highlight
+from pygments.util import ClassNotFound, OptionError, docstring_headline, \
+    guess_decode, guess_decode_from_terminal, terminal_encoding, \
+    UnclosingTextIOWrapper
+from pygments.lexers import get_all_lexers, get_lexer_by_name, guess_lexer, \
+    load_lexer_from_file, get_lexer_for_filename, find_lexer_class_for_filename
+from pygments.lexers.special import TextLexer
+from pygments.formatters.latex import LatexEmbeddedLexer, LatexFormatter
+from pygments.formatters import get_all_formatters, get_formatter_by_name, \
+    load_formatter_from_file, get_formatter_for_filename, find_formatter_class
+from pygments.formatters.terminal import TerminalFormatter
+from pygments.formatters.terminal256 import Terminal256Formatter, TerminalTrueColorFormatter
+from pygments.filters import get_all_filters, find_filter_class
+from pygments.styles import get_all_styles, get_style_by_name
+
+
+def _parse_options(o_strs):
+    opts = {}
+    if not o_strs:
+        return opts
+    for o_str in o_strs:
+        if not o_str.strip():
+            continue
+        o_args = o_str.split(',')
+        for o_arg in o_args:
+            o_arg = o_arg.strip()
+            try:
+                o_key, o_val = o_arg.split('=', 1)
+                o_key = o_key.strip()
+                o_val = o_val.strip()
+            except ValueError:
+                opts[o_arg] = True
+            else:
+                opts[o_key] = o_val
+    return opts
+
+
+def _parse_filters(f_strs):
+    filters = []
+    if not f_strs:
+        return filters
+    for f_str in f_strs:
+        if ':' in f_str:
+            fname, fopts = f_str.split(':', 1)
+            filters.append((fname, _parse_options([fopts])))
+        else:
+            filters.append((f_str, {}))
+    return filters
+
+
+def _print_help(what, name):
+    try:
+        if what == 'lexer':
+            cls = get_lexer_by_name(name)
+            print(f"Help on the {cls.name} lexer:")
+            print(dedent(cls.__doc__))
+        elif what == 'formatter':
+            cls = find_formatter_class(name)
+            print(f"Help on the {cls.name} formatter:")
+            print(dedent(cls.__doc__))
+        elif what == 'filter':
+            cls = find_filter_class(name)
+            print(f"Help on the {name} filter:")
+            print(dedent(cls.__doc__))
+        return 0
+    except (AttributeError, ValueError):
+        print(f"{what} not found!", file=sys.stderr)
+        return 1
+
+
+def _print_list(what):
+    if what == 'lexer':
+        print()
+        print("Lexers:")
+        print("~~~~~~~")
+
+        info = []
+        for fullname, names, exts, _ in get_all_lexers():
+            tup = (', '.join(names)+':', fullname,
+                   exts and '(filenames ' + ', '.join(exts) + ')' or '')
+            info.append(tup)
+        info.sort()
+        for i in info:
+            print(('* {}\n    {} {}').format(*i))
+
+    elif what == 'formatter':
+        print()
+        print("Formatters:")
+        print("~~~~~~~~~~~")
+
+        info = []
+        for cls in get_all_formatters():
+            doc = docstring_headline(cls)
+            tup = (', '.join(cls.aliases) + ':', doc, cls.filenames and
+                   '(filenames ' + ', '.join(cls.filenames) + ')' or '')
+            info.append(tup)
+        info.sort()
+        for i in info:
+            print(('* {}\n    {} {}').format(*i))
+
+    elif what == 'filter':
+        print()
+        print("Filters:")
+        print("~~~~~~~~")
+
+        for name in get_all_filters():
+            cls = find_filter_class(name)
+            print("* " + name + ':')
+            print(f"    {docstring_headline(cls)}")
+
+    elif what == 'style':
+        print()
+        print("Styles:")
+        print("~~~~~~~")
+
+        for name in get_all_styles():
+            cls = get_style_by_name(name)
+            print("* " + name + ':')
+            print(f"    {docstring_headline(cls)}")
+
+
+def _print_list_as_json(requested_items):
+    import json
+    result = {}
+    if 'lexer' in requested_items:
+        info = {}
+        for fullname, names, filenames, mimetypes in get_all_lexers():
+            info[fullname] = {
+                'aliases': names,
+                'filenames': filenames,
+                'mimetypes': mimetypes
+            }
+        result['lexers'] = info
+
+    if 'formatter' in requested_items:
+        info = {}
+        for cls in get_all_formatters():
+            doc = docstring_headline(cls)
+            info[cls.name] = {
+                'aliases': cls.aliases,
+                'filenames': cls.filenames,
+                'doc': doc
+            }
+        result['formatters'] = info
+
+    if 'filter' in requested_items:
+        info = {}
+        for name in get_all_filters():
+            cls = find_filter_class(name)
+            info[name] = {
+                'doc': docstring_headline(cls)
+            }
+        result['filters'] = info
+
+    if 'style' in requested_items:
+        info = {}
+        for name in get_all_styles():
+            cls = get_style_by_name(name)
+            info[name] = {
+                'doc': docstring_headline(cls)
+            }
+        result['styles'] = info
+
+    json.dump(result, sys.stdout)
+
+def main_inner(parser, argns):
+    if argns.help:
+        parser.print_help()
+        return 0
+
+    if argns.V:
+        print(f'Pygments version {__version__}, (c) 2006-present by Georg Brandl, Matthäus '
+              'Chajdas and contributors.')
+        return 0
+
+    def is_only_option(opt):
+        return not any(v for (k, v) in vars(argns).items() if k != opt)
+
+    # handle ``pygmentize -L``
+    if argns.L is not None:
+        arg_set = set()
+        for k, v in vars(argns).items():
+            if v:
+                arg_set.add(k)
+
+        arg_set.discard('L')
+        arg_set.discard('json')
+
+        if arg_set:
+            parser.print_help(sys.stderr)
+            return 2
+
+        # print version
+        if not argns.json:
+            main(['', '-V'])
+        allowed_types = {'lexer', 'formatter', 'filter', 'style'}
+        largs = [arg.rstrip('s') for arg in argns.L]
+        if any(arg not in allowed_types for arg in largs):
+            parser.print_help(sys.stderr)
+            return 0
+        if not largs:
+            largs = allowed_types
+        if not argns.json:
+            for arg in largs:
+                _print_list(arg)
+        else:
+            _print_list_as_json(largs)
+        return 0
+
+    # handle ``pygmentize -H``
+    if argns.H:
+        if not is_only_option('H'):
+            parser.print_help(sys.stderr)
+            return 2
+        what, name = argns.H
+        if what not in ('lexer', 'formatter', 'filter'):
+            parser.print_help(sys.stderr)
+            return 2
+        return _print_help(what, name)
+
+    # parse -O options
+    parsed_opts = _parse_options(argns.O or [])
+
+    # parse -P options
+    for p_opt in argns.P or []:
+        try:
+            name, value = p_opt.split('=', 1)
+        except ValueError:
+            parsed_opts[p_opt] = True
+        else:
+            parsed_opts[name] = value
+
+    # encodings
+    inencoding = parsed_opts.get('inencoding', parsed_opts.get('encoding'))
+    outencoding = parsed_opts.get('outencoding', parsed_opts.get('encoding'))
+
+    # handle ``pygmentize -N``
+    if argns.N:
+        lexer = find_lexer_class_for_filename(argns.N)
+        if lexer is None:
+            lexer = TextLexer
+
+        print(lexer.aliases[0])
+        return 0
+
+    # handle ``pygmentize -C``
+    if argns.C:
+        inp = sys.stdin.buffer.read()
+        try:
+            lexer = guess_lexer(inp, inencoding=inencoding)
+        except ClassNotFound:
+            lexer = TextLexer
+
+        print(lexer.aliases[0])
+        return 0
+
+    # handle ``pygmentize -S``
+    S_opt = argns.S
+    a_opt = argns.a
+    if S_opt is not None:
+        f_opt = argns.f
+        if not f_opt:
+            parser.print_help(sys.stderr)
+            return 2
+        if argns.l or argns.INPUTFILE:
+            parser.print_help(sys.stderr)
+            return 2
+
+        try:
+            parsed_opts['style'] = S_opt
+            fmter = get_formatter_by_name(f_opt, **parsed_opts)
+        except ClassNotFound as err:
+            print(err, file=sys.stderr)
+            return 1
+
+        print(fmter.get_style_defs(a_opt or ''))
+        return 0
+
+    # if no -S is given, -a is not allowed
+    if argns.a is not None:
+        parser.print_help(sys.stderr)
+        return 2
+
+    # parse -F options
+    F_opts = _parse_filters(argns.F or [])
+
+    # -x: allow custom (eXternal) lexers and formatters
+    allow_custom_lexer_formatter = bool(argns.x)
+
+    # select lexer
+    lexer = None
+
+    # given by name?
+    lexername = argns.l
+    if lexername:
+        # custom lexer, located relative to user's cwd
+        if allow_custom_lexer_formatter and '.py' in lexername:
+            try:
+                filename = None
+                name = None
+                if ':' in lexername:
+                    filename, name = lexername.rsplit(':', 1)
+
+                    if '.py' in name:
+                        # This can happen on Windows: If the lexername is
+                        # C:\lexer.py -- return to normal load path in that case
+                        name = None
+
+                if filename and name:
+                    lexer = load_lexer_from_file(filename, name,
+                                                 **parsed_opts)
+                else:
+                    lexer = load_lexer_from_file(lexername, **parsed_opts)
+            except ClassNotFound as err:
+                print('Error:', err, file=sys.stderr)
+                return 1
+        else:
+            try:
+                lexer = get_lexer_by_name(lexername, **parsed_opts)
+            except (OptionError, ClassNotFound) as err:
+                print('Error:', err, file=sys.stderr)
+                return 1
+
+    # read input code
+    code = None
+
+    if argns.INPUTFILE:
+        if argns.s:
+            print('Error: -s option not usable when input file specified',
+                  file=sys.stderr)
+            return 2
+
+        infn = argns.INPUTFILE
+        try:
+            with open(infn, 'rb') as infp:
+                code = infp.read()
+        except Exception as err:
+            print('Error: cannot read infile:', err, file=sys.stderr)
+            return 1
+        if not inencoding:
+            code, inencoding = guess_decode(code)
+
+        # do we have to guess the lexer?
+        if not lexer:
+            try:
+                lexer = get_lexer_for_filename(infn, code, **parsed_opts)
+            except ClassNotFound as err:
+                if argns.g:
+                    try:
+                        lexer = guess_lexer(code, **parsed_opts)
+                    except ClassNotFound:
+                        lexer = TextLexer(**parsed_opts)
+                else:
+                    print('Error:', err, file=sys.stderr)
+                    return 1
+            except OptionError as err:
+                print('Error:', err, file=sys.stderr)
+                return 1
+
+    elif not argns.s:  # treat stdin as full file (-s support is later)
+        # read code from terminal, always in binary mode since we want to
+        # decode ourselves and be tolerant with it
+        code = sys.stdin.buffer.read()  # use .buffer to get a binary stream
+        if not inencoding:
+            code, inencoding = guess_decode_from_terminal(code, sys.stdin)
+            # else the lexer will do the decoding
+        if not lexer:
+            try:
+                lexer = guess_lexer(code, **parsed_opts)
+            except ClassNotFound:
+                lexer = TextLexer(**parsed_opts)
+
+    else:  # -s option needs a lexer with -l
+        if not lexer:
+            print('Error: when using -s a lexer has to be selected with -l',
+                  file=sys.stderr)
+            return 2
+
+    # process filters
+    for fname, fopts in F_opts:
+        try:
+            lexer.add_filter(fname, **fopts)
+        except ClassNotFound as err:
+            print('Error:', err, file=sys.stderr)
+            return 1
+
+    # select formatter
+    outfn = argns.o
+    fmter = argns.f
+    if fmter:
+        # custom formatter, located relative to user's cwd
+        if allow_custom_lexer_formatter and '.py' in fmter:
+            try:
+                filename = None
+                name = None
+                if ':' in fmter:
+                    # Same logic as above for custom lexer
+                    filename, name = fmter.rsplit(':', 1)
+
+                    if '.py' in name:
+                        name = None
+
+                if filename and name:
+                    fmter = load_formatter_from_file(filename, name,
+                                                     **parsed_opts)
+                else:
+                    fmter = load_formatter_from_file(fmter, **parsed_opts)
+            except ClassNotFound as err:
+                print('Error:', err, file=sys.stderr)
+                return 1
+        else:
+            try:
+                fmter = get_formatter_by_name(fmter, **parsed_opts)
+            except (OptionError, ClassNotFound) as err:
+                print('Error:', err, file=sys.stderr)
+                return 1
+
+    if outfn:
+        if not fmter:
+            try:
+                fmter = get_formatter_for_filename(outfn, **parsed_opts)
+            except (OptionError, ClassNotFound) as err:
+                print('Error:', err, file=sys.stderr)
+                return 1
+        try:
+            outfile = open(outfn, 'wb')
+        except Exception as err:
+            print('Error: cannot open outfile:', err, file=sys.stderr)
+            return 1
+    else:
+        if not fmter:
+            if os.environ.get('COLORTERM','') in ('truecolor', '24bit'):
+                fmter = TerminalTrueColorFormatter(**parsed_opts)
+            elif '256' in os.environ.get('TERM', ''):
+                fmter = Terminal256Formatter(**parsed_opts)
+            else:
+                fmter = TerminalFormatter(**parsed_opts)
+        outfile = sys.stdout.buffer
+
+    # determine output encoding if not explicitly selected
+    if not outencoding:
+        if outfn:
+            # output file? use lexer encoding for now (can still be None)
+            fmter.encoding = inencoding
+        else:
+            # else use terminal encoding
+            fmter.encoding = terminal_encoding(sys.stdout)
+
+    # provide coloring under Windows, if possible
+    if not outfn and sys.platform in ('win32', 'cygwin') and \
+       fmter.name in ('Terminal', 'Terminal256'):  # pragma: no cover
+        # unfortunately colorama doesn't support binary streams on Py3
+        outfile = UnclosingTextIOWrapper(outfile, encoding=fmter.encoding)
+        fmter.encoding = None
+        try:
+            import colorama.initialise
+        except ImportError:
+            pass
+        else:
+            outfile = colorama.initialise.wrap_stream(
+                outfile, convert=None, strip=None, autoreset=False, wrap=True)
+
+    # When using the LaTeX formatter and the option `escapeinside` is
+    # specified, we need a special lexer which collects escaped text
+    # before running the chosen language lexer.
+    escapeinside = parsed_opts.get('escapeinside', '')
+    if len(escapeinside) == 2 and isinstance(fmter, LatexFormatter):
+        left = escapeinside[0]
+        right = escapeinside[1]
+        lexer = LatexEmbeddedLexer(left, right, lexer)
+
+    # ... and do it!
+    if not argns.s:
+        # process whole input as per normal...
+        try:
+            highlight(code, lexer, fmter, outfile)
+        finally:
+            if outfn:
+                outfile.close()
+        return 0
+    else:
+        # line by line processing of stdin (eg: for 'tail -f')...
+        try:
+            while 1:
+                line = sys.stdin.buffer.readline()
+                if not line:
+                    break
+                if not inencoding:
+                    line = guess_decode_from_terminal(line, sys.stdin)[0]
+                highlight(line, lexer, fmter, outfile)
+                if hasattr(outfile, 'flush'):
+                    outfile.flush()
+            return 0
+        except KeyboardInterrupt:  # pragma: no cover
+            return 0
+        finally:
+            if outfn:
+                outfile.close()
+
+
+class HelpFormatter(argparse.HelpFormatter):
+    def __init__(self, prog, indent_increment=2, max_help_position=16, width=None):
+        if width is None:
+            try:
+                width = shutil.get_terminal_size().columns - 2
+            except Exception:
+                pass
+        argparse.HelpFormatter.__init__(self, prog, indent_increment,
+                                        max_help_position, width)
+
+
+def main(args=sys.argv):
+    """
+    Main command line entry point.
+    """
+    desc = "Highlight an input file and write the result to an output file."
+    parser = argparse.ArgumentParser(description=desc, add_help=False,
+                                     formatter_class=HelpFormatter)
+
+    operation = parser.add_argument_group('Main operation')
+    lexersel = operation.add_mutually_exclusive_group()
+    lexersel.add_argument(
+        '-l', metavar='LEXER',
+        help='Specify the lexer to use.  (Query names with -L.)  If not '
+        'given and -g is not present, the lexer is guessed from the filename.')
+    lexersel.add_argument(
+        '-g', action='store_true',
+        help='Guess the lexer from the file contents, or pass through '
+        'as plain text if nothing can be guessed.')
+    operation.add_argument(
+        '-F', metavar='FILTER[:options]', action='append',
+        help='Add a filter to the token stream.  (Query names with -L.) '
+        'Filter options are given after a colon if necessary.')
+    operation.add_argument(
+        '-f', metavar='FORMATTER',
+        help='Specify the formatter to use.  (Query names with -L.) '
+        'If not given, the formatter is guessed from the output filename, '
+        'and defaults to the terminal formatter if the output is to the '
+        'terminal or an unknown file extension.')
+    operation.add_argument(
+        '-O', metavar='OPTION=value[,OPTION=value,...]', action='append',
+        help='Give options to the lexer and formatter as a comma-separated '
+        'list of key-value pairs. '
+        'Example: `-O bg=light,python=cool`.')
+    operation.add_argument(
+        '-P', metavar='OPTION=value', action='append',
+        help='Give a single option to the lexer and formatter - with this '
+        'you can pass options whose value contains commas and equal signs. '
+        'Example: `-P "heading=Pygments, the Python highlighter"`.')
+    operation.add_argument(
+        '-o', metavar='OUTPUTFILE',
+        help='Where to write the output.  Defaults to standard output.')
+
+    operation.add_argument(
+        'INPUTFILE', nargs='?',
+        help='Where to read the input.  Defaults to standard input.')
+
+    flags = parser.add_argument_group('Operation flags')
+    flags.add_argument(
+        '-v', action='store_true',
+        help='Print a detailed traceback on unhandled exceptions, which '
+        'is useful for debugging and bug reports.')
+    flags.add_argument(
+        '-s', action='store_true',
+        help='Process lines one at a time until EOF, rather than waiting to '
+        'process the entire file.  This only works for stdin, only for lexers '
+        'with no line-spanning constructs, and is intended for streaming '
+        'input such as you get from `tail -f`. '
+        'Example usage: `tail -f sql.log | pygmentize -s -l sql`.')
+    flags.add_argument(
+        '-x', action='store_true',
+        help='Allow custom lexers and formatters to be loaded from a .py file '
+        'relative to the current working directory. For example, '
+        '`-l ./customlexer.py -x`. By default, this option expects a file '
+        'with a class named CustomLexer or CustomFormatter; you can also '
+        'specify your own class name with a colon (`-l ./lexer.py:MyLexer`). '
+        'Users should be very careful not to use this option with untrusted '
+        'files, because it will import and run them.')
+    flags.add_argument('--json', help='Output as JSON. This can '
+        'be only used in conjunction with -L.',
+        default=False,
+        action='store_true')
+
+    special_modes_group = parser.add_argument_group(
+        'Special modes - do not do any highlighting')
+    special_modes = special_modes_group.add_mutually_exclusive_group()
+    special_modes.add_argument(
+        '-S', metavar='STYLE -f formatter',
+        help='Print style definitions for STYLE for a formatter '
+        'given with -f. The argument given by -a is formatter '
+        'dependent.')
+    special_modes.add_argument(
+        '-L', nargs='*', metavar='WHAT',
+        help='List lexers, formatters, styles or filters -- '
+        'give additional arguments for the thing(s) you want to list '
+        '(e.g. "styles"), or omit them to list everything.')
+    special_modes.add_argument(
+        '-N', metavar='FILENAME',
+        help='Guess and print out a lexer name based solely on the given '
+        'filename. Does not take input or highlight anything. If no specific '
+        'lexer can be determined, "text" is printed.')
+    special_modes.add_argument(
+        '-C', action='store_true',
+        help='Like -N, but print out a lexer name based solely on '
+        'a given content from standard input.')
+    special_modes.add_argument(
+        '-H', action='store', nargs=2, metavar=('NAME', 'TYPE'),
+        help='Print detailed help for the object  of type , '
+        'where  is one of "lexer", "formatter" or "filter".')
+    special_modes.add_argument(
+        '-V', action='store_true',
+        help='Print the package version.')
+    special_modes.add_argument(
+        '-h', '--help', action='store_true',
+        help='Print this help.')
+    special_modes_group.add_argument(
+        '-a', metavar='ARG',
+        help='Formatter-specific additional argument for the -S (print '
+        'style sheet) mode.')
+
+    argns = parser.parse_args(args[1:])
+
+    try:
+        return main_inner(parser, argns)
+    except BrokenPipeError:
+        # someone closed our stdout, e.g. by quitting a pager.
+        return 0
+    except Exception:
+        if argns.v:
+            print(file=sys.stderr)
+            print('*' * 65, file=sys.stderr)
+            print('An unhandled exception occurred while highlighting.',
+                  file=sys.stderr)
+            print('Please report the whole traceback to the issue tracker at',
+                  file=sys.stderr)
+            print('.',
+                  file=sys.stderr)
+            print('*' * 65, file=sys.stderr)
+            print(file=sys.stderr)
+            raise
+        import traceback
+        info = traceback.format_exception(*sys.exc_info())
+        msg = info[-1].strip()
+        if len(info) >= 3:
+            # extract relevant file and position info
+            msg += '\n   (f{})'.format(info[-2].split('\n')[0].strip()[1:])
+        print(file=sys.stderr)
+        print('*** Error while highlighting:', file=sys.stderr)
+        print(msg, file=sys.stderr)
+        print('*** If this is a bug you want to report, please rerun with -v.',
+              file=sys.stderr)
+        return 1
diff --git a/micromamba_root/Lib/site-packages/pygments/console.py b/micromamba_root/Lib/site-packages/pygments/console.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9009168cadbe25ba0bb1fc5427a5db0f1582830
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pygments/console.py
@@ -0,0 +1,70 @@
+"""
+    pygments.console
+    ~~~~~~~~~~~~~~~~
+
+    Format colored console output.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+esc = "\x1b["
+
+codes = {}
+codes[""] = ""
+codes["reset"] = esc + "39;49;00m"
+
+codes["bold"] = esc + "01m"
+codes["faint"] = esc + "02m"
+codes["standout"] = esc + "03m"
+codes["underline"] = esc + "04m"
+codes["blink"] = esc + "05m"
+codes["overline"] = esc + "06m"
+
+dark_colors = ["black", "red", "green", "yellow", "blue",
+               "magenta", "cyan", "gray"]
+light_colors = ["brightblack", "brightred", "brightgreen", "brightyellow", "brightblue",
+                "brightmagenta", "brightcyan", "white"]
+
+x = 30
+for dark, light in zip(dark_colors, light_colors):
+    codes[dark] = esc + "%im" % x
+    codes[light] = esc + "%im" % (60 + x)
+    x += 1
+
+del dark, light, x
+
+codes["white"] = codes["bold"]
+
+
+def reset_color():
+    return codes["reset"]
+
+
+def colorize(color_key, text):
+    return codes[color_key] + text + codes["reset"]
+
+
+def ansiformat(attr, text):
+    """
+    Format ``text`` with a color and/or some attributes::
+
+        color       normal color
+        *color*     bold color
+        _color_     underlined color
+        +color+     blinking color
+    """
+    result = []
+    if attr[:1] == attr[-1:] == '+':
+        result.append(codes['blink'])
+        attr = attr[1:-1]
+    if attr[:1] == attr[-1:] == '*':
+        result.append(codes['bold'])
+        attr = attr[1:-1]
+    if attr[:1] == attr[-1:] == '_':
+        result.append(codes['underline'])
+        attr = attr[1:-1]
+    result.append(codes[attr])
+    result.append(text)
+    result.append(codes['reset'])
+    return ''.join(result)
diff --git a/micromamba_root/Lib/site-packages/pygments/filter.py b/micromamba_root/Lib/site-packages/pygments/filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c926c26cfcf0ca7579f05affcab46c389595b71
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pygments/filter.py
@@ -0,0 +1,70 @@
+"""
+    pygments.filter
+    ~~~~~~~~~~~~~~~
+
+    Module that implements the default filter.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+
+def apply_filters(stream, filters, lexer=None):
+    """
+    Use this method to apply an iterable of filters to
+    a stream. If lexer is given it's forwarded to the
+    filter, otherwise the filter receives `None`.
+    """
+    def _apply(filter_, stream):
+        yield from filter_.filter(lexer, stream)
+    for filter_ in filters:
+        stream = _apply(filter_, stream)
+    return stream
+
+
+def simplefilter(f):
+    """
+    Decorator that converts a function into a filter::
+
+        @simplefilter
+        def lowercase(self, lexer, stream, options):
+            for ttype, value in stream:
+                yield ttype, value.lower()
+    """
+    return type(f.__name__, (FunctionFilter,), {
+        '__module__': getattr(f, '__module__'),
+        '__doc__': f.__doc__,
+        'function': f,
+    })
+
+
+class Filter:
+    """
+    Default filter. Subclass this class or use the `simplefilter`
+    decorator to create own filters.
+    """
+
+    def __init__(self, **options):
+        self.options = options
+
+    def filter(self, lexer, stream):
+        raise NotImplementedError()
+
+
+class FunctionFilter(Filter):
+    """
+    Abstract class used by `simplefilter` to create simple
+    function filters on the fly. The `simplefilter` decorator
+    automatically creates subclasses of this class for
+    functions passed to it.
+    """
+    function = None
+
+    def __init__(self, **options):
+        if not hasattr(self, 'function'):
+            raise TypeError(f'{self.__class__.__name__!r} used without bound function')
+        Filter.__init__(self, **options)
+
+    def filter(self, lexer, stream):
+        # pylint: disable=not-callable
+        yield from self.function(lexer, stream, self.options)
diff --git a/micromamba_root/Lib/site-packages/pygments/formatter.py b/micromamba_root/Lib/site-packages/pygments/formatter.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fa603d551c99fab81f2aa29037c3b8b89d0fcd5
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pygments/formatter.py
@@ -0,0 +1,129 @@
+"""
+    pygments.formatter
+    ~~~~~~~~~~~~~~~~~~
+
+    Base formatter class.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import codecs
+
+from pygments.util import get_bool_opt
+from pygments.styles import get_style_by_name
+
+__all__ = ['Formatter']
+
+
+def _lookup_style(style):
+    if isinstance(style, str):
+        return get_style_by_name(style)
+    return style
+
+
+class Formatter:
+    """
+    Converts a token stream to text.
+
+    Formatters should have attributes to help selecting them. These
+    are similar to the corresponding :class:`~pygments.lexer.Lexer`
+    attributes.
+
+    .. autoattribute:: name
+       :no-value:
+
+    .. autoattribute:: aliases
+       :no-value:
+
+    .. autoattribute:: filenames
+       :no-value:
+
+    You can pass options as keyword arguments to the constructor.
+    All formatters accept these basic options:
+
+    ``style``
+        The style to use, can be a string or a Style subclass
+        (default: "default"). Not used by e.g. the
+        TerminalFormatter.
+    ``full``
+        Tells the formatter to output a "full" document, i.e.
+        a complete self-contained document. This doesn't have
+        any effect for some formatters (default: false).
+    ``title``
+        If ``full`` is true, the title that should be used to
+        caption the document (default: '').
+    ``encoding``
+        If given, must be an encoding name. This will be used to
+        convert the Unicode token strings to byte strings in the
+        output. If it is "" or None, Unicode strings will be written
+        to the output file, which most file-like objects do not
+        support (default: None).
+    ``outencoding``
+        Overrides ``encoding`` if given.
+
+    """
+
+    #: Full name for the formatter, in human-readable form.
+    name = None
+
+    #: A list of short, unique identifiers that can be used to lookup
+    #: the formatter from a list, e.g. using :func:`.get_formatter_by_name()`.
+    aliases = []
+
+    #: A list of fnmatch patterns that match filenames for which this
+    #: formatter can produce output. The patterns in this list should be unique
+    #: among all formatters.
+    filenames = []
+
+    #: If True, this formatter outputs Unicode strings when no encoding
+    #: option is given.
+    unicodeoutput = True
+
+    def __init__(self, **options):
+        """
+        As with lexers, this constructor takes arbitrary optional arguments,
+        and if you override it, you should first process your own options, then
+        call the base class implementation.
+        """
+        self.style = _lookup_style(options.get('style', 'default'))
+        self.full = get_bool_opt(options, 'full', False)
+        self.title = options.get('title', '')
+        self.encoding = options.get('encoding', None) or None
+        if self.encoding in ('guess', 'chardet'):
+            # can happen for e.g. pygmentize -O encoding=guess
+            self.encoding = 'utf-8'
+        self.encoding = options.get('outencoding') or self.encoding
+        self.options = options
+
+    def get_style_defs(self, arg=''):
+        """
+        This method must return statements or declarations suitable to define
+        the current style for subsequent highlighted text (e.g. CSS classes
+        in the `HTMLFormatter`).
+
+        The optional argument `arg` can be used to modify the generation and
+        is formatter dependent (it is standardized because it can be given on
+        the command line).
+
+        This method is called by the ``-S`` :doc:`command-line option `,
+        the `arg` is then given by the ``-a`` option.
+        """
+        return ''
+
+    def format(self, tokensource, outfile):
+        """
+        This method must format the tokens from the `tokensource` iterable and
+        write the formatted version to the file object `outfile`.
+
+        Formatter options can control how exactly the tokens are converted.
+        """
+        if self.encoding:
+            # wrap the outfile in a StreamWriter
+            outfile = codecs.lookup(self.encoding)[3](outfile)
+        return self.format_unencoded(tokensource, outfile)
+
+    # Allow writing Formatter[str] or Formatter[bytes]. That's equivalent to
+    # Formatter. This helps when using third-party type stubs from typeshed.
+    def __class_getitem__(cls, name):
+        return cls
diff --git a/micromamba_root/Lib/site-packages/pygments/lexer.py b/micromamba_root/Lib/site-packages/pygments/lexer.py
new file mode 100644
index 0000000000000000000000000000000000000000..45e6585c991ba8644a1b3224bbed7ee8935b6a72
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pygments/lexer.py
@@ -0,0 +1,963 @@
+"""
+    pygments.lexer
+    ~~~~~~~~~~~~~~
+
+    Base lexer classes.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+import sys
+import time
+
+from pygments.filter import apply_filters, Filter
+from pygments.filters import get_filter_by_name
+from pygments.token import Error, Text, Other, Whitespace, _TokenType
+from pygments.util import get_bool_opt, get_int_opt, get_list_opt, \
+    make_analysator, Future, guess_decode
+from pygments.regexopt import regex_opt
+
+__all__ = ['Lexer', 'RegexLexer', 'ExtendedRegexLexer', 'DelegatingLexer',
+           'LexerContext', 'include', 'inherit', 'bygroups', 'using', 'this',
+           'default', 'words', 'line_re']
+
+line_re = re.compile('.*?\n')
+
+_encoding_map = [(b'\xef\xbb\xbf', 'utf-8'),
+                 (b'\xff\xfe\0\0', 'utf-32'),
+                 (b'\0\0\xfe\xff', 'utf-32be'),
+                 (b'\xff\xfe', 'utf-16'),
+                 (b'\xfe\xff', 'utf-16be')]
+
+_default_analyse = staticmethod(lambda x: 0.0)
+
+
+class LexerMeta(type):
+    """
+    This metaclass automagically converts ``analyse_text`` methods into
+    static methods which always return float values.
+    """
+
+    def __new__(mcs, name, bases, d):
+        if 'analyse_text' in d:
+            d['analyse_text'] = make_analysator(d['analyse_text'])
+        return type.__new__(mcs, name, bases, d)
+
+
+class Lexer(metaclass=LexerMeta):
+    """
+    Lexer for a specific language.
+
+    See also :doc:`lexerdevelopment`, a high-level guide to writing
+    lexers.
+
+    Lexer classes have attributes used for choosing the most appropriate
+    lexer based on various criteria.
+
+    .. autoattribute:: name
+       :no-value:
+    .. autoattribute:: aliases
+       :no-value:
+    .. autoattribute:: filenames
+       :no-value:
+    .. autoattribute:: alias_filenames
+    .. autoattribute:: mimetypes
+       :no-value:
+    .. autoattribute:: priority
+
+    Lexers included in Pygments should have two additional attributes:
+
+    .. autoattribute:: url
+       :no-value:
+    .. autoattribute:: version_added
+       :no-value:
+
+    Lexers included in Pygments may have additional attributes:
+
+    .. autoattribute:: _example
+       :no-value:
+
+    You can pass options to the constructor. The basic options recognized
+    by all lexers and processed by the base `Lexer` class are:
+
+    ``stripnl``
+        Strip leading and trailing newlines from the input (default: True).
+    ``stripall``
+        Strip all leading and trailing whitespace from the input
+        (default: False).
+    ``ensurenl``
+        Make sure that the input ends with a newline (default: True).  This
+        is required for some lexers that consume input linewise.
+
+        .. versionadded:: 1.3
+
+    ``tabsize``
+        If given and greater than 0, expand tabs in the input (default: 0).
+    ``encoding``
+        If given, must be an encoding name. This encoding will be used to
+        convert the input string to Unicode, if it is not already a Unicode
+        string (default: ``'guess'``, which uses a simple UTF-8 / Locale /
+        Latin1 detection.  Can also be ``'chardet'`` to use the chardet
+        library, if it is installed.
+    ``inencoding``
+        Overrides the ``encoding`` if given.
+    """
+
+    #: Full name of the lexer, in human-readable form
+    name = None
+
+    #: A list of short, unique identifiers that can be used to look
+    #: up the lexer from a list, e.g., using `get_lexer_by_name()`.
+    aliases = []
+
+    #: A list of `fnmatch` patterns that match filenames which contain
+    #: content for this lexer. The patterns in this list should be unique among
+    #: all lexers.
+    filenames = []
+
+    #: A list of `fnmatch` patterns that match filenames which may or may not
+    #: contain content for this lexer. This list is used by the
+    #: :func:`.guess_lexer_for_filename()` function, to determine which lexers
+    #: are then included in guessing the correct one. That means that
+    #: e.g. every lexer for HTML and a template language should include
+    #: ``\*.html`` in this list.
+    alias_filenames = []
+
+    #: A list of MIME types for content that can be lexed with this lexer.
+    mimetypes = []
+
+    #: Priority, should multiple lexers match and no content is provided
+    priority = 0
+
+    #: URL of the language specification/definition. Used in the Pygments
+    #: documentation. Set to an empty string to disable.
+    url = None
+
+    #: Version of Pygments in which the lexer was added.
+    version_added = None
+
+    #: Example file name. Relative to the ``tests/examplefiles`` directory.
+    #: This is used by the documentation generator to show an example.
+    _example = None
+
+    def __init__(self, **options):
+        """
+        This constructor takes arbitrary options as keyword arguments.
+        Every subclass must first process its own options and then call
+        the `Lexer` constructor, since it processes the basic
+        options like `stripnl`.
+
+        An example looks like this:
+
+        .. sourcecode:: python
+
+           def __init__(self, **options):
+               self.compress = options.get('compress', '')
+               Lexer.__init__(self, **options)
+
+        As these options must all be specifiable as strings (due to the
+        command line usage), there are various utility functions
+        available to help with that, see `Utilities`_.
+        """
+        self.options = options
+        self.stripnl = get_bool_opt(options, 'stripnl', True)
+        self.stripall = get_bool_opt(options, 'stripall', False)
+        self.ensurenl = get_bool_opt(options, 'ensurenl', True)
+        self.tabsize = get_int_opt(options, 'tabsize', 0)
+        self.encoding = options.get('encoding', 'guess')
+        self.encoding = options.get('inencoding') or self.encoding
+        self.filters = []
+        for filter_ in get_list_opt(options, 'filters', ()):
+            self.add_filter(filter_)
+
+    def __repr__(self):
+        if self.options:
+            return f''
+        else:
+            return f''
+
+    def add_filter(self, filter_, **options):
+        """
+        Add a new stream filter to this lexer.
+        """
+        if not isinstance(filter_, Filter):
+            filter_ = get_filter_by_name(filter_, **options)
+        self.filters.append(filter_)
+
+    def analyse_text(text):
+        """
+        A static method which is called for lexer guessing.
+
+        It should analyse the text and return a float in the range
+        from ``0.0`` to ``1.0``.  If it returns ``0.0``, the lexer
+        will not be selected as the most probable one, if it returns
+        ``1.0``, it will be selected immediately.  This is used by
+        `guess_lexer`.
+
+        The `LexerMeta` metaclass automatically wraps this function so
+        that it works like a static method (no ``self`` or ``cls``
+        parameter) and the return value is automatically converted to
+        `float`. If the return value is an object that is boolean `False`
+        it's the same as if the return values was ``0.0``.
+        """
+
+    def _preprocess_lexer_input(self, text):
+        """Apply preprocessing such as decoding the input, removing BOM and normalizing newlines."""
+
+        if not isinstance(text, str):
+            if self.encoding == 'guess':
+                text, _ = guess_decode(text)
+            elif self.encoding == 'chardet':
+                try:
+                    import chardet
+                except ImportError as e:
+                    raise ImportError('To enable chardet encoding guessing, '
+                                      'please install the chardet library '
+                                      'from http://chardet.feedparser.org/') from e
+                # check for BOM first
+                decoded = None
+                for bom, encoding in _encoding_map:
+                    if text.startswith(bom):
+                        decoded = text[len(bom):].decode(encoding, 'replace')
+                        break
+                # no BOM found, so use chardet
+                if decoded is None:
+                    enc = chardet.detect(text[:1024])  # Guess using first 1KB
+                    decoded = text.decode(enc.get('encoding') or 'utf-8',
+                                          'replace')
+                text = decoded
+            else:
+                text = text.decode(self.encoding)
+                if text.startswith('\ufeff'):
+                    text = text[len('\ufeff'):]
+        else:
+            if text.startswith('\ufeff'):
+                text = text[len('\ufeff'):]
+
+        # text now *is* a unicode string
+        text = text.replace('\r\n', '\n')
+        text = text.replace('\r', '\n')
+        if self.stripall:
+            text = text.strip()
+        elif self.stripnl:
+            text = text.strip('\n')
+        if self.tabsize > 0:
+            text = text.expandtabs(self.tabsize)
+        if self.ensurenl and not text.endswith('\n'):
+            text += '\n'
+
+        return text
+
+    def get_tokens(self, text, unfiltered=False):
+        """
+        This method is the basic interface of a lexer. It is called by
+        the `highlight()` function. It must process the text and return an
+        iterable of ``(tokentype, value)`` pairs from `text`.
+
+        Normally, you don't need to override this method. The default
+        implementation processes the options recognized by all lexers
+        (`stripnl`, `stripall` and so on), and then yields all tokens
+        from `get_tokens_unprocessed()`, with the ``index`` dropped.
+
+        If `unfiltered` is set to `True`, the filtering mechanism is
+        bypassed even if filters are defined.
+        """
+        text = self._preprocess_lexer_input(text)
+
+        def streamer():
+            for _, t, v in self.get_tokens_unprocessed(text):
+                yield t, v
+        stream = streamer()
+        if not unfiltered:
+            stream = apply_filters(stream, self.filters, self)
+        return stream
+
+    def get_tokens_unprocessed(self, text):
+        """
+        This method should process the text and return an iterable of
+        ``(index, tokentype, value)`` tuples where ``index`` is the starting
+        position of the token within the input text.
+
+        It must be overridden by subclasses. It is recommended to
+        implement it as a generator to maximize effectiveness.
+        """
+        raise NotImplementedError
+
+
+class DelegatingLexer(Lexer):
+    """
+    This lexer takes two lexer as arguments. A root lexer and
+    a language lexer. First everything is scanned using the language
+    lexer, afterwards all ``Other`` tokens are lexed using the root
+    lexer.
+
+    The lexers from the ``template`` lexer package use this base lexer.
+    """
+
+    def __init__(self, _root_lexer, _language_lexer, _needle=Other, **options):
+        self.root_lexer = _root_lexer(**options)
+        self.language_lexer = _language_lexer(**options)
+        self.needle = _needle
+        Lexer.__init__(self, **options)
+
+    def get_tokens_unprocessed(self, text):
+        buffered = ''
+        insertions = []
+        lng_buffer = []
+        for i, t, v in self.language_lexer.get_tokens_unprocessed(text):
+            if t is self.needle:
+                if lng_buffer:
+                    insertions.append((len(buffered), lng_buffer))
+                    lng_buffer = []
+                buffered += v
+            else:
+                lng_buffer.append((i, t, v))
+        if lng_buffer:
+            insertions.append((len(buffered), lng_buffer))
+        return do_insertions(insertions,
+                             self.root_lexer.get_tokens_unprocessed(buffered))
+
+
+# ------------------------------------------------------------------------------
+# RegexLexer and ExtendedRegexLexer
+#
+
+
+class include(str):  # pylint: disable=invalid-name
+    """
+    Indicates that a state should include rules from another state.
+    """
+    pass
+
+
+class _inherit:
+    """
+    Indicates the a state should inherit from its superclass.
+    """
+    def __repr__(self):
+        return 'inherit'
+
+inherit = _inherit()  # pylint: disable=invalid-name
+
+
+class combined(tuple):  # pylint: disable=invalid-name
+    """
+    Indicates a state combined from multiple states.
+    """
+
+    def __new__(cls, *args):
+        return tuple.__new__(cls, args)
+
+    def __init__(self, *args):
+        # tuple.__init__ doesn't do anything
+        pass
+
+
+class _PseudoMatch:
+    """
+    A pseudo match object constructed from a string.
+    """
+
+    def __init__(self, start, text):
+        self._text = text
+        self._start = start
+
+    def start(self, arg=None):
+        return self._start
+
+    def end(self, arg=None):
+        return self._start + len(self._text)
+
+    def group(self, arg=None):
+        if arg:
+            raise IndexError('No such group')
+        return self._text
+
+    def groups(self):
+        return (self._text,)
+
+    def groupdict(self):
+        return {}
+
+
+def bygroups(*args):
+    """
+    Callback that yields multiple actions for each group in the match.
+    """
+    def callback(lexer, match, ctx=None):
+        for i, action in enumerate(args):
+            if action is None:
+                continue
+            elif type(action) is _TokenType:
+                data = match.group(i + 1)
+                if data:
+                    yield match.start(i + 1), action, data
+            else:
+                data = match.group(i + 1)
+                if data is not None:
+                    if ctx:
+                        ctx.pos = match.start(i + 1)
+                    for item in action(lexer,
+                                       _PseudoMatch(match.start(i + 1), data), ctx):
+                        if item:
+                            yield item
+        if ctx:
+            ctx.pos = match.end()
+    return callback
+
+
+class _This:
+    """
+    Special singleton used for indicating the caller class.
+    Used by ``using``.
+    """
+
+this = _This()
+
+
+def using(_other, **kwargs):
+    """
+    Callback that processes the match with a different lexer.
+
+    The keyword arguments are forwarded to the lexer, except `state` which
+    is handled separately.
+
+    `state` specifies the state that the new lexer will start in, and can
+    be an enumerable such as ('root', 'inline', 'string') or a simple
+    string which is assumed to be on top of the root state.
+
+    Note: For that to work, `_other` must not be an `ExtendedRegexLexer`.
+    """
+    gt_kwargs = {}
+    if 'state' in kwargs:
+        s = kwargs.pop('state')
+        if isinstance(s, (list, tuple)):
+            gt_kwargs['stack'] = s
+        else:
+            gt_kwargs['stack'] = ('root', s)
+
+    if _other is this:
+        def callback(lexer, match, ctx=None):
+            # if keyword arguments are given the callback
+            # function has to create a new lexer instance
+            if kwargs:
+                # XXX: cache that somehow
+                d = dict(lexer.options)
+                d.update(kwargs)
+                lx = lexer.__class__(**d)
+            else:
+                lx = lexer
+            s = match.start()
+            for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs):
+                yield i + s, t, v
+            if ctx:
+                ctx.pos = match.end()
+    else:
+        def callback(lexer, match, ctx=None):
+            # XXX: cache that somehow
+            d = dict(lexer.options)
+            d.update(kwargs)
+            lx = _other(**d)
+
+            s = match.start()
+            for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs):
+                yield i + s, t, v
+            if ctx:
+                ctx.pos = match.end()
+    return callback
+
+
+class default:
+    """
+    Indicates a state or state action (e.g. #pop) to apply.
+    For example default('#pop') is equivalent to ('', Token, '#pop')
+    Note that state tuples may be used as well.
+
+    .. versionadded:: 2.0
+    """
+    def __init__(self, state):
+        self.state = state
+
+
+class words(Future):
+    """
+    Indicates a list of literal words that is transformed into an optimized
+    regex that matches any of the words.
+
+    .. versionadded:: 2.0
+    """
+    def __init__(self, words, prefix='', suffix=''):
+        self.words = words
+        self.prefix = prefix
+        self.suffix = suffix
+
+    def get(self):
+        return regex_opt(self.words, prefix=self.prefix, suffix=self.suffix)
+
+
+class RegexLexerMeta(LexerMeta):
+    """
+    Metaclass for RegexLexer, creates the self._tokens attribute from
+    self.tokens on the first instantiation.
+    """
+
+    def _process_regex(cls, regex, rflags, state):
+        """Preprocess the regular expression component of a token definition."""
+        if isinstance(regex, Future):
+            regex = regex.get()
+        return re.compile(regex, rflags).match
+
+    def _process_token(cls, token):
+        """Preprocess the token component of a token definition."""
+        assert type(token) is _TokenType or callable(token), \
+            f'token type must be simple type or callable, not {token!r}'
+        return token
+
+    def _process_new_state(cls, new_state, unprocessed, processed):
+        """Preprocess the state transition action of a token definition."""
+        if isinstance(new_state, str):
+            # an existing state
+            if new_state == '#pop':
+                return -1
+            elif new_state in unprocessed:
+                return (new_state,)
+            elif new_state == '#push':
+                return new_state
+            elif new_state[:5] == '#pop:':
+                return -int(new_state[5:])
+            else:
+                assert False, f'unknown new state {new_state!r}'
+        elif isinstance(new_state, combined):
+            # combine a new state from existing ones
+            tmp_state = '_tmp_%d' % cls._tmpname
+            cls._tmpname += 1
+            itokens = []
+            for istate in new_state:
+                assert istate != new_state, f'circular state ref {istate!r}'
+                itokens.extend(cls._process_state(unprocessed,
+                                                  processed, istate))
+            processed[tmp_state] = itokens
+            return (tmp_state,)
+        elif isinstance(new_state, tuple):
+            # push more than one state
+            for istate in new_state:
+                assert (istate in unprocessed or
+                        istate in ('#pop', '#push')), \
+                    'unknown new state ' + istate
+            return new_state
+        else:
+            assert False, f'unknown new state def {new_state!r}'
+
+    def _process_state(cls, unprocessed, processed, state):
+        """Preprocess a single state definition."""
+        assert isinstance(state, str), f"wrong state name {state!r}"
+        assert state[0] != '#', f"invalid state name {state!r}"
+        if state in processed:
+            return processed[state]
+        tokens = processed[state] = []
+        rflags = cls.flags
+        for tdef in unprocessed[state]:
+            if isinstance(tdef, include):
+                # it's a state reference
+                assert tdef != state, f"circular state reference {state!r}"
+                tokens.extend(cls._process_state(unprocessed, processed,
+                                                 str(tdef)))
+                continue
+            if isinstance(tdef, _inherit):
+                # should be processed already, but may not in the case of:
+                # 1. the state has no counterpart in any parent
+                # 2. the state includes more than one 'inherit'
+                continue
+            if isinstance(tdef, default):
+                new_state = cls._process_new_state(tdef.state, unprocessed, processed)
+                tokens.append((re.compile('').match, None, new_state))
+                continue
+
+            assert type(tdef) is tuple, f"wrong rule def {tdef!r}"
+
+            try:
+                rex = cls._process_regex(tdef[0], rflags, state)
+            except Exception as err:
+                raise ValueError(f"uncompilable regex {tdef[0]!r} in state {state!r} of {cls!r}: {err}") from err
+
+            token = cls._process_token(tdef[1])
+
+            if len(tdef) == 2:
+                new_state = None
+            else:
+                new_state = cls._process_new_state(tdef[2],
+                                                   unprocessed, processed)
+
+            tokens.append((rex, token, new_state))
+        return tokens
+
+    def process_tokendef(cls, name, tokendefs=None):
+        """Preprocess a dictionary of token definitions."""
+        processed = cls._all_tokens[name] = {}
+        tokendefs = tokendefs or cls.tokens[name]
+        for state in list(tokendefs):
+            cls._process_state(tokendefs, processed, state)
+        return processed
+
+    def get_tokendefs(cls):
+        """
+        Merge tokens from superclasses in MRO order, returning a single tokendef
+        dictionary.
+
+        Any state that is not defined by a subclass will be inherited
+        automatically.  States that *are* defined by subclasses will, by
+        default, override that state in the superclass.  If a subclass wishes to
+        inherit definitions from a superclass, it can use the special value
+        "inherit", which will cause the superclass' state definition to be
+        included at that point in the state.
+        """
+        tokens = {}
+        inheritable = {}
+        for c in cls.__mro__:
+            toks = c.__dict__.get('tokens', {})
+
+            for state, items in toks.items():
+                curitems = tokens.get(state)
+                if curitems is None:
+                    # N.b. because this is assigned by reference, sufficiently
+                    # deep hierarchies are processed incrementally (e.g. for
+                    # A(B), B(C), C(RegexLexer), B will be premodified so X(B)
+                    # will not see any inherits in B).
+                    tokens[state] = items
+                    try:
+                        inherit_ndx = items.index(inherit)
+                    except ValueError:
+                        continue
+                    inheritable[state] = inherit_ndx
+                    continue
+
+                inherit_ndx = inheritable.pop(state, None)
+                if inherit_ndx is None:
+                    continue
+
+                # Replace the "inherit" value with the items
+                curitems[inherit_ndx:inherit_ndx+1] = items
+                try:
+                    # N.b. this is the index in items (that is, the superclass
+                    # copy), so offset required when storing below.
+                    new_inh_ndx = items.index(inherit)
+                except ValueError:
+                    pass
+                else:
+                    inheritable[state] = inherit_ndx + new_inh_ndx
+
+        return tokens
+
+    def __call__(cls, *args, **kwds):
+        """Instantiate cls after preprocessing its token definitions."""
+        if '_tokens' not in cls.__dict__:
+            cls._all_tokens = {}
+            cls._tmpname = 0
+            if hasattr(cls, 'token_variants') and cls.token_variants:
+                # don't process yet
+                pass
+            else:
+                cls._tokens = cls.process_tokendef('', cls.get_tokendefs())
+
+        return type.__call__(cls, *args, **kwds)
+
+
+class RegexLexer(Lexer, metaclass=RegexLexerMeta):
+    """
+    Base for simple stateful regular expression-based lexers.
+    Simplifies the lexing process so that you need only
+    provide a list of states and regular expressions.
+    """
+
+    #: Flags for compiling the regular expressions.
+    #: Defaults to MULTILINE.
+    flags = re.MULTILINE
+
+    #: At all time there is a stack of states. Initially, the stack contains
+    #: a single state 'root'. The top of the stack is called "the current state".
+    #:
+    #: Dict of ``{'state': [(regex, tokentype, new_state), ...], ...}``
+    #:
+    #: ``new_state`` can be omitted to signify no state transition.
+    #: If ``new_state`` is a string, it is pushed on the stack. This ensure
+    #: the new current state is ``new_state``.
+    #: If ``new_state`` is a tuple of strings, all of those strings are pushed
+    #: on the stack and the current state will be the last element of the list.
+    #: ``new_state`` can also be ``combined('state1', 'state2', ...)``
+    #: to signify a new, anonymous state combined from the rules of two
+    #: or more existing ones.
+    #: Furthermore, it can be '#pop' to signify going back one step in
+    #: the state stack, or '#push' to push the current state on the stack
+    #: again. Note that if you push while in a combined state, the combined
+    #: state itself is pushed, and not only the state in which the rule is
+    #: defined.
+    #:
+    #: The tuple can also be replaced with ``include('state')``, in which
+    #: case the rules from the state named by the string are included in the
+    #: current one.
+    tokens = {}
+
+    def get_tokens_unprocessed(self, text, stack=('root',)):
+        """
+        Split ``text`` into (tokentype, text) pairs.
+
+        ``stack`` is the initial stack (default: ``['root']``)
+        """
+        pos = 0
+        tokendefs = self._tokens
+        statestack = list(stack)
+        statetokens = tokendefs[statestack[-1]]
+        while 1:
+            for rexmatch, action, new_state in statetokens:
+                m = rexmatch(text, pos)
+                if m:
+                    if action is not None:
+                        if type(action) is _TokenType:
+                            yield pos, action, m.group()
+                        else:
+                            yield from action(self, m)
+                    pos = m.end()
+                    if new_state is not None:
+                        # state transition
+                        if isinstance(new_state, tuple):
+                            for state in new_state:
+                                if state == '#pop':
+                                    if len(statestack) > 1:
+                                        statestack.pop()
+                                elif state == '#push':
+                                    statestack.append(statestack[-1])
+                                else:
+                                    statestack.append(state)
+                        elif isinstance(new_state, int):
+                            # pop, but keep at least one state on the stack
+                            # (random code leading to unexpected pops should
+                            # not allow exceptions)
+                            if abs(new_state) >= len(statestack):
+                                del statestack[1:]
+                            else:
+                                del statestack[new_state:]
+                        elif new_state == '#push':
+                            statestack.append(statestack[-1])
+                        else:
+                            assert False, f"wrong state def: {new_state!r}"
+                        statetokens = tokendefs[statestack[-1]]
+                    break
+            else:
+                # We are here only if all state tokens have been considered
+                # and there was not a match on any of them.
+                try:
+                    if text[pos] == '\n':
+                        # at EOL, reset state to "root"
+                        statestack = ['root']
+                        statetokens = tokendefs['root']
+                        yield pos, Whitespace, '\n'
+                        pos += 1
+                        continue
+                    yield pos, Error, text[pos]
+                    pos += 1
+                except IndexError:
+                    break
+
+
+class LexerContext:
+    """
+    A helper object that holds lexer position data.
+    """
+
+    def __init__(self, text, pos, stack=None, end=None):
+        self.text = text
+        self.pos = pos
+        self.end = end or len(text)  # end=0 not supported ;-)
+        self.stack = stack or ['root']
+
+    def __repr__(self):
+        return f'LexerContext({self.text!r}, {self.pos!r}, {self.stack!r})'
+
+
+class ExtendedRegexLexer(RegexLexer):
+    """
+    A RegexLexer that uses a context object to store its state.
+    """
+
+    def get_tokens_unprocessed(self, text=None, context=None):
+        """
+        Split ``text`` into (tokentype, text) pairs.
+        If ``context`` is given, use this lexer context instead.
+        """
+        tokendefs = self._tokens
+        if not context:
+            ctx = LexerContext(text, 0)
+            statetokens = tokendefs['root']
+        else:
+            ctx = context
+            statetokens = tokendefs[ctx.stack[-1]]
+            text = ctx.text
+        while 1:
+            for rexmatch, action, new_state in statetokens:
+                m = rexmatch(text, ctx.pos, ctx.end)
+                if m:
+                    if action is not None:
+                        if type(action) is _TokenType:
+                            yield ctx.pos, action, m.group()
+                            ctx.pos = m.end()
+                        else:
+                            yield from action(self, m, ctx)
+                            if not new_state:
+                                # altered the state stack?
+                                statetokens = tokendefs[ctx.stack[-1]]
+                    # CAUTION: callback must set ctx.pos!
+                    if new_state is not None:
+                        # state transition
+                        if isinstance(new_state, tuple):
+                            for state in new_state:
+                                if state == '#pop':
+                                    if len(ctx.stack) > 1:
+                                        ctx.stack.pop()
+                                elif state == '#push':
+                                    ctx.stack.append(ctx.stack[-1])
+                                else:
+                                    ctx.stack.append(state)
+                        elif isinstance(new_state, int):
+                            # see RegexLexer for why this check is made
+                            if abs(new_state) >= len(ctx.stack):
+                                del ctx.stack[1:]
+                            else:
+                                del ctx.stack[new_state:]
+                        elif new_state == '#push':
+                            ctx.stack.append(ctx.stack[-1])
+                        else:
+                            assert False, f"wrong state def: {new_state!r}"
+                        statetokens = tokendefs[ctx.stack[-1]]
+                    break
+            else:
+                try:
+                    if ctx.pos >= ctx.end:
+                        break
+                    if text[ctx.pos] == '\n':
+                        # at EOL, reset state to "root"
+                        ctx.stack = ['root']
+                        statetokens = tokendefs['root']
+                        yield ctx.pos, Text, '\n'
+                        ctx.pos += 1
+                        continue
+                    yield ctx.pos, Error, text[ctx.pos]
+                    ctx.pos += 1
+                except IndexError:
+                    break
+
+
+def do_insertions(insertions, tokens):
+    """
+    Helper for lexers which must combine the results of several
+    sublexers.
+
+    ``insertions`` is a list of ``(index, itokens)`` pairs.
+    Each ``itokens`` iterable should be inserted at position
+    ``index`` into the token stream given by the ``tokens``
+    argument.
+
+    The result is a combined token stream.
+
+    TODO: clean up the code here.
+    """
+    insertions = iter(insertions)
+    try:
+        index, itokens = next(insertions)
+    except StopIteration:
+        # no insertions
+        yield from tokens
+        return
+
+    realpos = None
+    insleft = True
+
+    # iterate over the token stream where we want to insert
+    # the tokens from the insertion list.
+    for i, t, v in tokens:
+        # first iteration. store the position of first item
+        if realpos is None:
+            realpos = i
+        oldi = 0
+        while insleft and i + len(v) >= index:
+            tmpval = v[oldi:index - i]
+            if tmpval:
+                yield realpos, t, tmpval
+                realpos += len(tmpval)
+            for it_index, it_token, it_value in itokens:
+                yield realpos, it_token, it_value
+                realpos += len(it_value)
+            oldi = index - i
+            try:
+                index, itokens = next(insertions)
+            except StopIteration:
+                insleft = False
+                break  # not strictly necessary
+        if oldi < len(v):
+            yield realpos, t, v[oldi:]
+            realpos += len(v) - oldi
+
+    # leftover tokens
+    while insleft:
+        # no normal tokens, set realpos to zero
+        realpos = realpos or 0
+        for p, t, v in itokens:
+            yield realpos, t, v
+            realpos += len(v)
+        try:
+            index, itokens = next(insertions)
+        except StopIteration:
+            insleft = False
+            break  # not strictly necessary
+
+
+class ProfilingRegexLexerMeta(RegexLexerMeta):
+    """Metaclass for ProfilingRegexLexer, collects regex timing info."""
+
+    def _process_regex(cls, regex, rflags, state):
+        if isinstance(regex, words):
+            rex = regex_opt(regex.words, prefix=regex.prefix,
+                            suffix=regex.suffix)
+        else:
+            rex = regex
+        compiled = re.compile(rex, rflags)
+
+        def match_func(text, pos, endpos=sys.maxsize):
+            info = cls._prof_data[-1].setdefault((state, rex), [0, 0.0])
+            t0 = time.time()
+            res = compiled.match(text, pos, endpos)
+            t1 = time.time()
+            info[0] += 1
+            info[1] += t1 - t0
+            return res
+        return match_func
+
+
+class ProfilingRegexLexer(RegexLexer, metaclass=ProfilingRegexLexerMeta):
+    """Drop-in replacement for RegexLexer that does profiling of its regexes."""
+
+    _prof_data = []
+    _prof_sort_index = 4  # defaults to time per call
+
+    def get_tokens_unprocessed(self, text, stack=('root',)):
+        # this needs to be a stack, since using(this) will produce nested calls
+        self.__class__._prof_data.append({})
+        yield from RegexLexer.get_tokens_unprocessed(self, text, stack)
+        rawdata = self.__class__._prof_data.pop()
+        data = sorted(((s, repr(r).strip('u\'').replace('\\\\', '\\')[:65],
+                        n, 1000 * t, 1000 * t / n)
+                       for ((s, r), (n, t)) in rawdata.items()),
+                      key=lambda x: x[self._prof_sort_index],
+                      reverse=True)
+        sum_total = sum(x[3] for x in data)
+
+        print()
+        print('Profiling result for %s lexing %d chars in %.3f ms' %
+              (self.__class__.__name__, len(text), sum_total))
+        print('=' * 110)
+        print('%-20s %-64s ncalls  tottime  percall' % ('state', 'regex'))
+        print('-' * 110)
+        for d in data:
+            print('%-20s %-65s %5d %8.4f %8.4f' % d)
+        print('=' * 110)
diff --git a/micromamba_root/Lib/site-packages/pygments/modeline.py b/micromamba_root/Lib/site-packages/pygments/modeline.py
new file mode 100644
index 0000000000000000000000000000000000000000..81ec15773dd6cdc40c72e7bda280ce33f645ef1a
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pygments/modeline.py
@@ -0,0 +1,43 @@
+"""
+    pygments.modeline
+    ~~~~~~~~~~~~~~~~~
+
+    A simple modeline parser (based on pymodeline).
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+__all__ = ['get_filetype_from_buffer']
+
+
+modeline_re = re.compile(r'''
+    (?: vi | vim | ex ) (?: [<=>]? \d* )? :
+    .* (?: ft | filetype | syn | syntax ) = ( [^:\s]+ )
+''', re.VERBOSE)
+
+
+def get_filetype_from_line(l): # noqa: E741
+    m = modeline_re.search(l)
+    if m:
+        return m.group(1)
+
+
+def get_filetype_from_buffer(buf, max_lines=5):
+    """
+    Scan the buffer for modelines and return filetype if one is found.
+    """
+    lines = buf.splitlines()
+    for line in lines[-1:-max_lines-1:-1]:
+        ret = get_filetype_from_line(line)
+        if ret:
+            return ret
+    for i in range(max_lines, -1, -1):
+        if i < len(lines):
+            ret = get_filetype_from_line(lines[i])
+            if ret:
+                return ret
+
+    return None
diff --git a/micromamba_root/Lib/site-packages/pygments/plugin.py b/micromamba_root/Lib/site-packages/pygments/plugin.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d6377f769cf68505f6c3ff5495fe01effb31d38
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pygments/plugin.py
@@ -0,0 +1,74 @@
+"""
+    pygments.plugin
+    ~~~~~~~~~~~~~~~
+
+    Pygments plugin interface.
+
+    lexer plugins::
+
+        [pygments.lexers]
+        yourlexer = yourmodule:YourLexer
+
+    formatter plugins::
+
+        [pygments.formatters]
+        yourformatter = yourformatter:YourFormatter
+        /.ext = yourformatter:YourFormatter
+
+    As you can see, you can define extensions for the formatter
+    with a leading slash.
+
+    syntax plugins::
+
+        [pygments.styles]
+        yourstyle = yourstyle:YourStyle
+
+    filter plugin::
+
+        [pygments.filter]
+        yourfilter = yourfilter:YourFilter
+
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+import functools
+from importlib.metadata import entry_points
+
+LEXER_ENTRY_POINT = 'pygments.lexers'
+FORMATTER_ENTRY_POINT = 'pygments.formatters'
+STYLE_ENTRY_POINT = 'pygments.styles'
+FILTER_ENTRY_POINT = 'pygments.filters'
+
+
+@functools.cache
+def iter_entry_points(group_name):
+    groups = entry_points()
+    if hasattr(groups, 'select'):
+        # New interface in Python 3.10 and newer versions of the
+        # importlib_metadata backport.
+        return groups.select(group=group_name)
+    else:
+        # Older interface, deprecated in Python 3.10 and recent
+        # importlib_metadata, but we need it in Python 3.8 and 3.9.
+        return groups.get(group_name, [])
+
+
+def find_plugin_lexers():
+    for entrypoint in iter_entry_points(LEXER_ENTRY_POINT):
+        yield entrypoint.load()
+
+
+def find_plugin_formatters():
+    for entrypoint in iter_entry_points(FORMATTER_ENTRY_POINT):
+        yield entrypoint.name, entrypoint.load()
+
+
+def find_plugin_styles():
+    for entrypoint in iter_entry_points(STYLE_ENTRY_POINT):
+        yield entrypoint.name, entrypoint.load()
+
+
+def find_plugin_filters():
+    for entrypoint in iter_entry_points(FILTER_ENTRY_POINT):
+        yield entrypoint.name, entrypoint.load()
diff --git a/micromamba_root/Lib/site-packages/pygments/regexopt.py b/micromamba_root/Lib/site-packages/pygments/regexopt.py
new file mode 100644
index 0000000000000000000000000000000000000000..9010eb3fb517ff4134b4f52581179fa80b0f7540
--- /dev/null
+++ b/micromamba_root/Lib/site-packages/pygments/regexopt.py
@@ -0,0 +1,102 @@
+"""
+    pygments.regexopt
+    ~~~~~~~~~~~~~~~~~
+
+    An algorithm that generates optimized regexes for matching long lists of
+    literal strings.
+
+    :copyright: Copyright 2006-present by the Pygments team, see AUTHORS.
+    :license: BSD, see LICENSE for details.
+"""
+
+import re
+from re import escape
+from itertools import groupby
+from operator import itemgetter
+
+CS_ESCAPE = re.compile(r'[\[\^\\\-\]]')
+FIRST_ELEMENT = itemgetter(0)
+
+
+def commonprefix(m):
+    """Given an iterable of strings, returns the longest common leading substring"""
+    if not m:
+        return ""
+    s1 = min(m)
+    s2 = max(m)
+    for i, c in enumerate(s1):
+        if c != s2[i]:
+            return s1[:i]
+    return s1
+
+
+def make_charset(letters):
+    return '[' + CS_ESCAPE.sub(lambda m: '\\' + m.group(), ''.join(letters)) + ']'
+
+
+def regex_opt_inner(strings, open_paren):
+    """Return a regex that matches any string in the sorted list of strings."""
+    close_paren = open_paren and ')' or ''
+    # print strings, repr(open_paren)
+    if not strings:
+        # print '-> nothing left'
+        return ''
+    first = strings[0]
+    if len(strings) == 1:
+        # print '-> only 1 string'
+        return open_paren + escape(first) + close_paren
+    if not first:
+        # print '-> first string empty'
+        return open_paren + regex_opt_inner(strings[1:], '(?:') \
+            + '?' + close_paren
+    if len(first) == 1:
+        # multiple one-char strings? make a charset
+        oneletter = []
+        rest = []
+        for s in strings:
+            if len(s) == 1:
+                oneletter.append(s)
+            else:
+                rest.append(s)
+        if len(oneletter) > 1:  # do we have more than one oneletter string?
+            if rest:
+                # print '-> 1-character + rest'
+                return open_paren + regex_opt_inner(rest, '') + '|' \
+                    + make_charset(oneletter) + close_paren
+            # print '-> only 1-character'
+            return open_paren + make_charset(oneletter) + close_paren
+    prefix = commonprefix(strings)
+    if prefix:
+        plen = len(prefix)
+        # we have a prefix for all strings
+        # print '-> prefix:', prefix
+        return open_paren + escape(prefix) \
+            + regex_opt_inner([s[plen:] for s in strings], '(?:') \
+            + close_paren
+    # is there a suffix?
+    strings_rev = [s[::-1] for s in strings]
+    suffix = commonprefix(strings_rev)
+    if suffix:
+        slen = len(suffix)
+        # print '-> suffix:', suffix[::-1]
+        return open_paren \
+            + regex_opt_inner(sorted(s[:-slen] for s in strings), '(?:') \
+            + escape(suffix[::-1]) + close_paren
+    # recurse on common 1-string prefixes
+    # print '-> last resort'
+    return open_paren + \
+        '|'.join(regex_opt_inner(list(group[1]), '')
+                 for group in groupby(strings, lambda s: s[0] == first[0])) \
+        + close_paren
+
+
+def regex_opt(strings, prefix='', suffix=''):
+    """Return a compiled regex that matches any string in the given list.
+
+    The strings to match must be literal strings, not regexes.  They will be
+    regex-escaped.
+
+    *prefix* and *suffix* are pre- and appended to the final regex.
+    """
+    strings = sorted(strings)
+    return prefix + regex_opt_inner(strings, '(') + suffix
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..5d61699e80dfd3aac0894e5916085e07f60d84bd
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/METADATA
@@ -0,0 +1,98 @@
+Metadata-Version: 2.4
+Name: greenlet
+Version: 3.5.0
+Summary: Lightweight in-process concurrent programming
+Author-email: Alexey Borzenkov 
+Maintainer-email: Jason Madden 
+License-Expression: MIT AND PSF-2.0
+Project-URL: Homepage, https://greenlet.readthedocs.io
+Project-URL: Documentation, https://greenlet.readthedocs.io
+Project-URL: Repository, https://github.com/python-greenlet/greenlet
+Project-URL: Issues, https://github.com/python-greenlet/greenlet/issues
+Project-URL: Changelog, https://greenlet.readthedocs.io/en/latest/changes.html
+Keywords: greenlet,coroutine,concurrency,threads,cooperative
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Natural Language :: English
+Classifier: Programming Language :: C
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Operating System :: OS Independent
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.10
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+License-File: LICENSE.PSF
+Provides-Extra: docs
+Requires-Dist: Sphinx; extra == "docs"
+Requires-Dist: furo; extra == "docs"
+Provides-Extra: test
+Requires-Dist: objgraph; extra == "test"
+Requires-Dist: psutil; extra == "test"
+Requires-Dist: setuptools; extra == "test"
+Dynamic: license-file
+
+.. This file is included into docs/history.rst
+
+
+Greenlets are lightweight coroutines for in-process concurrent
+programming.
+
+The "greenlet" package is a spin-off of `Stackless`_, a version of
+CPython that supports micro-threads called "tasklets". Tasklets run
+pseudo-concurrently (typically in a single or a few OS-level threads)
+and are synchronized with data exchanges on "channels".
+
+A "greenlet", on the other hand, is a still more primitive notion of
+micro-thread with no implicit scheduling; coroutines, in other words.
+This is useful when you want to control exactly when your code runs.
+You can build custom scheduled micro-threads on top of greenlet;
+however, it seems that greenlets are useful on their own as a way to
+make advanced control flow structures. For example, we can recreate
+generators; the difference with Python's own generators is that our
+generators can call nested functions and the nested functions can
+yield values too. (Additionally, you don't need a "yield" keyword. See
+the example in `test_generator.py
+`_).
+
+Greenlets are provided as a C extension module for the regular unmodified
+interpreter.
+
+.. _`Stackless`: http://www.stackless.com
+
+
+Who is using Greenlet?
+======================
+
+There are several libraries that use Greenlet as a more flexible
+alternative to Python's built in coroutine support:
+
+ - `Concurrence`_
+ - `Eventlet`_
+ - `Gevent`_
+
+.. _Concurrence: http://opensource.hyves.org/concurrence/
+.. _Eventlet: http://eventlet.net/
+.. _Gevent: http://www.gevent.org/
+
+Getting Greenlet
+================
+
+The easiest way to get Greenlet is to install it with pip::
+
+  pip install greenlet
+
+
+Source code archives and binary distributions are available on the
+python package index at https://pypi.org/project/greenlet
+
+The source code repository is hosted on github:
+https://github.com/python-greenlet/greenlet
+
+Documentation is available on readthedocs.org:
+https://greenlet.readthedocs.io
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..f48b78f64de396b89235b64d1322b49158569cf5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/RECORD
@@ -0,0 +1,123 @@
+../../Include/greenlet/greenlet.h,sha256=goR9ZprGoq71mBRhzBuexFvTNryvf4uceMHMIaSxh3o,4919
+greenlet-3.5.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+greenlet-3.5.0.dist-info/METADATA,sha256=iey5H4TPDrEoAXNHyeDevomTBC7z3YmbAOLKlEgNKwY,3829
+greenlet-3.5.0.dist-info/RECORD,,
+greenlet-3.5.0.dist-info/WHEEL,sha256=XHXMKJU3yoVh1ZanBXTJ5bDGb67oEYtF1S6bd8a4izI,101
+greenlet-3.5.0.dist-info/licenses/LICENSE,sha256=q5d7ZUYFZwMZUJSB7OSRmPQFoSk3KsOMlvUc2WwvRS4,1464
+greenlet-3.5.0.dist-info/licenses/LICENSE.PSF,sha256=ae-micx67Hc2I20wOcHWZeSwxzSlv-pav2MwI6uy__Q,2471
+greenlet-3.5.0.dist-info/top_level.txt,sha256=YSnRsCRoO61JGlP57o8iKL6rdLWDWuiyKD8ekpWUsDc,9
+greenlet/CObjects.cpp,sha256=kINy1jVD2EBvrDh5BkPEmxi5zXB1F3VEsE14yWe5NYg,3813
+greenlet/PyGreenlet.cpp,sha256=lAHY6_hNCrdYKjQyoKLGLPeK_qCcEB-ThGSbzMJfUUI,29025
+greenlet/PyGreenlet.hpp,sha256=LhUVgLOiWGOlnfjHfcpjjqhYuGrOdOsuKjhyVyRT0f0,1498
+greenlet/PyGreenletUnswitchable.cpp,sha256=3mWmGDzeOCdwfM1FWh8zWx6aVedFU2kUIX8F94cayt8,4306
+greenlet/PyModule.cpp,sha256=3E2mw9ZCwIjSecj5CflZnjj4ibNi74Hmp8Q44kFT_ZI,9014
+greenlet/TBrokenGreenlet.cpp,sha256=_hLV4vPhUsiwb5rnNnrUNbyCBHe0NPbWvlB-UtyNTOI,1066
+greenlet/TExceptionState.cpp,sha256=GKPJWNgvUtUVicGW2gl5nlT3qud-GeBNlKxSiCoWALU,1421
+greenlet/TGreenlet.cpp,sha256=SPVHS518HI8woEwWrj68ZcnVGjwDa2T8IltfuLk0nA4,26968
+greenlet/TGreenlet.hpp,sha256=L9AdGBS1bYSr_7IjDli-DoBvOLlI_CEymWPWUBzNr9U,30111
+greenlet/TGreenletGlobals.cpp,sha256=33JPbPzsPoaYE4WkTFBIU0HH9VbLr9ceLePMNH-IRE4,4043
+greenlet/TMainGreenlet.cpp,sha256=IgovSz9MWCkqH1tjHVTOIz6kmtaCreWVD1c0jvKCEn0,3756
+greenlet/TPythonState.cpp,sha256=59BxD9sJisDBN9n6qWJYQk45rkdfjPYHssp3B5v40wI,20100
+greenlet/TStackState.cpp,sha256=T295c_VRn3ov2yQ8n0evJN73YlieXX_8Tg2ddR4XRZc,7646
+greenlet/TThreadState.hpp,sha256=Kms-Zc3IDe9qOmGlLSPGGFgCGC-e0DVPJK_tEdhSuFA,24529
+greenlet/TThreadStateCreator.hpp,sha256=dkeUtQNd_4DbrwUaM7Ytq4KHgirGkSpxz5JQ5EPwmSo,2872
+greenlet/TThreadStateDestroy.cpp,sha256=J6o0P3cxIhC4oakCgb38Li7qwFTpEdhwhDU07PrL9sE,8395
+greenlet/TUserGreenlet.cpp,sha256=7hyCUS2HjvBmPVNK319VGMJHLQ-rhtj7UFjgwLQph2s,25007
+greenlet/__init__.py,sha256=MyYk1lc-oZ4V_Zoum8NUVqrz_3OJT9PZUn5BSSLq7bY,1504
+greenlet/__pycache__/__init__.cpython-311.pyc,,
+greenlet/_greenlet.cp311-win_amd64.pyd,sha256=bv9gtHRMYpCk94KAQcPqC3iFQ6DMXMUdui8-jXGZuEY,71680
+greenlet/greenlet.cpp,sha256=EBCyluuRRW72VDZSE7wASjGqVptYqUZfwpzOprAIGAM,11412
+greenlet/greenlet.h,sha256=goR9ZprGoq71mBRhzBuexFvTNryvf4uceMHMIaSxh3o,4919
+greenlet/greenlet_allocator.hpp,sha256=Ymeor5KOG_MmiBRSpJY6InFsatIJHnBPBrO7ETzliFE,1911
+greenlet/greenlet_compiler_compat.hpp,sha256=tP2AfsUu3zjkSqh5QUS9MWgI2675-wMpgwesmli4po0,4444
+greenlet/greenlet_cpython_compat.hpp,sha256=YwHBn2Zd09keukj0zkTjYE6u0kHbBK9qn2moLlPslCQ,3442
+greenlet/greenlet_exceptions.hpp,sha256=E6M80eSszo5dfEfvfm0iHJlEOSNMY0mepzif64Z6mfY,4674
+greenlet/greenlet_internal.hpp,sha256=EXkYELEfhXR0lQAR678GYoEKR_dIp_uEsbEgmiHjrnk,2877
+greenlet/greenlet_msvc_compat.hpp,sha256=6zttIzyIoiSREOGt2zGEos7sirU4_Bqxo-7UU6v7L4Y,3295
+greenlet/greenlet_refs.hpp,sha256=lTgXgszJzBbzA7HwWLO0RJcXjFRQmkz7Rm81_hKLHRs,39266
+greenlet/greenlet_slp_switch.hpp,sha256=YRz-KWeqi8E9_6ysufslzEVbus6EM0WtceVWXm5A0PQ,3401
+greenlet/greenlet_thread_support.hpp,sha256=KoLKoz1rG2NT37w1bA_GEAz370VLUPGKTfUQHqtKwFA,898
+greenlet/platform/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
+greenlet/platform/__pycache__/__init__.cpython-311.pyc,,
+greenlet/platform/setup_switch_x64_masm.cmd,sha256=ZpClUJeU0ujEPSTWNSepP0W2f9XiYQKA8QKSoVou8EU,143
+greenlet/platform/switch_aarch64_gcc.h,sha256=Bzt3HLXqPpBeXMFqPHv_iFrl3qQ-hLbg5U1-BLxhvDA,4431
+greenlet/platform/switch_alpha_unix.h,sha256=k9LA3BAtojTCGqMzmYyWg5I73jjHDqDE_UKZuWrEITE,701
+greenlet/platform/switch_amd64_unix.h,sha256=YvMD530xkEG_S4zBSgR3IlvARJMAiIP5lO85kH-Ixpw,2835
+greenlet/platform/switch_arm32_gcc.h,sha256=89_taedd3VelvYc_-TywNEVqAV77x_zDYaAPtOVGPP0,2558
+greenlet/platform/switch_arm32_ios.h,sha256=GEi3DbjVYwuSKsA6PUBtwV27oWfbtFpj_nZ-Dx2Yrz8,1959
+greenlet/platform/switch_arm64_masm.asm,sha256=RtKHfJETzcd6RVUv5UL1jhXCuzVc5IIES-NtPT-nPFo,1298
+greenlet/platform/switch_arm64_masm.obj,sha256=DmLnIB_icoEHAz1naue_pJPTZgR9ElM7-Nmztr-o9_U,746
+greenlet/platform/switch_arm64_msvc.h,sha256=CnFzBbEqaIliXwzNTxBtbG5WNpfphuZatpHTXVUfylI,414
+greenlet/platform/switch_csky_gcc.h,sha256=dJx1cCkiqgNari_cOY_KfnjzR3G-J2b_Mf6TKNzaXvk,1379
+greenlet/platform/switch_loongarch64_linux.h,sha256=mydHgN6yFNQzbDRWTYTYXM03rU_vQngeJyLTrGbY4qs,810
+greenlet/platform/switch_m68k_gcc.h,sha256=s8A58AzT0_csU9H7j5FlR9A8myKP3CJLWfDij756Eiw,966
+greenlet/platform/switch_mips_unix.h,sha256=rPH5D4Rn2IzUBBHHJwHF7Ga9QHvtvoiWz_LJtJVDEN8,1527
+greenlet/platform/switch_ppc64_aix.h,sha256=0kpzjH-gFk6l7J0qjNfFALAVydm-Gb-3xQEgeFHC5TQ,3963
+greenlet/platform/switch_ppc64_linux.h,sha256=J2H7nQdiZoFhkVWGWEFES6758VFspQ7PkUbHshZf8yI,3920
+greenlet/platform/switch_ppc_aix.h,sha256=7akkI638_kXcTj-z33z4Hp-yXCzBKZCgc9oywjgj2sI,3028
+greenlet/platform/switch_ppc_linux.h,sha256=z1G0G3sFmVeuweZpbfnW4T4YsqXLsGpAGkLhN1SzETg,2843
+greenlet/platform/switch_ppc_macosx.h,sha256=x6eeMN4JlCumd6oL2RnbTO24YvEi5Is1IwANClgcxbQ,2706
+greenlet/platform/switch_ppc_unix.h,sha256=B4e2xvK37ixz7E3eXUyafm4oJYwnSStbBk4HI-egl7M,2734
+greenlet/platform/switch_riscv_unix.h,sha256=MBhaF319hLczUNtfuyuBQFlw3fP9cXtv8fTnLbroBTc,990
+greenlet/platform/switch_s390_unix.h,sha256=vlduFQw6kpkalkx5mreVugwD77_3JZZmEGgLUUbCZg8,2850
+greenlet/platform/switch_sh_gcc.h,sha256=Salb5aBXHT_C6myIAB9QzoVgjtD4T4b1BsDOoGbRCIg,937
+greenlet/platform/switch_sparc_sun_gcc.h,sha256=A7T5AMMzTQaW7ZTLNAVl0RwJYc1ON_ZagcRR1dRU43g,2889
+greenlet/platform/switch_x32_unix.h,sha256=brLdkEECmpmMql9k4RNj1SzeAeat77LumkJy8O9G62Y,1572
+greenlet/platform/switch_x64_masm.asm,sha256=krAM4iTcFFUccNlAptXgx41oevPO5zsGOAdMdjU0rAY,1951
+greenlet/platform/switch_x64_masm.obj,sha256=GNtTNxYdo7idFUYsQv-mrXWgyT5EJ93-9q90lN6svtQ,1078
+greenlet/platform/switch_x64_msvc.h,sha256=LH4ZgQTC0PRuG38H7nRCUR5dDLQrz61bxaG4-5mZ9S0,1864
+greenlet/platform/switch_x86_msvc.h,sha256=nWtRXFfHb9rE3pjCe5o5tdoJyctklHBD4kVq7LX9fLs,13164
+greenlet/platform/switch_x86_unix.h,sha256=KqakzLbWleoUwgtpjDGt_4o63bOy5Q0Cxq8Re5n5OyA,3164
+greenlet/slp_platformselect.h,sha256=8tpogbpy7l8mS88NsVokrVpy8rGQWJQX_X3wjGGKsGQ,4036
+greenlet/tests/__init__.py,sha256=-Ev1aQIYbndrP0Dfc_P8g6JlOKnJWMOJFSrLOl3wHrQ,9984
+greenlet/tests/__pycache__/__init__.cpython-311.pyc,,
+greenlet/tests/__pycache__/fail_clearing_run_switches.cpython-311.pyc,,
+greenlet/tests/__pycache__/fail_cpp_exception.cpython-311.pyc,,
+greenlet/tests/__pycache__/fail_initialstub_already_started.cpython-311.pyc,,
+greenlet/tests/__pycache__/fail_slp_switch.cpython-311.pyc,,
+greenlet/tests/__pycache__/fail_switch_three_greenlets.cpython-311.pyc,,
+greenlet/tests/__pycache__/fail_switch_three_greenlets2.cpython-311.pyc,,
+greenlet/tests/__pycache__/fail_switch_two_greenlets.cpython-311.pyc,,
+greenlet/tests/__pycache__/leakcheck.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_contextvars.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_cpp.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_extension_interface.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_gc.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_generator.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_generator_nested.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_greenlet.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_greenlet_trash.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_interpreter_shutdown.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_leaks.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_stack_saved.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_throw.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_tracing.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_version.cpython-311.pyc,,
+greenlet/tests/__pycache__/test_weakref.cpython-311.pyc,,
+greenlet/tests/_test_extension.c,sha256=tEB1SJ_8R07pKrKtxnW6v_pE59_bwSxQlfJdXPXZsbU,7517
+greenlet/tests/_test_extension.cp311-win_amd64.pyd,sha256=611Cb4pfUd5pTp-PsWkNVvNBe4VosC7H4kDxJO8ao24,14848
+greenlet/tests/_test_extension_cpp.cp311-win_amd64.pyd,sha256=Pgw0ABFaMx8PCs0ac12T2gsrN05EmcHleaV7Kas3RiE,15872
+greenlet/tests/_test_extension_cpp.cpp,sha256=WTk6D--17qQ2FfJgPHGzgCcWo_J9LzYguNvox6x7vtA,6943
+greenlet/tests/fail_clearing_run_switches.py,sha256=v6lj1G7GTRml7CrUPRuzxkk68p1MfMmNwykba1mFc3c,1310
+greenlet/tests/fail_cpp_exception.py,sha256=-nUH8slJOxgTVfFx2uE7HwDlVh-dEskr6zR-jyjsJgM,1018
+greenlet/tests/fail_initialstub_already_started.py,sha256=Ku8SxVRpwE5TK8-7Netnd3i6_nrkUGtKpTR8TisQDzE,2039
+greenlet/tests/fail_slp_switch.py,sha256=FmUo8YsGmXt1HqAu9nsJZwH5OKjgmgzH2nkc8iExCRs,553
+greenlet/tests/fail_switch_three_greenlets.py,sha256=KXffSSGYpKFrfLzF9gDuVIvSs-GKVuDQw5cxdnHF14s,1000
+greenlet/tests/fail_switch_three_greenlets2.py,sha256=JDXE9CQdVeJ1rw4YGC1wA2AC3hN3N3JosLcUfjX1rm4,1340
+greenlet/tests/fail_switch_two_greenlets.py,sha256=UuUCa6YqV7Lshm3Ra7MzuLnIpw_1NVZtT-Num0DVMBg,858
+greenlet/tests/leakcheck.py,sha256=GOhPy3dlRHGrro32mxDspPiWcQu0CT9mXmbi4zlouIY,12947
+greenlet/tests/test_contextvars.py,sha256=X_ybZ6LlEKrWsX2Wlf7-taGc4yK8tFV2Aql-fz4FSIo,9846
+greenlet/tests/test_cpp.py,sha256=9YZT-6SbWMBCSJUjxyO0ylbhXN8N5FBv6PQj7H8jtGk,3255
+greenlet/tests/test_extension_interface.py,sha256=3H1KXWGqrg9OKfPObCaDDBP8Gl-Lj1i9kUeefSyB5pc,4961
+greenlet/tests/test_gc.py,sha256=lWYPr4MfFMyAt7zSyUnYxK4Yb_HWsdagOrnSMXZC6BM,3008
+greenlet/tests/test_generator.py,sha256=46DOhdQ61iyAv4Du_j5BVVrwlEoZwmlro6j5DKASQ7Y,1299
+greenlet/tests/test_generator_nested.py,sha256=MjgSMvUtJ2sd9zXSVMTBobsRXQp64rHTWS3xyoqsAbg,3886
+greenlet/tests/test_greenlet.py,sha256=wModw8H1ynXjZ3nvg99wZazXfC8VSJ02f82LYVFsy9M,51921
+greenlet/tests/test_greenlet_trash.py,sha256=uEprfwqNnofWimM6mzknODJzEKM8oOKAZXJRa7hxigk,8564
+greenlet/tests/test_interpreter_shutdown.py,sha256=435OM-vr2xllxvS7BfGpVkdsLJBynSptXnCxP0r93PA,34287
+greenlet/tests/test_leaks.py,sha256=8OBM7DaHWXenI3Wqu0sFw_fCJSwTh8FZev1wHg3CHao,19720
+greenlet/tests/test_stack_saved.py,sha256=2r2x_sTVoMTOjzTGVQHhYFRKyM1Foto4k04RsO9Gda4,465
+greenlet/tests/test_throw.py,sha256=hRbOM7chvmejDOyK99_9tVXZtLIVXb8dGeNCE1Whslk,3840
+greenlet/tests/test_tracing.py,sha256=BR5NqzpoD0bKgVLULitFZdOlAPXSJZUU1uLA23N2O6g,8851
+greenlet/tests/test_version.py,sha256=h3fqCsCwuevO4q4d7EHv0fUZVuHOIBC4rxOLt3KkTbg,1574
+greenlet/tests/test_weakref.py,sha256=vg44gv40Ip1zSfgu-NPWFKDUvc-Z_ew4UFjszBQXf0k,918
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..75a83ab128f69c4cd27d9a5be479a52a2597d3d1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (82.0.1)
+Root-Is-Purelib: false
+Tag: cp311-cp311-win_amd64
+
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..46725be4fd5ff62893d8def5f9e356d4d096328a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet-3.5.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+greenlet
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TBrokenGreenlet.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TBrokenGreenlet.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..0c00bdce5aa1594766a4e82bf745c22027b9475c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TBrokenGreenlet.cpp
@@ -0,0 +1,45 @@
+/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */
+/**
+ * Implementation of greenlet::UserGreenlet.
+ *
+ * Format with:
+ *  clang-format -i --style=file src/greenlet/greenlet.c
+ *
+ *
+ * Fix missing braces with:
+ *   clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements"
+*/
+
+#include "TGreenlet.hpp"
+
+namespace greenlet {
+
+void* BrokenGreenlet::operator new(size_t UNUSED(count))
+{
+    return allocator.allocate(1);
+}
+
+
+void BrokenGreenlet::operator delete(void* ptr)
+{
+    return allocator.deallocate(static_cast(ptr),
+                                1);
+}
+
+greenlet::PythonAllocator greenlet::BrokenGreenlet::allocator;
+
+bool
+BrokenGreenlet::force_slp_switch_error() const noexcept
+{
+    return this->_force_slp_switch_error;
+}
+
+UserGreenlet::switchstack_result_t BrokenGreenlet::g_switchstack(void)
+{
+  if (this->_force_switch_error) {
+    return switchstack_result_t(-1);
+  }
+  return UserGreenlet::g_switchstack();
+}
+
+}; //namespace greenlet
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TExceptionState.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TExceptionState.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..d26340bb90b511fdd4b5f601362e6605e21ab664
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TExceptionState.cpp
@@ -0,0 +1,62 @@
+#ifndef GREENLET_EXCEPTION_STATE_CPP
+#define GREENLET_EXCEPTION_STATE_CPP
+
+#include 
+#include "TGreenlet.hpp"
+
+namespace greenlet {
+
+
+ExceptionState::ExceptionState()
+{
+    this->clear();
+}
+
+void ExceptionState::operator<<(const PyThreadState *const tstate) noexcept
+{
+    this->exc_info = tstate->exc_info;
+    this->exc_state = tstate->exc_state;
+}
+
+void ExceptionState::operator>>(PyThreadState *const tstate) noexcept
+{
+    tstate->exc_state = this->exc_state;
+    tstate->exc_info =
+        this->exc_info ? this->exc_info : &tstate->exc_state;
+    this->clear();
+}
+
+void ExceptionState::clear() noexcept
+{
+    this->exc_info = nullptr;
+    this->exc_state.exc_value = nullptr;
+#if !GREENLET_PY311
+    this->exc_state.exc_type = nullptr;
+    this->exc_state.exc_traceback = nullptr;
+#endif
+    this->exc_state.previous_item = nullptr;
+}
+
+int ExceptionState::tp_traverse(visitproc visit, void* arg) noexcept
+{
+    Py_VISIT(this->exc_state.exc_value);
+#if !GREENLET_PY311
+    Py_VISIT(this->exc_state.exc_type);
+    Py_VISIT(this->exc_state.exc_traceback);
+#endif
+    return 0;
+}
+
+void ExceptionState::tp_clear() noexcept
+{
+    Py_CLEAR(this->exc_state.exc_value);
+#if !GREENLET_PY311
+    Py_CLEAR(this->exc_state.exc_type);
+    Py_CLEAR(this->exc_state.exc_traceback);
+#endif
+}
+
+
+}; // namespace greenlet
+
+#endif // GREENLET_EXCEPTION_STATE_CPP
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TGreenlet.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TGreenlet.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..37c6b1c08e562d00a3004ee90846ee582259b1ed
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TGreenlet.cpp
@@ -0,0 +1,729 @@
+/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */
+/**
+ * Implementation of greenlet::Greenlet.
+ *
+ * Format with:
+ *  clang-format -i --style=file src/greenlet/greenlet.c
+ *
+ *
+ * Fix missing braces with:
+ *   clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements"
+*/
+#ifndef TGREENLET_CPP
+#define TGREENLET_CPP
+#include "greenlet_internal.hpp"
+#include "TGreenlet.hpp"
+
+
+#include "TGreenletGlobals.cpp"
+#include "TThreadStateDestroy.cpp"
+
+namespace greenlet {
+
+Greenlet::Greenlet(PyGreenlet* p)
+    :  Greenlet(p, StackState())
+{
+}
+
+Greenlet::Greenlet(PyGreenlet* p, const StackState& initial_stack)
+    :  _self(p), stack_state(initial_stack)
+{
+    assert(p->pimpl == nullptr);
+    p->pimpl = this;
+}
+
+Greenlet::~Greenlet()
+{
+    // XXX: Can't do this. tp_clear is a virtual function, and by the
+    // time we're here, we've sliced off our child classes.
+    //this->tp_clear();
+    this->_self->pimpl = nullptr;
+}
+
+bool
+Greenlet::force_slp_switch_error() const noexcept
+{
+    return false;
+}
+
+void
+Greenlet::release_args()
+{
+    this->switch_args.CLEAR();
+}
+
+/**
+ * CAUTION: This will allocate memory and may trigger garbage
+ * collection and arbitrary Python code.
+ */
+OwnedObject
+Greenlet::throw_GreenletExit_during_dealloc(const ThreadState& UNUSED(current_thread_state))
+{
+    // If we're killed because we lost all references in the
+    // middle of a switch, that's ok. Don't reset the args/kwargs,
+    // we still want to pass them to the parent.
+    PyErr_SetString(mod_globs->PyExc_GreenletExit,
+                    "Killing the greenlet because all references have vanished.");
+    // To get here it had to have run before
+    return this->g_switch();
+}
+
+inline void
+Greenlet::slp_restore_state() noexcept
+{
+#ifdef SLP_BEFORE_RESTORE_STATE
+    SLP_BEFORE_RESTORE_STATE();
+#endif
+    this->stack_state.copy_heap_to_stack(
+           this->thread_state()->borrow_current()->stack_state);
+}
+
+
+inline int
+Greenlet::slp_save_state(char *const stackref) noexcept
+{
+    // XXX: This used to happen in the middle, before saving, but
+    // after finding the next owner. Does that matter? This is
+    // only defined for Sparc/GCC where it flushes register
+    // windows to the stack (I think)
+#ifdef SLP_BEFORE_SAVE_STATE
+    SLP_BEFORE_SAVE_STATE();
+#endif
+    return this->stack_state.copy_stack_to_heap(stackref,
+                                                this->thread_state()->borrow_current()->stack_state);
+}
+
+/**
+ * CAUTION: This will allocate memory and may trigger garbage
+ * collection and arbitrary Python code.
+ */
+OwnedObject
+Greenlet::on_switchstack_or_initialstub_failure(
+    Greenlet* target,
+    const Greenlet::switchstack_result_t& err,
+    const bool target_was_me,
+    const bool was_initial_stub)
+{
+    // If we get here, either g_initialstub()
+    // failed, or g_switchstack() failed. Either one of those
+    // cases SHOULD leave us in the original greenlet with a valid stack.
+    if (!PyErr_Occurred()) {
+        PyErr_SetString(
+            PyExc_SystemError,
+            was_initial_stub
+            ? "Failed to switch stacks into a greenlet for the first time."
+            : "Failed to switch stacks into a running greenlet.");
+    }
+    this->release_args();
+
+    if (target && !target_was_me) {
+        target->murder_in_place();
+    }
+
+    assert(!err.the_new_current_greenlet);
+    assert(!err.origin_greenlet);
+    return OwnedObject();
+
+}
+
+OwnedGreenlet
+Greenlet::g_switchstack_success() noexcept
+{
+    PyThreadState* tstate = PyThreadState_GET();
+    // restore the saved state
+    this->python_state >> tstate;
+    this->exception_state >> tstate;
+
+    // The thread state hasn't been changed yet.
+    ThreadState* thread_state = this->thread_state();
+    OwnedGreenlet result(thread_state->get_current());
+    thread_state->set_current(this->self());
+    //assert(thread_state->borrow_current().borrow() == this->_self);
+    return result;
+}
+
+Greenlet::switchstack_result_t
+Greenlet::g_switchstack(void)
+{
+    // if any of these assertions fail, it's likely because we
+    // switched away and tried to switch back to us. Early stages of
+    // switching are not reentrant because we re-use ``this->args()``.
+    // Switching away would happen if we trigger a garbage collection
+    // (by just using some Python APIs that happen to allocate Python
+    // objects) and some garbage had weakref callbacks or __del__ that
+    // switches (people don't write code like that by hand, but with
+    // gevent it's possible without realizing it)
+    assert(this->args() || PyErr_Occurred());
+    { /* save state */
+        if (this->thread_state()->is_current(this->self())) {
+            // Hmm, nothing to do.
+            // TODO: Does this bypass trace events that are
+            // important?
+            return switchstack_result_t(0,
+                                        this, this->thread_state()->borrow_current());
+        }
+        BorrowedGreenlet current = this->thread_state()->borrow_current();
+        PyThreadState* tstate = PyThreadState_GET();
+
+        current->python_state << tstate;
+        current->exception_state << tstate;
+        this->python_state.will_switch_from(tstate);
+        switching_thread_state = this;
+        current->expose_frames();
+    }
+    assert(this->args() || PyErr_Occurred());
+    // If this is the first switch into a greenlet, this will
+    // return twice, once with 1 in the new greenlet, once with 0
+    // in the origin.
+    int err;
+    if (this->force_slp_switch_error()) {
+        err = -1;
+    }
+    else {
+        err = slp_switch();
+    }
+
+    if (err < 0) { /* error */
+        // Tested by
+        // test_greenlet.TestBrokenGreenlets.test_failed_to_slp_switch_into_running
+        //
+        // It's not clear if it's worth trying to clean up and
+        // continue here. Failing to switch stacks is a big deal which
+        // may not be recoverable (who knows what state the stack is in).
+        // Also, we've stolen references in preparation for calling
+        // ``g_switchstack_success()`` and we don't have a clean
+        // mechanism for backing that all out.
+        Py_FatalError("greenlet: Failed low-level slp_switch(). The stack is probably corrupt.");
+    }
+
+    // No stack-based variables are valid anymore.
+
+    // But the global is thread_local volatile so we can reload it without the
+    // compiler caching it from earlier.
+    Greenlet* greenlet_that_switched_in = switching_thread_state; // aka this
+    switching_thread_state = nullptr;
+    // except that no stack variables are valid, we would:
+    // assert(this == greenlet_that_switched_in);
+
+    // switchstack success is where we restore the exception state,
+    // etc. It returns the origin greenlet because its convenient.
+
+    OwnedGreenlet origin = greenlet_that_switched_in->g_switchstack_success();
+    assert(greenlet_that_switched_in->args() || PyErr_Occurred());
+    return switchstack_result_t(err, greenlet_that_switched_in, origin);
+}
+
+
+inline void
+Greenlet::check_switch_allowed() const
+{
+    // TODO: Make this take a parameter of the current greenlet,
+    // or current main greenlet, to make the check for
+    // cross-thread switching cheaper. Surely somewhere up the
+    // call stack we've already accessed the thread local variable.
+
+    // We expect to always have a main greenlet now; accessing the thread state
+    // created it. However, if we get here and cleanup has already
+    // begun because we're a greenlet that was running in a
+    // (now dead) thread, these invariants will not hold true. In
+    // fact, accessing `this->thread_state` may not even be possible.
+
+    // If the thread this greenlet was running in is dead,
+    // we'll still have a reference to a main greenlet, but the
+    // thread state pointer we have is bogus (should be nullptr)
+    // TODO: Give the objects an API to determine if they belong
+    // to a dead thread.
+
+    const BorrowedMainGreenlet my_main_greenlet = this->find_main_greenlet_in_lineage();
+
+    if (!my_main_greenlet) {
+        throw PyErrOccurred(mod_globs->PyExc_GreenletError,
+                            "cannot switch to a garbage collected greenlet");
+    }
+
+    if (!my_main_greenlet->thread_state()) {
+        throw PyErrOccurred(mod_globs->PyExc_GreenletError,
+                            "cannot switch to a different thread (which happens to have exited)");
+    }
+
+    // The main greenlet we found was from the .parent lineage.
+    // That may or may not have any relationship to the main
+    // greenlet of the running thread. We can't actually access
+    // our this->thread_state members to try to check that,
+    // because it could be in the process of getting destroyed,
+    // but setting the main_greenlet->thread_state member to NULL
+    // may not be visible yet. So we need to check against the
+    // current thread state (once the cheaper checks are out of
+    // the way)
+    const BorrowedMainGreenlet main_greenlet_cur_thread = GET_THREAD_STATE().state().borrow_main_greenlet();
+    if (
+        // lineage main greenlet is not this thread's greenlet
+        main_greenlet_cur_thread != my_main_greenlet
+        || (
+            // atteched to some thread
+            this->main_greenlet()
+            // XXX: Same condition as above. Was this supposed to be
+            // this->main_greenlet()?
+            && main_greenlet_cur_thread != my_main_greenlet)
+        // switching into a known dead thread (XXX: which, if we get here,
+        // is bad, because we just accessed the thread state, which is
+        // gone!)
+        || (!main_greenlet_cur_thread->thread_state())) {
+        // CAUTION: This may trigger memory allocations, gc, and
+        // arbitrary Python code.
+        throw PyErrOccurred(
+            mod_globs->PyExc_GreenletError,
+            "Cannot switch to a different thread\n\tCurrent:  %R\n\tExpected: %R",
+            main_greenlet_cur_thread, my_main_greenlet);
+    }
+}
+
+const OwnedObject
+Greenlet::context() const
+{
+    using greenlet::PythonStateContext;
+    OwnedObject result;
+
+    if (this->is_currently_running_in_some_thread()) {
+        /* Currently running greenlet: context is stored in the thread state,
+           not the greenlet object. */
+        if (GET_THREAD_STATE().state().is_current(this->self())) {
+            result = PythonStateContext::context(PyThreadState_GET());
+        }
+        else {
+            throw ValueError(
+                            "cannot get context of a "
+                            "greenlet that is running in a different thread");
+        }
+    }
+    else {
+        /* Greenlet is not running: just return context. */
+        result = this->python_state.context();
+    }
+    if (!result) {
+        result = OwnedObject::None();
+    }
+    return result;
+}
+
+
+void
+Greenlet::context(BorrowedObject given)
+{
+    using greenlet::PythonStateContext;
+    if (!given) {
+        throw AttributeError("can't delete context attribute");
+    }
+    if (given.is_None()) {
+        /* "Empty context" is stored as NULL, not None. */
+        given = nullptr;
+    }
+
+    //checks type, incrs refcnt
+    greenlet::refs::OwnedContext context(given);
+    PyThreadState* tstate = PyThreadState_GET();
+
+    if (this->is_currently_running_in_some_thread()) {
+        if (!GET_THREAD_STATE().state().is_current(this->self())) {
+            throw ValueError("cannot set context of a greenlet"
+                             " that is running in a different thread");
+        }
+
+        /* Currently running greenlet: context is stored in the thread state,
+           not the greenlet object. */
+        OwnedObject octx = OwnedObject::consuming(PythonStateContext::context(tstate));
+        PythonStateContext::context(tstate, context.relinquish_ownership());
+    }
+    else {
+        /* Greenlet is not running: just set context. Note that the
+           greenlet may be dead.*/
+        this->python_state.context() = context;
+    }
+}
+
+/**
+ * CAUTION: May invoke arbitrary Python code.
+ *
+ * Figure out what the result of ``greenlet.switch(arg, kwargs)``
+ * should be and transfers ownership of it to the left-hand-side.
+ *
+ * If switch() was just passed an arg tuple, then we'll just return that.
+ * If only keyword arguments were passed, then we'll pass the keyword
+ * argument dict. Otherwise, we'll create a tuple of (args, kwargs) and
+ * return both.
+ *
+ * CAUTION: This may allocate a new tuple object, which may
+ * cause the Python garbage collector to run, which in turn may
+ * run arbitrary Python code that switches.
+ */
+OwnedObject& operator<<=(OwnedObject& lhs, greenlet::SwitchingArgs& rhs) noexcept
+{
+    // Because this may invoke arbitrary Python code, which could
+    // result in switching back to us, we need to get the
+    // arguments locally on the stack.
+    assert(rhs);
+    OwnedObject args = rhs.args();
+    OwnedObject kwargs = rhs.kwargs();
+    rhs.CLEAR();
+    // We shouldn't be called twice for the same switch.
+    assert(args || kwargs);
+    assert(!rhs);
+
+    if (!kwargs) {
+        lhs = args;
+    }
+    else if (!PyDict_Size(kwargs.borrow())) {
+        lhs = args;
+    }
+    else if (!PySequence_Length(args.borrow())) {
+        lhs = kwargs;
+    }
+    else {
+        // PyTuple_Pack allocates memory, may GC, may run arbitrary
+        // Python code.
+        lhs = OwnedObject::consuming(PyTuple_Pack(2, args.borrow(), kwargs.borrow()));
+    }
+    return lhs;
+}
+
+static OwnedObject
+g_handle_exit(const OwnedObject& greenlet_result)
+{
+    if (!greenlet_result && mod_globs->PyExc_GreenletExit.PyExceptionMatches()) {
+        /* catch and ignore GreenletExit */
+        PyErrFetchParam val;
+        // TODO: When we run on 3.12+ only (GREENLET_312), switch to the
+        // ``PyErr_GetRaisedException`` family of functions. The
+        // ``PyErr_Fetch`` family is deprecated on 3.12+, but is part
+        // of the stable ABI so it's not going anywhere.
+        PyErr_Fetch(PyErrFetchParam(), val, PyErrFetchParam());
+        if (!val) {
+            return OwnedObject::None();
+        }
+        return OwnedObject(val);
+    }
+
+    if (greenlet_result) {
+        // package the result into a 1-tuple
+        // PyTuple_Pack increments the reference of its arguments,
+        // so we always need to decref the greenlet result;
+        // the owner will do that.
+        return OwnedObject::consuming(PyTuple_Pack(1, greenlet_result.borrow()));
+    }
+
+    return OwnedObject();
+}
+
+
+
+/**
+ * May run arbitrary Python code.
+ */
+OwnedObject
+Greenlet::g_switch_finish(const switchstack_result_t& err)
+{
+    assert(err.the_new_current_greenlet == this);
+
+    ThreadState& state = *this->thread_state();
+    // Because calling the trace function could do arbitrary things,
+    // including switching away from this greenlet and then maybe
+    // switching back, we need to capture the arguments now so that
+    // they don't change.
+    OwnedObject result;
+    if (this->args()) {
+        result <<= this->args();
+    }
+    else {
+        assert(PyErr_Occurred());
+    }
+    assert(!this->args());
+    try {
+        // Our only caller handles the bad error case
+        assert(err.status >= 0);
+        assert(state.borrow_current() == this->self());
+        if (OwnedObject tracefunc = state.get_tracefunc()) {
+            assert(result || PyErr_Occurred());
+            g_calltrace(tracefunc,
+                        result ? mod_globs->event_switch : mod_globs->event_throw,
+                        err.origin_greenlet,
+                        this->self());
+        }
+        // The above could have invoked arbitrary Python code, but
+        // it couldn't switch back to this object and *also*
+        // throw an exception, so the args won't have changed.
+
+        if (PyErr_Occurred()) {
+            // We get here if we fell of the end of the run() function
+            // raising an exception. The switch itself was
+            // successful, but the function raised.
+            // valgrind reports that memory allocated here can still
+            // be reached after a test run.
+            throw PyErrOccurred::from_current();
+        }
+        return result;
+    }
+    catch (const PyErrOccurred&) {
+        /* Turn switch errors into switch throws */
+        /* Turn trace errors into switch throws */
+        this->release_args();
+        throw;
+    }
+}
+
+void
+Greenlet::g_calltrace(const OwnedObject& tracefunc,
+                      const greenlet::refs::ImmortalEventName& event,
+                      const BorrowedGreenlet& origin,
+                      const BorrowedGreenlet& target)
+{
+    PyErrPieces saved_exc;
+    try {
+        TracingGuard tracing_guard;
+        // TODO: We have saved the active exception (if any) that's
+        // about to be raised. In the 'throw' case, we could provide
+        // the exception to the tracefunction, which seems very helpful.
+        tracing_guard.CallTraceFunction(tracefunc, event, origin, target);
+    }
+    catch (const PyErrOccurred&) {
+        // In case of exceptions trace function is removed,
+        // and any existing exception is replaced with the tracing
+        // exception.
+        GET_THREAD_STATE().state().set_tracefunc(Py_None);
+        throw;
+    }
+
+    saved_exc.PyErrRestore();
+    assert(
+        (event == mod_globs->event_throw && PyErr_Occurred())
+        || (event == mod_globs->event_switch && !PyErr_Occurred())
+    );
+}
+
+void
+Greenlet::murder_in_place()
+{
+    if (this->active()) {
+        assert(!this->is_currently_running_in_some_thread());
+        this->deactivate_and_free();
+    }
+}
+
+inline void
+Greenlet::deactivate_and_free()
+{
+    if (!this->active()) {
+        return;
+    }
+    // Throw away any saved stack.
+    this->stack_state = StackState();
+    assert(!this->stack_state.active());
+    // Throw away any Python references.
+    // We're holding a borrowed reference to the last
+    // frame we executed. Since we borrowed it, the
+    // normal traversal, clear, and dealloc functions
+    // ignore it, meaning it leaks. (The thread state
+    // object can't find it to clear it when that's
+    // deallocated either, because by definition if we
+    // got an object on this list, it wasn't
+    // running and the thread state doesn't have
+    // this frame.)
+    // So here, we *do* clear it.
+    this->python_state.tp_clear(true);
+}
+
+bool
+Greenlet::belongs_to_thread(const ThreadState* thread_state) const
+{
+    if (!this->thread_state() // not running anywhere, or thread
+                              // exited
+        || !thread_state) { // same, or there is no thread state.
+        return false;
+    }
+    return true;
+}
+
+
+void
+Greenlet::deallocing_greenlet_in_thread(const ThreadState* current_thread_state)
+{
+    /* Cannot raise an exception to kill the greenlet if
+       it is not running in the same thread! */
+    if (this->belongs_to_thread(current_thread_state)) {
+        assert(current_thread_state);
+        // To get here it had to have run before
+        /* Send the greenlet a GreenletExit exception. */
+
+        // We don't care about the return value, only whether an
+        // exception happened.
+        this->throw_GreenletExit_during_dealloc(*current_thread_state);
+        return;
+    }
+
+    // Not the same thread! Temporarily save the greenlet
+    // into its thread's deleteme list, *if* it exists.
+    // If that thread has already exited, and processed its pending
+    // cleanup, we'll never be able to clean everything up: we won't
+    // be able to raise an exception.
+    // That's mostly OK! Since we can't add it to a list, our refcount
+    // won't increase, and we'll go ahead with the DECREFs later.
+
+    ThreadState *const  thread_state = this->thread_state();
+    if (thread_state) {
+        thread_state->delete_when_thread_running(this->self());
+    }
+    else {
+        // The thread is dead, we can't raise an exception.
+        // We need to make it look non-active, though, so that dealloc
+        // finishes killing it.
+        this->deactivate_and_free();
+    }
+    return;
+}
+
+
+int
+Greenlet::tp_traverse(visitproc visit, void* arg)
+{
+
+    int result;
+    if ((result = this->exception_state.tp_traverse(visit, arg)) != 0) {
+        return result;
+    }
+    //XXX: This is ugly. But so is handling everything having to do
+    //with the top frame.
+    bool visit_top_frame = this->was_running_in_dead_thread();
+    // When true, the thread is dead. Our implicit weak reference to the
+    // frame is now all that's left; we consider ourselves to
+    // strongly own it now.
+    if ((result = this->python_state.tp_traverse(visit, arg, visit_top_frame)) != 0) {
+        return result;
+    }
+    return 0;
+}
+
+int
+Greenlet::tp_clear()
+{
+    bool own_top_frame = this->was_running_in_dead_thread();
+    this->exception_state.tp_clear();
+    this->python_state.tp_clear(own_top_frame);
+    return 0;
+}
+
+bool Greenlet::is_currently_running_in_some_thread() const
+{
+    return this->stack_state.active() && !this->python_state.top_frame();
+}
+
+#if GREENLET_PY312
+void GREENLET_NOINLINE(Greenlet::expose_frames)()
+{
+    if (!this->python_state.top_frame()) {
+        return;
+    }
+
+    _PyInterpreterFrame* last_complete_iframe = nullptr;
+    _PyInterpreterFrame* iframe = this->python_state.top_frame()->f_frame;
+    while (iframe) {
+        // We must make a copy before looking at the iframe contents,
+        // since iframe might point to a portion of the greenlet's C stack
+        // that was spilled when switching greenlets.
+        _PyInterpreterFrame iframe_copy;
+        this->stack_state.copy_from_stack(&iframe_copy, iframe, sizeof(*iframe));
+        if (!_PyFrame_IsIncomplete(&iframe_copy)) {
+            // If the iframe were OWNED_BY_CSTACK then it would always be
+            // incomplete. Since it's not incomplete, it's not on the C stack
+            // and we can access it through the original `iframe` pointer
+            // directly.  This is important since GetFrameObject might
+            // lazily _create_ the frame object and we don't want the
+            // interpreter to lose track of it.
+            //
+            #if !GREENLET_PY315
+            // This enum value was removed in
+            //    https://github.com/python/cpython/pull/141108
+
+            assert(iframe_copy.owner != FRAME_OWNED_BY_CSTACK);
+            #endif
+
+            // We really want to just write:
+            //     PyFrameObject* frame = _PyFrame_GetFrameObject(iframe);
+            // but _PyFrame_GetFrameObject calls _PyFrame_MakeAndSetFrameObject
+            // which is not a visible symbol in libpython. The easiest
+            // way to get a public function to call it is using
+            // PyFrame_GetBack, which is defined as follows:
+            //     assert(frame != NULL);
+            //     assert(!_PyFrame_IsIncomplete(frame->f_frame));
+            //     PyFrameObject *back = frame->f_back;
+            //     if (back == NULL) {
+            //         _PyInterpreterFrame *prev = frame->f_frame->previous;
+            //         prev = _PyFrame_GetFirstComplete(prev);
+            //         if (prev) {
+            //             back = _PyFrame_GetFrameObject(prev);
+            //         }
+            //     }
+            //     return (PyFrameObject*)Py_XNewRef(back);
+            if (!iframe->frame_obj) {
+                PyFrameObject dummy_frame;
+                _PyInterpreterFrame dummy_iframe;
+                dummy_frame.f_back = nullptr;
+                dummy_frame.f_frame = &dummy_iframe;
+                // force the iframe to be considered complete without
+                // needing to check its code object:
+                dummy_iframe.owner = FRAME_OWNED_BY_GENERATOR;
+                dummy_iframe.previous = iframe;
+                assert(!_PyFrame_IsIncomplete(&dummy_iframe));
+                // Drop the returned reference immediately; the iframe
+                // continues to hold a strong reference
+                Py_XDECREF(PyFrame_GetBack(&dummy_frame));
+                assert(iframe->frame_obj);
+            }
+
+            // This is a complete frame, so make the last one of those we saw
+            // point at it, bypassing any incomplete frames (which may have
+            // been on the C stack) in between the two. We're overwriting
+            // last_complete_iframe->previous and need that to be reversible,
+            // so we store the original previous ptr in the frame object
+            // (which we must have created on a previous iteration through
+            // this loop). The frame object has a bunch of storage that is
+            // only used when its iframe is OWNED_BY_FRAME_OBJECT, which only
+            // occurs when the frame object outlives the frame's execution,
+            // which can't have happened yet because the frame is currently
+            // executing as far as the interpreter is concerned. So, we can
+            // reuse it for our own purposes.
+            assert(iframe->owner == FRAME_OWNED_BY_THREAD
+                   || iframe->owner == FRAME_OWNED_BY_GENERATOR);
+            if (last_complete_iframe) {
+                assert(last_complete_iframe->frame_obj);
+                memcpy(&last_complete_iframe->frame_obj->_f_frame_data[0],
+                       &last_complete_iframe->previous, sizeof(void *));
+                last_complete_iframe->previous = iframe;
+            }
+            last_complete_iframe = iframe;
+        }
+        // Frames that are OWNED_BY_FRAME_OBJECT are linked via the
+        // frame's f_back while all others are linked via the iframe's
+        // previous ptr. Since all the frames we traverse are running
+        // as far as the interpreter is concerned, we don't have to
+        // worry about the OWNED_BY_FRAME_OBJECT case.
+        iframe = iframe_copy.previous;
+    }
+
+    // Give the outermost complete iframe a null previous pointer to
+    // account for any potential incomplete/C-stack iframes between it
+    // and the actual top-of-stack
+    if (last_complete_iframe) {
+        assert(last_complete_iframe->frame_obj);
+        memcpy(&last_complete_iframe->frame_obj->_f_frame_data[0],
+               &last_complete_iframe->previous, sizeof(void *));
+        last_complete_iframe->previous = nullptr;
+    }
+}
+#else
+void Greenlet::expose_frames()
+{
+
+}
+#endif
+
+}; // namespace greenlet
+#endif
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TGreenlet.hpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TGreenlet.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..3fd109dbe4f5ec51f9304b23547e1b7490c54edf
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TGreenlet.hpp
@@ -0,0 +1,849 @@
+#ifndef GREENLET_GREENLET_HPP
+#define GREENLET_GREENLET_HPP
+/*
+ * Declarations of the core data structures.
+*/
+
+#define PY_SSIZE_T_CLEAN
+#include 
+
+#include 
+
+#include "greenlet_compiler_compat.hpp"
+#include "greenlet_refs.hpp"
+#include "greenlet_cpython_compat.hpp"
+#include "greenlet_allocator.hpp"
+
+using greenlet::refs::OwnedObject;
+using greenlet::refs::OwnedGreenlet;
+using greenlet::refs::OwnedMainGreenlet;
+using greenlet::refs::BorrowedGreenlet;
+
+#if PY_VERSION_HEX < 0x30B00A6
+    // prior to 3.11.0a6
+#  define _PyCFrame CFrame
+#  define _PyInterpreterFrame _interpreter_frame
+#endif
+
+#if GREENLET_PY312
+#  define Py_BUILD_CORE
+#  include "internal/pycore_frame.h"
+#endif
+
+#if GREENLET_PY314
+#  include "internal/pycore_interpframe_structs.h"
+#if defined(_MSC_VER) || defined(__MINGW64__)
+#   include "greenlet_msvc_compat.hpp"
+#else
+#  include "internal/pycore_interpframe.h"
+#endif
+#ifdef Py_GIL_DISABLED
+#   include "internal/pycore_tstate.h"
+#endif
+#endif
+
+// XXX: TODO: Work to remove all virtual functions
+// for speed of calling and size of objects (no vtable).
+// One pattern is the Curiously Recurring Template
+namespace greenlet
+{
+    class ExceptionState
+    {
+    private:
+        G_NO_COPIES_OF_CLS(ExceptionState);
+
+        // Even though these are borrowed objects, we actually own
+        // them, when they're not null.
+        // XXX: Express that in the API.
+    private:
+        _PyErr_StackItem* exc_info;
+        _PyErr_StackItem exc_state;
+    public:
+        ExceptionState();
+        void operator<<(const PyThreadState *const tstate) noexcept;
+        void operator>>(PyThreadState* tstate) noexcept;
+        void clear() noexcept;
+
+        int tp_traverse(visitproc visit, void* arg) noexcept;
+        void tp_clear() noexcept;
+    };
+
+    template
+    void operator<<(const PyThreadState *const tstate, T& exc);
+
+    class PythonStateContext
+    {
+    protected:
+        greenlet::refs::OwnedContext _context;
+    public:
+        inline const greenlet::refs::OwnedContext& context() const
+        {
+            return this->_context;
+        }
+        inline greenlet::refs::OwnedContext& context()
+        {
+            return this->_context;
+        }
+
+        inline void tp_clear()
+        {
+            this->_context.CLEAR();
+        }
+
+        template
+        inline static PyObject* context(T* tstate)
+        {
+            return tstate->context;
+        }
+
+        template
+        inline static void context(T* tstate, PyObject* new_context)
+        {
+            tstate->context = new_context;
+            tstate->context_ver++;
+        }
+    };
+    class SwitchingArgs;
+    class PythonState : public PythonStateContext
+    {
+    public:
+        typedef greenlet::refs::OwnedReference OwnedFrame;
+    private:
+        G_NO_COPIES_OF_CLS(PythonState);
+        // We own this if we're suspended (although currently we don't
+        // tp_traverse into it; that's a TODO). If we're running, it's
+        // empty. If we get deallocated and *still* have a frame, it
+        // won't be reachable from the place that normally decref's
+        // it, so we need to do it (hence owning it).
+        OwnedFrame _top_frame;
+#if GREENLET_USE_CFRAME
+        _PyCFrame* cframe;
+        int use_tracing;
+#endif
+#if GREENLET_PY314
+        int py_recursion_depth;
+        // I think this is only used by the JIT. At least,
+        // we only got errors not switching it when the JIT was enabled.
+        //    Python/generated_cases.c.h:12469: _PyEval_EvalFrameDefault:
+        //      Assertion `tstate->current_executor == NULL' failed.
+        // see https://github.com/python-greenlet/greenlet/issues/460
+        PyObject* current_executor;
+        _PyStackRef* stackpointer;
+    #ifdef Py_GIL_DISABLED
+        _PyCStackRef* c_stack_refs;
+    #endif
+#elif GREENLET_PY312
+        int py_recursion_depth;
+        int c_recursion_depth;
+#else
+        int recursion_depth;
+#endif
+#if GREENLET_PY313
+        PyObject *delete_later;
+#else
+        int trash_delete_nesting;
+#endif
+#if GREENLET_PY311
+        _PyInterpreterFrame* current_frame;
+        _PyStackChunk* datastack_chunk;
+        PyObject** datastack_top;
+        PyObject** datastack_limit;
+#endif
+        // The PyInterpreterFrame list on 3.12+ contains some entries that are
+        // on the C stack, which can't be directly accessed while a greenlet is
+        // suspended. In order to keep greenlet gr_frame introspection working,
+        // we adjust stack switching to rewrite the interpreter frame list
+        // to skip these C-stack frames; we call this "exposing" the greenlet's
+        // frames because it makes them valid to work with in Python. Then when
+        // the greenlet is resumed we need to remember to reverse the operation
+        // we did. The C-stack frames are "entry frames" which are a low-level
+        // interpreter detail; they're not needed for introspection, but do
+        // need to be present for the eval loop to work.
+        void unexpose_frames();
+
+    public:
+
+        PythonState();
+        // You can use this for testing whether we have a frame
+        // or not. It returns const so they can't modify it.
+        const OwnedFrame& top_frame() const noexcept;
+
+        inline void operator<<(const PyThreadState *const tstate) noexcept;
+        inline void operator>>(PyThreadState* tstate) noexcept;
+        void clear() noexcept;
+
+        int tp_traverse(visitproc visit, void* arg, bool visit_top_frame) noexcept;
+        void tp_clear(bool own_top_frame) noexcept;
+        void set_initial_state(const PyThreadState* const tstate) noexcept;
+#if GREENLET_USE_CFRAME
+        void set_new_cframe(_PyCFrame& frame) noexcept;
+#endif
+
+        void may_switch_away() noexcept;
+        inline void will_switch_from(PyThreadState *const origin_tstate) noexcept;
+        void did_finish(PyThreadState* tstate) noexcept;
+    };
+
+    class StackState
+    {
+        // By having only plain C (POD) members, no virtual functions
+        // or bases, we get a trivial assignment operator generated
+        // for us. However, that's not safe since we do manage memory.
+        // So we declare an assignment operator that only works if we
+        // don't have any memory allocated. (We don't use
+        // std::shared_ptr for reference counting just to keep this
+        // object small)
+    private:
+        char* _stack_start;
+        char* stack_stop;
+        char* stack_copy;
+        intptr_t _stack_saved;
+        StackState* stack_prev;
+        inline int copy_stack_to_heap_up_to(const char* const stop) noexcept;
+        inline void free_stack_copy() noexcept;
+
+    public:
+        /**
+         * Creates a started, but inactive, state, using *current*
+         * as the previous.
+         */
+        StackState(void* mark, StackState& current);
+        /**
+         * Creates an inactive, unstarted, state.
+         */
+        StackState();
+        ~StackState();
+        StackState(const StackState& other);
+        StackState& operator=(const StackState& other);
+        inline void copy_heap_to_stack(const StackState& current) noexcept;
+        inline int copy_stack_to_heap(char* const stackref, const StackState& current) noexcept;
+        inline bool started() const noexcept;
+        inline bool main() const noexcept;
+        inline bool active() const noexcept;
+        inline void set_active() noexcept;
+        inline void set_inactive() noexcept;
+        inline intptr_t stack_saved() const noexcept;
+        inline char* stack_start() const noexcept;
+        static inline StackState make_main() noexcept;
+#ifdef GREENLET_USE_STDIO
+        friend std::ostream& operator<<(std::ostream& os, const StackState& s);
+#endif
+
+        // Fill in [dest, dest + n) with the values that would be at
+        // [src, src + n) while this greenlet is running. This is like memcpy
+        // except that if the greenlet is suspended it accounts for the portion
+        // of the greenlet's stack that was spilled to the heap. `src` may
+        // be on this greenlet's stack, or on the heap, but not on a different
+        // greenlet's stack.
+        void copy_from_stack(void* dest, const void* src, size_t n) const;
+    };
+#ifdef GREENLET_USE_STDIO
+    std::ostream& operator<<(std::ostream& os, const StackState& s);
+#endif
+
+    class SwitchingArgs
+    {
+    private:
+        G_NO_ASSIGNMENT_OF_CLS(SwitchingArgs);
+        // If args and kwargs are both false (NULL), this is a *throw*, not a
+        // switch. PyErr_... must have been called already.
+        OwnedObject _args;
+        OwnedObject _kwargs;
+    public:
+
+        SwitchingArgs()
+        {}
+
+        SwitchingArgs(const OwnedObject& args, const OwnedObject& kwargs)
+            : _args(args),
+              _kwargs(kwargs)
+        {}
+
+        SwitchingArgs(const SwitchingArgs& other)
+            : _args(other._args),
+              _kwargs(other._kwargs)
+        {}
+
+        const OwnedObject& args()
+        {
+            return this->_args;
+        }
+
+        const OwnedObject& kwargs()
+        {
+            return this->_kwargs;
+        }
+
+        /**
+         * Moves ownership from the argument to this object.
+         */
+        SwitchingArgs& operator<<=(SwitchingArgs& other)
+        {
+            if (this != &other) {
+                this->_args = other._args;
+                this->_kwargs = other._kwargs;
+                other.CLEAR();
+            }
+            return *this;
+        }
+
+        /**
+         * Acquires ownership of the argument (consumes the reference).
+         */
+        SwitchingArgs& operator<<=(PyObject* args)
+        {
+            this->_args = OwnedObject::consuming(args);
+            this->_kwargs.CLEAR();
+            return *this;
+        }
+
+        /**
+         * Acquires ownership of the argument.
+         *
+         * Sets the args to be the given value; clears the kwargs.
+         */
+        SwitchingArgs& operator<<=(OwnedObject& args)
+        {
+            assert(&args != &this->_args);
+            this->_args = args;
+            this->_kwargs.CLEAR();
+            args.CLEAR();
+
+            return *this;
+        }
+
+        explicit operator bool() const noexcept
+        {
+            return this->_args || this->_kwargs;
+        }
+
+        inline void CLEAR()
+        {
+            this->_args.CLEAR();
+            this->_kwargs.CLEAR();
+        }
+
+        const std::string as_str() const noexcept
+        {
+            return PyUnicode_AsUTF8(
+                OwnedObject::consuming(
+                    PyUnicode_FromFormat(
+                        "SwitchingArgs(args=%R, kwargs=%R)",
+                        this->_args.borrow(),
+                        this->_kwargs.borrow()
+                    )
+                ).borrow()
+            );
+        }
+    };
+
+    class ThreadState;
+
+    class UserGreenlet;
+    class MainGreenlet;
+
+    class Greenlet
+    {
+    private:
+        G_NO_COPIES_OF_CLS(Greenlet);
+        PyGreenlet* const _self;
+    private:
+        // XXX: Work to remove these.
+        friend class ThreadState;
+        friend class UserGreenlet;
+        friend class MainGreenlet;
+    protected:
+        ExceptionState exception_state;
+        SwitchingArgs switch_args;
+        StackState stack_state;
+        PythonState python_state;
+        Greenlet(PyGreenlet* p, const StackState& initial_state);
+    public:
+        // This constructor takes ownership of the PyGreenlet, by
+        // setting ``p->pimpl = this;``.
+        Greenlet(PyGreenlet* p);
+        virtual ~Greenlet();
+
+        const OwnedObject context() const;
+
+        // You MUST call this _very_ early in the switching process to
+        // prepare anything that may need prepared. This might perform
+        // garbage collections or otherwise run arbitrary Python code.
+        //
+        // One specific use of it is for Python 3.11+, preventing
+        // running arbitrary code at unsafe times. See
+        // PythonState::may_switch_away().
+        inline void may_switch_away()
+        {
+            this->python_state.may_switch_away();
+        }
+
+        inline void context(refs::BorrowedObject new_context);
+
+        inline SwitchingArgs& args()
+        {
+            return this->switch_args;
+        }
+
+        virtual const refs::BorrowedMainGreenlet main_greenlet() const = 0;
+
+        inline intptr_t stack_saved() const noexcept
+        {
+            return this->stack_state.stack_saved();
+        }
+
+        // This is used by the macro SLP_SAVE_STATE to compute the
+        // difference in stack sizes. It might be nice to handle the
+        // computation ourself, but the type of the result
+        // varies by platform, so doing it in the macro is the
+        // simplest way.
+        inline const char* stack_start() const noexcept
+        {
+            return this->stack_state.stack_start();
+        }
+
+        virtual OwnedObject throw_GreenletExit_during_dealloc(const ThreadState& current_thread_state);
+
+        /**
+         * Depends on the state of this->args() or the current Python
+         * error indicator. Thus, it is not threadsafe or reentrant.
+         * You (you being ``green_switch``, the Python-level
+         * ``greenlet.switch`` method) should call
+         * ``check_switch_allowed`` in free-threaded builds before
+         * calling this method and catch ``PyErrOccurred`` if it isn't
+         * a valid switch. This method should also call that method
+         * because there are places where we can switch internally
+         * without going through the Python method.
+         */
+        virtual OwnedObject g_switch() = 0;
+        /**
+         * Force the greenlet to appear dead. Used when it's not
+         * possible to throw an exception into a greenlet anymore.
+         *
+         * This losses access to the thread state and the main greenlet.
+         */
+        virtual void murder_in_place();
+
+        /**
+         * Called when somebody notices we were running in a dead
+         * thread to allow cleaning up resources (because we can't
+         * raise GreenletExit into it anymore).
+         * This is very similar to ``murder_in_place()``, except that
+         * it DOES NOT lose the main greenlet or thread state.
+         */
+        inline void deactivate_and_free();
+
+
+        // Called when some thread wants to deallocate a greenlet
+        // object.
+        // The thread may or may not be the same thread the greenlet
+        // was running in.
+        // The thread state will be null if the thread the greenlet
+        // was running in was known to have exited.
+        void deallocing_greenlet_in_thread(const ThreadState* current_state);
+
+        // Must be called on 3.12+ before exposing a suspended greenlet's
+        // frames to user code. This rewrites the linked list of interpreter
+        // frames to skip the ones that are being stored on the C stack (which
+        // can't be safely accessed while the greenlet is suspended because
+        // that stack space might be hosting a different greenlet), and
+        // sets PythonState::frames_were_exposed so we remember to restore
+        // the original list before resuming the greenlet. The C-stack frames
+        // are a low-level interpreter implementation detail; while they're
+        // important to the bytecode eval loop, they're superfluous for
+        // introspection purposes.
+        void expose_frames();
+
+
+        // TODO: Figure out how to make these non-public.
+        inline void slp_restore_state() noexcept;
+        inline int slp_save_state(char *const stackref) noexcept;
+
+        inline bool is_currently_running_in_some_thread() const;
+        virtual bool belongs_to_thread(const ThreadState* state) const;
+
+        inline bool started() const
+        {
+            return this->stack_state.started();
+        }
+        inline bool active() const
+        {
+            return this->stack_state.active();
+        }
+        inline bool main() const
+        {
+            return this->stack_state.main();
+        }
+        virtual refs::BorrowedMainGreenlet find_main_greenlet_in_lineage() const = 0;
+
+        virtual const OwnedGreenlet parent() const = 0;
+        virtual void parent(const refs::BorrowedObject new_parent) = 0;
+
+        inline const PythonState::OwnedFrame& top_frame()
+        {
+            return this->python_state.top_frame();
+        }
+
+        virtual const OwnedObject& run() const = 0;
+        virtual void run(const refs::BorrowedObject nrun) = 0;
+
+
+        virtual int tp_traverse(visitproc visit, void* arg);
+        virtual int tp_clear();
+
+
+        // Return the thread state that the greenlet is running in, or
+        // null if the greenlet is not running or the thread is known
+        // to have exited.
+        virtual ThreadState* thread_state() const noexcept = 0;
+
+        // Return true if the greenlet is known to have been running
+        // (active) in a thread that has now exited.
+        virtual bool was_running_in_dead_thread() const noexcept = 0;
+
+        // Return a borrowed greenlet that is the Python object
+        // this object represents.
+        inline BorrowedGreenlet self() const noexcept
+        {
+            return BorrowedGreenlet(this->_self);
+        }
+
+        // For testing. If this returns true, we should pretend that
+        // slp_switch() failed.
+        virtual bool force_slp_switch_error() const noexcept;
+
+        // Check the preconditions for switching to this greenlet; if they
+        // aren't met, throws PyErrOccurred. Most callers will want to
+        // catch this and clear the arguments if they've been set.
+        inline void check_switch_allowed() const;
+
+    protected:
+        inline void release_args();
+
+        // The functions that must not be inlined are declared virtual.
+        // We also mark them as protected, not private, so that the
+        // compiler is forced to call them through a function pointer.
+        // (A sufficiently smart compiler could directly call a private
+        // virtual function since it can never be overridden in a
+        // subclass).
+
+        // Also TODO: Switch away from integer error codes and to enums,
+        // or throw exceptions when possible.
+        struct switchstack_result_t
+        {
+            int status;
+            Greenlet* the_new_current_greenlet;
+            OwnedGreenlet origin_greenlet;
+
+            switchstack_result_t()
+                : status(0),
+                  the_new_current_greenlet(nullptr)
+            {}
+
+            switchstack_result_t(int err)
+                : status(err),
+                  the_new_current_greenlet(nullptr)
+            {}
+
+            switchstack_result_t(int err, Greenlet* state, OwnedGreenlet& origin)
+                : status(err),
+                  the_new_current_greenlet(state),
+                  origin_greenlet(origin)
+            {
+            }
+
+            switchstack_result_t(int err, Greenlet* state, const BorrowedGreenlet& origin)
+                : status(err),
+                  the_new_current_greenlet(state),
+                  origin_greenlet(origin)
+            {
+            }
+
+            switchstack_result_t(const switchstack_result_t& other)
+                : status(other.status),
+                  the_new_current_greenlet(other.the_new_current_greenlet),
+                  origin_greenlet(other.origin_greenlet)
+            {}
+
+            switchstack_result_t& operator=(const switchstack_result_t& other)
+            {
+                this->status = other.status;
+                this->the_new_current_greenlet = other.the_new_current_greenlet;
+                this->origin_greenlet = other.origin_greenlet;
+                return *this;
+            }
+        };
+
+        OwnedObject on_switchstack_or_initialstub_failure(
+            Greenlet* target,
+            const switchstack_result_t& err,
+            const bool target_was_me=false,
+            const bool was_initial_stub=false);
+
+        // Returns the previous greenlet we just switched away from.
+        virtual OwnedGreenlet g_switchstack_success() noexcept;
+
+        class GreenletStartedWhileInPython : public std::runtime_error
+        {
+        public:
+            GreenletStartedWhileInPython() : std::runtime_error("")
+            {}
+        };
+
+    protected:
+
+
+        /**
+           Perform a stack switch into this greenlet.
+
+           This temporarily sets the global variable
+           ``switching_thread_state`` to this greenlet; as soon as the
+           call to ``slp_switch`` completes, this is reset to NULL.
+           Consequently, this depends on the GIL.
+
+           TODO: Adopt the stackman model and pass ``slp_switch`` a
+           callback function and context pointer; this eliminates the
+           need for global variables altogether.
+
+           Because the stack switch happens in this function, this
+           function can't use its own stack (local) variables, set
+           before the switch, and then accessed after the switch.
+
+           Further, you con't even access ``g_thread_state_global``
+           before and after the switch from the global variable.
+           Because it is thread local some compilers cache it in a
+           register/on the stack, notably new versions of MSVC; this
+           breaks with strange crashes sometime later, because writing
+           to anything in ``g_thread_state_global`` after the switch
+           is actually writing to random memory. For this reason, we
+           call a non-inlined function to finish the operation. (XXX:
+           The ``/GT`` MSVC compiler argument probably fixes that.)
+
+           It is very important that stack switch is 'atomic', i.e. no
+           calls into other Python code allowed (except very few that
+           are safe), because global variables are very fragile. (This
+           should no longer be the case with thread-local variables.)
+
+        */
+        // Made virtual to facilitate subclassing UserGreenlet for testing.
+        virtual switchstack_result_t g_switchstack(void);
+
+class TracingGuard
+{
+private:
+    PyThreadState* tstate;
+public:
+    TracingGuard()
+        : tstate(PyThreadState_GET())
+    {
+        PyThreadState_EnterTracing(this->tstate);
+    }
+
+    ~TracingGuard()
+    {
+        PyThreadState_LeaveTracing(this->tstate);
+        this->tstate = nullptr;
+    }
+
+    inline void CallTraceFunction(const OwnedObject& tracefunc,
+                                  const greenlet::refs::ImmortalEventName& event,
+                                  const BorrowedGreenlet& origin,
+                                  const BorrowedGreenlet& target)
+    {
+        // TODO: This calls tracefunc(event, (origin, target)). Add a shortcut
+        // function for that that's specialized to avoid the Py_BuildValue
+        // string parsing, or start with just using "ON" format with PyTuple_Pack(2,
+        // origin, target). That seems like what the N format is meant
+        // for.
+        // XXX: Why does event not automatically cast back to a PyObject?
+        // It tries to call the "deleted constructor ImmortalEventName
+        // const" instead.
+        assert(tracefunc);
+        assert(event);
+        assert(origin);
+        assert(target);
+        greenlet::refs::NewReference retval(
+            PyObject_CallFunction(
+                tracefunc.borrow(),
+                "O(OO)",
+                event.borrow(),
+                origin.borrow(),
+                target.borrow()
+            ));
+        if (!retval) {
+            throw PyErrOccurred::from_current();
+        }
+    }
+};
+
+      static void
+      g_calltrace(const OwnedObject& tracefunc,
+                  const greenlet::refs::ImmortalEventName& event,
+                  const greenlet::refs::BorrowedGreenlet& origin,
+                  const BorrowedGreenlet& target);
+    private:
+        OwnedObject g_switch_finish(const switchstack_result_t& err);
+
+    };
+
+    class UserGreenlet : public Greenlet
+    {
+    private:
+        static greenlet::PythonAllocator allocator;
+        OwnedMainGreenlet _main_greenlet;
+        OwnedObject _run_callable;
+        OwnedGreenlet _parent;
+    public:
+        static void* operator new(size_t UNUSED(count));
+        static void operator delete(void* ptr);
+
+        UserGreenlet(PyGreenlet* p, BorrowedGreenlet the_parent);
+        virtual ~UserGreenlet();
+
+        virtual refs::BorrowedMainGreenlet find_main_greenlet_in_lineage() const;
+        virtual bool was_running_in_dead_thread() const noexcept;
+        virtual ThreadState* thread_state() const noexcept;
+        virtual OwnedObject g_switch();
+        virtual const OwnedObject& run() const
+        {
+            if (this->started() || !this->_run_callable) {
+                throw AttributeError("run");
+            }
+            return this->_run_callable;
+        }
+        virtual void run(const refs::BorrowedObject nrun);
+
+        virtual const OwnedGreenlet parent() const;
+        virtual void parent(const refs::BorrowedObject new_parent);
+
+        virtual const refs::BorrowedMainGreenlet main_greenlet() const;
+
+        virtual void murder_in_place();
+        virtual bool belongs_to_thread(const ThreadState* state) const;
+        virtual int tp_traverse(visitproc visit, void* arg);
+        virtual int tp_clear();
+        class ParentIsCurrentGuard
+        {
+        private:
+            OwnedGreenlet oldparent;
+            UserGreenlet* greenlet;
+            G_NO_COPIES_OF_CLS(ParentIsCurrentGuard);
+        public:
+            ParentIsCurrentGuard(UserGreenlet* p, const ThreadState& thread_state);
+            ~ParentIsCurrentGuard();
+        };
+        virtual OwnedObject throw_GreenletExit_during_dealloc(const ThreadState& current_thread_state);
+    protected:
+        virtual switchstack_result_t g_initialstub(void* mark);
+    private:
+        // This function isn't meant to return.
+        // This accepts raw pointers and the ownership of them at the
+        // same time. The caller should use ``inner_bootstrap(origin.relinquish_ownership())``.
+        void inner_bootstrap(PyGreenlet* origin_greenlet, PyObject* run);
+    };
+
+    class BrokenGreenlet : public UserGreenlet
+    {
+    private:
+        static greenlet::PythonAllocator allocator;
+    public:
+        bool _force_switch_error = false;
+        bool _force_slp_switch_error = false;
+
+        static void* operator new(size_t UNUSED(count));
+        static void operator delete(void* ptr);
+        BrokenGreenlet(PyGreenlet* p, BorrowedGreenlet the_parent)
+            : UserGreenlet(p, the_parent)
+        {}
+        virtual ~BrokenGreenlet()
+        {}
+
+        virtual switchstack_result_t g_switchstack(void);
+        virtual bool force_slp_switch_error() const noexcept;
+
+    };
+
+    class MainGreenlet : public Greenlet
+    {
+    private:
+        static greenlet::PythonAllocator allocator;
+        refs::BorrowedMainGreenlet _self;
+        std::atomic _thread_state;
+        G_NO_COPIES_OF_CLS(MainGreenlet);
+    public:
+        static void* operator new(size_t UNUSED(count));
+        static void operator delete(void* ptr);
+
+        MainGreenlet(refs::BorrowedMainGreenlet::PyType*, ThreadState*);
+        virtual ~MainGreenlet();
+
+
+        virtual const OwnedObject& run() const;
+        virtual void run(const refs::BorrowedObject nrun);
+
+        virtual const OwnedGreenlet parent() const;
+        virtual void parent(const refs::BorrowedObject new_parent);
+
+        virtual const refs::BorrowedMainGreenlet main_greenlet() const;
+
+        virtual refs::BorrowedMainGreenlet find_main_greenlet_in_lineage() const;
+        virtual bool was_running_in_dead_thread() const noexcept;
+        virtual ThreadState* thread_state() const noexcept;
+        void thread_state(ThreadState*) noexcept;
+        virtual OwnedObject g_switch();
+        virtual int tp_traverse(visitproc visit, void* arg);
+    };
+
+    // Instantiate one on the stack to save the GC state,
+    // and then disable GC. When it goes out of scope, GC will be
+    // restored to its original state.
+    class GCDisabledGuard
+    {
+    private:
+        int was_enabled = 0;
+    public:
+        GCDisabledGuard()
+            : was_enabled(PyGC_IsEnabled())
+        {
+            PyGC_Disable();
+        }
+
+        ~GCDisabledGuard()
+        {
+            if (this->was_enabled) {
+                PyGC_Enable();
+            }
+        }
+    };
+
+    OwnedObject& operator<<=(OwnedObject& lhs, greenlet::SwitchingArgs& rhs) noexcept;
+
+    //TODO: Greenlet::g_switch() should call this automatically on its
+    //return value. As it is, the module code is calling it.
+    static inline OwnedObject
+    single_result(const OwnedObject& results)
+    {
+        if (results
+            && PyTuple_Check(results.borrow())
+            && PyTuple_GET_SIZE(results.borrow()) == 1) {
+            PyObject* result = PyTuple_GET_ITEM(results.borrow(), 0);
+            assert(result);
+            return OwnedObject::owning(result);
+        }
+        return results;
+    }
+
+
+    static OwnedObject
+    g_handle_exit(const OwnedObject& greenlet_result);
+
+
+    template
+    void operator<<(const PyThreadState *const lhs, T& rhs)
+    {
+        rhs.operator<<(lhs);
+    }
+
+} // namespace greenlet ;
+
+#endif
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TGreenletGlobals.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TGreenletGlobals.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..3bf7fd4b448f7212ba7ef22d4dd14aaddfbb14e6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TGreenletGlobals.cpp
@@ -0,0 +1,113 @@
+/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */
+/**
+ * Implementation of GreenletGlobals.
+ *
+ * Format with:
+ *  clang-format -i --style=file src/greenlet/greenlet.c
+ *
+ *
+ * Fix missing braces with:
+ *   clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements"
+*/
+#ifndef T_GREENLET_GLOBALS
+#define T_GREENLET_GLOBALS
+
+#include 
+
+#include "greenlet_refs.hpp"
+#include "greenlet_exceptions.hpp"
+#include "greenlet_thread_support.hpp"
+#include "greenlet_internal.hpp"
+
+namespace greenlet {
+
+// This encapsulates what were previously module global "constants"
+// established at init time.
+// This is a step towards Python3 style module state that allows
+// reloading.
+//
+// In an earlier iteration of this code, we used placement new to be
+// able to allocate this object statically still, so that references
+// to its members don't incur an extra pointer indirection.
+// But under some scenarios, that could result in crashes at
+// shutdown because apparently the destructor was getting run twice?
+class GreenletGlobals
+{
+
+public:
+    const greenlet::refs::ImmortalEventName event_switch;
+    const greenlet::refs::ImmortalEventName event_throw;
+    const greenlet::refs::ImmortalException PyExc_GreenletError;
+    const greenlet::refs::ImmortalException PyExc_GreenletExit;
+    const greenlet::refs::ImmortalObject empty_tuple;
+    const greenlet::refs::ImmortalObject empty_dict;
+    const greenlet::refs::ImmortalString str_run;
+    Mutex* const thread_states_to_destroy_lock;
+    greenlet::cleanup_queue_t thread_states_to_destroy;
+
+    GreenletGlobals() :
+        event_switch("switch"),
+        event_throw("throw"),
+        PyExc_GreenletError("greenlet.error"),
+        PyExc_GreenletExit("greenlet.GreenletExit", PyExc_BaseException),
+        empty_tuple(Require(PyTuple_New(0))),
+        empty_dict(Require(PyDict_New())),
+        str_run("run"),
+        thread_states_to_destroy_lock(new Mutex())
+    {}
+
+    ~GreenletGlobals()
+    {
+        // This object is (currently) effectively immortal, and not
+        // just because of those placement new tricks; if we try to
+        // deallocate the static object we allocated, and overwrote,
+        // we would be doing so at C++ teardown time, which is after
+        // the final Python GIL is released, and we can't use the API
+        // then.
+        // (The members will still be destructed, but they also don't
+        // do any deallocation.)
+    }
+
+    /**
+     * Must be holding the ``thread_states_to_destroy`` lock.
+     */
+    void queue_to_destroy(ThreadState* ts) const
+    {
+        // we're currently accessed through a static const object,
+        // implicitly marking our members as const, so code can't just
+        // call push_back (or pop_back) without casting away the
+        // const.
+        //
+        // Do that for callers.
+        greenlet::cleanup_queue_t& q = const_cast(
+            this->thread_states_to_destroy);
+        // make sure we don't ever try to clean up a state more than
+        // once. Because they're thread-local, and we ultimately call this
+        // method from the destructor of the thread local variable,
+        // we should never find the item already present. This check
+        // is nominally O(n) in the size of the vector.
+        assert(std::find(q.begin(), q.end(), ts) == q.end());
+        q.push_back(ts);
+    }
+
+    /**
+     * Must be holding the ``thread_states_to_destroy`` lock.
+     */
+    ThreadState* take_next_to_destroy() const
+    {
+        greenlet::cleanup_queue_t& q = const_cast(
+            this->thread_states_to_destroy);
+        if (q.empty()) {
+            return nullptr;
+        }
+        ThreadState* result = q.back();
+        q.pop_back();
+        return result;
+    }
+};
+
+}; // namespace greenlet
+
+static const greenlet::GreenletGlobals* mod_globs;
+
+#endif // T_GREENLET_GLOBALS
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TMainGreenlet.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TMainGreenlet.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..a96bd3c4c20e1da1e2e3c189dfd515d7ccf058ed
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TMainGreenlet.cpp
@@ -0,0 +1,163 @@
+/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */
+/**
+ * Implementation of greenlet::MainGreenlet.
+ *
+ * Format with:
+ *  clang-format -i --style=file src/greenlet/greenlet.c
+ *
+ *
+ * Fix missing braces with:
+ *   clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements"
+*/
+#ifndef T_MAIN_GREENLET_CPP
+#define T_MAIN_GREENLET_CPP
+
+#include "TGreenlet.hpp"
+
+#ifdef Py_GIL_DISABLED
+#include 
+#endif
+
+// Incremented when we create a main greenlet, in a new thread, decremented
+// when it is destroyed.
+#ifdef Py_GIL_DISABLED
+static std::atomic G_TOTAL_MAIN_GREENLETS(0);
+#else
+// Protected by the GIL.
+static Py_ssize_t G_TOTAL_MAIN_GREENLETS;
+#endif
+
+namespace greenlet {
+greenlet::PythonAllocator MainGreenlet::allocator;
+
+void* MainGreenlet::operator new(size_t UNUSED(count))
+{
+    return allocator.allocate(1);
+}
+
+
+void MainGreenlet::operator delete(void* ptr)
+{
+    return allocator.deallocate(static_cast(ptr),
+                                1);
+}
+
+
+MainGreenlet::MainGreenlet(PyGreenlet* p, ThreadState* state)
+    : Greenlet(p, StackState::make_main()),
+      _self(p),
+      _thread_state(state)
+{
+    G_TOTAL_MAIN_GREENLETS++;
+}
+
+MainGreenlet::~MainGreenlet()
+{
+    G_TOTAL_MAIN_GREENLETS--;
+    this->tp_clear();
+}
+
+ThreadState*
+MainGreenlet::thread_state() const noexcept
+{
+    return this->_thread_state;
+}
+
+void
+MainGreenlet::thread_state(ThreadState* t) noexcept
+{
+    // this method is only used during thread tear down, when it is
+    // called with nullptr, signalling the thread is dead.
+    assert(!t);
+    this->_thread_state = t;
+}
+
+
+const BorrowedMainGreenlet
+MainGreenlet::main_greenlet() const
+{
+    return this->_self;
+}
+
+BorrowedMainGreenlet
+MainGreenlet::find_main_greenlet_in_lineage() const
+{
+    return BorrowedMainGreenlet(this->_self);
+}
+
+bool
+MainGreenlet::was_running_in_dead_thread() const noexcept
+{
+    return !this->_thread_state;
+}
+
+OwnedObject
+MainGreenlet::g_switch()
+{
+    try {
+        this->check_switch_allowed();
+    }
+    catch (const PyErrOccurred&) {
+        this->release_args();
+        throw;
+    }
+
+    switchstack_result_t err = this->g_switchstack();
+    if (err.status < 0) {
+        // XXX: This code path is untested, but it is shared
+        // with the UserGreenlet path that is tested.
+        return this->on_switchstack_or_initialstub_failure(
+            this,
+            err,
+            true, // target was me
+            false // was initial stub
+        );
+    }
+
+    return err.the_new_current_greenlet->g_switch_finish(err);
+}
+
+int
+MainGreenlet::tp_traverse(visitproc visit, void* arg)
+{
+    ThreadState* thread_state = this->_thread_state.load();
+    if (thread_state) {
+        // we've already traversed main, (self), don't do it again.
+        int result = thread_state->tp_traverse(visit, arg, false);
+        if (result) {
+            return result;
+        }
+    }
+    return Greenlet::tp_traverse(visit, arg);
+}
+
+const OwnedObject&
+MainGreenlet::run() const
+{
+    throw AttributeError("Main greenlets do not have a run attribute.");
+}
+
+void
+MainGreenlet::run(const BorrowedObject UNUSED(nrun))
+{
+   throw AttributeError("Main greenlets do not have a run attribute.");
+}
+
+void
+MainGreenlet::parent(const BorrowedObject raw_new_parent)
+{
+    if (!raw_new_parent) {
+        throw AttributeError("can't delete attribute");
+    }
+    throw AttributeError("cannot set the parent of a main greenlet");
+}
+
+const OwnedGreenlet
+MainGreenlet::parent() const
+{
+    return OwnedGreenlet(); // null becomes None
+}
+
+}; // namespace greenlet
+
+#endif
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TPythonState.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TPythonState.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..8f6ab4e885bed93fb12c959c8ac16e1975c94479
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TPythonState.cpp
@@ -0,0 +1,490 @@
+#ifndef GREENLET_PYTHON_STATE_CPP
+#define GREENLET_PYTHON_STATE_CPP
+
+#include 
+#include "TGreenlet.hpp"
+
+namespace greenlet {
+
+PythonState::PythonState()
+    : _top_frame()
+#if GREENLET_USE_CFRAME
+    ,cframe(nullptr)
+    ,use_tracing(0)
+#endif
+#if GREENLET_PY314
+    ,py_recursion_depth(0)
+    ,current_executor(nullptr)
+    ,stackpointer(nullptr)
+    #ifdef Py_GIL_DISABLED
+    ,c_stack_refs(nullptr)
+    #endif
+#elif GREENLET_PY312
+    ,py_recursion_depth(0)
+    ,c_recursion_depth(0)
+#else
+    ,recursion_depth(0)
+#endif
+#if GREENLET_PY313
+    ,delete_later(nullptr)
+#else
+    ,trash_delete_nesting(0)
+#endif
+#if GREENLET_PY311
+    ,current_frame(nullptr)
+    ,datastack_chunk(nullptr)
+    ,datastack_top(nullptr)
+    ,datastack_limit(nullptr)
+#endif
+{
+#if GREENLET_USE_CFRAME
+    /*
+      The PyThreadState->cframe pointer usually points to memory on
+      the stack, alloceted in a call into PyEval_EvalFrameDefault.
+
+      Initially, before any evaluation begins, it points to the
+      initial PyThreadState object's ``root_cframe`` object, which is
+      statically allocated for the lifetime of the thread.
+
+      A greenlet can last for longer than a call to
+      PyEval_EvalFrameDefault, so we can't set its ``cframe`` pointer
+      to be the current ``PyThreadState->cframe``; nor could we use
+      one from the greenlet parent for the same reason. Yet a further
+      no: we can't allocate one scoped to the greenlet and then
+      destroy it when the greenlet is deallocated, because inside the
+      interpreter the _PyCFrame objects form a linked list, and that too
+      can result in accessing memory beyond its dynamic lifetime (if
+      the greenlet doesn't actually finish before it dies, its entry
+      could still be in the list).
+
+      Using the ``root_cframe`` is problematic, though, because its
+      members are never modified by the interpreter and are set to 0,
+      meaning that its ``use_tracing`` flag is never updated. We don't
+      want to modify that value in the ``root_cframe`` ourself: it
+      *shouldn't* matter much because we should probably never get
+      back to the point where that's the only cframe on the stack;
+      even if it did matter, the major consequence of an incorrect
+      value for ``use_tracing`` is that if its true the interpreter
+      does some extra work --- however, it's just good code hygiene.
+
+      Our solution: before a greenlet runs, after its initial
+      creation, it uses the ``root_cframe`` just to have something to
+      put there. However, once the greenlet is actually switched to
+      for the first time, ``g_initialstub`` (which doesn't actually
+      "return" while the greenlet is running) stores a new _PyCFrame on
+      its local stack, and copies the appropriate values from the
+      currently running _PyCFrame; this is then made the _PyCFrame for the
+      newly-minted greenlet. ``g_initialstub`` then proceeds to call
+      ``glet.run()``, which results in ``PyEval_...`` adding the
+      _PyCFrame to the list. Switches continue as normal. Finally, when
+      the greenlet finishes, the call to ``glet.run()`` returns and
+      the _PyCFrame is taken out of the linked list and the stack value
+      is now unused and free to expire.
+
+      XXX: I think we can do better. If we're deallocing in the same
+      thread, can't we traverse the list and unlink our frame?
+      Can we just keep a reference to the thread state in case we
+      dealloc in another thread? (Is that even possible if we're still
+      running and haven't returned from g_initialstub?)
+    */
+    this->cframe = &PyThreadState_GET()->root_cframe;
+#endif
+}
+
+
+inline void PythonState::may_switch_away() noexcept
+{
+#if GREENLET_PY311
+    // PyThreadState_GetFrame is probably going to have to allocate a
+    // new frame object. That may trigger garbage collection. Because
+    // we call this during the early phases of a switch (it doesn't
+    // matter to which greenlet, as this has a global effect), if a GC
+    // triggers a switch away, two things can happen, both bad:
+    // - We might not get switched back to, halting forward progress.
+    //   this is pathological, but possible.
+    // - We might get switched back to with a different set of
+    //   arguments or a throw instead of a switch. That would corrupt
+    //   our state (specifically, PyErr_Occurred() and this->args()
+    //   would no longer agree).
+    //
+    // Thus, when we call this API, we need to have GC disabled.
+    // This method serves as a bottleneck we call when maybe beginning
+    // a switch. In this way, it is always safe -- no risk of GC -- to
+    // use ``_GetFrame()`` whenever we need to, just as it was in
+    // <=3.10 (because subsequent calls will be cached and not
+    // allocate memory).
+
+    GCDisabledGuard no_gc;
+    Py_XDECREF(PyThreadState_GetFrame(PyThreadState_GET()));
+#endif
+}
+
+void PythonState::operator<<(const PyThreadState *const tstate) noexcept
+{
+    this->_context.steal(tstate->context);
+#if GREENLET_USE_CFRAME
+    /*
+      IMPORTANT: ``cframe`` is a pointer into the STACK. Thus, because
+      the call to ``slp_switch()`` changes the contents of the stack,
+      you cannot read from ``ts_current->cframe`` after that call and
+      necessarily get the same values you get from reading it here.
+      Anything you need to restore from now to then must be saved in a
+      global/threadlocal variable (because we can't use stack
+      variables here either). For things that need to persist across
+      the switch, use `will_switch_from`.
+    */
+    this->cframe = tstate->cframe;
+  #if !GREENLET_PY312
+    this->use_tracing = tstate->cframe->use_tracing;
+  #endif
+#endif // GREENLET_USE_CFRAME
+#if GREENLET_PY311
+  #if GREENLET_PY314
+    this->py_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining;
+    this->current_executor = tstate->current_executor;
+    #ifdef Py_GIL_DISABLED
+    this->c_stack_refs = ((_PyThreadStateImpl*)tstate)->c_stack_refs;
+    #endif
+  #elif GREENLET_PY312
+    this->py_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining;
+    this->c_recursion_depth = Py_C_RECURSION_LIMIT - tstate->c_recursion_remaining;
+  #else // not 312
+    this->recursion_depth = tstate->recursion_limit - tstate->recursion_remaining;
+  #endif // GREENLET_PY312
+  #if GREENLET_PY313
+    this->current_frame = tstate->current_frame;
+  #elif GREENLET_USE_CFRAME
+    this->current_frame = tstate->cframe->current_frame;
+  #endif
+    this->datastack_chunk = tstate->datastack_chunk;
+    this->datastack_top = tstate->datastack_top;
+    this->datastack_limit = tstate->datastack_limit;
+
+    PyFrameObject *frame = PyThreadState_GetFrame((PyThreadState *)tstate);
+    Py_XDECREF(frame);  // PyThreadState_GetFrame gives us a new
+                        // reference.
+    this->_top_frame.steal(frame);
+  #if GREENLET_PY314
+    if (this->top_frame()) {
+        this->stackpointer = this->_top_frame->f_frame->stackpointer;
+    }
+    else {
+        this->stackpointer = nullptr;
+    }
+  #endif
+  #if GREENLET_PY313
+    // By contract of _PyTrash_thread_deposit_object,
+    // the ``delete_later`` object has a refcount of 0.
+    // We take a strong reference to it.
+    //
+    // Now, ``delete_later`` is managed as a
+    // linked list whose objects are unconditionally deallocated
+    // WITHOUT calling DECREF on them, so it's not clear what that is
+    // actually accomplishing. That is, if another object is pushed on
+    // the list and then the list is deallocated, this object will
+    // still be deallocated. This strong reference serves as a form of
+    // resurrection, meaning that when operator>> DECREFs it, we might
+    // enter its ``tp_dealloc`` function again.
+    //
+    // In practice, it's quite difficult to arrange for this to be
+    // a non-null value during a greenlet switch.
+    // ``greenlet.tests.test_greenlet_trash`` tries, but under 3.14,
+    // at least, fails to do so.
+    this->delete_later = Py_XNewRef(tstate->delete_later);
+  #elif GREENLET_PY312
+    this->trash_delete_nesting = tstate->trash.delete_nesting;
+  #else // not 312 or 3.13+
+    this->trash_delete_nesting = tstate->trash_delete_nesting;
+  #endif // GREENLET_PY312
+#else // Not 311
+    this->recursion_depth = tstate->recursion_depth;
+    this->_top_frame.steal(tstate->frame);
+    this->trash_delete_nesting = tstate->trash_delete_nesting;
+#endif // GREENLET_PY311
+}
+
+#if GREENLET_PY312
+void GREENLET_NOINLINE(PythonState::unexpose_frames)()
+{
+    if (!this->top_frame()) {
+        return;
+    }
+
+    // See GreenletState::expose_frames() and the comment on frames_were_exposed
+    // for more information about this logic.
+    _PyInterpreterFrame *iframe = this->_top_frame->f_frame;
+    while (iframe != nullptr) {
+        _PyInterpreterFrame *prev_exposed = iframe->previous;
+        assert(iframe->frame_obj);
+        memcpy(&iframe->previous, &iframe->frame_obj->_f_frame_data[0],
+               sizeof(void *));
+        iframe = prev_exposed;
+    }
+}
+#else
+void PythonState::unexpose_frames()
+{}
+#endif
+
+void PythonState::operator>>(PyThreadState *const tstate) noexcept
+{
+    tstate->context = this->_context.relinquish_ownership();
+    /* Incrementing this value invalidates the contextvars cache,
+       which would otherwise remain valid across switches */
+    tstate->context_ver++;
+#if GREENLET_USE_CFRAME
+    tstate->cframe = this->cframe;
+    /*
+      If we were tracing, we need to keep tracing.
+      There should never be the possibility of hitting the
+      root_cframe here. See note above about why we can't
+      just copy this from ``origin->cframe->use_tracing``.
+    */
+  #if !GREENLET_PY312
+    tstate->cframe->use_tracing = this->use_tracing;
+  #endif
+#endif // GREENLET_USE_CFRAME
+#if GREENLET_PY311
+  #if GREENLET_PY314
+    tstate->py_recursion_remaining = tstate->py_recursion_limit - this->py_recursion_depth;
+    tstate->current_executor = this->current_executor;
+    #ifdef Py_GIL_DISABLED
+    ((_PyThreadStateImpl*)tstate)->c_stack_refs = this->c_stack_refs;
+    #endif
+    this->unexpose_frames();
+  #elif GREENLET_PY312
+    tstate->py_recursion_remaining = tstate->py_recursion_limit - this->py_recursion_depth;
+    tstate->c_recursion_remaining = Py_C_RECURSION_LIMIT - this->c_recursion_depth;
+    this->unexpose_frames();
+  #else // \/ 3.11
+    tstate->recursion_remaining = tstate->recursion_limit - this->recursion_depth;
+  #endif // GREENLET_PY312
+  #if GREENLET_PY313
+    tstate->current_frame = this->current_frame;
+  #elif GREENLET_USE_CFRAME
+    tstate->cframe->current_frame = this->current_frame;
+  #endif
+    tstate->datastack_chunk = this->datastack_chunk;
+    tstate->datastack_top = this->datastack_top;
+    tstate->datastack_limit = this->datastack_limit;
+#if GREENLET_PY314 && defined(Py_GIL_DISABLED)
+    if (this->top_frame()) {
+        this->_top_frame->f_frame->stackpointer = this->stackpointer;
+    }
+#endif
+    this->_top_frame.relinquish_ownership();
+  #if GREENLET_PY313
+    // See comments in operator<<. We own a strong reference to
+    // this->delete_later, which may or may not be the same object as
+    // tstate->delete_later (depending if something pushed an object
+    // onto the trashcan). Again, because ``delete_later`` is managed
+    // as a linked list, it's not clear that saving and restoring the
+    // value, especially without ever setting it to NULL, accomplishes
+    // much...but the code was added by a core dev, so assume correct.
+    //
+    // Recall that tstate->delete_later is supposed to have a refcount
+    // of 0, because objects are added there from their ``tp_dealloc``
+    // method. So we should only need to DECREF it if we're the ones
+    // that INCREF'd it in operator<<. (This is different than the
+    // core dev's original code which always did this.)
+    if (this->delete_later == tstate->delete_later) {
+        Py_XDECREF(tstate->delete_later);
+        tstate->delete_later = this->delete_later;
+        this->delete_later = nullptr;
+    }
+    else {
+        // it got switched behind our back. So the reference we own
+        // needs to be explicitly cleared.
+        tstate->delete_later = this->delete_later;
+        Py_CLEAR(this->delete_later);
+    }
+
+
+  #elif GREENLET_PY312
+    tstate->trash.delete_nesting = this->trash_delete_nesting;
+  #else // not 3.12
+    tstate->trash_delete_nesting = this->trash_delete_nesting;
+  #endif // GREENLET_PY312
+#else // not 3.11
+    tstate->frame = this->_top_frame.relinquish_ownership();
+    tstate->recursion_depth = this->recursion_depth;
+    tstate->trash_delete_nesting = this->trash_delete_nesting;
+#endif // GREENLET_PY311
+}
+
+inline void PythonState::will_switch_from(PyThreadState *const origin_tstate) noexcept
+{
+#if GREENLET_USE_CFRAME && !GREENLET_PY312
+    // The weird thing is, we don't actually save this for an
+    // effect on the current greenlet, it's saved for an
+    // effect on the target greenlet. That is, we want
+    // continuity of this setting across the greenlet switch.
+    this->use_tracing = origin_tstate->cframe->use_tracing;
+#endif
+}
+
+void PythonState::set_initial_state(const PyThreadState* const tstate) noexcept
+{
+    this->_top_frame = nullptr;
+#if GREENLET_PY314
+    this->py_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining;
+    this->current_executor = tstate->current_executor;
+    #ifdef Py_GIL_DISABLED
+    this->c_stack_refs = ((_PyThreadStateImpl*)tstate)->c_stack_refs;
+    #endif
+    // this->stackpointer is left null because this->_top_frame is
+    // null so there is no value to copy.
+#elif GREENLET_PY312
+    this->py_recursion_depth = tstate->py_recursion_limit - tstate->py_recursion_remaining;
+#if GREENLET_314
+    this->c_recursion_depth = 0; // unused on 3.14
+#else
+    this->c_recursion_depth = Py_C_RECURSION_LIMIT - tstate->c_recursion_remaining;
+#endif
+#elif GREENLET_PY311
+    this->recursion_depth = tstate->recursion_limit - tstate->recursion_remaining;
+#else
+    this->recursion_depth = tstate->recursion_depth;
+#endif
+}
+// TODO: Better state management about when we own the top frame.
+int PythonState::tp_traverse(visitproc visit, void* arg, bool own_top_frame) noexcept
+{
+    Py_VISIT(this->_context.borrow());
+    if (own_top_frame) {
+        Py_VISIT(this->_top_frame.borrow());
+    }
+#if GREENLET_PY314
+    // TODO: Should we be visiting the c_stack_refs objects?
+    // CPython uses a specific macro to do that which takes into
+    // account boxing and null values and then calls
+    // ``_PyGC_VisitStackRef``, but we don't have access to that, and
+    // we can't duplicate it ourself (because it compares
+    // ``visitproc`` to another function we can't access).
+    // The naive way of looping over c_stack_refs->ref and visiting
+    // those crashes the process (at least with GIL disabled).
+#endif
+    // Note that we DO NOT visit ``delete_later``. Even if it's
+    // non-null and we technically own a reference to it, its
+    // reference count already went to 0 once and it was in the
+    // process of being deallocated. The trash can mechanism linked it
+    // into a list that will be cleaned at some later time, and it has
+    // become untracked by the GC.
+    return 0;
+}
+
+void PythonState::tp_clear(bool own_top_frame) noexcept
+{
+    PythonStateContext::tp_clear();
+    // If we get here owning a frame,
+    // we got dealloc'd without being finished. We may or may not be
+    // in the same thread.
+    if (own_top_frame) {
+        this->_top_frame.CLEAR();
+    }
+}
+
+#if GREENLET_USE_CFRAME
+void PythonState::set_new_cframe(_PyCFrame& frame) noexcept
+{
+    frame = *PyThreadState_GET()->cframe;
+    /* Make the target greenlet refer to the stack value. */
+    this->cframe = &frame;
+    /*
+      And restore the link to the previous frame so this one gets
+      unliked appropriately.
+    */
+    this->cframe->previous = &PyThreadState_GET()->root_cframe;
+}
+#endif
+
+const PythonState::OwnedFrame& PythonState::top_frame() const noexcept
+{
+    return this->_top_frame;
+}
+
+void PythonState::did_finish(PyThreadState* tstate) noexcept
+{
+#if GREENLET_PY311
+    // See https://github.com/gevent/gevent/issues/1924 and
+    // https://github.com/python-greenlet/greenlet/issues/328. In
+    // short, Python 3.11 allocates memory for frames as a sort of
+    // linked list that's kept as part of PyThreadState in the
+    // ``datastack_chunk`` member and friends. These are saved and
+    // restored as part of switching greenlets.
+    //
+    // When we initially switch to a greenlet, we set those to NULL.
+    // That causes the frame management code to treat this like a
+    // brand new thread and start a fresh list of chunks, beginning
+    // with a new "root" chunk. As we make calls in this greenlet,
+    // those chunks get added, and as calls return, they get popped.
+    // But the frame code (pystate.c) is careful to make sure that the
+    // root chunk never gets popped.
+    //
+    // Thus, when a greenlet exits for the last time, there will be at
+    // least a single root chunk that we must be responsible for
+    // deallocating.
+    //
+    // The complex part is that these chunks are allocated and freed
+    // using ``_PyObject_VirtualAlloc``/``Free``. Those aren't public
+    // functions, and they aren't exported for linking. It so happens
+    // that we know they are just thin wrappers around the Arena
+    // allocator, so we can use that directly to deallocate in a
+    // compatible way.
+    //
+    // CAUTION: Check this implementation detail on every major version.
+    //
+    // It might be nice to be able to do this in our destructor, but
+    // can we be sure that no one else is using that memory? Plus, as
+    // described below, our pointers may not even be valid anymore. As
+    // a special case, there is one time that we know we can do this,
+    // and that's from the destructor of the associated UserGreenlet
+    // (NOT main greenlet)
+    PyObjectArenaAllocator alloc;
+    _PyStackChunk* chunk = nullptr;
+    if (tstate) {
+        // We really did finish, we can never be switched to again.
+        chunk = tstate->datastack_chunk;
+        // Unfortunately, we can't do much sanity checking. Our
+        // this->datastack_chunk pointer is out of date (evaluation may
+        // have popped down through it already) so we can't verify that
+        // we deallocate it. I don't think we can even check datastack_top
+        // for the same reason.
+
+        PyObject_GetArenaAllocator(&alloc);
+        tstate->datastack_chunk = nullptr;
+        tstate->datastack_limit = nullptr;
+        tstate->datastack_top = nullptr;
+
+    }
+    else if (this->datastack_chunk) {
+        // The UserGreenlet (NOT the main greenlet!) is being deallocated. If we're
+        // still holding a stack chunk, it's garbage because we know
+        // we can never switch back to let cPython clean it up.
+        // Because the last time we got switched away from, and we
+        // haven't run since then, we know our chain is valid and can
+        // be dealloced.
+        chunk = this->datastack_chunk;
+        PyObject_GetArenaAllocator(&alloc);
+    }
+
+    if (alloc.free && chunk) {
+        // In case the arena mechanism has been torn down already.
+        while (chunk) {
+            _PyStackChunk *prev = chunk->previous;
+            chunk->previous = nullptr;
+            alloc.free(alloc.ctx, chunk, chunk->size);
+            chunk = prev;
+        }
+    }
+
+    this->datastack_chunk = nullptr;
+    this->datastack_limit = nullptr;
+    this->datastack_top = nullptr;
+#endif
+}
+
+
+}; // namespace greenlet
+
+#endif // GREENLET_PYTHON_STATE_CPP
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TStackState.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TStackState.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c2fb540ff44a5039a96d18c93ff80ab688f3d1c2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TStackState.cpp
@@ -0,0 +1,265 @@
+#ifndef GREENLET_STACK_STATE_CPP
+#define GREENLET_STACK_STATE_CPP
+
+#include "TGreenlet.hpp"
+
+namespace greenlet {
+
+#ifdef GREENLET_USE_STDIO
+#include 
+using std::cerr;
+using std::endl;
+
+std::ostream& operator<<(std::ostream& os, const StackState& s)
+{
+    os << "StackState(stack_start=" << (void*)s._stack_start
+       << ", stack_stop=" << (void*)s.stack_stop
+       << ", stack_copy=" << (void*)s.stack_copy
+       << ", stack_saved=" << s._stack_saved
+       << ", stack_prev=" << s.stack_prev
+       << ", addr=" << &s
+       << ")";
+    return os;
+}
+#endif
+
+StackState::StackState(void* mark, StackState& current)
+    : _stack_start(nullptr),
+      stack_stop((char*)mark),
+      stack_copy(nullptr),
+      _stack_saved(0),
+      /* Skip a dying greenlet */
+      stack_prev(current._stack_start
+                 ? ¤t
+                 : current.stack_prev)
+{
+}
+
+StackState::StackState()
+    : _stack_start(nullptr),
+      stack_stop(nullptr),
+      stack_copy(nullptr),
+      _stack_saved(0),
+      stack_prev(nullptr)
+{
+}
+
+StackState::StackState(const StackState& other)
+// can't use a delegating constructor because of
+// MSVC for Python 2.7
+    : _stack_start(nullptr),
+      stack_stop(nullptr),
+      stack_copy(nullptr),
+      _stack_saved(0),
+      stack_prev(nullptr)
+{
+    this->operator=(other);
+}
+
+StackState& StackState::operator=(const StackState& other)
+{
+    if (&other == this) {
+        return *this;
+    }
+    if (other._stack_saved) {
+        throw std::runtime_error("Refusing to steal memory.");
+    }
+
+    //If we have memory allocated, dispose of it
+    this->free_stack_copy();
+
+    this->_stack_start = other._stack_start;
+    this->stack_stop = other.stack_stop;
+    this->stack_copy = other.stack_copy;
+    this->_stack_saved = other._stack_saved;
+    this->stack_prev = other.stack_prev;
+    return *this;
+}
+
+inline void StackState::free_stack_copy() noexcept
+{
+    PyMem_Free(this->stack_copy);
+    this->stack_copy = nullptr;
+    this->_stack_saved = 0;
+}
+
+inline void StackState::copy_heap_to_stack(const StackState& current) noexcept
+{
+
+    /* Restore the heap copy back into the C stack */
+    if (this->_stack_saved != 0) {
+        memcpy(this->_stack_start, this->stack_copy, this->_stack_saved);
+        this->free_stack_copy();
+    }
+    StackState* owner = const_cast(¤t);
+    if (!owner->_stack_start) {
+        owner = owner->stack_prev; /* greenlet is dying, skip it */
+    }
+    while (owner && owner->stack_stop <= this->stack_stop) {
+        // cerr << "\tOwner: " << owner << endl;
+        owner = owner->stack_prev; /* find greenlet with more stack */
+    }
+    this->stack_prev = owner;
+    // cerr << "\tFinished with: " << *this << endl;
+}
+
+inline int StackState::copy_stack_to_heap_up_to(const char* const stop) noexcept
+{
+    /* Save more of g's stack into the heap -- at least up to 'stop'
+       g->stack_stop |________|
+                     |        |
+                     |    __ stop       . . . . .
+                     |        |    ==>  .       .
+                     |________|          _______
+                     |        |         |       |
+                     |        |         |       |
+      g->stack_start |        |         |_______| g->stack_copy
+     */
+    intptr_t sz1 = this->_stack_saved;
+    intptr_t sz2 = stop - this->_stack_start;
+    assert(this->_stack_start);
+    if (sz2 > sz1) {
+        char* c = (char*)PyMem_Realloc(this->stack_copy, sz2);
+        if (!c) {
+            PyErr_NoMemory();
+            return -1;
+        }
+        memcpy(c + sz1, this->_stack_start + sz1, sz2 - sz1);
+        this->stack_copy = c;
+        this->_stack_saved = sz2;
+    }
+    return 0;
+}
+
+inline int StackState::copy_stack_to_heap(char* const stackref,
+                                          const StackState& current) noexcept
+{
+    /* must free all the C stack up to target_stop */
+    const char* const target_stop = this->stack_stop;
+
+    StackState* owner = const_cast(¤t);
+    assert(owner->_stack_saved == 0); // everything is present on the stack
+    if (!owner->_stack_start) {
+        owner = owner->stack_prev; /* not saved if dying */
+    }
+    else {
+        owner->_stack_start = stackref;
+    }
+
+    while (owner->stack_stop < target_stop) {
+        /* ts_current is entierely within the area to free */
+        if (owner->copy_stack_to_heap_up_to(owner->stack_stop)) {
+            return -1; /* XXX */
+        }
+        owner = owner->stack_prev;
+    }
+    if (owner != this) {
+        if (owner->copy_stack_to_heap_up_to(target_stop)) {
+            return -1; /* XXX */
+        }
+    }
+    return 0;
+}
+
+inline bool StackState::started() const noexcept
+{
+    return this->stack_stop != nullptr;
+}
+
+inline bool StackState::main() const noexcept
+{
+    return this->stack_stop == (char*)-1;
+}
+
+inline bool StackState::active() const noexcept
+{
+    return this->_stack_start != nullptr;
+}
+
+inline void StackState::set_active() noexcept
+{
+    assert(this->_stack_start == nullptr);
+    this->_stack_start = (char*)1;
+}
+
+inline void StackState::set_inactive() noexcept
+{
+    this->_stack_start = nullptr;
+    // XXX: What if we still have memory out there?
+    // That case is actually triggered by
+    // test_issue251_issue252_explicit_reference_not_collectable (greenlet.tests.test_leaks.TestLeaks)
+    // and
+    // test_issue251_issue252_need_to_collect_in_background
+    // (greenlet.tests.test_leaks.TestLeaks)
+    //
+    // Those objects never get deallocated, so the destructor never
+    // runs.
+    // It *seems* safe to clean up the memory here?
+    if (this->_stack_saved) {
+        this->free_stack_copy();
+    }
+}
+
+inline intptr_t StackState::stack_saved() const noexcept
+{
+    return this->_stack_saved;
+}
+
+inline char* StackState::stack_start() const noexcept
+{
+    return this->_stack_start;
+}
+
+
+inline StackState StackState::make_main() noexcept
+{
+    StackState s;
+    s._stack_start = (char*)1;
+    s.stack_stop = (char*)-1;
+    return s;
+}
+
+StackState::~StackState()
+{
+    if (this->_stack_saved != 0) {
+        this->free_stack_copy();
+    }
+}
+
+void StackState::copy_from_stack(void* vdest, const void* vsrc, size_t n) const
+{
+    char* dest = static_cast(vdest);
+    const char* src = static_cast(vsrc);
+    if (src + n <= this->_stack_start
+        || src >= this->_stack_start + this->_stack_saved
+        || this->_stack_saved == 0) {
+        // Nothing we're copying was spilled from the stack
+        memcpy(dest, src, n);
+        return;
+    }
+
+    if (src < this->_stack_start) {
+        // Copy the part before the saved stack.
+        // We know src + n > _stack_start due to the test above.
+        const size_t nbefore = this->_stack_start - src;
+        memcpy(dest, src, nbefore);
+        dest += nbefore;
+        src += nbefore;
+        n -= nbefore;
+    }
+    // We know src >= _stack_start after the before-copy, and
+    // src < _stack_start + _stack_saved due to the first if condition
+    size_t nspilled = std::min(n, this->_stack_start + this->_stack_saved - src);
+    memcpy(dest, this->stack_copy + (src - this->_stack_start), nspilled);
+    dest += nspilled;
+    src += nspilled;
+    n -= nspilled;
+    if (n > 0) {
+        // Copy the part after the saved stack
+        memcpy(dest, src, n);
+    }
+}
+
+}; // namespace greenlet
+
+#endif // GREENLET_STACK_STATE_CPP
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TThreadState.hpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TThreadState.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..7646d3d8879ce76d83a4a3db01e6c4ba673ad578
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TThreadState.hpp
@@ -0,0 +1,627 @@
+#ifndef GREENLET_THREAD_STATE_HPP
+#define GREENLET_THREAD_STATE_HPP
+
+#include 
+#include 
+#include 
+#include 
+
+#include "greenlet_internal.hpp"
+#include "greenlet_refs.hpp"
+#include "greenlet_thread_support.hpp"
+
+using greenlet::LockGuard;
+using greenlet::refs::BorrowedObject;
+using greenlet::refs::BorrowedGreenlet;
+using greenlet::refs::BorrowedMainGreenlet;
+using greenlet::refs::OwnedMainGreenlet;
+using greenlet::refs::OwnedObject;
+using greenlet::refs::OwnedGreenlet;
+using greenlet::refs::OwnedList;
+using greenlet::refs::PyErrFetchParam;
+using greenlet::refs::PyArgParseParam;
+using greenlet::refs::ImmortalString;
+using greenlet::refs::CreatedModule;
+using greenlet::refs::PyErrPieces;
+using greenlet::refs::NewReference;
+
+
+namespace greenlet {
+/**
+ * Thread-local state of greenlets.
+ *
+ * Each native thread will get exactly one of these objects,
+ * automatically accessed through the best available thread-local
+ * mechanism the compiler supports (``thread_local`` for C++11
+ * compilers or ``__thread``/``declspec(thread)`` for older GCC/clang
+ * or MSVC, respectively.)
+ *
+ * Previously, we kept thread-local state mostly in a bunch of
+ * ``static volatile`` variables in the main greenlet file.. This had
+ * the problem of requiring extra checks, loops, and great care
+ * accessing these variables if we potentially invoked any Python code
+ * that could release the GIL, because the state could change out from
+ * under us. Making the variables thread-local solves this problem.
+ *
+ * When we detected that a greenlet API accessing the current greenlet
+ * was invoked from a different thread than the greenlet belonged to,
+ * we stored a reference to the greenlet in the Python thread
+ * dictionary for the thread the greenlet belonged to. This could lead
+ * to memory leaks if the thread then exited (because of a reference
+ * cycle, as greenlets referred to the thread dictionary, and deleting
+ * non-current greenlets leaked their frame plus perhaps arguments on
+ * the C stack). If a thread exited while still having running
+ * greenlet objects (perhaps that had just switched back to the main
+ * greenlet), and did not invoke one of the greenlet APIs *in that
+ * thread, immediately before it exited, without some other thread
+ * then being invoked*, such a leak was guaranteed.
+ *
+ * This can be partly solved by using compiler thread-local variables
+ * instead of the Python thread dictionary, thus avoiding a cycle.
+ *
+ * To fully solve this problem, we need a reliable way to know that a
+ * thread is done and we should clean up the main greenlet. On POSIX,
+ * we can use the destructor function of ``pthread_key_create``, but
+ * there's nothing similar on Windows; a C++11 thread local object
+ * reliably invokes its destructor when the thread it belongs to exits
+ * (non-C++11 compilers offer ``__thread`` or ``declspec(thread)`` to
+ * create thread-local variables, but they can't hold C++ objects that
+ * invoke destructors; the C++11 version is the most portable solution
+ * I found). When the thread exits, we can drop references and
+ * otherwise manipulate greenlets and frames that we know can no
+ * longer be switched to.
+ *
+ * There are two small wrinkles. The first is that when the thread
+ * exits, it is too late to actually invoke Python APIs: the Python
+ * thread state is gone, and the GIL is released. To solve *this*
+ * problem, our destructor uses ``Py_AddPendingCall`` to transfer the
+ * destruction work to the main thread.
+ *
+ * The second is that once the thread exits, the thread local object
+ * is invalid and we can't even access a pointer to it, so we can't
+ * pass it to ``Py_AddPendingCall``. This is handled by actually using
+ * a second object that's thread local (ThreadStateCreator) and having
+ * it dynamically allocate this object so it can live until the
+ * pending call runs.
+ */
+
+
+
+class ThreadState {
+private:
+    // As of commit 08ad1dd7012b101db953f492e0021fb08634afad
+    // this class needed 56 bytes in o Py_DEBUG build
+    // on 64-bit macOS 11.
+    // Adding the vector takes us up to 80 bytes ()
+
+    /* Strong reference to the main greenlet */
+    OwnedMainGreenlet main_greenlet;
+
+    /* Strong reference to the current greenlet. */
+    OwnedGreenlet current_greenlet;
+
+    /* Strong reference to the trace function, if any. */
+    OwnedObject tracefunc;
+
+    // Use std::allocator (malloc/free) instead of PythonAllocator
+    // (PyMem_Malloc) for the deleteme list. During Py_FinalizeEx on
+    // Python < 3.11, the PyObject_Malloc pool that holds ThreadState
+    // can be disrupted, corrupting any PythonAllocator-backed
+    // containers. Using std::allocator makes this vector independent
+    // of Python's allocator lifecycle.
+    typedef std::vector deleteme_t;
+    /* A vector of raw PyGreenlet pointers representing things that need
+       deleted when this thread is running. The vector owns the
+       references, but you need to manually INCREF/DECREF as you use
+       them. We don't use a vector because we
+       make copy of this vector, and that would become O(n) as all the
+       refcounts are incremented in the copy.
+    */
+    deleteme_t deleteme;
+#ifdef Py_GIL_DISABLED
+    // On free-threaded builds, we need to protect shared access to
+    // the deleteme list by a mutex. It can be written from one thread
+    // while being read in another
+    Mutex deleteme_lock;
+#endif
+
+#ifdef GREENLET_NEEDS_EXCEPTION_STATE_SAVED
+    void* exception_state;
+#endif
+
+#ifdef Py_GIL_DISABLED
+    static std::atomic _clocks_used_doing_gc;
+#else
+    static std::clock_t _clocks_used_doing_gc;
+#endif
+    static ImmortalString get_referrers_name;
+
+    G_NO_COPIES_OF_CLS(ThreadState);
+
+
+    // Allocates a main greenlet for the thread state. If this fails,
+    // exits the process. Called only during constructing a ThreadState.
+    MainGreenlet* alloc_main()
+    {
+        PyGreenlet* gmain;
+
+        /* create the main greenlet for this thread */
+        gmain = reinterpret_cast(PyType_GenericAlloc(&PyGreenlet_Type, 0));
+        if (gmain == NULL) {
+            throw PyFatalError("alloc_main failed to alloc"); //exits the process
+        }
+
+        MainGreenlet* const main = new MainGreenlet(gmain, this);
+
+        assert(Py_REFCNT(gmain) == 1);
+        assert(gmain->pimpl == main);
+        return main;
+    }
+
+
+public:
+    // Allocate ThreadState with malloc/free rather than Python's
+    // object allocator. ThreadState outlives many Python objects and
+    // must remain valid throughout Py_FinalizeEx. On Python < 3.11,
+    // PyObject_Malloc pools can be disrupted during early
+    // finalization, corrupting any C++ objects stored in them.
+    static void* operator new(size_t count)
+    {
+        void* p = std::malloc(count);
+        if (!p) {
+            throw std::bad_alloc();
+        }
+        return p;
+    }
+
+    static void operator delete(void* ptr)
+    {
+        std::free(ptr);
+    }
+
+    static void init()
+    {
+        ThreadState::get_referrers_name = "get_referrers";
+        ThreadState::set_clocks_used_doing_gc(0);
+    }
+
+    ThreadState()
+    {
+
+#ifdef GREENLET_NEEDS_EXCEPTION_STATE_SAVED
+        this->exception_state = slp_get_exception_state();
+#endif
+
+        // XXX: Potentially dangerous, exposing a not fully
+        // constructed object.
+        MainGreenlet* const main = this->alloc_main();
+        this->main_greenlet = OwnedMainGreenlet::consuming(
+            main->self()
+        );
+        assert(this->main_greenlet);
+        this->current_greenlet = main->self();
+        // The main greenlet starts with 1 refs: The returned one. We
+        // then copied it to the current greenlet.
+        assert(this->main_greenlet.REFCNT() == 2);
+    }
+
+    inline void restore_exception_state()
+    {
+#ifdef GREENLET_NEEDS_EXCEPTION_STATE_SAVED
+        // It's probably important this be inlined and only call C
+        // functions to avoid adding an SEH frame.
+        slp_set_exception_state(this->exception_state);
+#endif
+    }
+
+    inline bool has_main_greenlet() const noexcept
+    {
+        return bool(this->main_greenlet);
+    }
+
+    // Called from the ThreadStateCreator when we're in non-standard
+    // threading mode. In that case, there is an object in the Python
+    // thread state dictionary that points to us. The main greenlet
+    // also traverses into us, in which case it's crucial not to
+    // traverse back into the main greenlet.
+    int tp_traverse(visitproc visit, void* arg, bool traverse_main=true)
+    {
+        if (traverse_main) {
+            Py_VISIT(main_greenlet.borrow_o());
+        }
+        if (traverse_main || current_greenlet != main_greenlet) {
+            Py_VISIT(current_greenlet.borrow_o());
+        }
+        Py_VISIT(tracefunc.borrow());
+        return 0;
+    }
+
+    inline BorrowedMainGreenlet borrow_main_greenlet() const noexcept
+    {
+        assert(this->main_greenlet);
+        assert(this->main_greenlet.REFCNT() >= 2);
+        return this->main_greenlet;
+    };
+
+    inline OwnedMainGreenlet get_main_greenlet() const noexcept
+    {
+        return this->main_greenlet;
+    }
+
+    /**
+     * If we have a main greenlet, mark it as dead by setting its
+     * thread_state to null (this part is atomic with respect to other
+     * threads looking at the main greenlet's thread_state).
+     */
+    inline bool mark_main_greenlet_dead() noexcept
+    {
+        PyGreenlet* main_greenlet = this->main_greenlet.borrow();
+        if (!main_greenlet) {
+            return false;
+        }
+        assert(main_greenlet->pimpl->thread_state() == this
+               || main_greenlet->pimpl->thread_state() == nullptr);
+        dynamic_cast(main_greenlet->pimpl)->thread_state(nullptr);
+        return true;
+    }
+
+    /**
+     * In addition to returning a new reference to the currunt
+     * greenlet, this performs any maintenance needed.
+     */
+    inline OwnedGreenlet get_current()
+    {
+        /* green_dealloc() cannot delete greenlets from other threads, so
+           it stores them in the thread dict; delete them now. */
+        this->clear_deleteme_list();
+        //assert(this->current_greenlet->main_greenlet == this->main_greenlet);
+        //assert(this->main_greenlet->main_greenlet == this->main_greenlet);
+        return this->current_greenlet;
+    }
+
+    /**
+     * As for non-const get_current();
+     */
+    inline BorrowedGreenlet borrow_current()
+    {
+        this->clear_deleteme_list();
+        return this->current_greenlet;
+    }
+
+    /**
+     * Does no maintenance.
+     */
+    inline OwnedGreenlet get_current() const
+    {
+        return this->current_greenlet;
+    }
+
+    template
+    inline bool is_current(const refs::PyObjectPointer& obj) const
+    {
+        return this->current_greenlet.borrow_o() == obj.borrow_o();
+    }
+
+    inline void set_current(const OwnedGreenlet& target)
+    {
+        this->current_greenlet = target;
+    }
+
+private:
+    /**
+     * Deref and remove the greenlets from the deleteme list. Must be
+     * holding the GIL.
+     *
+     * If *murder* is true, then we must be called from a different
+     * thread than the one that these greenlets were running in.
+     * In that case, if the greenlet was actually running, we destroy
+     * the frame reference and otherwise make it appear dead before
+     * proceeding; otherwise, we would try (and fail) to raise an
+     * exception in it and wind up right back in this list.
+     */
+    inline void clear_deleteme_list(const bool murder=false)
+    {
+#ifdef Py_GIL_DISABLED
+        LockGuard deleteme_guard(this->deleteme_lock);
+#endif
+        if (this->deleteme.empty()) {
+            return;
+        }
+        // Move the list contents out with swap — a constant-time
+        // pointer exchange that never allocates. The previous
+        // code used a copy (deleteme_t copy = this->deleteme)
+        // which allocated through PythonAllocator / PyMem_Malloc;
+        // that could SIGSEGV during early Py_FinalizeEx on Python
+        // < 3.11 when the allocator is partially torn down.
+        deleteme_t copy;
+        std::swap(copy, this->deleteme);
+
+        // During Py_FinalizeEx cleanup, the GC or atexit handlers
+        // may have already collected objects in this list,
+        // leaving dangling pointers. Attempting Py_DECREF on
+        // freed memory causes a SIGSEGV. g_greenlet_shutting_down
+        // covers the early atexit phase; Py_IsFinalizing() covers
+        // later phases. Thus, we deliberately leak.
+        if (greenlet::IsShuttingDown()) {
+            return;
+        }
+
+        // Preserve any pending exception so that cleanup-triggered
+        // errors don't accidentally swallow an unrelated exception
+        // (e.g. one set by throw() before a switch).
+        PyErrPieces incoming_err;
+
+        for(deleteme_t::iterator it = copy.begin(), end = copy.end();
+             it != end;
+             ++it ) {
+            PyGreenlet* to_del = *it;
+            if (murder) {
+                // Force each greenlet to appear dead; we can't raise an
+                // exception into it anymore anyway.
+                to_del->pimpl->murder_in_place();
+            }
+
+            // The only reference to these greenlets should be in
+            // this list, decreffing them should let them be
+            // deleted again, triggering calls to green_dealloc()
+            // in the correct thread (if we're not murdering).
+            // This may run arbitrary Python code and switch
+            // threads or greenlets!
+            Py_DECREF(to_del);
+            if (PyErr_Occurred()) {
+                PyErr_WriteUnraisable(nullptr);
+                PyErr_Clear();
+            }
+        }
+        // Not worried about C++ exception safety here in terms of
+        // making sure we restore the error. Either we'll catch it
+        // above and establish the error from that exception
+        // (which, yes, might overwrite something from before we
+        // entered, but we're in an undefined situation at that
+        // point) or we won't catch it at all and will crash the
+        // process.
+        //
+        // As for Python exception safety, there's no chance we're
+        // overwriting an exception (from the loop) with no
+        // exception (captured NULLs before we entered the loop),
+        // because there CAN'T BE any exception from the loop ---
+        // we clear them. So we're either restoring a pre-existing
+        // exception, or leaving the exception unset (by restoring
+        // NULL).
+        incoming_err.PyErrRestore();
+    }
+
+public:
+
+    /**
+     * Returns a new reference, or a false object.
+     */
+    inline OwnedObject get_tracefunc() const
+    {
+        return tracefunc;
+    };
+
+
+    inline void set_tracefunc(BorrowedObject tracefunc)
+    {
+        assert(tracefunc);
+        if (tracefunc == BorrowedObject(Py_None)) {
+            this->tracefunc.CLEAR();
+        }
+        else {
+            this->tracefunc = tracefunc;
+        }
+    }
+
+    /**
+     * Given a reference to a greenlet that some other thread
+     * attempted to delete (has a refcount of 0) store it for later
+     * deletion when the thread this state belongs to is current.
+     */
+    inline void delete_when_thread_running(PyGreenlet* to_del)
+    {
+        Py_INCREF(to_del);
+#ifdef Py_GIL_DISABLED
+        LockGuard deleteme_guard(this->deleteme_lock);
+#endif
+        this->deleteme.push_back(to_del);
+    }
+
+    /**
+     * Set to std::clock_t(-1) to disable.
+     */
+    inline static std::clock_t clocks_used_doing_gc()
+    {
+#ifdef Py_GIL_DISABLED
+        return ThreadState::_clocks_used_doing_gc.load(std::memory_order_relaxed);
+#else
+        return ThreadState::_clocks_used_doing_gc;
+#endif
+    }
+
+    inline static void set_clocks_used_doing_gc(std::clock_t value)
+    {
+#ifdef Py_GIL_DISABLED
+        ThreadState::_clocks_used_doing_gc.store(value, std::memory_order_relaxed);
+#else
+        ThreadState::_clocks_used_doing_gc = value;
+#endif
+    }
+
+    inline static void add_clocks_used_doing_gc(std::clock_t value)
+    {
+#ifdef Py_GIL_DISABLED
+        ThreadState::_clocks_used_doing_gc.fetch_add(value, std::memory_order_relaxed);
+#else
+        ThreadState::_clocks_used_doing_gc += value;
+#endif
+    }
+
+    // Runs in some arbitrary thread that Python is using to invoke
+    // pending callbacks. This may not be the thread that was
+    // running the greenlets.
+    ~ThreadState()
+    {
+        if (!PyInterpreterState_Head()) {
+            // We shouldn't get here (our callers protect us)
+            // but if we do, all we can do is bail early.
+            return;
+        }
+
+        // During interpreter finalization, Python APIs like
+        // PyImport_ImportModule are unsafe (the import machinery may
+        // be partially torn down). On Python < 3.11, perform only the
+        // minimal cleanup that is safe: clear our strong references
+        // so we don't leak, but skip the GC-based leak detection.
+        //
+        // Python 3.11+ restructured interpreter finalization so that
+        // these APIs remain safe during shutdown.
+        if (greenlet::IsShuttingDown()) {
+            this->tracefunc.CLEAR();
+            if (this->current_greenlet) {
+                this->current_greenlet->murder_in_place();
+                this->current_greenlet.CLEAR();
+            }
+            this->main_greenlet.CLEAR();
+            return;
+        }
+
+        // We should not have an "origin" greenlet; that only exists
+        // for the temporary time during a switch, which should not
+        // be in progress as the thread dies.
+        //assert(!this->switching_state.origin);
+
+        this->tracefunc.CLEAR();
+
+        // Forcibly GC as much as we can.
+        this->clear_deleteme_list(true);
+
+        // The pending call did this.
+        assert(this->main_greenlet->thread_state() == nullptr);
+
+        // If the main greenlet is the current greenlet,
+        // then we "fell off the end" and the thread died.
+        // It's possible that there is some other greenlet that
+        // switched to us, leaving a reference to the main greenlet
+        // on the stack, somewhere uncollectible. Try to detect that.
+        if (this->current_greenlet == this->main_greenlet && this->current_greenlet) {
+            assert(
+                this->current_greenlet->is_currently_running_in_some_thread()
+                || this->current_greenlet->was_running_in_dead_thread()
+            );
+            // Drop one reference we hold.
+            this->current_greenlet.CLEAR();
+            assert(!this->current_greenlet);
+            // Only our reference to the main greenlet should be left,
+            // But hold onto the pointer in case we need to do extra cleanup.
+            PyGreenlet* old_main_greenlet = this->main_greenlet.borrow();
+            Py_ssize_t cnt = this->main_greenlet.REFCNT();
+            this->main_greenlet.CLEAR();
+            if (ThreadState::clocks_used_doing_gc() != std::clock_t(-1)
+                && cnt == 2 && Py_REFCNT(old_main_greenlet) == 1) {
+                // Highly likely that the reference is somewhere on
+                // the stack, not reachable by GC. Verify.
+                // XXX: This is O(n) in the total number of objects.
+                // TODO: Add a way to disable this at runtime, and
+                // another way to report on it.
+                std::clock_t begin = std::clock();
+                NewReference gc(PyImport_ImportModule("gc"));
+                if (gc) {
+                    OwnedObject get_referrers = gc.PyRequireAttr(ThreadState::get_referrers_name);
+                    OwnedList refs(get_referrers.PyCall(old_main_greenlet));
+                    if (refs && refs.empty()) {
+                        assert(refs.REFCNT() == 1);
+                        // We found nothing! So we left a dangling
+                        // reference: Probably the last thing some
+                        // other greenlet did was call
+                        // 'getcurrent().parent.switch()' to switch
+                        // back to us. Clean it up. This will be the
+                        // case on CPython 3.7 and newer, as they use
+                        // an internal calling conversion that avoids
+                        // creating method objects and storing them on
+                        // the stack.
+                        Py_DECREF(old_main_greenlet);
+                    }
+                    else if (refs
+                             && refs.size() == 1
+                             && PyCFunction_Check(refs.at(0))
+                             && Py_REFCNT(refs.at(0)) == 2) {
+                        assert(refs.REFCNT() == 1);
+                        // Ok, we found a C method that refers to the
+                        // main greenlet, and its only referenced
+                        // twice, once in the list we just created,
+                        // once from...somewhere else. If we can't
+                        // find where else, then this is a leak.
+                        // This happens in older versions of CPython
+                        // that create a bound method object somewhere
+                        // on the stack that we'll never get back to.
+                        if (PyCFunction_GetFunction(refs.at(0).borrow()) == (PyCFunction)green_switch) {
+                            BorrowedObject function_w = refs.at(0);
+                            refs.clear(); // destroy the reference
+                                          // from the list.
+                            // back to one reference. Can *it* be
+                            // found?
+                            assert(function_w.REFCNT() == 1);
+                            refs = get_referrers.PyCall(function_w);
+                            if (refs && refs.empty()) {
+                                // Nope, it can't be found so it won't
+                                // ever be GC'd. Drop it.
+                                Py_CLEAR(function_w);
+                            }
+                        }
+                    }
+                    std::clock_t end = std::clock();
+                    ThreadState::add_clocks_used_doing_gc(end - begin);
+                }
+            }
+        }
+
+        // We need to make sure this greenlet appears to be dead,
+        // because otherwise deallocing it would fail to raise an
+        // exception in it (the thread is dead) and put it back in our
+        // deleteme list.
+        if (this->current_greenlet) {
+            this->current_greenlet->murder_in_place();
+            this->current_greenlet.CLEAR();
+        }
+
+        if (this->main_greenlet) {
+            // Couldn't have been the main greenlet that was running
+            // when the thread exited (because we already cleared this
+            // pointer if it was). This shouldn't be possible?
+
+            // If the main greenlet was current when the thread died (it
+            // should be, right?) then we cleared its self pointer above
+            // when we cleared the current greenlet's main greenlet pointer.
+            // assert(this->main_greenlet->main_greenlet == this->main_greenlet
+            //        || !this->main_greenlet->main_greenlet);
+            // // self reference, probably gone
+            // this->main_greenlet->main_greenlet.CLEAR();
+
+            // This will actually go away when the ivar is destructed.
+            this->main_greenlet.CLEAR();
+        }
+
+        if (PyErr_Occurred()) {
+            PyErr_WriteUnraisable(NULL);
+            PyErr_Clear();
+        }
+
+    }
+
+};
+
+ImmortalString ThreadState::get_referrers_name(nullptr);
+#ifdef Py_GIL_DISABLED
+std::atomic ThreadState::_clocks_used_doing_gc(0);
+#else
+std::clock_t ThreadState::_clocks_used_doing_gc(0);
+#endif
+
+
+
+
+
+}; // namespace greenlet
+
+#endif
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TThreadStateCreator.hpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TThreadStateCreator.hpp
new file mode 100644
index 0000000000000000000000000000000000000000..c3fbb311e7284b7361d3a05969527312a8ee2f50
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TThreadStateCreator.hpp
@@ -0,0 +1,105 @@
+#ifndef GREENLET_THREAD_STATE_CREATOR_HPP
+#define GREENLET_THREAD_STATE_CREATOR_HPP
+
+#include 
+#include 
+
+#include "greenlet_internal.hpp"
+#include "greenlet_refs.hpp"
+#include "greenlet_thread_support.hpp"
+
+#include "TThreadState.hpp"
+
+namespace greenlet {
+
+
+typedef void (*ThreadStateDestructor)(ThreadState* const);
+
+// Only one of these, auto created per thread as a thread_local.
+// This means we don't have to worry about atomic access to the
+// internals, because by definition all access is happening on a
+// single thread.
+// Constructing the state constructs the MainGreenlet.
+template
+class ThreadStateCreator
+{
+private:
+    // Initialized to 1, and, if still 1, created on access.
+    // Set to 0 on destruction.
+    ThreadState* _state;
+    G_NO_COPIES_OF_CLS(ThreadStateCreator);
+
+    inline bool has_initialized_state() const noexcept
+    {
+        return this->_state != (ThreadState*)1;
+    }
+
+    inline bool has_state() const noexcept
+    {
+        return this->has_initialized_state() && this->_state != nullptr;
+    }
+
+public:
+
+    ThreadStateCreator() :
+        _state((ThreadState*)1)
+    {
+    }
+
+    ~ThreadStateCreator()
+    {
+        if (this->has_state()) {
+            Destructor(this->_state);
+        }
+
+        this->_state = nullptr;
+    }
+
+    inline ThreadState& state()
+    {
+        // The main greenlet will own this pointer when it is created,
+        // which will be right after this. The plan is to give every
+        // greenlet a pointer to the main greenlet for the thread it
+        // runs in; if we are doing something cross-thread, we need to
+        // access the pointer from the main greenlet. Deleting the
+        // thread, and hence the thread-local storage, will delete the
+        // state pointer in the main greenlet.
+        if (!this->has_initialized_state()) {
+            // XXX: Assuming allocation never fails
+            this->_state = new ThreadState;
+            // For non-standard threading, we need to store an object
+            // in the Python thread state dictionary so that it can be
+            // DECREF'd when the thread ends (ideally; the dict could
+            // last longer) and clean this object up.
+        }
+        if (!this->_state) {
+            throw std::runtime_error("Accessing state after destruction.");
+        }
+        return *this->_state;
+    }
+
+    operator ThreadState&()
+    {
+        return this->state();
+    }
+
+    operator ThreadState*()
+    {
+        return &this->state();
+    }
+
+    inline int tp_traverse(visitproc visit, void* arg)
+    {
+        if (this->has_state()) {
+            return this->_state->tp_traverse(visit, arg);
+        }
+        return 0;
+    }
+
+};
+
+
+
+}; // namespace greenlet
+
+#endif
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TThreadStateDestroy.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TThreadStateDestroy.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..da1bad43e8bdb6f81e16db1bc41651668898f8cc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TThreadStateDestroy.cpp
@@ -0,0 +1,217 @@
+/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */
+/**
+ * Implementation of the ThreadState destructors.
+ *
+ * Format with:
+ *  clang-format -i --style=file src/greenlet/greenlet.c
+ *
+ *
+ * Fix missing braces with:
+ *   clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements"
+*/
+#ifndef T_THREADSTATE_DESTROY
+#define T_THREADSTATE_DESTROY
+
+#include "TGreenlet.hpp"
+
+#include "greenlet_thread_support.hpp"
+#include "greenlet_compiler_compat.hpp"
+#include "TGreenletGlobals.cpp"
+#include "TThreadState.hpp"
+#include "TThreadStateCreator.hpp"
+
+namespace greenlet {
+
+extern "C" {
+
+struct ThreadState_DestroyNoGIL
+{
+    /**
+       This function uses the same lock that the PendingCallback does
+     */
+    static void
+    MarkGreenletDeadAndQueueCleanup(ThreadState* const state)
+    {
+#if GREENLET_BROKEN_THREAD_LOCAL_CLEANUP_JUST_LEAK
+        // One rare platform.
+        return;
+#endif
+        // We are *NOT* holding the GIL. Our thread is in the middle
+        // of its death throes and the Python thread state is already
+        // gone so we can't use most Python APIs. One that is safe is
+        // ``Py_AddPendingCall``, unless the interpreter itself has
+        // been torn down. There is a limited number of calls that can
+        // be queued: 32 (NPENDINGCALLS) in CPython 3.10, so we
+        // coalesce these calls using our own queue.
+
+        if (!MarkGreenletDeadIfNeeded(state)) {
+            // No state, or no greenlet
+            return;
+        }
+
+        // XXX: Because we don't have the GIL, this is a race condition.
+        if (!PyInterpreterState_Head()) {
+            // We have to leak the thread state, if the
+            // interpreter has shut down when we're getting
+            // deallocated, we can't run the cleanup code that
+            // deleting it would imply.
+            return;
+        }
+
+        AddToCleanupQueue(state);
+
+    }
+
+private:
+
+    // If the state has an allocated main greenlet:
+    // - mark the greenlet as dead by disassociating it from the state;
+    // - return 1
+    // Otherwise, return 0.
+    static bool
+    MarkGreenletDeadIfNeeded(ThreadState* const state)
+    {
+        if (!state) {
+            return false;
+        }
+        LockGuard cleanup_lock(*mod_globs->thread_states_to_destroy_lock);
+        // mark the thread as dead ASAP.
+        // TODO: While the state variable tracking the death is
+        // atomic, and used with the strictest memory ordering, could
+        // this still be hiding race conditions? Specifically, is
+        // there a scenario where a thread is dying and thread local
+        // variables are being deconstructed, and some other thread
+        // tries to switch/throw to a greenlet owned by this thread,
+        // such that we think the switch will work but it won't?
+        return state->mark_main_greenlet_dead();
+    }
+
+    static void
+    AddToCleanupQueue(ThreadState* const state)
+    {
+        assert(state && state->has_main_greenlet());
+
+        // NOTE: Because we're not holding the GIL here, some other
+        // Python thread could run and call ``os.fork()``, which would
+        // be bad if that happened while we are holding the cleanup
+        // lock (it wouldn't function in the child process).
+        // Make a best effort to try to keep the duration we hold the
+        // lock short.
+        // TODO: On platforms that support it, use ``pthread_atfork`` to
+        // drop this lock.
+        LockGuard cleanup_lock(*mod_globs->thread_states_to_destroy_lock);
+
+        mod_globs->queue_to_destroy(state);
+        if (mod_globs->thread_states_to_destroy.size() == 1) {
+            // We added the first item to the queue. We need to schedule
+            // the cleanup.
+
+            // A size greater than 1 means that we have already added the pending call,
+            // and in fact, it may be executing now.
+            // If it is executing, our lock makes sure that it will see the item we just added
+            // to the queue on its next iteration (after we release the lock)
+            //
+            // A size of 1 means there is no pending call, OR the pending call is
+            // currently executing, has dropped the lock, and is deleting the last item
+            // from the queue; its next iteration will go ahead and delete the item we just added.
+            // And the pending call we schedule here will have no work to do.
+            int result = AddPendingCall(
+                           PendingCallback_DestroyQueue,
+                            nullptr);
+            if (result < 0) {
+                // Hmm, what can we do here?
+                fprintf(stderr,
+                        "greenlet: WARNING: failed in call to Py_AddPendingCall; "
+                        "expect a memory leak.\n");
+            }
+        }
+    }
+
+    static int
+    PendingCallback_DestroyQueue(void* UNUSED(arg))
+    {
+        // We're may or may not be holding the GIL here (depending on
+        // Py_GIL_DISABLED), so calls to ``os.fork()`` may or may not
+        // be possible.
+        while (1) {
+            ThreadState* to_destroy;
+            {
+                LockGuard cleanup_lock(*mod_globs->thread_states_to_destroy_lock);
+                if (mod_globs->thread_states_to_destroy.empty()) {
+                    break;
+                }
+                to_destroy = mod_globs->take_next_to_destroy();
+            }
+            assert(to_destroy);
+            assert(to_destroy->has_main_greenlet());
+            // Drop the lock while we do the actual deletion.
+            // This allows other calls to MarkGreenletDeadAndQueueCleanup
+            // to enter and add to our queue.
+            DestroyOne(to_destroy);
+        }
+        return 0;
+    }
+
+    static void
+    DestroyOne(const ThreadState* const state)
+    {
+        // May or may not be holding the GIL (depending on Py_GIL_DISABLED).
+        // Passed a non-shared pointer to the actual thread state.
+        // state -> main greenlet
+        //
+        // The thread_state in the main greenlet has already been
+        // cleared by the time this function runs from our pending
+        // callback, but the greenlet itself is still there.
+#ifndef NDEBUG
+        PyGreenlet* main(state->borrow_main_greenlet());
+        assert(main);
+        assert(main->pimpl->thread_state() == nullptr);
+#endif
+        delete state; // Deleting this runs the destructor, DECREFs the main greenlet.
+    }
+
+
+    static int AddPendingCall(int (*func)(void*), void* arg)
+    {
+        // If the interpreter is in the middle of finalizing, we can't
+        // add a pending call. Trying to do so will end up in a
+        // SIGSEGV, as Py_AddPendingCall will not be able to get the
+        // interpreter and will try to dereference a NULL pointer.
+        // It's possible this can still segfault if we happen to get
+        // context switched, and maybe we should just always implement
+        // our own AddPendingCall, but I'd like to see if this works
+        // first
+        if (greenlet::IsShuttingDown()) {
+#ifdef GREENLET_DEBUG
+            // No need to log in the general case. Yes, we'll leak,
+            // but we're shutting down so it should be ok.
+            fprintf(stderr,
+                    "greenlet: WARNING: Interpreter is finalizing. Ignoring "
+                    "call to Py_AddPendingCall; \n");
+#endif
+            return 0;
+        }
+        return Py_AddPendingCall(func, arg);
+    }
+
+
+
+
+
+};
+};
+
+}; // namespace greenlet
+
+// The intent when GET_THREAD_STATE() is needed multiple times in a
+// function is to take a reference to its return value in a local
+// variable, to avoid the thread-local indirection. On some platforms
+// (macOS), accessing a thread-local involves a function call (plus an
+// initial function call in each function that uses a thread local);
+// in contrast, static volatile variables are at some pre-computed
+// offset.
+typedef greenlet::ThreadStateCreator ThreadStateCreator;
+static thread_local ThreadStateCreator g_thread_state_global;
+#define GET_THREAD_STATE() g_thread_state_global
+
+#endif //T_THREADSTATE_DESTROY
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TUserGreenlet.cpp b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TUserGreenlet.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c0fc6bebc83262c142058a753121e08452965d26
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/TUserGreenlet.cpp
@@ -0,0 +1,674 @@
+/* -*- indent-tabs-mode: nil; tab-width: 4; -*- */
+/**
+ * Implementation of greenlet::UserGreenlet.
+ *
+ * Format with:
+ *  clang-format -i --style=file src/greenlet/greenlet.c
+ *
+ *
+ * Fix missing braces with:
+ *   clang-tidy src/greenlet/greenlet.c -fix -checks="readability-braces-around-statements"
+*/
+#ifndef T_USER_GREENLET_CPP
+#define T_USER_GREENLET_CPP
+
+#include "greenlet_internal.hpp"
+#include "TGreenlet.hpp"
+
+#include "TThreadStateDestroy.cpp"
+
+
+namespace greenlet {
+using greenlet::refs::BorrowedMainGreenlet;
+greenlet::PythonAllocator UserGreenlet::allocator;
+
+void* UserGreenlet::operator new(size_t UNUSED(count))
+{
+    return allocator.allocate(1);
+}
+
+
+void UserGreenlet::operator delete(void* ptr)
+{
+    return allocator.deallocate(static_cast(ptr),
+                                1);
+}
+
+
+UserGreenlet::UserGreenlet(PyGreenlet* p, BorrowedGreenlet the_parent)
+    : Greenlet(p), _parent(the_parent)
+{
+}
+
+UserGreenlet::~UserGreenlet()
+{
+    // Python 3.11: If we don't clear out the raw frame datastack
+    // when deleting an unfinished greenlet,
+    // TestLeaks.test_untracked_memory_doesnt_increase_unfinished_thread_dealloc_in_main fails.
+    this->python_state.did_finish(nullptr);
+    this->tp_clear();
+}
+
+
+const BorrowedMainGreenlet
+UserGreenlet::main_greenlet() const
+{
+    return this->_main_greenlet;
+}
+
+
+BorrowedMainGreenlet
+UserGreenlet::find_main_greenlet_in_lineage() const
+{
+    if (this->started()) {
+        assert(this->_main_greenlet);
+        return BorrowedMainGreenlet(this->_main_greenlet);
+    }
+
+    if (!this->_parent) {
+        /* garbage collected greenlet in chain */
+        // XXX: WHAT?
+        return BorrowedMainGreenlet(nullptr);
+    }
+
+    return this->_parent->find_main_greenlet_in_lineage();
+}
+
+
+/**
+ * CAUTION: This will allocate memory and may trigger garbage
+ * collection and arbitrary Python code.
+ */
+OwnedObject
+UserGreenlet::throw_GreenletExit_during_dealloc(const ThreadState& current_thread_state)
+{
+    /* The dying greenlet cannot be a parent of ts_current
+       because the 'parent' field chain would hold a
+       reference */
+    UserGreenlet::ParentIsCurrentGuard with_current_parent(this, current_thread_state);
+
+    // We don't care about the return value, only whether an
+    // exception happened. Whether or not an exception happens,
+    // we need to restore the parent in case the greenlet gets
+    // resurrected.
+    return Greenlet::throw_GreenletExit_during_dealloc(current_thread_state);
+}
+
+ThreadState*
+UserGreenlet::thread_state() const noexcept
+{
+    // TODO: maybe make this throw, if the thread state isn't there?
+    // if (!this->main_greenlet) {
+    //     throw std::runtime_error("No thread state"); // TODO: Better exception
+    // }
+    if (!this->_main_greenlet) {
+        return nullptr;
+    }
+    return this->_main_greenlet->thread_state();
+}
+
+
+bool
+UserGreenlet::was_running_in_dead_thread() const noexcept
+{
+    return this->_main_greenlet && !this->thread_state();
+}
+
+OwnedObject
+UserGreenlet::g_switch()
+{
+    try {
+        if (!this->args() && !PyErr_Occurred()) {
+            // we have nothing to send as the result of switching,
+            // most likely because we've somehow allowed concurrent
+            // uses of switch from multiple threads (which may or may
+            // not be allowed by check_switch_allowed)
+            // ``green_switch`` defends against this by calling
+            // ``check_switch_allowed`` before messing with
+            // ``args()``, but we have at least one internal caller
+            // (``throw_GreenletExit_during_dealloc``) so we keep both
+            // this explicit check and our call to
+            // ``check_switch_allowed``
+            throw PyErrOccurred(mod_globs->PyExc_GreenletError,
+                                "cannot switch with no pending arguments or exception");
+        }
+        this->check_switch_allowed();
+    }
+    catch (const PyErrOccurred&) {
+        this->release_args();
+        throw;
+    }
+
+    // Switching greenlets used to attempt to clean out ones that need
+    // deleted *if* we detected a thread switch. Should it still do
+    // that?
+    // An issue is that if we delete a greenlet from another thread,
+    // it gets queued to this thread, and ``kill_greenlet()`` switches
+    // back into the greenlet
+
+    /* find the real target by ignoring dead greenlets,
+       and if necessary starting a greenlet. */
+    switchstack_result_t err;
+    Greenlet* target = this;
+    // TODO: probably cleaner to handle the case where we do
+    // switch to ourself separately from the other cases.
+    // This can probably even further be simplified if we keep
+    // track of the switching_state we're going for and just call
+    // into g_switch() if it's not ourself. The main problem with that
+    // is that we would be using more stack space.
+    bool target_was_me = true;
+    bool was_initial_stub = false;
+    while (target) {
+        if (target->active()) {
+            if (!target_was_me) {
+                target->args() <<= this->args();
+                assert(!this->args());
+            }
+            err = target->g_switchstack();
+            break;
+        }
+        if (!target->started()) {
+            // We never encounter a main greenlet that's not started.
+            assert(!target->main());
+            UserGreenlet* real_target = static_cast(target);
+            assert(real_target);
+            void* dummymarker;
+            was_initial_stub = true;
+            if (!target_was_me) {
+                target->args() <<= this->args();
+                assert(!this->args());
+            }
+            try {
+                // This can only throw back to us while we're
+                // still in this greenlet. Once the new greenlet
+                // is bootstrapped, it has its own exception state.
+                err = real_target->g_initialstub(&dummymarker);
+            }
+            catch (const PyErrOccurred&) {
+                this->release_args();
+                throw;
+            }
+            catch (const GreenletStartedWhileInPython&) {
+                // The greenlet was started sometime before this
+                // greenlet actually switched to it, i.e.,
+                // "concurrent" calls to switch() or throw().
+                // We need to retry the switch.
+                // Note that the current greenlet has been reset
+                // to this one (or we wouldn't be running!)
+                continue;
+            }
+            break;
+        }
+
+        target = target->parent();
+        target_was_me = false;
+    }
+    // The ``this`` pointer and all other stack or register based
+    // variables are invalid now, at least where things succeed
+    // above.
+    // But this one, probably not so much? It's not clear if it's
+    // safe to throw an exception at this point.
+
+    if (err.status < 0) {
+        // If we get here, either g_initialstub()
+        // failed, or g_switchstack() failed. Either one of those
+        // cases SHOULD leave us in the original greenlet with a valid
+        // stack.
+        return this->on_switchstack_or_initialstub_failure(target, err, target_was_me, was_initial_stub);
+    }
+
+    // err.the_new_current_greenlet would be the same as ``target``,
+    // if target wasn't probably corrupt.
+    return err.the_new_current_greenlet->g_switch_finish(err);
+}
+
+
+
+Greenlet::switchstack_result_t
+UserGreenlet::g_initialstub(void* mark)
+{
+    OwnedObject run;
+
+    // We need to grab a reference to the current switch arguments
+    // in case we're entered concurrently during the call to
+    // GetAttr() and have to try again.
+    // We'll restore them when we return in that case.
+    // Scope them tightly to avoid ref leaks.
+    {
+        SwitchingArgs args(this->args());
+
+        /* save exception in case getattr clears it */
+        PyErrPieces saved;
+
+        /*
+          self.run is the object to call in the new greenlet.
+          This could run arbitrary python code and switch greenlets!
+        */
+        run = this->self().PyRequireAttr(mod_globs->str_run);
+        /* restore saved exception */
+        saved.PyErrRestore();
+
+
+        /* recheck that it's safe to switch in case greenlet reparented anywhere above */
+        this->check_switch_allowed();
+
+        /* by the time we got here another start could happen elsewhere,
+         * that means it should now be a regular switch.
+         * This can happen if the Python code is a subclass that implements
+         * __getattribute__ or __getattr__, or makes ``run`` a descriptor;
+         * all of those can run arbitrary code that switches back into
+         * this greenlet.
+         */
+        if (this->stack_state.started()) {
+            // the successful switch cleared these out, we need to
+            // restore our version. They will be copied on up to the
+            // next target.
+            assert(!this->args());
+            this->args() <<= args;
+            throw GreenletStartedWhileInPython();
+        }
+    }
+
+    // Sweet, if we got here, we have the go-ahead and will switch
+    // greenlets.
+    // Nothing we do from here on out should allow for a thread or
+    // greenlet switch: No arbitrary calls to Python, including
+    // decref'ing
+
+#if GREENLET_USE_CFRAME
+    /* OK, we need it, we're about to switch greenlets, save the state. */
+    /*
+      See green_new(). This is a stack-allocated variable used
+      while *self* is in PyObject_Call().
+      We want to defer copying the state info until we're sure
+      we need it and are in a stable place to do so.
+    */
+    _PyCFrame trace_info;
+
+    this->python_state.set_new_cframe(trace_info);
+#endif
+    /* start the greenlet */
+    ThreadState& thread_state = GET_THREAD_STATE().state();
+    this->stack_state = StackState(mark,
+                                   thread_state.borrow_current()->stack_state);
+    this->python_state.set_initial_state(PyThreadState_GET());
+    this->exception_state.clear();
+    this->_main_greenlet = thread_state.get_main_greenlet();
+
+    /* perform the initial switch */
+    switchstack_result_t err = this->g_switchstack();
+    /* returns twice!
+       The 1st time with ``err == 1``: we are in the new greenlet.
+       This one owns a greenlet that used to be current.
+       The 2nd time with ``err <= 0``: back in the caller's
+       greenlet; this happens if the child finishes or switches
+       explicitly to us. Either way, the ``err`` variable is
+       created twice at the same memory location, but possibly
+       having different ``origin`` values. Note that it's not
+       constructed for the second time until the switch actually happens.
+    */
+    if (err.status == 1) {
+        // In the new greenlet.
+
+        // This never returns! Calling inner_bootstrap steals
+        // the contents of our run object within this stack frame, so
+        // it is not valid to do anything with it.
+        try {
+            this->inner_bootstrap(err.origin_greenlet.relinquish_ownership(),
+                                  run.relinquish_ownership());
+        }
+        // Getting a C++ exception here isn't good. It's probably a
+        // bug in the underlying greenlet, meaning it's probably a
+        // C++ extension. We're going to abort anyway, but try to
+        // display some nice information *if* possible. Some obscure
+        // platforms don't properly support this (old 32-bit Arm, see see
+        // https://github.com/python-greenlet/greenlet/issues/385); that's not
+        // great, but should usually be OK because, as mentioned above, we're
+        // terminating anyway.
+        //
+        // The catching is tested by
+        // ``test_cpp.CPPTests.test_unhandled_exception_in_greenlet_aborts``.
+        //
+        // PyErrOccurred can theoretically be thrown by
+        // inner_bootstrap() -> g_switch_finish(), but that should
+        // never make it back to here. It is a std::exception and
+        // would be caught if it is.
+        catch (const std::exception& e) {
+            std::string base = "greenlet: Unhandled C++ exception: ";
+            base += e.what();
+            Py_FatalError(base.c_str());
+        }
+        catch (...) {
+            // Some compilers/runtimes use exceptions internally.
+            // It appears that GCC on Linux with libstdc++ throws an
+            // exception internally at process shutdown time to unwind
+            // stacks and clean up resources. Depending on exactly
+            // where we are when the process exits, that could result
+            // in an unknown exception getting here. If we
+            // Py_FatalError() or abort() here, we interfere with
+            // orderly process shutdown. Throwing the exception on up
+            // is the right thing to do.
+            //
+            // gevent's ``examples/dns_mass_resolve.py`` demonstrates this.
+#ifndef NDEBUG
+            fprintf(stderr,
+                    "greenlet: inner_bootstrap threw unknown exception; "
+                    "is the process terminating?\n");
+#endif
+            throw;
+        }
+        Py_FatalError("greenlet: inner_bootstrap returned with no exception.\n");
+    }
+
+
+    // In contrast, notice that we're keeping the origin greenlet
+    // around as an owned reference; we need it to call the trace
+    // function for the switch back into the parent. It was only
+    // captured at the time the switch actually happened, though,
+    // so we haven't been keeping an extra reference around this
+    // whole time.
+
+    /* back in the parent */
+    if (err.status < 0) {
+        /* start failed badly, restore greenlet state */
+        this->stack_state = StackState();
+        this->_main_greenlet.CLEAR();
+        // CAUTION: This may run arbitrary Python code.
+        run.CLEAR(); // inner_bootstrap didn't run, we own the reference.
+    }
+
+    // In the success case, the spawned code (inner_bootstrap) will
+    // take care of decrefing this, so we relinquish ownership so as
+    // to not double-decref.
+
+    run.relinquish_ownership();
+
+    return err;
+}
+
+
+void
+UserGreenlet::inner_bootstrap(PyGreenlet* origin_greenlet, PyObject* run)
+{
+    // The arguments here would be another great place for move.
+    // As it is, we take them as a reference so that when we clear
+    // them we clear what's on the stack above us. Do that NOW, and
+    // without using a C++ RAII object,
+    // so there's no way that exiting the parent frame can clear it,
+    // or we clear it unexpectedly. This arises in the context of the
+    // interpreter shutting down. See https://github.com/python-greenlet/greenlet/issues/325
+    //PyObject* run = _run.relinquish_ownership();
+
+    /* in the new greenlet */
+    assert(this->thread_state()->borrow_current() == BorrowedGreenlet(this->_self));
+    // C++ exceptions cannot propagate to the parent greenlet from
+    // here. (TODO: Do we need a catch(...) clause, perhaps on the
+    // function itself? ALl we could do is terminate the program.)
+    // NOTE: On 32-bit Windows, the call chain is extremely
+    // important here in ways that are subtle, having to do with
+    // the depth of the SEH list. The call to restore it MUST NOT
+    // add a new SEH handler to the list, or we'll restore it to
+    // the wrong thing.
+    this->thread_state()->restore_exception_state();
+    /* stack variables from above are no good and also will not unwind! */
+    // EXCEPT: That can't be true, we access run, among others, here.
+
+    this->stack_state.set_active(); /* running */
+
+    // We're about to possibly run Python code again, which
+    // could switch back/away to/from us, so we need to grab the
+    // arguments locally.
+    SwitchingArgs args;
+    args <<= this->args();
+    assert(!this->args());
+
+    // XXX: We could clear this much earlier, right?
+    // Or would that introduce the possibility of running Python
+    // code when we don't want to?
+    // CAUTION: This may run arbitrary Python code.
+    this->_run_callable.CLEAR();
+
+
+    // The first switch we need to manually call the trace
+    // function here instead of in g_switch_finish, because we
+    // never return there.
+    if (OwnedObject tracefunc = this->thread_state()->get_tracefunc()) {
+        OwnedGreenlet trace_origin;
+        trace_origin = origin_greenlet;
+        try {
+            g_calltrace(tracefunc,
+                        args ? mod_globs->event_switch : mod_globs->event_throw,
+                        trace_origin,
+                        this->_self);
+        }
+        catch (const PyErrOccurred&) {
+            /* Turn trace errors into switch throws */
+            args.CLEAR();
+        }
+    }
+
+    // We no longer need the origin, it was only here for
+    // tracing.
+    // We may never actually exit this stack frame so we need
+    // to explicitly clear it.
+    // This could run Python code and switch.
+    Py_CLEAR(origin_greenlet);
+
+    OwnedObject result;
+    if (!args) {
+        /* pending exception */
+        result = NULL;
+    }
+    else {
+        /* call g.run(*args, **kwargs) */
+        // This could result in further switches
+        try {
+            //result = run.PyCall(args.args(), args.kwargs());
+            // CAUTION: Just invoking this, before the function even
+            // runs, may cause memory allocations, which may trigger
+            // GC, which may run arbitrary Python code.
+            result = OwnedObject::consuming(PyObject_Call(run, args.args().borrow(), args.kwargs().borrow()));
+        }
+        catch (...) {
+            // Unhandled C++ exception!
+
+            // If we declare ourselves as noexcept, if we don't catch
+            // this here, most platforms will just abort() the
+            // process. But on 64-bit Windows with older versions of
+            // the C runtime, this can actually corrupt memory and
+            // just return. We see this when compiling with the
+            // Windows 7.0 SDK targeting Windows Server 2008, but not
+            // when using the Appveyor Visual Studio 2019 image. So
+            // this currently only affects Python 2.7 on Windows 64.
+            // That is, the tests pass and the runtime aborts
+            // everywhere else.
+            //
+            // However, if we catch it and try to continue with a
+            // Python error, then all Windows 64 bit platforms corrupt
+            // memory. So all we can do is manually abort, hopefully
+            // with a good error message. (Note that the above was
+            // tested WITHOUT the `/EHr` switch being used at compile
+            // time, so MSVC may have "optimized" out important
+            // checking. Using that switch, we may be in a better
+            // place in terms of memory corruption.) But sometimes it
+            // can't be caught here at all, which is confusing but not
+            // terribly surprising; so again, the G_NOEXCEPT_WIN32
+            // plus "/EHr".
+            //
+            // Hopefully the basic C stdlib is still functional enough
+            // for us to at least print an error.
+            //
+            // It gets more complicated than that, though, on some
+            // platforms, specifically at least Linux/gcc/libstdc++. They use
+            // an exception to unwind the stack when a background
+            // thread exits. (See comments about noexcept.) So this
+            // may not actually represent anything untoward. On those
+            // platforms we allow throws of this to propagate, or
+            // attempt to anyway.
+# if defined(WIN32) || defined(_WIN32)
+            Py_FatalError(
+                "greenlet: Unhandled C++ exception from a greenlet run function. "
+                "Because memory is likely corrupted, terminating process.");
+            std::abort();
+#else
+            throw;
+#endif
+        }
+    }
+    // These lines may run arbitrary code
+    args.CLEAR();
+    Py_CLEAR(run);
+
+    if (!result
+        && mod_globs->PyExc_GreenletExit.PyExceptionMatches()
+        && (this->args())) {
+        // This can happen, for example, if our only reference
+        // goes away after we switch back to the parent.
+        // See test_dealloc_switch_args_not_lost
+        PyErrPieces clear_error;
+        result <<= this->args();
+        result = single_result(result);
+    }
+    this->release_args();
+    this->python_state.did_finish(PyThreadState_GET());
+
+    result = g_handle_exit(result);
+    assert(this->thread_state()->borrow_current() == this->_self);
+
+    /* jump back to parent */
+    this->stack_state.set_inactive(); /* dead */
+
+
+    // TODO: Can we decref some things here? Release our main greenlet
+    // and maybe parent?
+    for (Greenlet* parent = this->_parent;
+         parent;
+         parent = parent->parent()) {
+        // We need to somewhere consume a reference to
+        // the result; in most cases we'll never have control
+        // back in this stack frame again. Calling
+        // green_switch actually adds another reference!
+        // This would probably be clearer with a specific API
+        // to hand results to the parent.
+        parent->args() <<= result;
+        assert(!result);
+        // The parent greenlet now owns the result; in the
+        // typical case we'll never get back here to assign to
+        // result and thus release the reference.
+        try {
+            result = parent->g_switch();
+        }
+        catch (const PyErrOccurred&) {
+            // Ignore, keep passing the error on up.
+        }
+
+        /* Return here means switch to parent failed,
+         * in which case we throw *current* exception
+         * to the next parent in chain.
+         */
+        assert(!result);
+    }
+    /* We ran out of parents, cannot continue */
+    PyErr_WriteUnraisable(this->self().borrow_o());
+    Py_FatalError("greenlet: ran out of parent greenlets while propagating exception; "
+                  "cannot continue");
+    std::abort();
+}
+
+void
+UserGreenlet::run(const BorrowedObject nrun)
+{
+    if (this->started()) {
+        throw AttributeError(
+                        "run cannot be set "
+                        "after the start of the greenlet");
+    }
+    this->_run_callable = nrun;
+}
+
+const OwnedGreenlet
+UserGreenlet::parent() const
+{
+    return this->_parent;
+}
+
+void
+UserGreenlet::parent(const BorrowedObject raw_new_parent)
+{
+    if (!raw_new_parent) {
+        throw AttributeError("can't delete attribute");
+    }
+
+    BorrowedMainGreenlet main_greenlet_of_new_parent;
+    BorrowedGreenlet new_parent(raw_new_parent.borrow()); // could
+                                                          // throw
+                                                          // TypeError!
+    for (BorrowedGreenlet p = new_parent; p; p = p->parent()) {
+        if (p == this->self()) {
+            throw ValueError("cyclic parent chain");
+        }
+        main_greenlet_of_new_parent = p->main_greenlet();
+    }
+
+    if (!main_greenlet_of_new_parent) {
+        throw ValueError("parent must not be garbage collected");
+    }
+
+    if (this->started()
+        && this->_main_greenlet != main_greenlet_of_new_parent) {
+        throw ValueError("parent cannot be on a different thread");
+    }
+
+    this->_parent = new_parent;
+}
+
+void
+UserGreenlet::murder_in_place()
+{
+    this->_main_greenlet.CLEAR();
+    Greenlet::murder_in_place();
+}
+
+bool
+UserGreenlet::belongs_to_thread(const ThreadState* thread_state) const
+{
+    return Greenlet::belongs_to_thread(thread_state) && this->_main_greenlet == thread_state->borrow_main_greenlet();
+}
+
+
+int
+UserGreenlet::tp_traverse(visitproc visit, void* arg)
+{
+    Py_VISIT(this->_parent.borrow_o());
+    Py_VISIT(this->_main_greenlet.borrow_o());
+    Py_VISIT(this->_run_callable.borrow_o());
+
+    return Greenlet::tp_traverse(visit, arg);
+}
+
+int
+UserGreenlet::tp_clear()
+{
+    Greenlet::tp_clear();
+    this->_parent.CLEAR();
+    this->_main_greenlet.CLEAR();
+    this->_run_callable.CLEAR();
+    return 0;
+}
+
+UserGreenlet::ParentIsCurrentGuard::ParentIsCurrentGuard(UserGreenlet* p,
+                                                     const ThreadState& thread_state)
+    : oldparent(p->_parent),
+      greenlet(p)
+{
+    p->_parent = thread_state.get_current();
+}
+
+UserGreenlet::ParentIsCurrentGuard::~ParentIsCurrentGuard()
+{
+    this->greenlet->_parent = oldparent;
+    oldparent.CLEAR();
+}
+
+}; //namespace greenlet
+#endif
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..aff2f00587bfbade8c95d413c5634f4f9ce85917
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/__init__.py
@@ -0,0 +1,62 @@
+# -*- coding: utf-8 -*-
+"""
+The root of the greenlet package.
+"""
+
+__all__ = [
+    '__version__',
+    '_C_API',
+
+    'GreenletExit',
+    'error',
+
+    'getcurrent',
+    'greenlet',
+
+    'gettrace',
+    'settrace',
+]
+
+# pylint:disable=no-name-in-module
+
+###
+# Metadata
+###
+__version__ = '3.5.0'
+from ._greenlet import _C_API # pylint:disable=no-name-in-module
+
+###
+# Exceptions
+###
+from ._greenlet import GreenletExit
+from ._greenlet import error
+
+###
+# greenlets
+###
+from ._greenlet import getcurrent
+from ._greenlet import greenlet
+
+###
+# tracing
+###
+from ._greenlet import gettrace
+from ._greenlet import settrace
+
+###
+# Constants
+# These constants aren't documented and aren't recommended.
+# In 1.0, USE_GC and USE_TRACING are always true, and USE_CONTEXT_VARS
+# is the same as ``sys.version_info[:2] >= 3.7``
+###
+from ._greenlet import GREENLET_USE_CONTEXT_VARS # pylint:disable=unused-import
+from ._greenlet import GREENLET_USE_GC # pylint:disable=unused-import
+from ._greenlet import GREENLET_USE_TRACING # pylint:disable=unused-import
+
+# Controlling the use of the gc module. Provisional API for this greenlet
+# implementation in 2.0.
+from ._greenlet import CLOCKS_PER_SEC # pylint:disable=unused-import
+from ._greenlet import enable_optional_cleanup # pylint:disable=unused-import
+from ._greenlet import get_clocks_used_doing_optional_cleanup # pylint:disable=unused-import
+
+# Other APIS in the _greenlet module are for test support.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/_greenlet.cp311-win_amd64.pyd b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/_greenlet.cp311-win_amd64.pyd
new file mode 100644
index 0000000000000000000000000000000000000000..dc82f1e5ec8f33f6504e9afa97757790d86e6f67
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/greenlet/_greenlet.cp311-win_amd64.pyd differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..083db6f4340fb522f5bdadae7b326fdff3b6661f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/__init__.py
@@ -0,0 +1,2347 @@
+# Copyright 2015-2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""gRPC's Python API."""
+
+import abc
+import contextlib
+import enum
+import logging
+import sys
+
+from grpc import _compression
+from grpc._cython import cygrpc as _cygrpc
+from grpc._runtime_protos import protos
+from grpc._runtime_protos import protos_and_services
+from grpc._runtime_protos import services
+
+logging.getLogger(__name__).addHandler(logging.NullHandler())
+
+try:
+    # pylint: disable=ungrouped-imports
+    from grpc._grpcio_metadata import __version__
+except ImportError:
+    __version__ = "dev0"
+
+############################## Future Interface  ###############################
+
+
+class FutureTimeoutError(Exception):
+    """Indicates that a method call on a Future timed out."""
+
+
+class FutureCancelledError(Exception):
+    """Indicates that the computation underlying a Future was cancelled."""
+
+
+class Future(abc.ABC):
+    """A representation of a computation in another control flow.
+
+    Computations represented by a Future may be yet to be begun,
+    may be ongoing, or may have already completed.
+    """
+
+    @abc.abstractmethod
+    def cancel(self):
+        """Attempts to cancel the computation.
+
+        This method does not block.
+
+        Returns:
+            bool:
+            Returns True if the computation was canceled.
+
+            Returns False under all other circumstances, for example:
+
+            1. computation has begun and could not be canceled.
+            2. computation has finished
+            3. computation is scheduled for execution and it is impossible
+                to determine its state without blocking.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def cancelled(self):
+        """Describes whether the computation was cancelled.
+
+        This method does not block.
+
+        Returns:
+            bool:
+            Returns True if the computation was cancelled before its result became
+            available.
+
+            Returns False under all other circumstances, for example:
+
+            1. computation was not cancelled.
+            2. computation's result is available.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def running(self):
+        """Describes whether the computation is taking place.
+
+        This method does not block.
+
+        Returns:
+            Returns True if the computation is scheduled for execution or
+            currently executing.
+
+            Returns False if the computation already executed or was cancelled.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def done(self):
+        """Describes whether the computation has taken place.
+
+        This method does not block.
+
+        Returns:
+            bool:
+            Returns True if the computation already executed or was cancelled.
+            Returns False if the computation is scheduled for execution or
+            currently executing.
+            This is exactly opposite of the running() method's result.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def result(self, timeout=None):
+        """Returns the result of the computation or raises its exception.
+
+        This method may return immediately or may block.
+
+        Args:
+          timeout: The length of time in seconds to wait for the computation to
+            finish or be cancelled. If None, the call will block until the
+            computations's termination.
+
+        Returns:
+          The return value of the computation.
+
+        Raises:
+          FutureTimeoutError: If a timeout value is passed and the computation
+            does not terminate within the allotted time.
+          FutureCancelledError: If the computation was cancelled.
+          Exception: If the computation raised an exception, this call will
+            raise the same exception.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def exception(self, timeout=None):
+        """Return the exception raised by the computation.
+
+        This method may return immediately or may block.
+
+        Args:
+          timeout: The length of time in seconds to wait for the computation to
+            terminate or be cancelled. If None, the call will block until the
+            computations's termination.
+
+        Returns:
+            The exception raised by the computation, or None if the computation
+            did not raise an exception.
+
+        Raises:
+          FutureTimeoutError: If a timeout value is passed and the computation
+            does not terminate within the allotted time.
+          FutureCancelledError: If the computation was cancelled.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def traceback(self, timeout=None):
+        """Access the traceback of the exception raised by the computation.
+
+        This method may return immediately or may block.
+
+        Args:
+          timeout: The length of time in seconds to wait for the computation
+            to terminate or be cancelled. If None, the call will block until
+            the computation's termination.
+
+        Returns:
+            The traceback of the exception raised by the computation, or None
+            if the computation did not raise an exception.
+
+        Raises:
+          FutureTimeoutError: If a timeout value is passed and the computation
+            does not terminate within the allotted time.
+          FutureCancelledError: If the computation was cancelled.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def add_done_callback(self, fn):
+        """Adds a function to be called at completion of the computation.
+
+        The callback will be passed this Future object describing the outcome
+        of the computation.  Callbacks will be invoked after the future is
+        terminated, whether successfully or not.
+
+        If the computation has already completed, the callback will be called
+        immediately.
+
+        Exceptions raised in the callback will be logged at ERROR level, but
+        will not terminate any threads of execution.
+
+        Args:
+          fn: A callable taking this Future object as its single parameter.
+        """
+        raise NotImplementedError()
+
+
+################################  gRPC Enums  ##################################
+
+
+@enum.unique
+class ChannelConnectivity(enum.Enum):
+    """Mirrors grpc_connectivity_state in the gRPC Core.
+
+    Attributes:
+      IDLE: The channel is idle.
+      CONNECTING: The channel is connecting.
+      READY: The channel is ready to conduct RPCs.
+      TRANSIENT_FAILURE: The channel has seen a failure from which it expects
+        to recover.
+      SHUTDOWN: The channel has seen a failure from which it cannot recover.
+    """
+
+    IDLE = (_cygrpc.ConnectivityState.idle, "idle")
+    CONNECTING = (_cygrpc.ConnectivityState.connecting, "connecting")
+    READY = (_cygrpc.ConnectivityState.ready, "ready")
+    TRANSIENT_FAILURE = (
+        _cygrpc.ConnectivityState.transient_failure,
+        "transient failure",
+    )
+    SHUTDOWN = (_cygrpc.ConnectivityState.shutdown, "shutdown")
+
+
+@enum.unique
+class StatusCode(enum.Enum):
+    """Mirrors grpc_status_code in the gRPC Core.
+
+    Attributes:
+      OK: Not an error; returned on success
+      CANCELLED: The operation was cancelled (typically by the caller).
+      UNKNOWN: Unknown error.
+      INVALID_ARGUMENT: Client specified an invalid argument.
+      DEADLINE_EXCEEDED: Deadline expired before operation could complete.
+      NOT_FOUND: Some requested entity (e.g., file or directory) was not found.
+      ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory)
+        already exists.
+      PERMISSION_DENIED: The caller does not have permission to execute the specified
+        operation.
+      UNAUTHENTICATED: The request does not have valid authentication credentials for the
+        operation.
+      RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or
+        perhaps the entire file system is out of space.
+      FAILED_PRECONDITION: Operation was rejected because the system is not in a state
+        required for the operation's execution.
+      ABORTED: The operation was aborted, typically due to a concurrency issue
+        like sequencer check failures, transaction aborts, etc.
+      UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service.
+      INTERNAL: Internal errors.  Means some invariants expected by underlying
+        system has been broken.
+      UNAVAILABLE: The service is currently unavailable.
+      DATA_LOSS: Unrecoverable data loss or corruption.
+    """
+
+    OK = (_cygrpc.StatusCode.ok, "ok")
+    CANCELLED = (_cygrpc.StatusCode.cancelled, "cancelled")
+    UNKNOWN = (_cygrpc.StatusCode.unknown, "unknown")
+    INVALID_ARGUMENT = (_cygrpc.StatusCode.invalid_argument, "invalid argument")
+    DEADLINE_EXCEEDED = (
+        _cygrpc.StatusCode.deadline_exceeded,
+        "deadline exceeded",
+    )
+    NOT_FOUND = (_cygrpc.StatusCode.not_found, "not found")
+    ALREADY_EXISTS = (_cygrpc.StatusCode.already_exists, "already exists")
+    PERMISSION_DENIED = (
+        _cygrpc.StatusCode.permission_denied,
+        "permission denied",
+    )
+    RESOURCE_EXHAUSTED = (
+        _cygrpc.StatusCode.resource_exhausted,
+        "resource exhausted",
+    )
+    FAILED_PRECONDITION = (
+        _cygrpc.StatusCode.failed_precondition,
+        "failed precondition",
+    )
+    ABORTED = (_cygrpc.StatusCode.aborted, "aborted")
+    OUT_OF_RANGE = (_cygrpc.StatusCode.out_of_range, "out of range")
+    UNIMPLEMENTED = (_cygrpc.StatusCode.unimplemented, "unimplemented")
+    INTERNAL = (_cygrpc.StatusCode.internal, "internal")
+    UNAVAILABLE = (_cygrpc.StatusCode.unavailable, "unavailable")
+    DATA_LOSS = (_cygrpc.StatusCode.data_loss, "data loss")
+    UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, "unauthenticated")
+
+
+#############################  gRPC Status  ################################
+
+
+class Status(abc.ABC):
+    """Describes the status of an RPC.
+
+    This is an EXPERIMENTAL API.
+
+    Attributes:
+      code: A StatusCode object to be sent to the client.
+      details: A UTF-8-encodable string to be sent to the client upon
+        termination of the RPC.
+      trailing_metadata: The trailing :term:`metadata` in the RPC.
+    """
+
+
+#############################  gRPC Exceptions  ################################
+
+
+class RpcError(Exception):
+    """Raised by the gRPC library to indicate non-OK-status RPC termination."""
+
+
+##############################  Shared Context  ################################
+
+
+class RpcContext(abc.ABC):
+    """Provides RPC-related information and action."""
+
+    @abc.abstractmethod
+    def is_active(self):
+        """Describes whether the RPC is active or has terminated.
+
+        Returns:
+          bool:
+          True if RPC is active, False otherwise.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def time_remaining(self):
+        """Describes the length of allowed time remaining for the RPC.
+
+        Returns:
+          A nonnegative float indicating the length of allowed time in seconds
+          remaining for the RPC to complete before it is considered to have
+          timed out, or None if no deadline was specified for the RPC.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def cancel(self):
+        """Cancels the RPC.
+
+        Idempotent and has no effect if the RPC has already terminated.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def add_callback(self, callback):
+        """Registers a callback to be called on RPC termination.
+
+        Args:
+          callback: A no-parameter callable to be called on RPC termination.
+
+        Returns:
+          True if the callback was added and will be called later; False if
+            the callback was not added and will not be called (because the RPC
+            already terminated or some other reason).
+        """
+        raise NotImplementedError()
+
+
+#########################  Invocation-Side Context  ############################
+
+
+class Call(RpcContext, metaclass=abc.ABCMeta):
+    """Invocation-side utility object for an RPC."""
+
+    @abc.abstractmethod
+    def initial_metadata(self):
+        """Accesses the initial metadata sent by the server.
+
+        This method blocks until the value is available.
+
+        Returns:
+          The initial :term:`metadata`.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def trailing_metadata(self):
+        """Accesses the trailing metadata sent by the server.
+
+        This method blocks until the value is available.
+
+        Returns:
+          The trailing :term:`metadata`.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def code(self):
+        """Accesses the status code sent by the server.
+
+        This method blocks until the value is available.
+
+        Returns:
+          The StatusCode value for the RPC.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def details(self):
+        """Accesses the details sent by the server.
+
+        This method blocks until the value is available.
+
+        Returns:
+          The details string of the RPC.
+        """
+        raise NotImplementedError()
+
+
+##############  Invocation-Side Interceptor Interfaces & Classes  ##############
+
+
+class ClientCallDetails(abc.ABC):
+    """Describes an RPC to be invoked.
+
+    Attributes:
+      method: The method name of the RPC.
+      timeout: An optional duration of time in seconds to allow for the RPC.
+      metadata: Optional :term:`metadata` to be transmitted to
+        the service-side of the RPC.
+      credentials: An optional CallCredentials for the RPC.
+      wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
+      compression: An element of grpc.Compression, e.g.
+        grpc.Compression.Gzip.
+    """
+
+
+class UnaryUnaryClientInterceptor(abc.ABC):
+    """Affords intercepting unary-unary invocations."""
+
+    @abc.abstractmethod
+    def intercept_unary_unary(self, continuation, client_call_details, request):
+        """Intercepts a unary-unary invocation asynchronously.
+
+        Args:
+          continuation: A function that proceeds with the invocation by
+            executing the next interceptor in chain or invoking the
+            actual RPC on the underlying Channel. It is the interceptor's
+            responsibility to call it if it decides to move the RPC forward.
+            The interceptor can use
+            `response_future = continuation(client_call_details, request)`
+            to continue with the RPC. `continuation` returns an object that is
+            both a Call for the RPC and a Future. In the event of RPC
+            completion, the return Call-Future's result value will be
+            the response message of the RPC. Should the event terminate
+            with non-OK status, the returned Call-Future's exception value
+            will be an RpcError.
+          client_call_details: A ClientCallDetails object describing the
+            outgoing RPC.
+          request: The request value for the RPC.
+
+        Returns:
+            An object that is both a Call for the RPC and a Future.
+            In the event of RPC completion, the return Call-Future's
+            result value will be the response message of the RPC.
+            Should the event terminate with non-OK status, the returned
+            Call-Future's exception value will be an RpcError.
+        """
+        raise NotImplementedError()
+
+
+class UnaryStreamClientInterceptor(abc.ABC):
+    """Affords intercepting unary-stream invocations."""
+
+    @abc.abstractmethod
+    def intercept_unary_stream(
+        self, continuation, client_call_details, request
+    ):
+        """Intercepts a unary-stream invocation.
+
+        Args:
+          continuation: A function that proceeds with the invocation by
+            executing the next interceptor in chain or invoking the
+            actual RPC on the underlying Channel. It is the interceptor's
+            responsibility to call it if it decides to move the RPC forward.
+            The interceptor can use
+            `response_iterator = continuation(client_call_details, request)`
+            to continue with the RPC. `continuation` returns an object that is
+            both a Call for the RPC and an iterator for response values.
+            Drawing response values from the returned Call-iterator may
+            raise RpcError indicating termination of the RPC with non-OK
+            status.
+          client_call_details: A ClientCallDetails object describing the
+            outgoing RPC.
+          request: The request value for the RPC.
+
+        Returns:
+            An object that is both a Call for the RPC and an iterator of
+            response values. Drawing response values from the returned
+            Call-iterator may raise RpcError indicating termination of
+            the RPC with non-OK status. This object *should* also fulfill the
+            Future interface, though it may not.
+        """
+        raise NotImplementedError()
+
+
+class StreamUnaryClientInterceptor(abc.ABC):
+    """Affords intercepting stream-unary invocations."""
+
+    @abc.abstractmethod
+    def intercept_stream_unary(
+        self, continuation, client_call_details, request_iterator
+    ):
+        """Intercepts a stream-unary invocation asynchronously.
+
+        Args:
+          continuation: A function that proceeds with the invocation by
+            executing the next interceptor in chain or invoking the
+            actual RPC on the underlying Channel. It is the interceptor's
+            responsibility to call it if it decides to move the RPC forward.
+            The interceptor can use
+            `response_future = continuation(client_call_details, request_iterator)`
+            to continue with the RPC. `continuation` returns an object that is
+            both a Call for the RPC and a Future. In the event of RPC completion,
+            the return Call-Future's result value will be the response message
+            of the RPC. Should the event terminate with non-OK status, the
+            returned Call-Future's exception value will be an RpcError.
+          client_call_details: A ClientCallDetails object describing the
+            outgoing RPC.
+          request_iterator: An iterator that yields request values for the RPC.
+
+        Returns:
+          An object that is both a Call for the RPC and a Future.
+          In the event of RPC completion, the return Call-Future's
+          result value will be the response message of the RPC.
+          Should the event terminate with non-OK status, the returned
+          Call-Future's exception value will be an RpcError.
+        """
+        raise NotImplementedError()
+
+
+class StreamStreamClientInterceptor(abc.ABC):
+    """Affords intercepting stream-stream invocations."""
+
+    @abc.abstractmethod
+    def intercept_stream_stream(
+        self, continuation, client_call_details, request_iterator
+    ):
+        """Intercepts a stream-stream invocation.
+
+        Args:
+          continuation: A function that proceeds with the invocation by
+            executing the next interceptor in chain or invoking the
+            actual RPC on the underlying Channel. It is the interceptor's
+            responsibility to call it if it decides to move the RPC forward.
+            The interceptor can use
+            `response_iterator = continuation(client_call_details, request_iterator)`
+            to continue with the RPC. `continuation` returns an object that is
+            both a Call for the RPC and an iterator for response values.
+            Drawing response values from the returned Call-iterator may
+            raise RpcError indicating termination of the RPC with non-OK
+            status.
+          client_call_details: A ClientCallDetails object describing the
+            outgoing RPC.
+          request_iterator: An iterator that yields request values for the RPC.
+
+        Returns:
+          An object that is both a Call for the RPC and an iterator of
+          response values. Drawing response values from the returned
+          Call-iterator may raise RpcError indicating termination of
+          the RPC with non-OK status. This object *should* also fulfill the
+          Future interface, though it may not.
+        """
+        raise NotImplementedError()
+
+
+############  Authentication & Authorization Interfaces & Classes  #############
+
+
+class ChannelCredentials(object):
+    """An encapsulation of the data required to create a secure Channel.
+
+    This class has no supported interface - it exists to define the type of its
+    instances and its instances exist to be passed to other functions. For
+    example, ssl_channel_credentials returns an instance of this class and
+    secure_channel requires an instance of this class.
+    """
+
+    def __init__(self, credentials):
+        self._credentials = credentials
+
+
+class CallCredentials(object):
+    """An encapsulation of the data required to assert an identity over a call.
+
+    A CallCredentials has to be used with secure Channel, otherwise the
+    metadata will not be transmitted to the server.
+
+    A CallCredentials may be composed with ChannelCredentials to always assert
+    identity for every call over that Channel.
+
+    This class has no supported interface - it exists to define the type of its
+    instances and its instances exist to be passed to other functions.
+    """
+
+    def __init__(self, credentials):
+        self._credentials = credentials
+
+
+class AuthMetadataContext(abc.ABC):
+    """Provides information to call credentials metadata plugins.
+
+    Attributes:
+      service_url: A string URL of the service being called into.
+      method_name: A string of the fully qualified method name being called.
+    """
+
+
+class AuthMetadataPluginCallback(abc.ABC):
+    """Callback object received by a metadata plugin."""
+
+    def __call__(self, metadata, error):
+        """Passes to the gRPC runtime authentication metadata for an RPC.
+
+        Args:
+          metadata: The :term:`metadata` used to construct the CallCredentials.
+          error: An Exception to indicate error or None to indicate success.
+        """
+        raise NotImplementedError()
+
+
+class AuthMetadataPlugin(abc.ABC):
+    """A specification for custom authentication."""
+
+    def __call__(self, context, callback):
+        """Implements authentication by passing metadata to a callback.
+
+        This method will be invoked asynchronously in a separate thread.
+
+        Args:
+          context: An AuthMetadataContext providing information on the RPC that
+            the plugin is being called to authenticate.
+          callback: An AuthMetadataPluginCallback to be invoked either
+            synchronously or asynchronously.
+        """
+        raise NotImplementedError()
+
+
+class ServerCredentials(object):
+    """An encapsulation of the data required to open a secure port on a Server.
+
+    This class has no supported interface - it exists to define the type of its
+    instances and its instances exist to be passed to other functions.
+    """
+
+    def __init__(self, credentials):
+        self._credentials = credentials
+
+
+class ServerCertificateConfiguration(object):
+    """A certificate configuration for use with an SSL-enabled Server.
+
+    Instances of this class can be returned in the certificate configuration
+    fetching callback.
+
+    This class has no supported interface -- it exists to define the
+    type of its instances and its instances exist to be passed to
+    other functions.
+    """
+
+    def __init__(self, certificate_configuration):
+        self._certificate_configuration = certificate_configuration
+
+
+########################  Multi-Callable Interfaces  ###########################
+
+
+class UnaryUnaryMultiCallable(abc.ABC):
+    """Affords invoking a unary-unary RPC from client-side."""
+
+    @abc.abstractmethod
+    def __call__(
+        self,
+        request,
+        timeout=None,
+        metadata=None,
+        credentials=None,
+        wait_for_ready=None,
+        compression=None,
+    ):
+        """Synchronously invokes the underlying RPC.
+
+        Args:
+          request: The request value for the RPC.
+          timeout: An optional duration of time in seconds to allow
+            for the RPC.
+          metadata: Optional :term:`metadata` to be transmitted to the
+            service-side of the RPC.
+          credentials: An optional CallCredentials for the RPC. Only valid for
+            secure Channel.
+          wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
+          compression: An element of grpc.Compression, e.g.
+            grpc.Compression.Gzip.
+
+        Returns:
+          The response value for the RPC.
+
+        Raises:
+          RpcError: Indicating that the RPC terminated with non-OK status. The
+            raised RpcError will also be a Call for the RPC affording the RPC's
+            metadata, status code, and details.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def with_call(
+        self,
+        request,
+        timeout=None,
+        metadata=None,
+        credentials=None,
+        wait_for_ready=None,
+        compression=None,
+    ):
+        """Synchronously invokes the underlying RPC.
+
+        Args:
+          request: The request value for the RPC.
+          timeout: An optional durating of time in seconds to allow for
+            the RPC.
+          metadata: Optional :term:`metadata` to be transmitted to the
+            service-side of the RPC.
+          credentials: An optional CallCredentials for the RPC. Only valid for
+            secure Channel.
+          wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
+          compression: An element of grpc.Compression, e.g.
+            grpc.Compression.Gzip.
+
+        Returns:
+          The response value for the RPC and a Call value for the RPC.
+
+        Raises:
+          RpcError: Indicating that the RPC terminated with non-OK status. The
+            raised RpcError will also be a Call for the RPC affording the RPC's
+            metadata, status code, and details.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def future(
+        self,
+        request,
+        timeout=None,
+        metadata=None,
+        credentials=None,
+        wait_for_ready=None,
+        compression=None,
+    ):
+        """Asynchronously invokes the underlying RPC.
+
+        Args:
+          request: The request value for the RPC.
+          timeout: An optional duration of time in seconds to allow for
+            the RPC.
+          metadata: Optional :term:`metadata` to be transmitted to the
+            service-side of the RPC.
+          credentials: An optional CallCredentials for the RPC. Only valid for
+            secure Channel.
+          wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
+          compression: An element of grpc.Compression, e.g.
+            grpc.Compression.Gzip.
+
+        Returns:
+            An object that is both a Call for the RPC and a Future.
+            In the event of RPC completion, the return Call-Future's result
+            value will be the response message of the RPC.
+            Should the event terminate with non-OK status,
+            the returned Call-Future's exception value will be an RpcError.
+        """
+        raise NotImplementedError()
+
+
+class UnaryStreamMultiCallable(abc.ABC):
+    """Affords invoking a unary-stream RPC from client-side."""
+
+    @abc.abstractmethod
+    def __call__(
+        self,
+        request,
+        timeout=None,
+        metadata=None,
+        credentials=None,
+        wait_for_ready=None,
+        compression=None,
+    ):
+        """Invokes the underlying RPC.
+
+        Args:
+          request: The request value for the RPC.
+          timeout: An optional duration of time in seconds to allow for
+            the RPC. If None, the timeout is considered infinite.
+          metadata: An optional :term:`metadata` to be transmitted to the
+            service-side of the RPC.
+          credentials: An optional CallCredentials for the RPC. Only valid for
+            secure Channel.
+          wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
+          compression: An element of grpc.Compression, e.g.
+            grpc.Compression.Gzip.
+
+        Returns:
+            An object that is a Call for the RPC, an iterator of response
+            values, and a Future for the RPC. Drawing response values from the
+            returned Call-iterator may raise RpcError indicating termination of
+            the RPC with non-OK status.
+        """
+        raise NotImplementedError()
+
+
+class StreamUnaryMultiCallable(abc.ABC):
+    """Affords invoking a stream-unary RPC from client-side."""
+
+    @abc.abstractmethod
+    def __call__(
+        self,
+        request_iterator,
+        timeout=None,
+        metadata=None,
+        credentials=None,
+        wait_for_ready=None,
+        compression=None,
+    ):
+        """Synchronously invokes the underlying RPC.
+
+        Args:
+          request_iterator: An iterator that yields request values for
+            the RPC.
+          timeout: An optional duration of time in seconds to allow for
+            the RPC. If None, the timeout is considered infinite.
+          metadata: Optional :term:`metadata` to be transmitted to the
+            service-side of the RPC.
+          credentials: An optional CallCredentials for the RPC. Only valid for
+            secure Channel.
+          wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
+          compression: An element of grpc.Compression, e.g.
+            grpc.Compression.Gzip.
+
+        Returns:
+          The response value for the RPC.
+
+        Raises:
+          RpcError: Indicating that the RPC terminated with non-OK status. The
+            raised RpcError will also implement grpc.Call, affording methods
+            such as metadata, code, and details.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def with_call(
+        self,
+        request_iterator,
+        timeout=None,
+        metadata=None,
+        credentials=None,
+        wait_for_ready=None,
+        compression=None,
+    ):
+        """Synchronously invokes the underlying RPC on the client.
+
+        Args:
+          request_iterator: An iterator that yields request values for
+            the RPC.
+          timeout: An optional duration of time in seconds to allow for
+            the RPC. If None, the timeout is considered infinite.
+          metadata: Optional :term:`metadata` to be transmitted to the
+            service-side of the RPC.
+          credentials: An optional CallCredentials for the RPC. Only valid for
+            secure Channel.
+          wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
+          compression: An element of grpc.Compression, e.g.
+            grpc.Compression.Gzip.
+
+        Returns:
+          The response value for the RPC and a Call object for the RPC.
+
+        Raises:
+          RpcError: Indicating that the RPC terminated with non-OK status. The
+            raised RpcError will also be a Call for the RPC affording the RPC's
+            metadata, status code, and details.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def future(
+        self,
+        request_iterator,
+        timeout=None,
+        metadata=None,
+        credentials=None,
+        wait_for_ready=None,
+        compression=None,
+    ):
+        """Asynchronously invokes the underlying RPC on the client.
+
+        Args:
+          request_iterator: An iterator that yields request values for the RPC.
+          timeout: An optional duration of time in seconds to allow for
+            the RPC. If None, the timeout is considered infinite.
+          metadata: Optional :term:`metadata` to be transmitted to the
+            service-side of the RPC.
+          credentials: An optional CallCredentials for the RPC. Only valid for
+            secure Channel.
+          wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
+          compression: An element of grpc.Compression, e.g.
+            grpc.Compression.Gzip.
+
+        Returns:
+            An object that is both a Call for the RPC and a Future.
+            In the event of RPC completion, the return Call-Future's result value
+            will be the response message of the RPC. Should the event terminate
+            with non-OK status, the returned Call-Future's exception value will
+            be an RpcError.
+        """
+        raise NotImplementedError()
+
+
+class StreamStreamMultiCallable(abc.ABC):
+    """Affords invoking a stream-stream RPC on client-side."""
+
+    @abc.abstractmethod
+    def __call__(
+        self,
+        request_iterator,
+        timeout=None,
+        metadata=None,
+        credentials=None,
+        wait_for_ready=None,
+        compression=None,
+    ):
+        """Invokes the underlying RPC on the client.
+
+        Args:
+          request_iterator: An iterator that yields request values for the RPC.
+          timeout: An optional duration of time in seconds to allow for
+            the RPC. If not specified, the timeout is considered infinite.
+          metadata: Optional :term:`metadata` to be transmitted to the
+            service-side of the RPC.
+          credentials: An optional CallCredentials for the RPC. Only valid for
+            secure Channel.
+          wait_for_ready: An optional flag to enable :term:`wait_for_ready` mechanism.
+          compression: An element of grpc.Compression, e.g.
+            grpc.Compression.Gzip.
+
+        Returns:
+            An object that is a Call for the RPC, an iterator of response
+            values, and a Future for the RPC. Drawing response values from the
+            returned Call-iterator may raise RpcError indicating termination of
+            the RPC with non-OK status.
+        """
+        raise NotImplementedError()
+
+
+#############################  Channel Interface  ##############################
+
+
+class Channel(abc.ABC):
+    """Affords RPC invocation via generic methods on client-side.
+
+    Channel objects implement the Context Manager type, although they need not
+    support being entered and exited multiple times.
+    """
+
+    @abc.abstractmethod
+    def subscribe(self, callback, try_to_connect=False):
+        """Subscribe to this Channel's connectivity state machine.
+
+        A Channel may be in any of the states described by ChannelConnectivity.
+        This method allows application to monitor the state transitions.
+        The typical use case is to debug or gain better visibility into gRPC
+        runtime's state.
+
+        Args:
+          callback: A callable to be invoked with ChannelConnectivity argument.
+            ChannelConnectivity describes current state of the channel.
+            The callable will be invoked immediately upon subscription
+            and again for every change to ChannelConnectivity until it
+            is unsubscribed or this Channel object goes out of scope.
+          try_to_connect: A boolean indicating whether or not this Channel
+            should attempt to connect immediately. If set to False, gRPC
+            runtime decides when to connect.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def unsubscribe(self, callback):
+        """Unsubscribes a subscribed callback from this Channel's connectivity.
+
+        Args:
+          callback: A callable previously registered with this Channel from
+          having been passed to its "subscribe" method.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def unary_unary(
+        self,
+        method,
+        request_serializer=None,
+        response_deserializer=None,
+        _registered_method=False,
+    ):
+        """Creates a UnaryUnaryMultiCallable for a unary-unary method.
+
+        Args:
+          method: The name of the RPC method.
+          request_serializer: Optional :term:`serializer` for serializing the request
+            message. Request goes unserialized in case None is passed.
+          response_deserializer: Optional :term:`deserializer` for deserializing the
+            response message. Response goes undeserialized in case None
+            is passed.
+          _registered_method: Implementation Private. A bool representing whether the method
+            is registered.
+
+        Returns:
+          A UnaryUnaryMultiCallable value for the named unary-unary method.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def unary_stream(
+        self,
+        method,
+        request_serializer=None,
+        response_deserializer=None,
+        _registered_method=False,
+    ):
+        """Creates a UnaryStreamMultiCallable for a unary-stream method.
+
+        Args:
+          method: The name of the RPC method.
+          request_serializer: Optional :term:`serializer` for serializing the request
+            message. Request goes unserialized in case None is passed.
+          response_deserializer: Optional :term:`deserializer` for deserializing the
+            response message. Response goes undeserialized in case None is
+            passed.
+          _registered_method: Implementation Private. A bool representing whether the method
+            is registered.
+
+        Returns:
+          A UnaryStreamMultiCallable value for the name unary-stream method.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def stream_unary(
+        self,
+        method,
+        request_serializer=None,
+        response_deserializer=None,
+        _registered_method=False,
+    ):
+        """Creates a StreamUnaryMultiCallable for a stream-unary method.
+
+        Args:
+          method: The name of the RPC method.
+          request_serializer: Optional :term:`serializer` for serializing the request
+            message. Request goes unserialized in case None is passed.
+          response_deserializer: Optional :term:`deserializer` for deserializing the
+            response message. Response goes undeserialized in case None is
+            passed.
+          _registered_method: Implementation Private. A bool representing whether the method
+            is registered.
+
+        Returns:
+          A StreamUnaryMultiCallable value for the named stream-unary method.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def stream_stream(
+        self,
+        method,
+        request_serializer=None,
+        response_deserializer=None,
+        _registered_method=False,
+    ):
+        """Creates a StreamStreamMultiCallable for a stream-stream method.
+
+        Args:
+          method: The name of the RPC method.
+          request_serializer: Optional :term:`serializer` for serializing the request
+            message. Request goes unserialized in case None is passed.
+          response_deserializer: Optional :term:`deserializer` for deserializing the
+            response message. Response goes undeserialized in case None
+            is passed.
+          _registered_method: Implementation Private. A bool representing whether the method
+            is registered.
+
+        Returns:
+          A StreamStreamMultiCallable value for the named stream-stream method.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def close(self):
+        """Closes this Channel and releases all resources held by it.
+
+        Closing the Channel will immediately terminate all RPCs active with the
+        Channel and it is not valid to invoke new RPCs with the Channel.
+
+        This method is idempotent.
+        """
+        raise NotImplementedError()
+
+    def __enter__(self):
+        """Enters the runtime context related to the channel object."""
+        raise NotImplementedError()
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        """Exits the runtime context related to the channel object."""
+        raise NotImplementedError()
+
+
+##########################  Service-Side Context  ##############################
+
+
+class ServicerContext(RpcContext, metaclass=abc.ABCMeta):
+    """A context object passed to method implementations."""
+
+    @abc.abstractmethod
+    def invocation_metadata(self):
+        """Accesses the metadata sent by the client.
+
+        Returns:
+          The invocation :term:`metadata`.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def peer(self):
+        """Identifies the peer that invoked the RPC being serviced.
+
+        Returns:
+          A string identifying the peer that invoked the RPC being serviced.
+          The string format is determined by gRPC runtime.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def peer_identities(self):
+        """Gets one or more peer identity(s).
+
+        Equivalent to
+        servicer_context.auth_context().get(servicer_context.peer_identity_key())
+
+        Returns:
+          An iterable of the identities, or None if the call is not
+          authenticated. Each identity is returned as a raw bytes type.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def peer_identity_key(self):
+        """The auth property used to identify the peer.
+
+        For example, "x509_common_name" or "x509_subject_alternative_name" are
+        used to identify an SSL peer.
+
+        Returns:
+          The auth property (string) that indicates the
+          peer identity, or None if the call is not authenticated.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def auth_context(self):
+        """Gets the auth context for the call.
+
+        Returns:
+          A map of strings to an iterable of bytes for each auth property.
+        """
+        raise NotImplementedError()
+
+    def set_compression(self, compression):
+        """Set the compression algorithm to be used for the entire call.
+
+        Args:
+          compression: An element of grpc.Compression, e.g.
+            grpc.Compression.Gzip.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def send_initial_metadata(self, initial_metadata):
+        """Sends the initial metadata value to the client.
+
+        This method need not be called by implementations if they have no
+        metadata to add to what the gRPC runtime will transmit.
+
+        Args:
+          initial_metadata: The initial :term:`metadata`.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def set_trailing_metadata(self, trailing_metadata):
+        """Sets the trailing metadata for the RPC.
+
+        Sets the trailing metadata to be sent upon completion of the RPC.
+
+        If this method is invoked multiple times throughout the lifetime of an
+        RPC, the value supplied in the final invocation will be the value sent
+        over the wire.
+
+        This method need not be called by implementations if they have no
+        metadata to add to what the gRPC runtime will transmit.
+
+        Args:
+          trailing_metadata: The trailing :term:`metadata`.
+        """
+        raise NotImplementedError()
+
+    def trailing_metadata(self):
+        """Access value to be used as trailing metadata upon RPC completion.
+
+        This is an EXPERIMENTAL API.
+
+        Returns:
+          The trailing :term:`metadata` for the RPC.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def abort(self, code, details):
+        """Raises an exception to terminate the RPC with a non-OK status.
+
+        The code and details passed as arguments will supersede any existing
+        ones.
+
+        Args:
+          code: A StatusCode object to be sent to the client.
+            It must not be StatusCode.OK.
+          details: A UTF-8-encodable string to be sent to the client upon
+            termination of the RPC.
+
+        Raises:
+          Exception: An exception is always raised to signal the abortion the
+            RPC to the gRPC runtime.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def abort_with_status(self, status):
+        """Raises an exception to terminate the RPC with a non-OK status.
+
+        The status passed as argument will supersede any existing status code,
+        status message and trailing metadata.
+
+        This is an EXPERIMENTAL API.
+
+        Args:
+          status: A grpc.Status object. The status code in it must not be
+            StatusCode.OK.
+
+        Raises:
+          Exception: An exception is always raised to signal the abortion the
+            RPC to the gRPC runtime.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def set_code(self, code):
+        """Sets the value to be used as status code upon RPC completion.
+
+        This method need not be called by method implementations if they wish
+        the gRPC runtime to determine the status code of the RPC.
+
+        Args:
+          code: A StatusCode object to be sent to the client.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def set_details(self, details):
+        """Sets the value to be used as detail string upon RPC completion.
+
+        This method need not be called by method implementations if they have
+        no details to transmit.
+
+        Args:
+          details: A UTF-8-encodable string to be sent to the client upon
+            termination of the RPC.
+        """
+        raise NotImplementedError()
+
+    def code(self):
+        """Accesses the value to be used as status code upon RPC completion.
+
+        This is an EXPERIMENTAL API.
+
+        Returns:
+          The StatusCode value for the RPC.
+        """
+        raise NotImplementedError()
+
+    def details(self):
+        """Accesses the value to be used as detail string upon RPC completion.
+
+        This is an EXPERIMENTAL API.
+
+        Returns:
+          The details string of the RPC.
+        """
+        raise NotImplementedError()
+
+    def disable_next_message_compression(self):
+        """Disables compression for the next response message.
+
+        This method will override any compression configuration set during
+        server creation or set on the call.
+        """
+        raise NotImplementedError()
+
+
+#####################  Service-Side Handler Interfaces  ########################
+
+
+class RpcMethodHandler(abc.ABC):
+    """An implementation of a single RPC method.
+
+    Attributes:
+      request_streaming: Whether the RPC supports exactly one request message
+        or any arbitrary number of request messages.
+      response_streaming: Whether the RPC supports exactly one response message
+        or any arbitrary number of response messages.
+      request_deserializer: A callable :term:`deserializer` that accepts a byte string and
+        returns an object suitable to be passed to this object's business
+        logic, or None to indicate that this object's business logic should be
+        passed the raw request bytes.
+      response_serializer: A callable :term:`serializer` that accepts an object produced
+        by this object's business logic and returns a byte string, or None to
+        indicate that the byte strings produced by this object's business logic
+        should be transmitted on the wire as they are.
+      unary_unary: This object's application-specific business logic as a
+        callable value that takes a request value and a ServicerContext object
+        and returns a response value. Only non-None if both request_streaming
+        and response_streaming are False.
+      unary_stream: This object's application-specific business logic as a
+        callable value that takes a request value and a ServicerContext object
+        and returns an iterator of response values. Only non-None if
+        request_streaming is False and response_streaming is True.
+      stream_unary: This object's application-specific business logic as a
+        callable value that takes an iterator of request values and a
+        ServicerContext object and returns a response value. Only non-None if
+        request_streaming is True and response_streaming is False.
+      stream_stream: This object's application-specific business logic as a
+        callable value that takes an iterator of request values and a
+        ServicerContext object and returns an iterator of response values.
+        Only non-None if request_streaming and response_streaming are both
+        True.
+    """
+
+
+class HandlerCallDetails(abc.ABC):
+    """Describes an RPC that has just arrived for service.
+
+    Attributes:
+      method: The method name of the RPC.
+      invocation_metadata: The :term:`metadata` sent by the client.
+    """
+
+
+class GenericRpcHandler(abc.ABC):
+    """An implementation of arbitrarily many RPC methods."""
+
+    @abc.abstractmethod
+    def service(self, handler_call_details):
+        """Returns the handler for servicing the RPC.
+
+        Args:
+          handler_call_details: A HandlerCallDetails describing the RPC.
+
+        Returns:
+          An RpcMethodHandler with which the RPC may be serviced if the
+          implementation chooses to service this RPC, or None otherwise.
+        """
+        raise NotImplementedError()
+
+
+class ServiceRpcHandler(GenericRpcHandler, metaclass=abc.ABCMeta):
+    """An implementation of RPC methods belonging to a service.
+
+    A service handles RPC methods with structured names of the form
+    '/Service.Name/Service.Method', where 'Service.Name' is the value
+    returned by service_name(), and 'Service.Method' is the method
+    name.  A service can have multiple method names, but only a single
+    service name.
+    """
+
+    @abc.abstractmethod
+    def service_name(self):
+        """Returns this service's name.
+
+        Returns:
+          The service name.
+        """
+        raise NotImplementedError()
+
+
+####################  Service-Side Interceptor Interfaces  #####################
+
+
+class ServerInterceptor(abc.ABC):
+    """Affords intercepting incoming RPCs on the service-side."""
+
+    @abc.abstractmethod
+    def intercept_service(self, continuation, handler_call_details):
+        """Intercepts incoming RPCs before handing them over to a handler.
+
+        State can be passed from an interceptor to downstream interceptors
+        via contextvars. The first interceptor is called from an empty
+        contextvars.Context, and the same Context is used for downstream
+        interceptors and for the final handler call. Note that there are no
+        guarantees that interceptors and handlers will be called from the
+        same thread.
+
+        Args:
+          continuation: A function that takes a HandlerCallDetails and
+            proceeds to invoke the next interceptor in the chain, if any,
+            or the RPC handler lookup logic, with the call details passed
+            as an argument, and returns an RpcMethodHandler instance if
+            the RPC is considered serviced, or None otherwise.
+          handler_call_details: A HandlerCallDetails describing the RPC.
+
+        Returns:
+          An RpcMethodHandler with which the RPC may be serviced if the
+          interceptor chooses to service this RPC, or None otherwise.
+        """
+        raise NotImplementedError()
+
+
+#############################  Server Interface  ###############################
+
+
+class Server(abc.ABC):
+    """Services RPCs."""
+
+    @abc.abstractmethod
+    def add_generic_rpc_handlers(self, generic_rpc_handlers):
+        """Registers GenericRpcHandlers with this Server.
+
+        This method is only safe to call before the server is started.
+
+        Args:
+          generic_rpc_handlers: An iterable of GenericRpcHandlers that will be
+          used to service RPCs.
+        """
+        raise NotImplementedError()
+
+    def add_registered_method_handlers(  # noqa: B027
+        self, service_name, method_handlers
+    ):
+        """Registers GenericRpcHandlers with this Server.
+
+        This method is only safe to call before the server is started.
+
+        If the same method have both generic and registered handler,
+        registered handler will take precedence.
+
+        Args:
+          service_name: The service name.
+          method_handlers: A dictionary that maps method names to corresponding
+            RpcMethodHandler.
+        """
+
+    @abc.abstractmethod
+    def add_insecure_port(self, address):
+        """Opens an insecure port for accepting RPCs.
+
+        This method may only be called before starting the server.
+
+        Args:
+          address: The address for which to open a port. If the port is 0,
+            or not specified in the address, then gRPC runtime will choose a port.
+
+        Returns:
+          An integer port on which server will accept RPC requests.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def add_secure_port(self, address, server_credentials):
+        """Opens a secure port for accepting RPCs.
+
+        This method may only be called before starting the server.
+
+        Args:
+          address: The address for which to open a port.
+            if the port is 0, or not specified in the address, then gRPC
+            runtime will choose a port.
+          server_credentials: A ServerCredentials object.
+
+        Returns:
+          An integer port on which server will accept RPC requests.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def start(self):
+        """Starts this Server.
+
+        This method may only be called once. (i.e. it is not idempotent).
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def stop(self, grace):
+        """Stops this Server.
+
+        This method immediately stop service of new RPCs in all cases.
+
+        If a grace period is specified, this method waits until all active
+        RPCs are finished or until the grace period is reached. RPCs that haven't
+        been terminated within the grace period are aborted.
+        If a grace period is not specified (by passing None for `grace`),
+        all existing RPCs are aborted immediately and this method
+        blocks until the last RPC handler terminates.
+
+        This method is idempotent and may be called at any time.
+        Passing a smaller grace value in a subsequent call will have
+        the effect of stopping the Server sooner (passing None will
+        have the effect of stopping the server immediately). Passing
+        a larger grace value in a subsequent call *will not* have the
+        effect of stopping the server later (i.e. the most restrictive
+        grace value is used).
+
+        Args:
+          grace: A duration of time in seconds or None.
+
+        Returns:
+          A threading.Event that will be set when this Server has completely
+          stopped, i.e. when running RPCs either complete or are aborted and
+          all handlers have terminated.
+        """
+        raise NotImplementedError()
+
+    def wait_for_termination(self, timeout=None):
+        """Block current thread until the server stops.
+
+        This is an EXPERIMENTAL API.
+
+        The wait will not consume computational resources during blocking, and
+        it will block until one of the two following conditions are met:
+
+        1) The server is stopped or terminated;
+        2) A timeout occurs if timeout is not `None`.
+
+        The timeout argument works in the same way as `threading.Event.wait()`.
+        https://docs.python.org/3/library/threading.html#threading.Event.wait
+
+        Args:
+          timeout: A floating point number specifying a timeout for the
+            operation in seconds.
+
+        Returns:
+          A bool indicates if the operation times out.
+        """
+        raise NotImplementedError()
+
+
+#################################  Functions    ################################
+
+
+def unary_unary_rpc_method_handler(
+    behavior, request_deserializer=None, response_serializer=None
+):
+    """Creates an RpcMethodHandler for a unary-unary RPC method.
+
+    Args:
+      behavior: The implementation of an RPC that accepts one request
+        and returns one response.
+      request_deserializer: An optional :term:`deserializer` for request deserialization.
+      response_serializer: An optional :term:`serializer` for response serialization.
+
+    Returns:
+      An RpcMethodHandler object that is typically used by grpc.Server.
+    """
+    from grpc import _utilities  # pylint: disable=cyclic-import
+
+    return _utilities.RpcMethodHandler(
+        False,
+        False,
+        request_deserializer,
+        response_serializer,
+        behavior,
+        None,
+        None,
+        None,
+    )
+
+
+def unary_stream_rpc_method_handler(
+    behavior, request_deserializer=None, response_serializer=None
+):
+    """Creates an RpcMethodHandler for a unary-stream RPC method.
+
+    Args:
+      behavior: The implementation of an RPC that accepts one request
+        and returns an iterator of response values.
+      request_deserializer: An optional :term:`deserializer` for request deserialization.
+      response_serializer: An optional :term:`serializer` for response serialization.
+
+    Returns:
+      An RpcMethodHandler object that is typically used by grpc.Server.
+    """
+    from grpc import _utilities  # pylint: disable=cyclic-import
+
+    return _utilities.RpcMethodHandler(
+        False,
+        True,
+        request_deserializer,
+        response_serializer,
+        None,
+        behavior,
+        None,
+        None,
+    )
+
+
+def stream_unary_rpc_method_handler(
+    behavior, request_deserializer=None, response_serializer=None
+):
+    """Creates an RpcMethodHandler for a stream-unary RPC method.
+
+    Args:
+      behavior: The implementation of an RPC that accepts an iterator of
+        request values and returns a single response value.
+      request_deserializer: An optional :term:`deserializer` for request deserialization.
+      response_serializer: An optional :term:`serializer` for response serialization.
+
+    Returns:
+      An RpcMethodHandler object that is typically used by grpc.Server.
+    """
+    from grpc import _utilities  # pylint: disable=cyclic-import
+
+    return _utilities.RpcMethodHandler(
+        True,
+        False,
+        request_deserializer,
+        response_serializer,
+        None,
+        None,
+        behavior,
+        None,
+    )
+
+
+def stream_stream_rpc_method_handler(
+    behavior, request_deserializer=None, response_serializer=None
+):
+    """Creates an RpcMethodHandler for a stream-stream RPC method.
+
+    Args:
+      behavior: The implementation of an RPC that accepts an iterator of
+        request values and returns an iterator of response values.
+      request_deserializer: An optional :term:`deserializer` for request deserialization.
+      response_serializer: An optional :term:`serializer` for response serialization.
+
+    Returns:
+      An RpcMethodHandler object that is typically used by grpc.Server.
+    """
+    from grpc import _utilities  # pylint: disable=cyclic-import
+
+    return _utilities.RpcMethodHandler(
+        True,
+        True,
+        request_deserializer,
+        response_serializer,
+        None,
+        None,
+        None,
+        behavior,
+    )
+
+
+def method_handlers_generic_handler(service, method_handlers):
+    """Creates a GenericRpcHandler from RpcMethodHandlers.
+
+    Args:
+      service: The name of the service that is implemented by the
+        method_handlers.
+      method_handlers: A dictionary that maps method names to corresponding
+        RpcMethodHandler.
+
+    Returns:
+      A GenericRpcHandler. This is typically added to the grpc.Server object
+      with add_generic_rpc_handlers() before starting the server.
+    """
+    from grpc import _utilities  # pylint: disable=cyclic-import
+
+    return _utilities.DictionaryGenericHandler(service, method_handlers)
+
+
+def ssl_channel_credentials(
+    root_certificates=None, private_key=None, certificate_chain=None
+):
+    """Creates a ChannelCredentials for use with an SSL-enabled Channel.
+
+    Args:
+      root_certificates: The PEM-encoded root certificates as a byte string,
+        or None to retrieve them from a default location chosen by gRPC
+        runtime.
+      private_key: The PEM-encoded private key as a byte string, or None if no
+        private key should be used.
+      certificate_chain: The PEM-encoded certificate chain as a byte string
+        to use or None if no certificate chain should be used.
+
+    Returns:
+      A ChannelCredentials for use with an SSL-enabled Channel.
+    """
+    return ChannelCredentials(
+        _cygrpc.SSLChannelCredentials(
+            root_certificates, private_key, certificate_chain
+        )
+    )
+
+
+def xds_channel_credentials(fallback_credentials=None):
+    """Creates a ChannelCredentials for use with xDS. This is an EXPERIMENTAL
+      API.
+
+    Args:
+      fallback_credentials: Credentials to use in case it is not possible to
+        establish a secure connection via xDS. If no fallback_credentials
+        argument is supplied, a default SSLChannelCredentials is used.
+    """
+    fallback_credentials = (
+        ssl_channel_credentials()
+        if fallback_credentials is None
+        else fallback_credentials
+    )
+    return ChannelCredentials(
+        _cygrpc.XDSChannelCredentials(fallback_credentials._credentials)
+    )
+
+
+def metadata_call_credentials(metadata_plugin, name=None):
+    """Construct CallCredentials from an AuthMetadataPlugin.
+
+    Args:
+      metadata_plugin: An AuthMetadataPlugin to use for authentication.
+      name: An optional name for the plugin.
+
+    Returns:
+      A CallCredentials.
+    """
+    from grpc import _plugin_wrapping  # pylint: disable=cyclic-import
+
+    return _plugin_wrapping.metadata_plugin_call_credentials(
+        metadata_plugin, name
+    )
+
+
+def access_token_call_credentials(access_token):
+    """Construct CallCredentials from an access token.
+
+    Args:
+      access_token: A string to place directly in the http request
+        authorization header, for example
+        "authorization: Bearer ".
+
+    Returns:
+      A CallCredentials.
+    """
+    from grpc import _auth  # pylint: disable=cyclic-import
+    from grpc import _plugin_wrapping  # pylint: disable=cyclic-import
+
+    return _plugin_wrapping.metadata_plugin_call_credentials(
+        _auth.AccessTokenAuthMetadataPlugin(access_token), None
+    )
+
+
+def composite_call_credentials(*call_credentials):
+    """Compose multiple CallCredentials to make a new CallCredentials.
+
+    Args:
+      *call_credentials: At least two CallCredentials objects.
+
+    Returns:
+      A CallCredentials object composed of the given CallCredentials objects.
+    """
+    return CallCredentials(
+        _cygrpc.CompositeCallCredentials(
+            tuple(
+                single_call_credentials._credentials
+                for single_call_credentials in call_credentials
+            )
+        )
+    )
+
+
+def composite_channel_credentials(channel_credentials, *call_credentials):
+    """Compose a ChannelCredentials and one or more CallCredentials objects.
+
+    Args:
+      channel_credentials: A ChannelCredentials object.
+      *call_credentials: One or more CallCredentials objects.
+
+    Returns:
+      A ChannelCredentials composed of the given ChannelCredentials and
+        CallCredentials objects.
+    """
+    return ChannelCredentials(
+        _cygrpc.CompositeChannelCredentials(
+            tuple(
+                single_call_credentials._credentials
+                for single_call_credentials in call_credentials
+            ),
+            channel_credentials._credentials,
+        )
+    )
+
+
+def ssl_server_credentials(
+    private_key_certificate_chain_pairs,
+    root_certificates=None,
+    require_client_auth=False,
+):
+    """Creates a ServerCredentials for use with an SSL-enabled Server.
+
+    Args:
+      private_key_certificate_chain_pairs: A list of pairs of the form
+        [PEM-encoded private key, PEM-encoded certificate chain].
+      root_certificates: An optional byte string of PEM-encoded client root
+        certificates that the server will use to verify client authentication.
+        If omitted, require_client_auth must also be False.
+      require_client_auth: A boolean indicating whether or not to require
+        clients to be authenticated. May only be True if root_certificates
+        is not None.
+
+    Returns:
+      A ServerCredentials for use with an SSL-enabled Server. Typically, this
+      object is an argument to add_secure_port() method during server setup.
+    """
+    if not private_key_certificate_chain_pairs:
+        error_msg = (
+            "At least one private key-certificate chain pair is required!"
+        )
+        raise ValueError(error_msg)
+    if require_client_auth and root_certificates is None:
+        error_msg = "Illegal to require client auth without providing root certificates!"
+        raise ValueError(error_msg)
+    return ServerCredentials(
+        _cygrpc.server_credentials_ssl(
+            root_certificates,
+            [
+                _cygrpc.SslPemKeyCertPair(key, pem)
+                for key, pem in private_key_certificate_chain_pairs
+            ],
+            require_client_auth,
+        )
+    )
+
+
+def xds_server_credentials(fallback_credentials):
+    """Creates a ServerCredentials for use with xDS. This is an EXPERIMENTAL
+      API.
+
+    Args:
+      fallback_credentials: Credentials to use in case it is not possible to
+        establish a secure connection via xDS. No default value is provided.
+    """
+    return ServerCredentials(
+        _cygrpc.xds_server_credentials(fallback_credentials._credentials)
+    )
+
+
+def insecure_server_credentials():
+    """Creates a credentials object directing the server to use no credentials.
+      This is an EXPERIMENTAL API.
+
+    This object cannot be used directly in a call to `add_secure_port`.
+    Instead, it should be used to construct other credentials objects, e.g.
+    with xds_server_credentials.
+    """
+    return ServerCredentials(_cygrpc.insecure_server_credentials())
+
+
+def ssl_server_certificate_configuration(
+    private_key_certificate_chain_pairs, root_certificates=None
+):
+    """Creates a ServerCertificateConfiguration for use with a Server.
+
+    Args:
+      private_key_certificate_chain_pairs: A collection of pairs of
+        the form [PEM-encoded private key, PEM-encoded certificate
+        chain].
+      root_certificates: An optional byte string of PEM-encoded client root
+        certificates that the server will use to verify client authentication.
+
+    Returns:
+      A ServerCertificateConfiguration that can be returned in the certificate
+        configuration fetching callback.
+    """
+    if private_key_certificate_chain_pairs:
+        return ServerCertificateConfiguration(
+            _cygrpc.server_certificate_config_ssl(
+                root_certificates,
+                [
+                    _cygrpc.SslPemKeyCertPair(key, pem)
+                    for key, pem in private_key_certificate_chain_pairs
+                ],
+            )
+        )
+    error_msg = "At least one private key-certificate chain pair is required!"
+    raise ValueError(error_msg)
+
+
+def dynamic_ssl_server_credentials(
+    initial_certificate_configuration,
+    certificate_configuration_fetcher,
+    require_client_authentication=False,
+):
+    """Creates a ServerCredentials for use with an SSL-enabled Server.
+
+    Args:
+      initial_certificate_configuration (ServerCertificateConfiguration): The
+        certificate configuration with which the server will be initialized.
+      certificate_configuration_fetcher (callable): A callable that takes no
+        arguments and should return a ServerCertificateConfiguration to
+        replace the server's current certificate, or None for no change
+        (i.e., the server will continue its current certificate
+        config). The library will call this callback on *every* new
+        client connection before starting the TLS handshake with the
+        client, thus allowing the user application to optionally
+        return a new ServerCertificateConfiguration that the server will then
+        use for the handshake.
+      require_client_authentication: A boolean indicating whether or not to
+        require clients to be authenticated.
+
+    Returns:
+      A ServerCredentials.
+    """
+    return ServerCredentials(
+        _cygrpc.server_credentials_ssl_dynamic_cert_config(
+            initial_certificate_configuration,
+            certificate_configuration_fetcher,
+            require_client_authentication,
+        )
+    )
+
+
+@enum.unique
+class LocalConnectionType(enum.Enum):
+    """Types of local connection for local credential creation.
+
+    Attributes:
+      UDS: Unix domain socket connections
+      LOCAL_TCP: Local TCP connections.
+    """
+
+    UDS = _cygrpc.LocalConnectionType.uds
+    LOCAL_TCP = _cygrpc.LocalConnectionType.local_tcp
+
+
+def local_channel_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
+    """Creates a local ChannelCredentials used for local connections.
+
+    This is an EXPERIMENTAL API.
+
+    Local credentials are used by local TCP endpoints (e.g. localhost:10000)
+    also UDS connections.
+
+    The connections created by local channel credentials are not
+    encrypted, but will be checked if they are local or not.
+    The UDS connections are considered secure by providing peer authentication
+    and data confidentiality while TCP connections are considered insecure.
+
+    It is allowed to transmit call credentials over connections created by
+    local channel credentials.
+
+    Local channel credentials are useful for 1) eliminating insecure_channel usage;
+    2) enable unit testing for call credentials without setting up secrets.
+
+    Args:
+      local_connect_type: Local connection type (either
+        grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
+
+    Returns:
+      A ChannelCredentials for use with a local Channel
+    """
+    return ChannelCredentials(
+        _cygrpc.channel_credentials_local(local_connect_type.value)
+    )
+
+
+def local_server_credentials(local_connect_type=LocalConnectionType.LOCAL_TCP):
+    """Creates a local ServerCredentials used for local connections.
+
+    This is an EXPERIMENTAL API.
+
+    Local credentials are used by local TCP endpoints (e.g. localhost:10000)
+    also UDS connections.
+
+    The connections created by local server credentials are not
+    encrypted, but will be checked if they are local or not.
+    The UDS connections are considered secure by providing peer authentication
+    and data confidentiality while TCP connections are considered insecure.
+
+    It is allowed to transmit call credentials over connections created by local
+    server credentials.
+
+    Local server credentials are useful for 1) eliminating insecure_channel usage;
+    2) enable unit testing for call credentials without setting up secrets.
+
+    Args:
+      local_connect_type: Local connection type (either
+        grpc.LocalConnectionType.UDS or grpc.LocalConnectionType.LOCAL_TCP)
+
+    Returns:
+      A ServerCredentials for use with a local Server
+    """
+    return ServerCredentials(
+        _cygrpc.server_credentials_local(local_connect_type.value)
+    )
+
+
+def alts_channel_credentials(service_accounts=None):
+    """Creates a ChannelCredentials for use with an ALTS-enabled Channel.
+
+    This is an EXPERIMENTAL API.
+    ALTS credentials API can only be used in GCP environment as it relies on
+    handshaker service being available. For more info about ALTS see
+    https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
+
+    Args:
+      service_accounts: A list of server identities accepted by the client.
+        If target service accounts are provided and none of them matches the
+        peer identity of the server, handshake will fail. The arg can be empty
+        if the client does not have any information about trusted server
+        identity.
+
+    Returns:
+      A ChannelCredentials for use with an ALTS-enabled Channel
+    """
+    return ChannelCredentials(
+        _cygrpc.channel_credentials_alts(service_accounts or [])
+    )
+
+
+def alts_server_credentials():
+    """Creates a ServerCredentials for use with an ALTS-enabled connection.
+
+    This is an EXPERIMENTAL API.
+    ALTS credentials API can only be used in GCP environment as it relies on
+    handshaker service being available. For more info about ALTS see
+    https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
+
+    Returns:
+      A ServerCredentials for use with an ALTS-enabled Server
+    """
+    return ServerCredentials(_cygrpc.server_credentials_alts())
+
+
+def compute_engine_channel_credentials(call_credentials):
+    """Creates a compute engine channel credential.
+
+    This credential can only be used in a GCP environment as it relies on
+    a handshaker service. For more info about ALTS, see
+    https://cloud.google.com/security/encryption-in-transit/application-layer-transport-security
+
+    This channel credential is expected to be used as part of a composite
+    credential in conjunction with a call credentials that authenticates the
+    VM's default service account. If used with any other sort of call
+    credential, the connection may suddenly and unexpectedly begin failing RPCs.
+    """
+    return ChannelCredentials(
+        _cygrpc.channel_credentials_compute_engine(
+            call_credentials._credentials
+        )
+    )
+
+
+def channel_ready_future(channel):
+    """Creates a Future that tracks when a Channel is ready.
+
+    Cancelling the Future does not affect the channel's state machine.
+    It merely decouples the Future from channel state machine.
+
+    Args:
+      channel: A Channel object.
+
+    Returns:
+      A Future object that matures when the channel connectivity is
+      ChannelConnectivity.READY.
+    """
+    from grpc import _utilities  # pylint: disable=cyclic-import
+
+    return _utilities.channel_ready_future(channel)
+
+
+def insecure_channel(target, options=None, compression=None):
+    """Creates an insecure Channel to a server.
+
+    The returned Channel is thread-safe.
+
+    Args:
+      target: The server address
+      options: An optional list of key-value pairs (:term:`channel_arguments`
+        in gRPC Core runtime) to configure the channel.
+      compression: An optional value indicating the compression method to be
+        used over the lifetime of the channel.
+
+    Returns:
+      A Channel.
+    """
+    from grpc import _channel  # pylint: disable=cyclic-import
+
+    return _channel.Channel(
+        target, () if options is None else options, None, compression
+    )
+
+
+def secure_channel(target, credentials, options=None, compression=None):
+    """Creates a secure Channel to a server.
+
+    The returned Channel is thread-safe.
+
+    Args:
+      target: The server address.
+      credentials: A ChannelCredentials instance.
+      options: An optional list of key-value pairs (:term:`channel_arguments`
+        in gRPC Core runtime) to configure the channel.
+      compression: An optional value indicating the compression method to be
+        used over the lifetime of the channel.
+
+    Returns:
+      A Channel.
+    """
+    from grpc import _channel  # pylint: disable=cyclic-import
+    from grpc.experimental import _insecure_channel_credentials
+
+    if credentials._credentials is _insecure_channel_credentials:
+        raise ValueError(
+            "secure_channel cannot be called with insecure credentials."
+            + " Call insecure_channel instead."
+        )
+    return _channel.Channel(
+        target,
+        () if options is None else options,
+        credentials._credentials,
+        compression,
+    )
+
+
+def intercept_channel(channel, *interceptors):
+    """Intercepts a channel through a set of interceptors.
+
+    Args:
+      channel: A Channel.
+      interceptors: Zero or more objects of type
+        UnaryUnaryClientInterceptor,
+        UnaryStreamClientInterceptor,
+        StreamUnaryClientInterceptor, or
+        StreamStreamClientInterceptor.
+        Interceptors are given control in the order they are listed.
+
+    Returns:
+      A Channel that intercepts each invocation via the provided interceptors.
+
+    Raises:
+      TypeError: If interceptor does not derive from any of
+        UnaryUnaryClientInterceptor,
+        UnaryStreamClientInterceptor,
+        StreamUnaryClientInterceptor, or
+        StreamStreamClientInterceptor.
+    """
+    from grpc import _interceptor  # pylint: disable=cyclic-import
+
+    return _interceptor.intercept_channel(channel, *interceptors)
+
+
+def server(
+    thread_pool,
+    handlers=None,
+    interceptors=None,
+    options=None,
+    maximum_concurrent_rpcs=None,
+    compression=None,
+    xds=False,
+):
+    """Creates a Server with which RPCs can be serviced.
+
+    Args:
+      thread_pool: A futures.ThreadPoolExecutor to be used by the Server
+        to execute RPC handlers.
+      handlers: An optional list of GenericRpcHandlers used for executing RPCs.
+        More handlers may be added by calling add_generic_rpc_handlers any time
+        before the server is started.
+      interceptors: An optional list of ServerInterceptor objects that observe
+        and optionally manipulate the incoming RPCs before handing them over to
+        handlers. The interceptors are given control in the order they are
+        specified. This is an EXPERIMENTAL API.
+      options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime)
+        to configure the channel.
+      maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server
+        will service before returning RESOURCE_EXHAUSTED status, or None to
+        indicate no limit.
+      compression: An element of grpc.Compression, e.g.
+        grpc.Compression.Gzip. This compression algorithm will be used for the
+        lifetime of the server unless overridden.
+      xds: If set to true, retrieves server configuration via xDS. This is an
+        EXPERIMENTAL option.
+
+    Returns:
+      A Server object.
+    """
+    from grpc import _server  # pylint: disable=cyclic-import
+
+    return _server.create_server(
+        thread_pool,
+        () if handlers is None else handlers,
+        () if interceptors is None else interceptors,
+        () if options is None else options,
+        maximum_concurrent_rpcs,
+        compression,
+        xds,
+    )
+
+
+@contextlib.contextmanager
+def _create_servicer_context(rpc_event, state, request_deserializer):
+    from grpc import _server  # pylint: disable=cyclic-import
+
+    context = _server._Context(rpc_event, state, request_deserializer)
+    yield context
+    context._finalize_state()  # pylint: disable=protected-access
+
+
+@enum.unique
+class Compression(enum.IntEnum):
+    """Indicates the compression method to be used for an RPC.
+
+    Attributes:
+     NoCompression: Do not use compression algorithm.
+     Deflate: Use "Deflate" compression algorithm.
+     Gzip: Use "Gzip" compression algorithm.
+    """
+
+    NoCompression = _compression.NoCompression
+    Deflate = _compression.Deflate
+    Gzip = _compression.Gzip
+
+
+###################################  __all__  #################################
+
+__all__ = (
+    "AuthMetadataContext",
+    "AuthMetadataPlugin",
+    "AuthMetadataPluginCallback",
+    "Call",
+    "CallCredentials",
+    "Channel",
+    "ChannelConnectivity",
+    "ChannelCredentials",
+    "ClientCallDetails",
+    "Compression",
+    "Future",
+    "FutureCancelledError",
+    "FutureTimeoutError",
+    "GenericRpcHandler",
+    "HandlerCallDetails",
+    "LocalConnectionType",
+    "RpcContext",
+    "RpcError",
+    "RpcMethodHandler",
+    "Server",
+    "ServerCertificateConfiguration",
+    "ServerCredentials",
+    "ServerInterceptor",
+    "ServiceRpcHandler",
+    "ServicerContext",
+    "Status",
+    "StatusCode",
+    "StreamStreamClientInterceptor",
+    "StreamStreamMultiCallable",
+    "StreamUnaryClientInterceptor",
+    "StreamUnaryMultiCallable",
+    "UnaryStreamClientInterceptor",
+    "UnaryStreamMultiCallable",
+    "UnaryUnaryClientInterceptor",
+    "UnaryUnaryMultiCallable",
+    "access_token_call_credentials",
+    "alts_channel_credentials",
+    "alts_server_credentials",
+    "channel_ready_future",
+    "composite_call_credentials",
+    "composite_channel_credentials",
+    "compute_engine_channel_credentials",
+    "dynamic_ssl_server_credentials",
+    "insecure_channel",
+    "insecure_server_credentials",
+    "intercept_channel",
+    "local_channel_credentials",
+    "local_server_credentials",
+    "metadata_call_credentials",
+    "method_handlers_generic_handler",
+    "protos",
+    "protos_and_services",
+    "secure_channel",
+    "server",
+    "services",
+    "ssl_channel_credentials",
+    "ssl_server_certificate_configuration",
+    "ssl_server_credentials",
+    "stream_stream_rpc_method_handler",
+    "stream_unary_rpc_method_handler",
+    "unary_stream_rpc_method_handler",
+    "unary_unary_rpc_method_handler",
+    "xds_channel_credentials",
+    "xds_server_credentials",
+)
+
+############################### Extension Shims ################################
+
+# Here to maintain backwards compatibility; avoid using these in new code!
+try:
+    import grpc_tools
+
+    sys.modules.update({"grpc.tools": grpc_tools})
+except ImportError:
+    pass
+try:
+    import grpc_health
+
+    sys.modules.update({"grpc.health": grpc_health})
+except ImportError:
+    pass
+try:
+    import grpc_reflection
+
+    sys.modules.update({"grpc.reflection": grpc_reflection})
+except ImportError:
+    pass
+
+# Prevents import order issue in the case of renamed path.
+if sys.version_info >= (3, 6) and __name__ == "grpc":
+    from grpc import aio  # pylint: disable=ungrouped-imports
+
+    sys.modules.update({"grpc.aio": aio})
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_auth.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_auth.py
new file mode 100644
index 0000000000000000000000000000000000000000..69b87a22338aa5bd3f2e52af2b26977934bab05c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_auth.py
@@ -0,0 +1,80 @@
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""GRPCAuthMetadataPlugins for standard authentication."""
+
+import inspect
+from typing import Any, Optional
+
+import grpc
+
+
+def _sign_request(
+    callback: grpc.AuthMetadataPluginCallback,
+    token: Optional[str],
+    error: Optional[Exception],
+):
+    metadata = (("authorization", "Bearer {}".format(token)),)
+    callback(metadata, error)
+
+
+class GoogleCallCredentials(grpc.AuthMetadataPlugin):
+    """Metadata wrapper for GoogleCredentials from the oauth2client library."""
+
+    _is_jwt: bool
+    _credentials: Any
+
+    # TODO(xuanwn): Give credentials an actual type.
+    def __init__(self, credentials: Any):
+        self._credentials = credentials
+        # Hack to determine if these are JWT creds and we need to pass # noqa: FIX004
+        # additional_claims when getting a token
+        self._is_jwt = (
+            "additional_claims"
+            in inspect.getfullargspec(credentials.get_access_token).args
+        )
+
+    def __call__(
+        self,
+        context: grpc.AuthMetadataContext,
+        callback: grpc.AuthMetadataPluginCallback,
+    ):
+        try:
+            if self._is_jwt:
+                access_token = self._credentials.get_access_token(
+                    additional_claims={
+                        "aud": context.service_url  # pytype: disable=attribute-error
+                    }
+                ).access_token
+            else:
+                access_token = self._credentials.get_access_token().access_token
+        except Exception as exception:  # pylint: disable=broad-except
+            _sign_request(callback, None, exception)
+        else:
+            _sign_request(callback, access_token, None)
+
+
+class AccessTokenAuthMetadataPlugin(grpc.AuthMetadataPlugin):
+    """Metadata wrapper for raw access token credentials."""
+
+    _access_token: str
+
+    def __init__(self, access_token: str):
+        self._access_token = access_token
+
+    def __call__(
+        self,
+        context: grpc.AuthMetadataContext,
+        callback: grpc.AuthMetadataPluginCallback,
+    ):
+        _sign_request(callback, self._access_token, None)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_channel.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_channel.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4676fa54ed75bdcdd5295fbb110fa421175e7bb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_channel.py
@@ -0,0 +1,2229 @@
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Invocation-side implementation of gRPC Python."""
+
+import copy
+import functools
+import logging
+import os
+import sys
+import threading
+import time
+import types
+from typing import (
+    Any,
+    Callable,
+    Dict,
+    Iterator,
+    List,
+    Optional,
+    Sequence,
+    Set,
+    Tuple,
+    Union,
+)
+
+import grpc
+from grpc import _common
+from grpc import _compression
+from grpc import _grpcio_metadata
+from grpc import _observability
+from grpc._cython import cygrpc
+from grpc._typing import ChannelArgumentType
+from grpc._typing import DeserializingFunction
+from grpc._typing import IntegratedCallFactory
+from grpc._typing import MetadataType
+from grpc._typing import NullaryCallbackType
+from grpc._typing import ResponseType
+from grpc._typing import SerializingFunction
+from grpc._typing import UserTag
+import grpc.experimental
+
+_LOGGER = logging.getLogger(__name__)
+
+_USER_AGENT = "grpc-python/{}".format(_grpcio_metadata.__version__)
+
+_EMPTY_FLAGS = 0
+
+# NOTE(rbellevi): No guarantees are given about the maintenance of this
+# environment variable.
+_DEFAULT_SINGLE_THREADED_UNARY_STREAM = (
+    os.getenv("GRPC_SINGLE_THREADED_UNARY_STREAM") is not None
+)
+
+_UNARY_UNARY_INITIAL_DUE = (
+    cygrpc.OperationType.send_initial_metadata,
+    cygrpc.OperationType.send_message,
+    cygrpc.OperationType.send_close_from_client,
+    cygrpc.OperationType.receive_initial_metadata,
+    cygrpc.OperationType.receive_message,
+    cygrpc.OperationType.receive_status_on_client,
+)
+_UNARY_STREAM_INITIAL_DUE = (
+    cygrpc.OperationType.send_initial_metadata,
+    cygrpc.OperationType.send_message,
+    cygrpc.OperationType.send_close_from_client,
+    cygrpc.OperationType.receive_initial_metadata,
+    cygrpc.OperationType.receive_status_on_client,
+)
+_STREAM_UNARY_INITIAL_DUE = (
+    cygrpc.OperationType.send_initial_metadata,
+    cygrpc.OperationType.receive_initial_metadata,
+    cygrpc.OperationType.receive_message,
+    cygrpc.OperationType.receive_status_on_client,
+)
+_STREAM_STREAM_INITIAL_DUE = (
+    cygrpc.OperationType.send_initial_metadata,
+    cygrpc.OperationType.receive_initial_metadata,
+    cygrpc.OperationType.receive_status_on_client,
+)
+
+_CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE = (
+    "Exception calling channel subscription callback!"
+)
+
+_OK_RENDEZVOUS_REPR_FORMAT = (
+    '<{} of RPC that terminated with:\n\tstatus = {}\n\tdetails = "{}"\n>'
+)
+
+_NON_OK_RENDEZVOUS_REPR_FORMAT = (
+    "<{} of RPC that terminated with:\n"
+    "\tstatus = {}\n"
+    '\tdetails = "{}"\n'
+    '\tdebug_error_string = "{}"\n'
+    ">"
+)
+
+
+def _deadline(timeout: Optional[float]) -> Optional[float]:
+    return None if timeout is None else time.time() + timeout
+
+
+def _unknown_code_details(
+    unknown_cygrpc_code: Optional[grpc.StatusCode], details: Optional[str]
+) -> str:
+    return 'Server sent unknown code {} and details "{}"'.format(
+        unknown_cygrpc_code, details
+    )
+
+
+class _RPCState(object):
+    condition: threading.Condition
+    due: Set[cygrpc.OperationType]
+    initial_metadata: Optional[MetadataType]
+    response: Any
+    trailing_metadata: Optional[MetadataType]
+    code: Optional[grpc.StatusCode]
+    details: Optional[str]
+    debug_error_string: Optional[str]
+    cancelled: bool
+    callbacks: List[NullaryCallbackType]
+    fork_epoch: Optional[int]
+    rpc_start_time: Optional[float]  # In relative seconds
+    rpc_end_time: Optional[float]  # In relative seconds
+    method: Optional[str]
+    target: Optional[str]
+
+    def __init__(
+        self,
+        due: Sequence[cygrpc.OperationType],
+        initial_metadata: Optional[MetadataType],
+        trailing_metadata: Optional[MetadataType],
+        code: Optional[grpc.StatusCode],
+        details: Optional[str],
+    ):
+        # `condition` guards all members of _RPCState. `notify_all` is called on
+        # `condition` when the state of the RPC has changed.
+        self.condition = threading.Condition()
+
+        # The cygrpc.OperationType objects representing events due from the RPC's
+        # completion queue. If an operation is in `due`, it is guaranteed that
+        # `operate()` has been called on a corresponding operation. But the
+        # converse is not true. That is, in the case of failed `operate()`
+        # calls, there may briefly be events in `due` that do not correspond to
+        # operations submitted to Core.
+        self.due = set(due)
+        self.initial_metadata = initial_metadata
+        self.response = None
+        self.trailing_metadata = trailing_metadata
+        self.code = code
+        self.details = details
+        self.debug_error_string = None
+        # The following three fields are used for observability.
+        # Updates to those fields do not trigger self.condition.
+        self.rpc_start_time = None
+        self.rpc_end_time = None
+        self.method = None
+        self.target = None
+
+        # The semantics of grpc.Future.cancel and grpc.Future.cancelled are
+        # slightly wonky, so they have to be tracked separately from the rest of the
+        # result of the RPC. This field tracks whether cancellation was requested
+        # prior to termination of the RPC.
+        self.cancelled = False
+        self.callbacks = []
+        self.fork_epoch = cygrpc.get_fork_epoch()
+
+    def reset_postfork_child(self):
+        self.condition = threading.Condition()
+
+
+def _abort(state: _RPCState, code: grpc.StatusCode, details: str) -> None:
+    if state.code is None:
+        state.code = code
+        state.details = details
+        if state.initial_metadata is None:
+            state.initial_metadata = ()
+        state.trailing_metadata = ()
+
+
+def _handle_event(
+    event: cygrpc.BaseEvent,
+    state: _RPCState,
+    response_deserializer: Optional[DeserializingFunction],
+) -> List[NullaryCallbackType]:
+    callbacks = []
+    for batch_operation in event.batch_operations:
+        operation_type = batch_operation.type()
+        state.due.remove(operation_type)
+        if operation_type == cygrpc.OperationType.receive_initial_metadata:
+            state.initial_metadata = batch_operation.initial_metadata()
+        elif operation_type == cygrpc.OperationType.receive_message:
+            serialized_response = batch_operation.message()
+            if serialized_response is not None:
+                response = _common.deserialize(
+                    serialized_response, response_deserializer
+                )
+                if response is None:
+                    details = "Exception deserializing response!"
+                    _abort(state, grpc.StatusCode.INTERNAL, details)
+                else:
+                    state.response = response
+        elif operation_type == cygrpc.OperationType.receive_status_on_client:
+            state.trailing_metadata = batch_operation.trailing_metadata()
+            if state.code is None:
+                code = _common.CYGRPC_STATUS_CODE_TO_STATUS_CODE.get(
+                    batch_operation.code()
+                )
+                if code is None:
+                    state.code = grpc.StatusCode.UNKNOWN
+                    state.details = _unknown_code_details(
+                        code, batch_operation.details()
+                    )
+                else:
+                    state.code = code
+                    state.details = batch_operation.details()
+                    state.debug_error_string = batch_operation.error_string()
+            state.rpc_end_time = time.perf_counter()
+            _observability.maybe_record_rpc_latency(state)
+            callbacks.extend(state.callbacks)
+            state.callbacks = None
+    return callbacks
+
+
+def _event_handler(
+    state: _RPCState, response_deserializer: Optional[DeserializingFunction]
+) -> UserTag:
+    def handle_event(event):
+        with state.condition:
+            callbacks = _handle_event(event, state, response_deserializer)
+            state.condition.notify_all()
+            done = not state.due
+        for callback in callbacks:
+            try:
+                callback()
+            except Exception as e:  # pylint: disable=broad-except
+                # NOTE(rbellevi): We suppress but log errors here so as not to
+                # kill the channel spin thread.
+                _LOGGER.error(
+                    "Exception in callback %s: %s", repr(callback.func), repr(e)
+                )
+        return done and state.fork_epoch >= cygrpc.get_fork_epoch()
+
+    return handle_event
+
+
+# TODO(xuanwn): Create a base class for IntegratedCall and SegregatedCall.
+# pylint: disable=too-many-statements
+def _consume_request_iterator(
+    request_iterator: Iterator,
+    state: _RPCState,
+    call: Union[cygrpc.IntegratedCall, cygrpc.SegregatedCall],
+    request_serializer: SerializingFunction,
+    event_handler: Optional[UserTag],
+) -> None:
+    """Consume a request supplied by the user."""
+
+    def consume_request_iterator():  # pylint: disable=too-many-branches
+        # Iterate over the request iterator until it is exhausted or an error
+        # condition is encountered.
+        while True:
+            return_from_user_request_generator_invoked = False
+            try:
+                # The thread may die in user-code. Do not block fork for this.
+                cygrpc.enter_user_request_generator()
+                request = next(request_iterator)
+            except StopIteration:
+                break
+            except Exception:  # pylint: disable=broad-except
+                cygrpc.return_from_user_request_generator()
+                return_from_user_request_generator_invoked = True
+                code = grpc.StatusCode.UNKNOWN
+                details = "Exception iterating requests!"
+                _LOGGER.exception(details)
+                call.cancel(
+                    _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code], details
+                )
+                _abort(state, code, details)
+                return
+            finally:
+                if not return_from_user_request_generator_invoked:
+                    cygrpc.return_from_user_request_generator()
+            serialized_request = _common.serialize(request, request_serializer)
+            with state.condition:
+                if state.code is None and not state.cancelled:
+                    if serialized_request is None:
+                        code = grpc.StatusCode.INTERNAL
+                        details = "Exception serializing request!"
+                        call.cancel(
+                            _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code],
+                            details,
+                        )
+                        _abort(state, code, details)
+                        return
+                    state.due.add(cygrpc.OperationType.send_message)
+                    operations = (
+                        cygrpc.SendMessageOperation(
+                            serialized_request, _EMPTY_FLAGS
+                        ),
+                    )
+                    operating = call.operate(operations, event_handler)
+                    if not operating:
+                        state.due.remove(cygrpc.OperationType.send_message)
+                        return
+
+                    def _done():
+                        return (
+                            state.code is not None
+                            or cygrpc.OperationType.send_message
+                            not in state.due
+                        )
+
+                    _common.wait(
+                        state.condition.wait,
+                        _done,
+                        spin_cb=functools.partial(
+                            cygrpc.block_if_fork_in_progress, state
+                        ),
+                    )
+                    if state.code is not None:
+                        return
+                else:
+                    return
+        with state.condition:
+            if state.code is None:
+                state.due.add(cygrpc.OperationType.send_close_from_client)
+                operations = (
+                    cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
+                )
+                operating = call.operate(operations, event_handler)
+                if not operating:
+                    state.due.remove(
+                        cygrpc.OperationType.send_close_from_client
+                    )
+
+    consumption_thread = cygrpc.ForkManagedThread(
+        target=consume_request_iterator
+    )
+    consumption_thread.setDaemon(True)
+    consumption_thread.start()
+
+
+def _rpc_state_string(class_name: str, rpc_state: _RPCState) -> str:
+    """Calculates error string for RPC."""
+    with rpc_state.condition:
+        if rpc_state.code is None:
+            return "<{} object>".format(class_name)
+        if rpc_state.code is grpc.StatusCode.OK:
+            return _OK_RENDEZVOUS_REPR_FORMAT.format(
+                class_name, rpc_state.code, rpc_state.details
+            )
+        return _NON_OK_RENDEZVOUS_REPR_FORMAT.format(
+            class_name,
+            rpc_state.code,
+            rpc_state.details,
+            rpc_state.debug_error_string,
+        )
+
+
+class _InactiveRpcError(grpc.RpcError, grpc.Call, grpc.Future):
+    """An RPC error not tied to the execution of a particular RPC.
+
+    The RPC represented by the state object must not be in-progress or
+    cancelled.
+
+    Attributes:
+      _state: An instance of _RPCState.
+    """
+
+    _state: _RPCState
+
+    def __init__(self, state: _RPCState):
+        with state.condition:
+            self._state = _RPCState(
+                (),
+                copy.deepcopy(state.initial_metadata),
+                copy.deepcopy(state.trailing_metadata),
+                state.code,
+                copy.deepcopy(state.details),
+            )
+            self._state.response = copy.copy(state.response)
+            self._state.debug_error_string = copy.copy(state.debug_error_string)
+
+    def initial_metadata(self) -> Optional[MetadataType]:
+        return self._state.initial_metadata
+
+    def trailing_metadata(self) -> Optional[MetadataType]:
+        return self._state.trailing_metadata
+
+    def code(self) -> Optional[grpc.StatusCode]:
+        return self._state.code
+
+    def details(self) -> Optional[str]:
+        return _common.decode(self._state.details)
+
+    def debug_error_string(self) -> Optional[str]:
+        return _common.decode(self._state.debug_error_string)
+
+    def _repr(self) -> str:
+        return _rpc_state_string(self.__class__.__name__, self._state)
+
+    def __repr__(self) -> str:
+        return self._repr()
+
+    def __str__(self) -> str:
+        return self._repr()
+
+    def cancel(self) -> bool:
+        """See grpc.Future.cancel."""
+        return False
+
+    def cancelled(self) -> bool:
+        """See grpc.Future.cancelled."""
+        return False
+
+    def running(self) -> bool:
+        """See grpc.Future.running."""
+        return False
+
+    def done(self) -> bool:
+        """See grpc.Future.done."""
+        return True
+
+    def result(
+        self, timeout: Optional[float] = None
+    ) -> Any:  # pylint: disable=unused-argument
+        """See grpc.Future.result."""
+        raise self
+
+    def exception(
+        self, timeout: Optional[float] = None  # pylint: disable=unused-argument
+    ) -> Optional[Exception]:
+        """See grpc.Future.exception."""
+        return self
+
+    def traceback(
+        self, timeout: Optional[float] = None  # pylint: disable=unused-argument
+    ) -> Optional[types.TracebackType]:
+        """See grpc.Future.traceback."""
+        try:
+            raise self
+        except grpc.RpcError:
+            return sys.exc_info()[2]
+
+    def add_done_callback(
+        self,
+        fn: Callable[[grpc.Future], None],
+        timeout: Optional[float] = None,  # pylint: disable=unused-argument
+    ) -> None:
+        """See grpc.Future.add_done_callback."""
+        fn(self)
+
+
+class _Rendezvous(grpc.RpcError, grpc.RpcContext):
+    """An RPC iterator.
+
+    Attributes:
+      _state: An instance of _RPCState.
+      _call: An instance of SegregatedCall or IntegratedCall.
+        In either case, the _call object is expected to have operate, cancel,
+        and next_event methods.
+      _response_deserializer: A callable taking bytes and return a Python
+        object.
+      _deadline: A float representing the deadline of the RPC in seconds. Or
+        possibly None, to represent an RPC with no deadline at all.
+    """
+
+    _state: _RPCState
+    _call: Union[cygrpc.SegregatedCall, cygrpc.IntegratedCall]
+    _response_deserializer: Optional[DeserializingFunction]
+    _deadline: Optional[float]
+
+    def __init__(
+        self,
+        state: _RPCState,
+        call: Union[cygrpc.SegregatedCall, cygrpc.IntegratedCall],
+        response_deserializer: Optional[DeserializingFunction],
+        deadline: Optional[float],
+    ):
+        super(_Rendezvous, self).__init__()
+        self._state = state
+        self._call = call
+        self._response_deserializer = response_deserializer
+        self._deadline = deadline
+
+    def is_active(self) -> bool:
+        """See grpc.RpcContext.is_active"""
+        with self._state.condition:
+            return self._state.code is None
+
+    def time_remaining(self) -> Optional[float]:
+        """See grpc.RpcContext.time_remaining"""
+        with self._state.condition:
+            if self._deadline is None:
+                return None
+            return max(self._deadline - time.time(), 0)
+
+    def cancel(self) -> bool:
+        """See grpc.RpcContext.cancel"""
+        with self._state.condition:
+            if self._state.code is None:
+                code = grpc.StatusCode.CANCELLED
+                details = "Locally cancelled by application!"
+                self._call.cancel(
+                    _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code], details
+                )
+                self._state.cancelled = True
+                _abort(self._state, code, details)
+                self._state.condition.notify_all()
+                return True
+            return False
+
+    def add_callback(self, callback: NullaryCallbackType) -> bool:
+        """See grpc.RpcContext.add_callback"""
+        with self._state.condition:
+            if self._state.callbacks is None:
+                return False
+            self._state.callbacks.append(callback)
+            return True
+
+    def __iter__(self):
+        return self
+
+    def next(self):
+        return self._next()
+
+    def __next__(self):
+        return self._next()
+
+    def _next(self):
+        raise NotImplementedError()
+
+    def debug_error_string(self) -> Optional[str]:
+        raise NotImplementedError()
+
+    def _repr(self) -> str:
+        return _rpc_state_string(self.__class__.__name__, self._state)
+
+    def __repr__(self) -> str:
+        return self._repr()
+
+    def __str__(self) -> str:
+        return self._repr()
+
+    def __del__(self) -> None:
+        with self._state.condition:
+            if self._state.code is None:
+                self._state.code = grpc.StatusCode.CANCELLED
+                self._state.details = "Cancelled upon garbage collection!"
+                self._state.cancelled = True
+                self._call.cancel(
+                    _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[self._state.code],
+                    self._state.details,
+                )
+                self._state.condition.notify_all()
+
+
+class _SingleThreadedRendezvous(
+    _Rendezvous, grpc.Call, grpc.Future
+):  # pylint: disable=too-many-ancestors
+    """An RPC iterator operating entirely on a single thread.
+
+    The __next__ method of _SingleThreadedRendezvous does not depend on the
+    existence of any other thread, including the "channel spin thread".
+    However, this means that its interface is entirely synchronous. So this
+    class cannot completely fulfill the grpc.Future interface. The result,
+    exception, and traceback methods will never block and will instead raise
+    an exception if calling the method would result in blocking.
+
+    This means that these methods are safe to call from add_done_callback
+    handlers.
+    """
+
+    _state: _RPCState
+
+    def _is_complete(self) -> bool:
+        return self._state.code is not None
+
+    def cancelled(self) -> bool:
+        with self._state.condition:
+            return self._state.cancelled
+
+    def running(self) -> bool:
+        with self._state.condition:
+            return self._state.code is None
+
+    def done(self) -> bool:
+        with self._state.condition:
+            return self._state.code is not None
+
+    def result(self, timeout: Optional[float] = None) -> Any:
+        """Returns the result of the computation or raises its exception.
+
+        This method will never block. Instead, it will raise an exception
+        if calling this method would otherwise result in blocking.
+
+        Since this method will never block, any `timeout` argument passed will
+        be ignored.
+        """
+        del timeout
+        with self._state.condition:
+            if not self._is_complete():
+                error_msg = (
+                    "_SingleThreadedRendezvous only supports "
+                    "result() when the RPC is complete."
+                )
+                raise grpc.experimental.UsageError(error_msg)
+            if self._state.code is grpc.StatusCode.OK:
+                return self._state.response
+            if self._state.cancelled:
+                raise grpc.FutureCancelledError()
+            raise self
+
+    def exception(self, timeout: Optional[float] = None) -> Optional[Exception]:
+        """Return the exception raised by the computation.
+
+        This method will never block. Instead, it will raise an exception
+        if calling this method would otherwise result in blocking.
+
+        Since this method will never block, any `timeout` argument passed will
+        be ignored.
+        """
+        del timeout
+        with self._state.condition:
+            if not self._is_complete():
+                error_msg = (
+                    "_SingleThreadedRendezvous only supports "
+                    "exception() when the RPC is complete."
+                )
+                raise grpc.experimental.UsageError(error_msg)
+            if self._state.code is grpc.StatusCode.OK:
+                return None
+            if self._state.cancelled:
+                raise grpc.FutureCancelledError()
+            return self
+
+    def traceback(
+        self, timeout: Optional[float] = None
+    ) -> Optional[types.TracebackType]:
+        """Access the traceback of the exception raised by the computation.
+
+        This method will never block. Instead, it will raise an exception
+        if calling this method would otherwise result in blocking.
+
+        Since this method will never block, any `timeout` argument passed will
+        be ignored.
+        """
+        del timeout
+        with self._state.condition:
+            if not self._is_complete():
+                msg = (
+                    "_SingleThreadedRendezvous only supports "
+                    "traceback() when the RPC is complete."
+                )
+                raise grpc.experimental.UsageError(msg)
+            if self._state.code is grpc.StatusCode.OK:
+                return None
+            if self._state.cancelled:
+                raise grpc.FutureCancelledError()
+            try:
+                raise self
+            except grpc.RpcError:
+                return sys.exc_info()[2]
+
+    def add_done_callback(self, fn: Callable[[grpc.Future], None]) -> None:
+        with self._state.condition:
+            if self._state.code is None:
+                self._state.callbacks.append(functools.partial(fn, self))
+                return
+
+        fn(self)
+
+    def initial_metadata(self) -> Optional[MetadataType]:
+        """See grpc.Call.initial_metadata"""
+        with self._state.condition:
+            # NOTE(gnossen): Based on our initial call batch, we are guaranteed
+            # to receive initial metadata before any messages.
+            while self._state.initial_metadata is None:
+                self._consume_next_event()
+            return self._state.initial_metadata
+
+    def trailing_metadata(self) -> Optional[MetadataType]:
+        """See grpc.Call.trailing_metadata"""
+        with self._state.condition:
+            if self._state.trailing_metadata is None:
+                error_msg = (
+                    "Cannot get trailing metadata until RPC is completed."
+                )
+                raise grpc.experimental.UsageError(error_msg)
+            return self._state.trailing_metadata
+
+    def code(self) -> Optional[grpc.StatusCode]:
+        """See grpc.Call.code"""
+        with self._state.condition:
+            if self._state.code is None:
+                error_msg = "Cannot get code until RPC is completed."
+                raise grpc.experimental.UsageError(error_msg)
+            return self._state.code
+
+    def details(self) -> Optional[str]:
+        """See grpc.Call.details"""
+        with self._state.condition:
+            if self._state.details is None:
+                error_msg = "Cannot get details until RPC is completed."
+                raise grpc.experimental.UsageError(error_msg)
+            return _common.decode(self._state.details)
+
+    def _consume_next_event(self) -> Optional[cygrpc.BaseEvent]:
+        event = self._call.next_event()
+        with self._state.condition:
+            callbacks = _handle_event(
+                event, self._state, self._response_deserializer
+            )
+            for callback in callbacks:
+                # NOTE(gnossen): We intentionally allow exceptions to bubble up
+                # to the user when running on a single thread.
+                callback()
+        return event
+
+    def _next_response(self) -> Any:
+        while True:
+            self._consume_next_event()
+            with self._state.condition:
+                if self._state.response is not None:
+                    response = self._state.response
+                    self._state.response = None
+                    return response
+                if cygrpc.OperationType.receive_message not in self._state.due:
+                    if self._state.code is grpc.StatusCode.OK:
+                        raise StopIteration()
+                    if self._state.code is not None:
+                        raise self
+
+    def _next(self) -> Any:
+        with self._state.condition:
+            if self._state.code is None:
+                # We tentatively add the operation as expected and remove
+                # it if the enqueue operation fails. This allows us to guarantee that
+                # if an event has been submitted to the core completion queue,
+                # it is in `due`. If we waited until after a successful
+                # enqueue operation then a signal could interrupt this
+                # thread between the enqueue operation and the addition of the
+                # operation to `due`. This would cause an exception on the
+                # channel spin thread when the operation completes and no
+                # corresponding operation would be present in state.due.
+                # Note that, since `condition` is held through this block, there is
+                # no data race on `due`.
+                self._state.due.add(cygrpc.OperationType.receive_message)
+                operating = self._call.operate(
+                    (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),), None
+                )
+                if not operating:
+                    self._state.due.remove(cygrpc.OperationType.receive_message)
+            elif self._state.code is grpc.StatusCode.OK:
+                raise StopIteration()
+            else:
+                raise self
+        return self._next_response()
+
+    def debug_error_string(self) -> Optional[str]:
+        with self._state.condition:
+            if self._state.debug_error_string is None:
+                error_msg = (
+                    "Cannot get debug error string until RPC is completed."
+                )
+                raise grpc.experimental.UsageError(error_msg)
+            return _common.decode(self._state.debug_error_string)
+
+
+class _MultiThreadedRendezvous(
+    _Rendezvous, grpc.Call, grpc.Future
+):  # pylint: disable=too-many-ancestors
+    """An RPC iterator that depends on a channel spin thread.
+
+    This iterator relies upon a per-channel thread running in the background,
+    dequeueing events from the completion queue, and notifying threads waiting
+    on the threading.Condition object in the _RPCState object.
+
+    This extra thread allows _MultiThreadedRendezvous to fulfill the grpc.Future interface
+    and to mediate a bidirection streaming RPC.
+    """
+
+    _state: _RPCState
+
+    def initial_metadata(self) -> Optional[MetadataType]:
+        """See grpc.Call.initial_metadata"""
+        with self._state.condition:
+
+            def _done():
+                return self._state.initial_metadata is not None
+
+            _common.wait(self._state.condition.wait, _done)
+            return self._state.initial_metadata
+
+    def trailing_metadata(self) -> Optional[MetadataType]:
+        """See grpc.Call.trailing_metadata"""
+        with self._state.condition:
+
+            def _done():
+                return self._state.trailing_metadata is not None
+
+            _common.wait(self._state.condition.wait, _done)
+            return self._state.trailing_metadata
+
+    def code(self) -> Optional[grpc.StatusCode]:
+        """See grpc.Call.code"""
+        with self._state.condition:
+
+            def _done():
+                return self._state.code is not None
+
+            _common.wait(self._state.condition.wait, _done)
+            return self._state.code
+
+    def details(self) -> Optional[str]:
+        """See grpc.Call.details"""
+        with self._state.condition:
+
+            def _done():
+                return self._state.details is not None
+
+            _common.wait(self._state.condition.wait, _done)
+            return _common.decode(self._state.details)
+
+    def debug_error_string(self) -> Optional[str]:
+        with self._state.condition:
+
+            def _done():
+                return self._state.debug_error_string is not None
+
+            _common.wait(self._state.condition.wait, _done)
+            return _common.decode(self._state.debug_error_string)
+
+    def cancelled(self) -> bool:
+        with self._state.condition:
+            return self._state.cancelled
+
+    def running(self) -> bool:
+        with self._state.condition:
+            return self._state.code is None
+
+    def done(self) -> bool:
+        with self._state.condition:
+            return self._state.code is not None
+
+    def _is_complete(self) -> bool:
+        return self._state.code is not None
+
+    def result(self, timeout: Optional[float] = None) -> Any:
+        """Returns the result of the computation or raises its exception.
+
+        See grpc.Future.result for the full API contract.
+        """
+        with self._state.condition:
+            timed_out = _common.wait(
+                self._state.condition.wait, self._is_complete, timeout=timeout
+            )
+            if timed_out:
+                raise grpc.FutureTimeoutError()
+            if self._state.code is grpc.StatusCode.OK:
+                return self._state.response
+            if self._state.cancelled:
+                raise grpc.FutureCancelledError()
+            raise self
+
+    def exception(self, timeout: Optional[float] = None) -> Optional[Exception]:
+        """Return the exception raised by the computation.
+
+        See grpc.Future.exception for the full API contract.
+        """
+        with self._state.condition:
+            timed_out = _common.wait(
+                self._state.condition.wait, self._is_complete, timeout=timeout
+            )
+            if timed_out:
+                raise grpc.FutureTimeoutError()
+            if self._state.code is grpc.StatusCode.OK:
+                return None
+            if self._state.cancelled:
+                raise grpc.FutureCancelledError()
+            return self
+
+    def traceback(
+        self, timeout: Optional[float] = None
+    ) -> Optional[types.TracebackType]:
+        """Access the traceback of the exception raised by the computation.
+
+        See grpc.future.traceback for the full API contract.
+        """
+        with self._state.condition:
+            timed_out = _common.wait(
+                self._state.condition.wait, self._is_complete, timeout=timeout
+            )
+            if timed_out:
+                raise grpc.FutureTimeoutError()
+            if self._state.code is grpc.StatusCode.OK:
+                return None
+            if self._state.cancelled:
+                raise grpc.FutureCancelledError()
+            try:
+                raise self
+            except grpc.RpcError:
+                return sys.exc_info()[2]
+
+    def add_done_callback(self, fn: Callable[[grpc.Future], None]) -> None:
+        with self._state.condition:
+            if self._state.code is None:
+                self._state.callbacks.append(functools.partial(fn, self))
+                return
+
+        fn(self)
+
+    def _next(self) -> Any:
+        with self._state.condition:
+            if self._state.code is None:
+                event_handler = _event_handler(
+                    self._state, self._response_deserializer
+                )
+                self._state.due.add(cygrpc.OperationType.receive_message)
+                operating = self._call.operate(
+                    (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
+                    event_handler,
+                )
+                if not operating:
+                    self._state.due.remove(cygrpc.OperationType.receive_message)
+            elif self._state.code is grpc.StatusCode.OK:
+                raise StopIteration()
+            else:
+                raise self
+
+            def _response_ready():
+                return self._state.response is not None or (
+                    cygrpc.OperationType.receive_message not in self._state.due
+                    and self._state.code is not None
+                )
+
+            _common.wait(self._state.condition.wait, _response_ready)
+            if self._state.response is not None:
+                response = self._state.response
+                self._state.response = None
+                return response
+            if cygrpc.OperationType.receive_message not in self._state.due:
+                if self._state.code is grpc.StatusCode.OK:
+                    raise StopIteration()
+                if self._state.code is not None:
+                    raise self
+
+
+def _start_unary_request(
+    request: Any,
+    timeout: Optional[float],
+    request_serializer: SerializingFunction,
+) -> Tuple[Optional[float], Optional[bytes], Optional[grpc.RpcError]]:
+    deadline = _deadline(timeout)
+    serialized_request = _common.serialize(request, request_serializer)
+    if serialized_request is None:
+        state = _RPCState(
+            (),
+            (),
+            (),
+            grpc.StatusCode.INTERNAL,
+            "Exception serializing request!",
+        )
+        error = _InactiveRpcError(state)
+        return deadline, None, error
+    return deadline, serialized_request, None
+
+
+def _end_unary_response_blocking(
+    state: _RPCState,
+    call: cygrpc.SegregatedCall,
+    with_call: bool,
+    deadline: Optional[float],
+) -> Union[ResponseType, Tuple[ResponseType, grpc.Call]]:
+    if state.code is grpc.StatusCode.OK:
+        if with_call:
+            rendezvous = _MultiThreadedRendezvous(state, call, None, deadline)
+            return state.response, rendezvous
+        return state.response
+    raise _InactiveRpcError(state)  # pytype: disable=not-instantiable
+
+
+def _stream_unary_invocation_operations(
+    metadata: Optional[MetadataType], initial_metadata_flags: int
+) -> Sequence[Sequence[cygrpc.Operation]]:
+    return (
+        (
+            cygrpc.SendInitialMetadataOperation(
+                metadata, initial_metadata_flags
+            ),
+            cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
+            cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
+        ),
+        (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
+    )
+
+
+def _stream_unary_invocation_operations_and_tags(
+    metadata: Optional[MetadataType], initial_metadata_flags: int
+) -> Sequence[Tuple[Sequence[cygrpc.Operation], Optional[UserTag]]]:
+    return tuple(
+        (
+            operations,
+            None,
+        )
+        for operations in _stream_unary_invocation_operations(
+            metadata, initial_metadata_flags
+        )
+    )
+
+
+def _determine_deadline(user_deadline: Optional[float]) -> Optional[float]:
+    parent_deadline = cygrpc.get_deadline_from_context()
+    if parent_deadline is None and user_deadline is None:
+        return None
+    if parent_deadline is not None and user_deadline is None:
+        return parent_deadline
+    if user_deadline is not None and parent_deadline is None:
+        return user_deadline
+    return min(parent_deadline, user_deadline)
+
+
+class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
+    _channel: cygrpc.Channel
+    _managed_call: IntegratedCallFactory
+    _method: bytes
+    _target: bytes
+    _request_serializer: Optional[SerializingFunction]
+    _response_deserializer: Optional[DeserializingFunction]
+    _context: Any
+    _registered_call_handle: Optional[int]
+
+    __slots__ = [
+        "_channel",
+        "_context",
+        "_managed_call",
+        "_method",
+        "_request_serializer",
+        "_response_deserializer",
+        "_target",
+    ]
+
+    # pylint: disable=too-many-arguments
+    def __init__(
+        self,
+        channel: cygrpc.Channel,
+        managed_call: IntegratedCallFactory,
+        method: bytes,
+        target: bytes,
+        request_serializer: Optional[SerializingFunction],
+        response_deserializer: Optional[DeserializingFunction],
+        _registered_call_handle: Optional[int],
+    ):
+        self._channel = channel
+        self._managed_call = managed_call
+        self._method = method
+        self._target = target
+        self._request_serializer = request_serializer
+        self._response_deserializer = response_deserializer
+        self._context = cygrpc.build_census_context()
+        self._registered_call_handle = _registered_call_handle
+
+    def _prepare(
+        self,
+        request: Any,
+        timeout: Optional[float],
+        metadata: Optional[MetadataType],
+        wait_for_ready: Optional[bool],
+        compression: Optional[grpc.Compression],
+    ) -> Tuple[
+        Optional[_RPCState],
+        Optional[Sequence[cygrpc.Operation]],
+        Optional[float],
+        Optional[grpc.RpcError],
+    ]:
+        deadline, serialized_request, rendezvous = _start_unary_request(
+            request, timeout, self._request_serializer
+        )
+        initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
+            wait_for_ready
+        )
+        augmented_metadata = _compression.augment_metadata(
+            metadata, compression
+        )
+        if serialized_request is None:
+            return None, None, None, rendezvous
+        state = _RPCState(_UNARY_UNARY_INITIAL_DUE, None, None, None, None)
+        operations = (
+            cygrpc.SendInitialMetadataOperation(
+                augmented_metadata, initial_metadata_flags
+            ),
+            cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS),
+            cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
+            cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),
+            cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),
+            cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
+        )
+        return state, operations, deadline, None
+
+    def _blocking(
+        self,
+        request: Any,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Tuple[_RPCState, cygrpc.SegregatedCall]:
+        state, operations, deadline, rendezvous = self._prepare(
+            request, timeout, metadata, wait_for_ready, compression
+        )
+        if state is None:
+            raise rendezvous  # pylint: disable-msg=raising-bad-type
+        state.rpc_start_time = time.perf_counter()
+        state.method = _common.decode(self._method)
+        state.target = _common.decode(self._target)
+        call = self._channel.segregated_call(
+            cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
+            self._method,
+            None,
+            _determine_deadline(deadline),
+            metadata,
+            None if credentials is None else credentials._credentials,
+            (
+                (
+                    operations,
+                    None,
+                ),
+            ),
+            self._context,
+            self._registered_call_handle,
+        )
+        event = call.next_event()
+        _handle_event(event, state, self._response_deserializer)
+        return state, call
+
+    def __call__(
+        self,
+        request: Any,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Any:
+        state, call = self._blocking(
+            request, timeout, metadata, credentials, wait_for_ready, compression
+        )
+        return _end_unary_response_blocking(state, call, False, None)
+
+    def with_call(
+        self,
+        request: Any,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Tuple[Any, grpc.Call]:
+        state, call = self._blocking(
+            request, timeout, metadata, credentials, wait_for_ready, compression
+        )
+        return _end_unary_response_blocking(state, call, True, None)
+
+    def future(
+        self,
+        request: Any,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> _MultiThreadedRendezvous:
+        state, operations, deadline, rendezvous = self._prepare(
+            request, timeout, metadata, wait_for_ready, compression
+        )
+        if state is None:
+            raise rendezvous  # pylint: disable-msg=raising-bad-type
+        event_handler = _event_handler(state, self._response_deserializer)
+        state.rpc_start_time = time.perf_counter()
+        state.method = _common.decode(self._method)
+        state.target = _common.decode(self._target)
+        call = self._managed_call(
+            cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
+            self._method,
+            None,
+            deadline,
+            metadata,
+            None if credentials is None else credentials._credentials,
+            (operations,),
+            event_handler,
+            self._context,
+            self._registered_call_handle,
+        )
+        return _MultiThreadedRendezvous(
+            state, call, self._response_deserializer, deadline
+        )
+
+
+class _SingleThreadedUnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
+    _channel: cygrpc.Channel
+    _method: bytes
+    _target: bytes
+    _request_serializer: Optional[SerializingFunction]
+    _response_deserializer: Optional[DeserializingFunction]
+    _context: Any
+    _registered_call_handle: Optional[int]
+
+    __slots__ = [
+        "_channel",
+        "_context",
+        "_method",
+        "_request_serializer",
+        "_response_deserializer",
+        "_target",
+    ]
+
+    # pylint: disable=too-many-arguments
+    def __init__(
+        self,
+        channel: cygrpc.Channel,
+        method: bytes,
+        target: bytes,
+        request_serializer: SerializingFunction,
+        response_deserializer: DeserializingFunction,
+        _registered_call_handle: Optional[int],
+    ):
+        self._channel = channel
+        self._method = method
+        self._target = target
+        self._request_serializer = request_serializer
+        self._response_deserializer = response_deserializer
+        self._context = cygrpc.build_census_context()
+        self._registered_call_handle = _registered_call_handle
+
+    def __call__(  # pylint: disable=too-many-locals
+        self,
+        request: Any,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> _SingleThreadedRendezvous:
+        deadline = _deadline(timeout)
+        serialized_request = _common.serialize(
+            request, self._request_serializer
+        )
+        if serialized_request is None:
+            state = _RPCState(
+                (),
+                (),
+                (),
+                grpc.StatusCode.INTERNAL,
+                "Exception serializing request!",
+            )
+            raise _InactiveRpcError(state)
+
+        state = _RPCState(_UNARY_STREAM_INITIAL_DUE, None, None, None, None)
+        call_credentials = (
+            None if credentials is None else credentials._credentials
+        )
+        initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
+            wait_for_ready
+        )
+        augmented_metadata = _compression.augment_metadata(
+            metadata, compression
+        )
+        operations = (
+            (
+                cygrpc.SendInitialMetadataOperation(
+                    augmented_metadata, initial_metadata_flags
+                ),
+                cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS),
+                cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
+            ),
+            (cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),),
+            (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
+        )
+        operations_and_tags = tuple((ops, None) for ops in operations)
+        state.rpc_start_time = time.perf_counter()
+        state.method = _common.decode(self._method)
+        state.target = _common.decode(self._target)
+        call = self._channel.segregated_call(
+            cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
+            self._method,
+            None,
+            _determine_deadline(deadline),
+            metadata,
+            call_credentials,
+            operations_and_tags,
+            self._context,
+            self._registered_call_handle,
+        )
+        return _SingleThreadedRendezvous(
+            state, call, self._response_deserializer, deadline
+        )
+
+
+class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
+    _channel: cygrpc.Channel
+    _managed_call: IntegratedCallFactory
+    _method: bytes
+    _target: bytes
+    _request_serializer: Optional[SerializingFunction]
+    _response_deserializer: Optional[DeserializingFunction]
+    _context: Any
+    _registered_call_handle: Optional[int]
+
+    __slots__ = [
+        "_channel",
+        "_context",
+        "_managed_call",
+        "_method",
+        "_request_serializer",
+        "_response_deserializer",
+        "_target",
+    ]
+
+    # pylint: disable=too-many-arguments
+    def __init__(
+        self,
+        channel: cygrpc.Channel,
+        managed_call: IntegratedCallFactory,
+        method: bytes,
+        target: bytes,
+        request_serializer: SerializingFunction,
+        response_deserializer: DeserializingFunction,
+        _registered_call_handle: Optional[int],
+    ):
+        self._channel = channel
+        self._managed_call = managed_call
+        self._method = method
+        self._target = target
+        self._request_serializer = request_serializer
+        self._response_deserializer = response_deserializer
+        self._context = cygrpc.build_census_context()
+        self._registered_call_handle = _registered_call_handle
+
+    def __call__(  # pylint: disable=too-many-locals
+        self,
+        request: Any,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> _MultiThreadedRendezvous:
+        deadline, serialized_request, rendezvous = _start_unary_request(
+            request, timeout, self._request_serializer
+        )
+        initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
+            wait_for_ready
+        )
+        if serialized_request is None:
+            raise rendezvous  # pylint: disable-msg=raising-bad-type
+        augmented_metadata = _compression.augment_metadata(
+            metadata, compression
+        )
+        state = _RPCState(_UNARY_STREAM_INITIAL_DUE, None, None, None, None)
+        operations = (
+            (
+                cygrpc.SendInitialMetadataOperation(
+                    augmented_metadata, initial_metadata_flags
+                ),
+                cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS),
+                cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS),
+                cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
+            ),
+            (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
+        )
+        state.rpc_start_time = time.perf_counter()
+        state.method = _common.decode(self._method)
+        state.target = _common.decode(self._target)
+        call = self._managed_call(
+            cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
+            self._method,
+            None,
+            _determine_deadline(deadline),
+            metadata,
+            None if credentials is None else credentials._credentials,
+            operations,
+            _event_handler(state, self._response_deserializer),
+            self._context,
+            self._registered_call_handle,
+        )
+        return _MultiThreadedRendezvous(
+            state, call, self._response_deserializer, deadline
+        )
+
+
+class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
+    _channel: cygrpc.Channel
+    _managed_call: IntegratedCallFactory
+    _method: bytes
+    _target: bytes
+    _request_serializer: Optional[SerializingFunction]
+    _response_deserializer: Optional[DeserializingFunction]
+    _context: Any
+    _registered_call_handle: Optional[int]
+
+    __slots__ = [
+        "_channel",
+        "_context",
+        "_managed_call",
+        "_method",
+        "_request_serializer",
+        "_response_deserializer",
+        "_target",
+    ]
+
+    # pylint: disable=too-many-arguments
+    def __init__(
+        self,
+        channel: cygrpc.Channel,
+        managed_call: IntegratedCallFactory,
+        method: bytes,
+        target: bytes,
+        request_serializer: Optional[SerializingFunction],
+        response_deserializer: Optional[DeserializingFunction],
+        _registered_call_handle: Optional[int],
+    ):
+        self._channel = channel
+        self._managed_call = managed_call
+        self._method = method
+        self._target = target
+        self._request_serializer = request_serializer
+        self._response_deserializer = response_deserializer
+        self._context = cygrpc.build_census_context()
+        self._registered_call_handle = _registered_call_handle
+
+    def _blocking(
+        self,
+        request_iterator: Iterator,
+        timeout: Optional[float],
+        metadata: Optional[MetadataType],
+        credentials: Optional[grpc.CallCredentials],
+        wait_for_ready: Optional[bool],
+        compression: Optional[grpc.Compression],
+    ) -> Tuple[_RPCState, cygrpc.SegregatedCall]:
+        deadline = _deadline(timeout)
+        state = _RPCState(_STREAM_UNARY_INITIAL_DUE, None, None, None, None)
+        initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
+            wait_for_ready
+        )
+        augmented_metadata = _compression.augment_metadata(
+            metadata, compression
+        )
+        state.rpc_start_time = time.perf_counter()
+        state.method = _common.decode(self._method)
+        state.target = _common.decode(self._target)
+        call = self._channel.segregated_call(
+            cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
+            self._method,
+            None,
+            _determine_deadline(deadline),
+            augmented_metadata,
+            None if credentials is None else credentials._credentials,
+            _stream_unary_invocation_operations_and_tags(
+                augmented_metadata, initial_metadata_flags
+            ),
+            self._context,
+            self._registered_call_handle,
+        )
+        _consume_request_iterator(
+            request_iterator, state, call, self._request_serializer, None
+        )
+        while True:
+            event = call.next_event()
+            with state.condition:
+                _handle_event(event, state, self._response_deserializer)
+                state.condition.notify_all()
+                if not state.due:
+                    break
+        return state, call
+
+    def __call__(
+        self,
+        request_iterator: Iterator,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Any:
+        state, call = self._blocking(
+            request_iterator,
+            timeout,
+            metadata,
+            credentials,
+            wait_for_ready,
+            compression,
+        )
+        return _end_unary_response_blocking(state, call, False, None)
+
+    def with_call(
+        self,
+        request_iterator: Iterator,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Tuple[Any, grpc.Call]:
+        state, call = self._blocking(
+            request_iterator,
+            timeout,
+            metadata,
+            credentials,
+            wait_for_ready,
+            compression,
+        )
+        return _end_unary_response_blocking(state, call, True, None)
+
+    def future(
+        self,
+        request_iterator: Iterator,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> _MultiThreadedRendezvous:
+        deadline = _deadline(timeout)
+        state = _RPCState(_STREAM_UNARY_INITIAL_DUE, None, None, None, None)
+        event_handler = _event_handler(state, self._response_deserializer)
+        initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
+            wait_for_ready
+        )
+        augmented_metadata = _compression.augment_metadata(
+            metadata, compression
+        )
+        state.rpc_start_time = time.perf_counter()
+        state.method = _common.decode(self._method)
+        state.target = _common.decode(self._target)
+        call = self._managed_call(
+            cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
+            self._method,
+            None,
+            deadline,
+            augmented_metadata,
+            None if credentials is None else credentials._credentials,
+            _stream_unary_invocation_operations(
+                metadata, initial_metadata_flags
+            ),
+            event_handler,
+            self._context,
+            self._registered_call_handle,
+        )
+        _consume_request_iterator(
+            request_iterator,
+            state,
+            call,
+            self._request_serializer,
+            event_handler,
+        )
+        return _MultiThreadedRendezvous(
+            state, call, self._response_deserializer, deadline
+        )
+
+
+class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable):
+    _channel: cygrpc.Channel
+    _managed_call: IntegratedCallFactory
+    _method: bytes
+    _target: bytes
+    _request_serializer: Optional[SerializingFunction]
+    _response_deserializer: Optional[DeserializingFunction]
+    _context: Any
+    _registered_call_handle: Optional[int]
+
+    __slots__ = [
+        "_channel",
+        "_context",
+        "_managed_call",
+        "_method",
+        "_request_serializer",
+        "_response_deserializer",
+        "_target",
+    ]
+
+    # pylint: disable=too-many-arguments
+    def __init__(
+        self,
+        channel: cygrpc.Channel,
+        managed_call: IntegratedCallFactory,
+        method: bytes,
+        target: bytes,
+        request_serializer: Optional[SerializingFunction],
+        response_deserializer: Optional[DeserializingFunction],
+        _registered_call_handle: Optional[int],
+    ):
+        self._channel = channel
+        self._managed_call = managed_call
+        self._method = method
+        self._target = target
+        self._request_serializer = request_serializer
+        self._response_deserializer = response_deserializer
+        self._context = cygrpc.build_census_context()
+        self._registered_call_handle = _registered_call_handle
+
+    def __call__(
+        self,
+        request_iterator: Iterator,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> _MultiThreadedRendezvous:
+        deadline = _deadline(timeout)
+        state = _RPCState(_STREAM_STREAM_INITIAL_DUE, None, None, None, None)
+        initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready(
+            wait_for_ready
+        )
+        augmented_metadata = _compression.augment_metadata(
+            metadata, compression
+        )
+        operations = (
+            (
+                cygrpc.SendInitialMetadataOperation(
+                    augmented_metadata, initial_metadata_flags
+                ),
+                cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS),
+            ),
+            (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),),
+        )
+        event_handler = _event_handler(state, self._response_deserializer)
+        state.rpc_start_time = time.perf_counter()
+        state.method = _common.decode(self._method)
+        state.target = _common.decode(self._target)
+        call = self._managed_call(
+            cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS,
+            self._method,
+            None,
+            _determine_deadline(deadline),
+            augmented_metadata,
+            None if credentials is None else credentials._credentials,
+            operations,
+            event_handler,
+            self._context,
+            self._registered_call_handle,
+        )
+        _consume_request_iterator(
+            request_iterator,
+            state,
+            call,
+            self._request_serializer,
+            event_handler,
+        )
+        return _MultiThreadedRendezvous(
+            state, call, self._response_deserializer, deadline
+        )
+
+
+class _InitialMetadataFlags(int):
+    """Stores immutable initial metadata flags"""
+
+    def __new__(cls, value: int = _EMPTY_FLAGS):
+        value &= cygrpc.InitialMetadataFlags.used_mask
+        return super(_InitialMetadataFlags, cls).__new__(cls, value)
+
+    def with_wait_for_ready(self, wait_for_ready: Optional[bool]) -> int:
+        if wait_for_ready is not None:
+            if wait_for_ready:
+                return self.__class__(
+                    self
+                    | cygrpc.InitialMetadataFlags.wait_for_ready
+                    | cygrpc.InitialMetadataFlags.wait_for_ready_explicitly_set
+                )
+            if not wait_for_ready:
+                return self.__class__(
+                    self & ~cygrpc.InitialMetadataFlags.wait_for_ready
+                    | cygrpc.InitialMetadataFlags.wait_for_ready_explicitly_set
+                )
+        return self
+
+
+class _ChannelCallState(object):
+    channel: cygrpc.Channel
+    managed_calls: int
+    threading: bool
+
+    def __init__(self, channel: cygrpc.Channel):
+        self.lock = threading.Lock()
+        self.channel = channel
+        self.managed_calls = 0
+        self.threading = False
+
+    def reset_postfork_child(self) -> None:
+        self.managed_calls = 0
+
+    def __del__(self):
+        try:
+            self.channel.close(
+                cygrpc.StatusCode.cancelled, "Channel deallocated!"
+            )
+        except (TypeError, AttributeError):
+            pass
+
+
+def _run_channel_spin_thread(state: _ChannelCallState) -> None:
+    def channel_spin():
+        while True:
+            cygrpc.block_if_fork_in_progress(state)
+            event = state.channel.next_call_event()
+            if event.completion_type == cygrpc.CompletionType.queue_timeout:
+                continue
+            call_completed = event.tag(event)
+            if call_completed:
+                with state.lock:
+                    state.managed_calls -= 1
+                    if state.managed_calls == 0:
+                        return
+
+    channel_spin_thread = cygrpc.ForkManagedThread(target=channel_spin)
+    channel_spin_thread.setDaemon(True)
+    channel_spin_thread.start()
+
+
+def _channel_managed_call_management(state: _ChannelCallState):
+    # pylint: disable=too-many-arguments
+    def create(
+        flags: int,
+        method: bytes,
+        host: Optional[str],
+        deadline: Optional[float],
+        metadata: Optional[MetadataType],
+        credentials: Optional[cygrpc.CallCredentials],
+        operations: Sequence[Sequence[cygrpc.Operation]],
+        event_handler: UserTag,
+        context: Any,
+        _registered_call_handle: Optional[int],
+    ) -> cygrpc.IntegratedCall:
+        """Creates a cygrpc.IntegratedCall.
+
+        Args:
+          flags: An integer bitfield of call flags.
+          method: The RPC method.
+          host: A host string for the created call.
+          deadline: A float to be the deadline of the created call or None if
+            the call is to have an infinite deadline.
+          metadata: The metadata for the call or None.
+          credentials: A cygrpc.CallCredentials or None.
+          operations: A sequence of sequences of cygrpc.Operations to be
+            started on the call.
+          event_handler: A behavior to call to handle the events resultant from
+            the operations on the call.
+          context: Context object for distributed tracing.
+          _registered_call_handle: An int representing the call handle of the
+            method, or None if the method is not registered.
+
+        Returns:
+          A cygrpc.IntegratedCall with which to conduct an RPC.
+        """
+        operations_and_tags = tuple(
+            (
+                operation,
+                event_handler,
+            )
+            for operation in operations
+        )
+        with state.lock:
+            call = state.channel.integrated_call(
+                flags,
+                method,
+                host,
+                deadline,
+                metadata,
+                credentials,
+                operations_and_tags,
+                context,
+                _registered_call_handle,
+            )
+            if state.managed_calls == 0:
+                state.managed_calls = 1
+                _run_channel_spin_thread(state)
+            else:
+                state.managed_calls += 1
+            return call
+
+    return create
+
+
+class _ChannelConnectivityState(object):
+    lock: threading.RLock
+    channel: grpc.Channel
+    polling: bool
+    connectivity: grpc.ChannelConnectivity
+    try_to_connect: bool
+    # TODO(xuanwn): Refactor this: https://github.com/grpc/grpc/issues/31704
+    callbacks_and_connectivities: List[
+        Sequence[
+            Union[
+                Callable[[grpc.ChannelConnectivity], None],
+                Optional[grpc.ChannelConnectivity],
+            ]
+        ]
+    ]
+    delivering: bool
+
+    def __init__(self, channel: grpc.Channel):
+        self.lock = threading.RLock()
+        self.channel = channel
+        self.polling = False
+        self.connectivity = None
+        self.try_to_connect = False
+        self.callbacks_and_connectivities = []
+        self.delivering = False
+
+    def reset_postfork_child(self) -> None:
+        self.polling = False
+        self.connectivity = None
+        self.try_to_connect = False
+        self.callbacks_and_connectivities = []
+        self.delivering = False
+
+
+def _deliveries(
+    state: _ChannelConnectivityState,
+) -> List[Callable[[grpc.ChannelConnectivity], None]]:
+    callbacks_needing_update = []
+    for callback_and_connectivity in state.callbacks_and_connectivities:
+        callback, callback_connectivity = callback_and_connectivity
+        if callback_connectivity is not state.connectivity:
+            callbacks_needing_update.append(callback)
+            callback_and_connectivity[1] = state.connectivity
+    return callbacks_needing_update
+
+
+def _deliver(
+    state: _ChannelConnectivityState,
+    initial_connectivity: grpc.ChannelConnectivity,
+    initial_callbacks: Sequence[Callable[[grpc.ChannelConnectivity], None]],
+) -> None:
+    connectivity = initial_connectivity
+    callbacks = initial_callbacks
+    while True:
+        for callback in callbacks:
+            cygrpc.block_if_fork_in_progress(state)
+            try:
+                callback(connectivity)
+            except Exception:  # pylint: disable=broad-except
+                _LOGGER.exception(
+                    _CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE
+                )
+        with state.lock:
+            callbacks = _deliveries(state)
+            if callbacks:
+                connectivity = state.connectivity
+            else:
+                state.delivering = False
+                return
+
+
+def _spawn_delivery(
+    state: _ChannelConnectivityState,
+    callbacks: Sequence[Callable[[grpc.ChannelConnectivity], None]],
+) -> None:
+    delivering_thread = cygrpc.ForkManagedThread(
+        target=_deliver,
+        args=(
+            state,
+            state.connectivity,
+            callbacks,
+        ),
+    )
+    delivering_thread.setDaemon(True)
+    delivering_thread.start()
+    state.delivering = True
+
+
+# NOTE(https://github.com/grpc/grpc/issues/3064): We'd rather not poll.
+def _poll_connectivity(
+    state: _ChannelConnectivityState,
+    channel: grpc.Channel,
+    initial_try_to_connect: bool,
+) -> None:
+    try_to_connect = initial_try_to_connect
+    connectivity = channel.check_connectivity_state(try_to_connect)
+    with state.lock:
+        state.connectivity = (
+            _common.CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY[
+                connectivity
+            ]
+        )
+        callbacks = tuple(
+            callback for callback, _ in state.callbacks_and_connectivities
+        )
+        for callback_and_connectivity in state.callbacks_and_connectivities:
+            callback_and_connectivity[1] = state.connectivity
+        if callbacks:
+            _spawn_delivery(state, callbacks)
+    while True:
+        event = channel.watch_connectivity_state(
+            connectivity, time.time() + 0.2
+        )
+        cygrpc.block_if_fork_in_progress(state)
+        with state.lock:
+            if (
+                not state.callbacks_and_connectivities
+                and not state.try_to_connect
+            ):
+                state.polling = False
+                state.connectivity = None
+                break
+            try_to_connect = state.try_to_connect
+            state.try_to_connect = False
+        if event.success or try_to_connect:
+            connectivity = channel.check_connectivity_state(try_to_connect)
+            with state.lock:
+                state.connectivity = (
+                    _common.CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY[
+                        connectivity
+                    ]
+                )
+                if not state.delivering:
+                    callbacks = _deliveries(state)
+                    if callbacks:
+                        _spawn_delivery(state, callbacks)
+
+
+def _subscribe(
+    state: _ChannelConnectivityState,
+    callback: Callable[[grpc.ChannelConnectivity], None],
+    try_to_connect: bool,
+) -> None:
+    with state.lock:
+        if not state.callbacks_and_connectivities and not state.polling:
+            polling_thread = cygrpc.ForkManagedThread(
+                target=_poll_connectivity,
+                args=(state, state.channel, bool(try_to_connect)),
+            )
+            polling_thread.setDaemon(True)
+            polling_thread.start()
+            state.polling = True
+            state.callbacks_and_connectivities.append([callback, None])
+        elif not state.delivering and state.connectivity is not None:
+            _spawn_delivery(state, (callback,))
+            state.try_to_connect |= bool(try_to_connect)
+            state.callbacks_and_connectivities.append(
+                [callback, state.connectivity]
+            )
+        else:
+            state.try_to_connect |= bool(try_to_connect)
+            state.callbacks_and_connectivities.append([callback, None])
+
+
+def _unsubscribe(
+    state: _ChannelConnectivityState,
+    callback: Callable[[grpc.ChannelConnectivity], None],
+) -> None:
+    with state.lock:
+        for index, (subscribed_callback, _unused_connectivity) in enumerate(
+            state.callbacks_and_connectivities
+        ):
+            if callback == subscribed_callback:
+                state.callbacks_and_connectivities.pop(index)
+                break
+
+
+def _augment_options(
+    base_options: Sequence[ChannelArgumentType],
+    compression: Optional[grpc.Compression],
+) -> Sequence[ChannelArgumentType]:
+    compression_option = _compression.create_channel_option(compression)
+    return (
+        tuple(base_options)
+        + compression_option
+        + (
+            (
+                cygrpc.ChannelArgKey.primary_user_agent_string,
+                _USER_AGENT,
+            ),
+        )
+    )
+
+
+def _separate_channel_options(
+    options: Sequence[ChannelArgumentType],
+) -> Tuple[Sequence[ChannelArgumentType], Sequence[ChannelArgumentType]]:
+    """Separates core channel options from Python channel options."""
+    core_options = []
+    python_options = []
+    for pair in options:
+        if (
+            pair[0]
+            == grpc.experimental.ChannelOptions.SingleThreadedUnaryStream
+        ):
+            python_options.append(pair)
+        else:
+            core_options.append(pair)
+    return python_options, core_options
+
+
+class Channel(grpc.Channel):
+    """A cygrpc.Channel-backed implementation of grpc.Channel."""
+
+    _single_threaded_unary_stream: bool
+    _channel: cygrpc.Channel
+    _call_state: _ChannelCallState
+    _connectivity_state: _ChannelConnectivityState
+    _target: str
+    _registered_call_handles: Dict[str, int]
+
+    def __init__(
+        self,
+        target: str,
+        options: Sequence[ChannelArgumentType],
+        credentials: Optional[grpc.ChannelCredentials],
+        compression: Optional[grpc.Compression],
+    ):
+        """Constructor.
+
+        Args:
+          target: The target to which to connect.
+          options: Configuration options for the channel.
+          credentials: A cygrpc.ChannelCredentials or None.
+          compression: An optional value indicating the compression method to be
+            used over the lifetime of the channel.
+        """
+        python_options, core_options = _separate_channel_options(options)
+        self._single_threaded_unary_stream = (
+            _DEFAULT_SINGLE_THREADED_UNARY_STREAM
+        )
+        self._process_python_options(python_options)
+        self._channel = cygrpc.Channel(
+            _common.encode(target),
+            _augment_options(core_options, compression),
+            credentials,
+        )
+        self._target = target
+        self._call_state = _ChannelCallState(self._channel)
+        self._connectivity_state = _ChannelConnectivityState(self._channel)
+        cygrpc.fork_register_channel(self)
+        if cygrpc.g_gevent_activated:
+            cygrpc.gevent_increment_channel_count()
+
+    def _get_registered_call_handle(self, method: str) -> int:
+        """
+        Get the registered call handle for a method.
+
+        This is a semi-private method. It is intended for use only by gRPC generated code.
+
+        This method is not thread-safe.
+
+        Args:
+          method: Required, the method name for the RPC.
+
+        Returns:
+          The registered call handle pointer in the form of a Python Long.
+        """
+        return self._channel.get_registered_call_handle(_common.encode(method))
+
+    def _process_python_options(
+        self, python_options: Sequence[ChannelArgumentType]
+    ) -> None:
+        """Sets channel attributes according to python-only channel options."""
+        for pair in python_options:
+            if (
+                pair[0]
+                == grpc.experimental.ChannelOptions.SingleThreadedUnaryStream
+            ):
+                self._single_threaded_unary_stream = True
+
+    def subscribe(
+        self,
+        callback: Callable[[grpc.ChannelConnectivity], None],
+        try_to_connect: Optional[bool] = None,
+    ) -> None:
+        _subscribe(self._connectivity_state, callback, try_to_connect)
+
+    def unsubscribe(
+        self, callback: Callable[[grpc.ChannelConnectivity], None]
+    ) -> None:
+        _unsubscribe(self._connectivity_state, callback)
+
+    # pylint: disable=arguments-differ
+    def unary_unary(
+        self,
+        method: str,
+        request_serializer: Optional[SerializingFunction] = None,
+        response_deserializer: Optional[DeserializingFunction] = None,
+        _registered_method: Optional[bool] = False,
+    ) -> grpc.UnaryUnaryMultiCallable:
+        _registered_call_handle = None
+        if _registered_method:
+            _registered_call_handle = self._get_registered_call_handle(method)
+        return _UnaryUnaryMultiCallable(
+            self._channel,
+            _channel_managed_call_management(self._call_state),
+            _common.encode(method),
+            _common.encode(self._target),
+            request_serializer,
+            response_deserializer,
+            _registered_call_handle,
+        )
+
+    # pylint: disable=arguments-differ
+    def unary_stream(
+        self,
+        method: str,
+        request_serializer: Optional[SerializingFunction] = None,
+        response_deserializer: Optional[DeserializingFunction] = None,
+        _registered_method: Optional[bool] = False,
+    ) -> grpc.UnaryStreamMultiCallable:
+        _registered_call_handle = None
+        if _registered_method:
+            _registered_call_handle = self._get_registered_call_handle(method)
+        # NOTE(rbellevi): Benchmarks have shown that running a unary-stream RPC
+        # on a single Python thread results in an appreciable speed-up. However,
+        # due to slight differences in capability, the multi-threaded variant
+        # remains the default.
+        if self._single_threaded_unary_stream:
+            return _SingleThreadedUnaryStreamMultiCallable(
+                self._channel,
+                _common.encode(method),
+                _common.encode(self._target),
+                request_serializer,
+                response_deserializer,
+                _registered_call_handle,
+            )
+        return _UnaryStreamMultiCallable(
+            self._channel,
+            _channel_managed_call_management(self._call_state),
+            _common.encode(method),
+            _common.encode(self._target),
+            request_serializer,
+            response_deserializer,
+            _registered_call_handle,
+        )
+
+    # pylint: disable=arguments-differ
+    def stream_unary(
+        self,
+        method: str,
+        request_serializer: Optional[SerializingFunction] = None,
+        response_deserializer: Optional[DeserializingFunction] = None,
+        _registered_method: Optional[bool] = False,
+    ) -> grpc.StreamUnaryMultiCallable:
+        _registered_call_handle = None
+        if _registered_method:
+            _registered_call_handle = self._get_registered_call_handle(method)
+        return _StreamUnaryMultiCallable(
+            self._channel,
+            _channel_managed_call_management(self._call_state),
+            _common.encode(method),
+            _common.encode(self._target),
+            request_serializer,
+            response_deserializer,
+            _registered_call_handle,
+        )
+
+    # pylint: disable=arguments-differ
+    def stream_stream(
+        self,
+        method: str,
+        request_serializer: Optional[SerializingFunction] = None,
+        response_deserializer: Optional[DeserializingFunction] = None,
+        _registered_method: Optional[bool] = False,
+    ) -> grpc.StreamStreamMultiCallable:
+        _registered_call_handle = None
+        if _registered_method:
+            _registered_call_handle = self._get_registered_call_handle(method)
+        return _StreamStreamMultiCallable(
+            self._channel,
+            _channel_managed_call_management(self._call_state),
+            _common.encode(method),
+            _common.encode(self._target),
+            request_serializer,
+            response_deserializer,
+            _registered_call_handle,
+        )
+
+    def _unsubscribe_all(self) -> None:
+        state = self._connectivity_state
+        if state:
+            with state.lock:
+                del state.callbacks_and_connectivities[:]
+
+    def _close(self) -> None:
+        self._unsubscribe_all()
+        self._channel.close(cygrpc.StatusCode.cancelled, "Channel closed!")
+        cygrpc.fork_unregister_channel(self)
+        if cygrpc.g_gevent_activated:
+            cygrpc.gevent_decrement_channel_count()
+
+    def _close_on_fork(self) -> None:
+        self._unsubscribe_all()
+        self._channel.close_on_fork(
+            cygrpc.StatusCode.cancelled, "Channel closed due to fork"
+        )
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        self._close()
+        return False
+
+    def close(self) -> None:
+        self._close()
+
+    def __del__(self):
+        # TODO(https://github.com/grpc/grpc/issues/12531): Several releases
+        # after 1.12 (1.16 or thereabouts?) add a "self._channel.close" call
+        # here (or more likely, call self._close() here). We don't do this today
+        # because many valid use cases today allow the channel to be deleted
+        # immediately after stubs are created. After a sufficient period of time
+        # has passed for all users to be trusted to freeze out to their channels
+        # for as long as they are in use and to close them after using them,
+        # then deletion of this grpc._channel.Channel instance can be made to
+        # effect closure of the underlying cygrpc.Channel instance.
+        try:
+            self._unsubscribe_all()
+        except:  # pylint: disable=bare-except # noqa: E722
+            # Exceptions in __del__ are ignored by Python anyway, but they can
+            # keep spamming logs.  Just silence them.
+            pass
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_common.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe3712848cf560b878c2f5df0b7059b72042941a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_common.py
@@ -0,0 +1,180 @@
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Shared implementation."""
+
+import logging
+import time
+from typing import Any, AnyStr, Callable, Optional, Union
+
+import grpc
+from grpc._cython import cygrpc
+from grpc._typing import DeserializingFunction
+from grpc._typing import SerializingFunction
+
+_LOGGER = logging.getLogger(__name__)
+
+CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY = {
+    cygrpc.ConnectivityState.idle: grpc.ChannelConnectivity.IDLE,
+    cygrpc.ConnectivityState.connecting: grpc.ChannelConnectivity.CONNECTING,
+    cygrpc.ConnectivityState.ready: grpc.ChannelConnectivity.READY,
+    cygrpc.ConnectivityState.transient_failure: grpc.ChannelConnectivity.TRANSIENT_FAILURE,
+    cygrpc.ConnectivityState.shutdown: grpc.ChannelConnectivity.SHUTDOWN,
+}
+
+CYGRPC_STATUS_CODE_TO_STATUS_CODE = {
+    cygrpc.StatusCode.ok: grpc.StatusCode.OK,
+    cygrpc.StatusCode.cancelled: grpc.StatusCode.CANCELLED,
+    cygrpc.StatusCode.unknown: grpc.StatusCode.UNKNOWN,
+    cygrpc.StatusCode.invalid_argument: grpc.StatusCode.INVALID_ARGUMENT,
+    cygrpc.StatusCode.deadline_exceeded: grpc.StatusCode.DEADLINE_EXCEEDED,
+    cygrpc.StatusCode.not_found: grpc.StatusCode.NOT_FOUND,
+    cygrpc.StatusCode.already_exists: grpc.StatusCode.ALREADY_EXISTS,
+    cygrpc.StatusCode.permission_denied: grpc.StatusCode.PERMISSION_DENIED,
+    cygrpc.StatusCode.unauthenticated: grpc.StatusCode.UNAUTHENTICATED,
+    cygrpc.StatusCode.resource_exhausted: grpc.StatusCode.RESOURCE_EXHAUSTED,
+    cygrpc.StatusCode.failed_precondition: grpc.StatusCode.FAILED_PRECONDITION,
+    cygrpc.StatusCode.aborted: grpc.StatusCode.ABORTED,
+    cygrpc.StatusCode.out_of_range: grpc.StatusCode.OUT_OF_RANGE,
+    cygrpc.StatusCode.unimplemented: grpc.StatusCode.UNIMPLEMENTED,
+    cygrpc.StatusCode.internal: grpc.StatusCode.INTERNAL,
+    cygrpc.StatusCode.unavailable: grpc.StatusCode.UNAVAILABLE,
+    cygrpc.StatusCode.data_loss: grpc.StatusCode.DATA_LOSS,
+}
+STATUS_CODE_TO_CYGRPC_STATUS_CODE = {
+    grpc_code: cygrpc_code
+    for cygrpc_code, grpc_code in CYGRPC_STATUS_CODE_TO_STATUS_CODE.items()
+}
+
+MAXIMUM_WAIT_TIMEOUT = 0.1
+
+_ERROR_MESSAGE_PORT_BINDING_FAILED = (
+    "Failed to bind to address %s; set "
+    "GRPC_VERBOSITY=debug environment variable to see detailed error message."
+)
+
+
+def encode(s: AnyStr) -> bytes:
+    if isinstance(s, bytes):
+        return s
+    return s.encode("utf8")
+
+
+def decode(b: AnyStr) -> str:
+    if isinstance(b, bytes):
+        return b.decode("utf-8", "replace")
+    return b
+
+
+def _transform(
+    message: Any,
+    transformer: Union[SerializingFunction, DeserializingFunction, None],
+    exception_message: str,
+) -> Any:
+    if transformer is None:
+        return message
+    try:
+        return transformer(message)
+    except Exception:  # pylint: disable=broad-except
+        _LOGGER.exception(exception_message)
+        return None
+
+
+def serialize(message: Any, serializer: Optional[SerializingFunction]) -> bytes:
+    return _transform(message, serializer, "Exception serializing message!")
+
+
+def deserialize(
+    serialized_message: bytes, deserializer: Optional[DeserializingFunction]
+) -> Any:
+    return _transform(
+        serialized_message, deserializer, "Exception deserializing message!"
+    )
+
+
+def fully_qualified_method(group: str, method: str) -> str:
+    return "/{}/{}".format(group, method)
+
+
+def _wait_once(
+    wait_fn: Callable[..., bool],
+    timeout: float,
+    spin_cb: Optional[Callable[[], None]],
+):
+    wait_fn(timeout=timeout)
+    if spin_cb is not None:
+        spin_cb()
+
+
+def wait(
+    wait_fn: Callable[..., bool],
+    wait_complete_fn: Callable[[], bool],
+    timeout: Optional[float] = None,
+    spin_cb: Optional[Callable[[], None]] = None,
+) -> bool:
+    """Blocks waiting for an event without blocking the thread indefinitely.
+
+    See https://github.com/grpc/grpc/issues/19464 for full context. CPython's
+    `threading.Event.wait` and `threading.Condition.wait` methods, if invoked
+    without a timeout kwarg, may block the calling thread indefinitely. If the
+    call is made from the main thread, this means that signal handlers may not
+    run for an arbitrarily long period of time.
+
+    This wrapper calls the supplied wait function with an arbitrary short
+    timeout to ensure that no signal handler has to wait longer than
+    MAXIMUM_WAIT_TIMEOUT before executing.
+
+    Args:
+      wait_fn: A callable acceptable a single float-valued kwarg named
+        `timeout`. This function is expected to be one of `threading.Event.wait`
+        or `threading.Condition.wait`.
+      wait_complete_fn: A callable taking no arguments and returning a bool.
+        When this function returns true, it indicates that waiting should cease.
+      timeout: An optional float-valued number of seconds after which the wait
+        should cease.
+      spin_cb: An optional Callable taking no arguments and returning nothing.
+        This callback will be called on each iteration of the spin. This may be
+        used for, e.g. work related to forking.
+
+    Returns:
+      True if a timeout was supplied and it was reached. False otherwise.
+    """
+    if timeout is None:
+        while not wait_complete_fn():
+            _wait_once(wait_fn, MAXIMUM_WAIT_TIMEOUT, spin_cb)
+    else:
+        end = time.time() + timeout
+        while not wait_complete_fn():
+            remaining = min(end - time.time(), MAXIMUM_WAIT_TIMEOUT)
+            if remaining < 0:
+                return True
+            _wait_once(wait_fn, remaining, spin_cb)
+    return False
+
+
+def validate_port_binding_result(address: str, port: int) -> int:
+    """Validates if the port binding succeed.
+
+    If the port returned by Core is 0, the binding is failed. However, in that
+    case, the Core API doesn't return a detailed failing reason. The best we
+    can do is raising an exception to prevent further confusion.
+
+    Args:
+        address: The address string to be bound.
+        port: An int returned by core
+    """
+    if port == 0:
+        # The Core API doesn't return a failure message. The best we can do
+        # is raising an exception to prevent further confusion.
+        raise RuntimeError(_ERROR_MESSAGE_PORT_BINDING_FAILED % address)
+    return port
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_compression.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_compression.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f8a7a9fd22ae5fbe616da3d7eb4c64242167429
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_compression.py
@@ -0,0 +1,71 @@
+# Copyright 2019 The gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+from typing import Optional
+
+import grpc
+from grpc._cython import cygrpc
+from grpc._typing import MetadataType
+
+NoCompression = cygrpc.CompressionAlgorithm.none
+Deflate = cygrpc.CompressionAlgorithm.deflate
+Gzip = cygrpc.CompressionAlgorithm.gzip
+
+_METADATA_STRING_MAPPING = {
+    NoCompression: "identity",
+    Deflate: "deflate",
+    Gzip: "gzip",
+}
+
+
+def _compression_algorithm_to_metadata_value(
+    compression: grpc.Compression,
+) -> str:
+    return _METADATA_STRING_MAPPING[compression]
+
+
+def compression_algorithm_to_metadata(compression: grpc.Compression):
+    return (
+        cygrpc.GRPC_COMPRESSION_REQUEST_ALGORITHM_MD_KEY,
+        _compression_algorithm_to_metadata_value(compression),
+    )
+
+
+def create_channel_option(compression: Optional[grpc.Compression]):
+    return (
+        ((cygrpc.GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM, int(compression)),)
+        if compression
+        else ()
+    )
+
+
+def augment_metadata(
+    metadata: Optional[MetadataType], compression: Optional[grpc.Compression]
+):
+    if not metadata and not compression:
+        return None
+    base_metadata = tuple(metadata) if metadata else ()
+    compression_metadata = (
+        (compression_algorithm_to_metadata(compression),) if compression else ()
+    )
+    return base_metadata + compression_metadata
+
+
+__all__ = (
+    "Deflate",
+    "Gzip",
+    "NoCompression",
+)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_grpcio_metadata.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_grpcio_metadata.py
new file mode 100644
index 0000000000000000000000000000000000000000..88930fc3dfd42425dfae81dc40189c11474c9f7f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_grpcio_metadata.py
@@ -0,0 +1 @@
+__version__ = """1.80.0"""
\ No newline at end of file
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_interceptor.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_interceptor.py
new file mode 100644
index 0000000000000000000000000000000000000000..1438710fc3e72990e453e3acb6f8e361c8ef030e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_interceptor.py
@@ -0,0 +1,809 @@
+# Copyright 2017 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Implementation of gRPC Python interceptors."""
+
+import collections
+import sys
+import types
+from typing import Any, Callable, Optional, Sequence, Tuple, Union
+
+import grpc
+
+from ._typing import DeserializingFunction
+from ._typing import DoneCallbackType
+from ._typing import MetadataType
+from ._typing import RequestIterableType
+from ._typing import SerializingFunction
+
+
+class _ServicePipeline(object):
+    interceptors: Tuple[grpc.ServerInterceptor]
+
+    def __init__(self, interceptors: Sequence[grpc.ServerInterceptor]):
+        self.interceptors = tuple(interceptors)
+
+    def _continuation(self, thunk: Callable, index: int) -> Callable:
+        return lambda context: self._intercept_at(thunk, index, context)
+
+    def _intercept_at(
+        self, thunk: Callable, index: int, context: grpc.HandlerCallDetails
+    ) -> grpc.RpcMethodHandler:
+        if index < len(self.interceptors):
+            interceptor = self.interceptors[index]
+            thunk = self._continuation(thunk, index + 1)
+            return interceptor.intercept_service(thunk, context)
+        return thunk(context)
+
+    def execute(
+        self, thunk: Callable, context: grpc.HandlerCallDetails
+    ) -> grpc.RpcMethodHandler:
+        return self._intercept_at(thunk, 0, context)
+
+
+def service_pipeline(
+    interceptors: Optional[Sequence[grpc.ServerInterceptor]],
+) -> Optional[_ServicePipeline]:
+    return _ServicePipeline(interceptors) if interceptors else None
+
+
+class _ClientCallDetails(
+    collections.namedtuple(
+        "_ClientCallDetails",
+        (
+            "method",
+            "timeout",
+            "metadata",
+            "credentials",
+            "wait_for_ready",
+            "compression",
+        ),
+    ),
+    grpc.ClientCallDetails,
+):
+    pass
+
+
+def _unwrap_client_call_details(
+    call_details: grpc.ClientCallDetails,
+    default_details: grpc.ClientCallDetails,
+) -> Tuple[
+    str, float, MetadataType, grpc.CallCredentials, bool, grpc.Compression
+]:
+    try:
+        method = call_details.method  # pytype: disable=attribute-error
+    except AttributeError:
+        method = default_details.method  # pytype: disable=attribute-error
+
+    try:
+        timeout = call_details.timeout  # pytype: disable=attribute-error
+    except AttributeError:
+        timeout = default_details.timeout  # pytype: disable=attribute-error
+
+    try:
+        metadata = call_details.metadata  # pytype: disable=attribute-error
+    except AttributeError:
+        metadata = default_details.metadata  # pytype: disable=attribute-error
+
+    try:
+        credentials = (
+            call_details.credentials
+        )  # pytype: disable=attribute-error
+    except AttributeError:
+        credentials = (
+            default_details.credentials
+        )  # pytype: disable=attribute-error
+
+    try:
+        wait_for_ready = (
+            call_details.wait_for_ready
+        )  # pytype: disable=attribute-error
+    except AttributeError:
+        wait_for_ready = (
+            default_details.wait_for_ready
+        )  # pytype: disable=attribute-error
+
+    try:
+        compression = (
+            call_details.compression
+        )  # pytype: disable=attribute-error
+    except AttributeError:
+        compression = (
+            default_details.compression
+        )  # pytype: disable=attribute-error
+
+    return method, timeout, metadata, credentials, wait_for_ready, compression
+
+
+class _FailureOutcome(
+    grpc.RpcError, grpc.Future, grpc.Call
+):  # pylint: disable=too-many-ancestors
+    _exception: Exception
+    _traceback: types.TracebackType
+
+    def __init__(self, exception: Exception, traceback: types.TracebackType):
+        super(_FailureOutcome, self).__init__()
+        self._exception = exception
+        self._traceback = traceback
+
+    def initial_metadata(self) -> Optional[MetadataType]:
+        return None
+
+    def trailing_metadata(self) -> Optional[MetadataType]:
+        return None
+
+    def code(self) -> Optional[grpc.StatusCode]:
+        return grpc.StatusCode.INTERNAL
+
+    def details(self) -> Optional[str]:
+        return "Exception raised while intercepting the RPC"
+
+    def cancel(self) -> bool:
+        return False
+
+    def cancelled(self) -> bool:
+        return False
+
+    def is_active(self) -> bool:
+        return False
+
+    def time_remaining(self) -> Optional[float]:
+        return None
+
+    def running(self) -> bool:
+        return False
+
+    def done(self) -> bool:
+        return True
+
+    def result(self, ignored_timeout: Optional[float] = None):
+        raise self._exception
+
+    def exception(
+        self, ignored_timeout: Optional[float] = None
+    ) -> Optional[Exception]:
+        return self._exception
+
+    def traceback(
+        self, ignored_timeout: Optional[float] = None
+    ) -> Optional[types.TracebackType]:
+        return self._traceback
+
+    def add_callback(self, unused_callback) -> bool:
+        return False
+
+    def add_done_callback(self, fn: DoneCallbackType) -> None:
+        fn(self)
+
+    def __iter__(self):
+        return self
+
+    def __next__(self):
+        raise self._exception
+
+    def next(self):
+        return self.__next__()
+
+
+class _UnaryOutcome(grpc.Call, grpc.Future):
+    _response: Any
+    _call: grpc.Call
+
+    def __init__(self, response: Any, call: grpc.Call):
+        self._response = response
+        self._call = call
+
+    def initial_metadata(self) -> Optional[MetadataType]:
+        return self._call.initial_metadata()
+
+    def trailing_metadata(self) -> Optional[MetadataType]:
+        return self._call.trailing_metadata()
+
+    def code(self) -> Optional[grpc.StatusCode]:
+        return self._call.code()
+
+    def details(self) -> Optional[str]:
+        return self._call.details()
+
+    def is_active(self) -> bool:
+        return self._call.is_active()
+
+    def time_remaining(self) -> Optional[float]:
+        return self._call.time_remaining()
+
+    def cancel(self) -> bool:
+        return self._call.cancel()
+
+    def add_callback(self, callback) -> bool:
+        return self._call.add_callback(callback)
+
+    def cancelled(self) -> bool:
+        return False
+
+    def running(self) -> bool:
+        return False
+
+    def done(self) -> bool:
+        return True
+
+    def result(self, ignored_timeout: Optional[float] = None):
+        return self._response
+
+    def exception(self, ignored_timeout: Optional[float] = None):
+        return None
+
+    def traceback(self, ignored_timeout: Optional[float] = None):
+        return None
+
+    def add_done_callback(self, fn: DoneCallbackType) -> None:
+        fn(self)
+
+
+class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable):
+    _thunk: Callable
+    _method: str
+    _interceptor: grpc.UnaryUnaryClientInterceptor
+
+    def __init__(
+        self,
+        thunk: Callable,
+        method: str,
+        interceptor: grpc.UnaryUnaryClientInterceptor,
+    ):
+        self._thunk = thunk
+        self._method = method
+        self._interceptor = interceptor
+
+    def __call__(
+        self,
+        request: Any,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Any:
+        response, ignored_call = self._with_call(
+            request,
+            timeout=timeout,
+            metadata=metadata,
+            credentials=credentials,
+            wait_for_ready=wait_for_ready,
+            compression=compression,
+        )
+        return response
+
+    def _with_call(
+        self,
+        request: Any,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Tuple[Any, grpc.Call]:
+        client_call_details = _ClientCallDetails(
+            self._method,
+            timeout,
+            metadata,
+            credentials,
+            wait_for_ready,
+            compression,
+        )
+
+        def continuation(new_details, request):
+            (
+                new_method,
+                new_timeout,
+                new_metadata,
+                new_credentials,
+                new_wait_for_ready,
+                new_compression,
+            ) = _unwrap_client_call_details(new_details, client_call_details)
+            try:
+                response, call = self._thunk(new_method).with_call(
+                    request,
+                    timeout=new_timeout,
+                    metadata=new_metadata,
+                    credentials=new_credentials,
+                    wait_for_ready=new_wait_for_ready,
+                    compression=new_compression,
+                )
+                return _UnaryOutcome(response, call)
+            except grpc.RpcError as rpc_error:
+                return rpc_error
+            except Exception as exception:  # pylint:disable=broad-except
+                return _FailureOutcome(exception, sys.exc_info()[2])
+
+        call = self._interceptor.intercept_unary_unary(
+            continuation, client_call_details, request
+        )
+        return call.result(), call
+
+    def with_call(
+        self,
+        request: Any,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Tuple[Any, grpc.Call]:
+        return self._with_call(
+            request,
+            timeout=timeout,
+            metadata=metadata,
+            credentials=credentials,
+            wait_for_ready=wait_for_ready,
+            compression=compression,
+        )
+
+    def future(
+        self,
+        request: Any,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Any:
+        client_call_details = _ClientCallDetails(
+            self._method,
+            timeout,
+            metadata,
+            credentials,
+            wait_for_ready,
+            compression,
+        )
+
+        def continuation(new_details, request):
+            (
+                new_method,
+                new_timeout,
+                new_metadata,
+                new_credentials,
+                new_wait_for_ready,
+                new_compression,
+            ) = _unwrap_client_call_details(new_details, client_call_details)
+            return self._thunk(new_method).future(
+                request,
+                timeout=new_timeout,
+                metadata=new_metadata,
+                credentials=new_credentials,
+                wait_for_ready=new_wait_for_ready,
+                compression=new_compression,
+            )
+
+        try:
+            return self._interceptor.intercept_unary_unary(
+                continuation, client_call_details, request
+            )
+        except Exception as exception:  # pylint:disable=broad-except
+            return _FailureOutcome(exception, sys.exc_info()[2])
+
+
+class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable):
+    _thunk: Callable
+    _method: str
+    _interceptor: grpc.UnaryStreamClientInterceptor
+
+    def __init__(
+        self,
+        thunk: Callable,
+        method: str,
+        interceptor: grpc.UnaryStreamClientInterceptor,
+    ):
+        self._thunk = thunk
+        self._method = method
+        self._interceptor = interceptor
+
+    def __call__(
+        self,
+        request: Any,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ):
+        client_call_details = _ClientCallDetails(
+            self._method,
+            timeout,
+            metadata,
+            credentials,
+            wait_for_ready,
+            compression,
+        )
+
+        def continuation(new_details, request):
+            (
+                new_method,
+                new_timeout,
+                new_metadata,
+                new_credentials,
+                new_wait_for_ready,
+                new_compression,
+            ) = _unwrap_client_call_details(new_details, client_call_details)
+            return self._thunk(new_method)(
+                request,
+                timeout=new_timeout,
+                metadata=new_metadata,
+                credentials=new_credentials,
+                wait_for_ready=new_wait_for_ready,
+                compression=new_compression,
+            )
+
+        try:
+            return self._interceptor.intercept_unary_stream(
+                continuation, client_call_details, request
+            )
+        except Exception as exception:  # pylint:disable=broad-except
+            return _FailureOutcome(exception, sys.exc_info()[2])
+
+
+class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable):
+    _thunk: Callable
+    _method: str
+    _interceptor: grpc.StreamUnaryClientInterceptor
+
+    def __init__(
+        self,
+        thunk: Callable,
+        method: str,
+        interceptor: grpc.StreamUnaryClientInterceptor,
+    ):
+        self._thunk = thunk
+        self._method = method
+        self._interceptor = interceptor
+
+    def __call__(
+        self,
+        request_iterator: RequestIterableType,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Any:
+        response, ignored_call = self._with_call(
+            request_iterator,
+            timeout=timeout,
+            metadata=metadata,
+            credentials=credentials,
+            wait_for_ready=wait_for_ready,
+            compression=compression,
+        )
+        return response
+
+    def _with_call(
+        self,
+        request_iterator: RequestIterableType,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Tuple[Any, grpc.Call]:
+        client_call_details = _ClientCallDetails(
+            self._method,
+            timeout,
+            metadata,
+            credentials,
+            wait_for_ready,
+            compression,
+        )
+
+        def continuation(new_details, request_iterator):
+            (
+                new_method,
+                new_timeout,
+                new_metadata,
+                new_credentials,
+                new_wait_for_ready,
+                new_compression,
+            ) = _unwrap_client_call_details(new_details, client_call_details)
+            try:
+                response, call = self._thunk(new_method).with_call(
+                    request_iterator,
+                    timeout=new_timeout,
+                    metadata=new_metadata,
+                    credentials=new_credentials,
+                    wait_for_ready=new_wait_for_ready,
+                    compression=new_compression,
+                )
+                return _UnaryOutcome(response, call)
+            except grpc.RpcError as rpc_error:
+                return rpc_error
+            except Exception as exception:  # pylint:disable=broad-except
+                return _FailureOutcome(exception, sys.exc_info()[2])
+
+        call = self._interceptor.intercept_stream_unary(
+            continuation, client_call_details, request_iterator
+        )
+        return call.result(), call
+
+    def with_call(
+        self,
+        request_iterator: RequestIterableType,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Tuple[Any, grpc.Call]:
+        return self._with_call(
+            request_iterator,
+            timeout=timeout,
+            metadata=metadata,
+            credentials=credentials,
+            wait_for_ready=wait_for_ready,
+            compression=compression,
+        )
+
+    def future(
+        self,
+        request_iterator: RequestIterableType,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ) -> Any:
+        client_call_details = _ClientCallDetails(
+            self._method,
+            timeout,
+            metadata,
+            credentials,
+            wait_for_ready,
+            compression,
+        )
+
+        def continuation(new_details, request_iterator):
+            (
+                new_method,
+                new_timeout,
+                new_metadata,
+                new_credentials,
+                new_wait_for_ready,
+                new_compression,
+            ) = _unwrap_client_call_details(new_details, client_call_details)
+            return self._thunk(new_method).future(
+                request_iterator,
+                timeout=new_timeout,
+                metadata=new_metadata,
+                credentials=new_credentials,
+                wait_for_ready=new_wait_for_ready,
+                compression=new_compression,
+            )
+
+        try:
+            return self._interceptor.intercept_stream_unary(
+                continuation, client_call_details, request_iterator
+            )
+        except Exception as exception:  # pylint:disable=broad-except
+            return _FailureOutcome(exception, sys.exc_info()[2])
+
+
+class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable):
+    _thunk: Callable
+    _method: str
+    _interceptor: grpc.StreamStreamClientInterceptor
+
+    def __init__(
+        self,
+        thunk: Callable,
+        method: str,
+        interceptor: grpc.StreamStreamClientInterceptor,
+    ):
+        self._thunk = thunk
+        self._method = method
+        self._interceptor = interceptor
+
+    def __call__(
+        self,
+        request_iterator: RequestIterableType,
+        timeout: Optional[float] = None,
+        metadata: Optional[MetadataType] = None,
+        credentials: Optional[grpc.CallCredentials] = None,
+        wait_for_ready: Optional[bool] = None,
+        compression: Optional[grpc.Compression] = None,
+    ):
+        client_call_details = _ClientCallDetails(
+            self._method,
+            timeout,
+            metadata,
+            credentials,
+            wait_for_ready,
+            compression,
+        )
+
+        def continuation(new_details, request_iterator):
+            (
+                new_method,
+                new_timeout,
+                new_metadata,
+                new_credentials,
+                new_wait_for_ready,
+                new_compression,
+            ) = _unwrap_client_call_details(new_details, client_call_details)
+            return self._thunk(new_method)(
+                request_iterator,
+                timeout=new_timeout,
+                metadata=new_metadata,
+                credentials=new_credentials,
+                wait_for_ready=new_wait_for_ready,
+                compression=new_compression,
+            )
+
+        try:
+            return self._interceptor.intercept_stream_stream(
+                continuation, client_call_details, request_iterator
+            )
+        except Exception as exception:  # pylint:disable=broad-except
+            return _FailureOutcome(exception, sys.exc_info()[2])
+
+
+class _Channel(grpc.Channel):
+    _channel: grpc.Channel
+    _interceptor: Union[
+        grpc.UnaryUnaryClientInterceptor,
+        grpc.UnaryStreamClientInterceptor,
+        grpc.StreamStreamClientInterceptor,
+        grpc.StreamUnaryClientInterceptor,
+    ]
+
+    def __init__(
+        self,
+        channel: grpc.Channel,
+        interceptor: Union[
+            grpc.UnaryUnaryClientInterceptor,
+            grpc.UnaryStreamClientInterceptor,
+            grpc.StreamStreamClientInterceptor,
+            grpc.StreamUnaryClientInterceptor,
+        ],
+    ):
+        self._channel = channel
+        self._interceptor = interceptor
+
+    def subscribe(
+        self, callback: Callable, try_to_connect: Optional[bool] = False
+    ):
+        self._channel.subscribe(callback, try_to_connect=try_to_connect)
+
+    def unsubscribe(self, callback: Callable):
+        self._channel.unsubscribe(callback)
+
+    # pylint: disable=arguments-differ
+    def unary_unary(
+        self,
+        method: str,
+        request_serializer: Optional[SerializingFunction] = None,
+        response_deserializer: Optional[DeserializingFunction] = None,
+        _registered_method: Optional[bool] = False,
+    ) -> grpc.UnaryUnaryMultiCallable:
+        # pytype: disable=wrong-arg-count
+        thunk = lambda m: self._channel.unary_unary(
+            m,
+            request_serializer,
+            response_deserializer,
+            _registered_method,
+        )
+        # pytype: enable=wrong-arg-count
+        if isinstance(self._interceptor, grpc.UnaryUnaryClientInterceptor):
+            return _UnaryUnaryMultiCallable(thunk, method, self._interceptor)
+        return thunk(method)
+
+    # pylint: disable=arguments-differ
+    def unary_stream(
+        self,
+        method: str,
+        request_serializer: Optional[SerializingFunction] = None,
+        response_deserializer: Optional[DeserializingFunction] = None,
+        _registered_method: Optional[bool] = False,
+    ) -> grpc.UnaryStreamMultiCallable:
+        # pytype: disable=wrong-arg-count
+        thunk = lambda m: self._channel.unary_stream(
+            m,
+            request_serializer,
+            response_deserializer,
+            _registered_method,
+        )
+        # pytype: enable=wrong-arg-count
+        if isinstance(self._interceptor, grpc.UnaryStreamClientInterceptor):
+            return _UnaryStreamMultiCallable(thunk, method, self._interceptor)
+        return thunk(method)
+
+    # pylint: disable=arguments-differ
+    def stream_unary(
+        self,
+        method: str,
+        request_serializer: Optional[SerializingFunction] = None,
+        response_deserializer: Optional[DeserializingFunction] = None,
+        _registered_method: Optional[bool] = False,
+    ) -> grpc.StreamUnaryMultiCallable:
+        # pytype: disable=wrong-arg-count
+        thunk = lambda m: self._channel.stream_unary(
+            m,
+            request_serializer,
+            response_deserializer,
+            _registered_method,
+        )
+        # pytype: enable=wrong-arg-count
+        if isinstance(self._interceptor, grpc.StreamUnaryClientInterceptor):
+            return _StreamUnaryMultiCallable(thunk, method, self._interceptor)
+        return thunk(method)
+
+    # pylint: disable=arguments-differ
+    def stream_stream(
+        self,
+        method: str,
+        request_serializer: Optional[SerializingFunction] = None,
+        response_deserializer: Optional[DeserializingFunction] = None,
+        _registered_method: Optional[bool] = False,
+    ) -> grpc.StreamStreamMultiCallable:
+        # pytype: disable=wrong-arg-count
+        thunk = lambda m: self._channel.stream_stream(
+            m,
+            request_serializer,
+            response_deserializer,
+            _registered_method,
+        )
+        # pytype: enable=wrong-arg-count
+        if isinstance(self._interceptor, grpc.StreamStreamClientInterceptor):
+            return _StreamStreamMultiCallable(thunk, method, self._interceptor)
+        return thunk(method)
+
+    def _close(self):
+        self._channel.close()
+
+    def __enter__(self):
+        return self
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        self._close()
+        return False
+
+    def close(self):
+        self._channel.close()
+
+
+def intercept_channel(
+    channel: grpc.Channel,
+    *interceptors: Optional[
+        Sequence[
+            Union[
+                grpc.UnaryUnaryClientInterceptor,
+                grpc.UnaryStreamClientInterceptor,
+                grpc.StreamStreamClientInterceptor,
+                grpc.StreamUnaryClientInterceptor,
+            ]
+        ]
+    ],
+) -> grpc.Channel:
+    for interceptor in reversed(list(interceptors)):
+        if (
+            not isinstance(interceptor, grpc.UnaryUnaryClientInterceptor)
+            and not isinstance(interceptor, grpc.UnaryStreamClientInterceptor)
+            and not isinstance(interceptor, grpc.StreamUnaryClientInterceptor)
+            and not isinstance(interceptor, grpc.StreamStreamClientInterceptor)
+        ):
+            error_msg = (
+                "interceptor must be "
+                "grpc.UnaryUnaryClientInterceptor or "
+                "grpc.UnaryStreamClientInterceptor or "
+                "grpc.StreamUnaryClientInterceptor or "
+                "grpc.StreamStreamClientInterceptor"
+            )
+            raise TypeError(error_msg)
+        channel = _Channel(channel, interceptor)
+    return channel
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_observability.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_observability.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef5396390628564227413d53b0a83555fa839497
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_observability.py
@@ -0,0 +1,312 @@
+# Copyright 2023 The gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import abc
+import contextlib
+import logging
+import threading
+from typing import (
+    Any,
+    Generator,
+    Generic,
+    List,
+    Optional,
+    Tuple,
+    TypeVar,
+    Union,
+)
+
+from grpc._cython import cygrpc as _cygrpc
+from grpc._typing import ChannelArgumentType
+
+_LOGGER = logging.getLogger(__name__)
+
+_channel = Any  # _channel.py imports this module.
+ClientCallTracerCapsule = TypeVar("ClientCallTracerCapsule")
+ServerCallTracerFactoryCapsule = TypeVar("ServerCallTracerFactoryCapsule")
+
+_plugin_lock: threading.RLock = threading.RLock()
+_OBSERVABILITY_PLUGIN: Optional["ObservabilityPlugin"] = None
+_SERVICES_TO_EXCLUDE: List[bytes] = [
+    b"google.monitoring.v3.MetricService",
+    b"google.devtools.cloudtrace.v2.TraceService",
+]
+
+
+class ServerCallTracerFactory:
+    """An encapsulation of a ServerCallTracerFactory.
+
+    Instances of this class can be passed to a Channel as values for the
+    grpc.experimental.server_call_tracer_factory option
+    """
+
+    def __init__(self, address):
+        self._address = address
+
+    def __int__(self):
+        return self._address
+
+
+class ObservabilityPlugin(
+    Generic[ClientCallTracerCapsule, ServerCallTracerFactoryCapsule],
+    metaclass=abc.ABCMeta,
+):
+    """Abstract base class for observability plugin.
+
+    *This is a semi-private class that was intended for the exclusive use of
+     the gRPC team.*
+
+    The ClientCallTracerCapsule and ClientCallTracerCapsule created by this
+    plugin should be injected to gRPC core using observability_init at the
+    start of a program, before any channels/servers are built.
+
+    Any future methods added to this interface cannot have the
+    @abc.abstractmethod annotation.
+
+    Attributes:
+      _stats_enabled: A bool indicates whether tracing is enabled.
+      _tracing_enabled: A bool indicates whether stats(metrics) is enabled.
+      _registered_methods: A set which stores the registered method names in
+        bytes.
+    """
+
+    _tracing_enabled: bool = False
+    _stats_enabled: bool = False
+
+    @abc.abstractmethod
+    def create_client_call_tracer(
+        self, method_name: bytes, target: bytes
+    ) -> ClientCallTracerCapsule:
+        """Creates a ClientCallTracerCapsule.
+
+        After register the plugin, if tracing or stats is enabled, this method
+        will be called after a call was created, the ClientCallTracer created
+        by this method will be saved to call context.
+
+        The ClientCallTracer is an object which implements `grpc_core::ClientCallTracer`
+        interface and wrapped in a PyCapsule using `client_call_tracer` as name.
+
+        Args:
+          method_name: The method name of the call in byte format.
+          target: The channel target of the call in byte format.
+          registered_method: Whether this method is pre-registered.
+
+        Returns:
+          A PyCapsule which stores a ClientCallTracer object.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def save_trace_context(
+        self, trace_id: str, span_id: str, is_sampled: bool
+    ) -> None:
+        """Saves the trace_id and span_id related to the current span.
+
+        After register the plugin, if tracing is enabled, this method will be
+        called after the server finished sending response.
+
+        This method can be used to propagate census context.
+
+        Args:
+          trace_id: The identifier for the trace associated with the span as a
+            32-character hexadecimal encoded string,
+            e.g. 26ed0036f2eff2b7317bccce3e28d01f
+          span_id: The identifier for the span as a 16-character hexadecimal encoded
+            string. e.g. 113ec879e62583bc
+          is_sampled: A bool indicates whether the span is sampled.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def create_server_call_tracer_factory(
+        self,
+        *,
+        xds: bool = False,
+    ) -> Optional[ServerCallTracerFactoryCapsule]:
+        """Creates a ServerCallTracerFactoryCapsule.
+
+        This method will be called at server initialization time to create a
+        ServerCallTracerFactory, which will be registered to gRPC core.
+
+        The ServerCallTracerFactory is an object which implements
+        `grpc_core::ServerCallTracerFactory` interface and wrapped in a PyCapsule
+        using `server_call_tracer_factory` as name.
+
+        Args:
+          xds: Whether the server is xds server.
+
+        Returns:
+          A PyCapsule which stores a ServerCallTracerFactory object. Or None if
+        plugin decides not to create ServerCallTracerFactory.
+        """
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def record_rpc_latency(
+        self, method: str, target: str, rpc_latency: float, status_code: Any
+    ) -> None:
+        """Record the latency of the RPC.
+
+        After register the plugin, if stats is enabled, this method will be
+        called at the end of each RPC.
+
+        Args:
+          method: The fully-qualified name of the RPC method being invoked.
+          target: The target name of the RPC method being invoked.
+          rpc_latency: The latency for the RPC in seconds, equals to the time between
+            when the client invokes the RPC and when the client receives the status.
+          status_code: An element of grpc.StatusCode in string format representing the
+            final status for the RPC.
+        """
+        raise NotImplementedError()
+
+    def set_tracing(self, enable: bool) -> None:
+        """Enable or disable tracing.
+
+        Args:
+          enable: A bool indicates whether tracing should be enabled.
+        """
+        self._tracing_enabled = enable
+
+    def set_stats(self, enable: bool) -> None:
+        """Enable or disable stats(metrics).
+
+        Args:
+          enable: A bool indicates whether stats should be enabled.
+        """
+        self._stats_enabled = enable
+
+    def save_registered_method(self, method_name: bytes) -> None:
+        """Saves the method name to registered_method list.
+
+        When exporting metrics, method name for unregistered methods will be replaced
+        with 'other' by default.
+
+        Args:
+          method_name: The method name in bytes.
+        """
+        raise NotImplementedError()
+
+    @property
+    def tracing_enabled(self) -> bool:
+        return self._tracing_enabled
+
+    @property
+    def stats_enabled(self) -> bool:
+        return self._stats_enabled
+
+    @property
+    def observability_enabled(self) -> bool:
+        return self.tracing_enabled or self.stats_enabled
+
+
+@contextlib.contextmanager
+def get_plugin() -> Generator[Optional[ObservabilityPlugin], None, None]:
+    """Get the ObservabilityPlugin in _observability module.
+
+    Returns:
+      The ObservabilityPlugin currently registered with the _observability
+    module. Or None if no plugin exists at the time of calling this method.
+    """
+    with _plugin_lock:
+        yield _OBSERVABILITY_PLUGIN
+
+
+def set_plugin(observability_plugin: Optional[ObservabilityPlugin]) -> None:
+    """Save ObservabilityPlugin to _observability module.
+
+    Args:
+      observability_plugin: The ObservabilityPlugin to save.
+
+    Raises:
+      ValueError: If an ObservabilityPlugin was already registered at the
+    time of calling this method.
+    """
+    global _OBSERVABILITY_PLUGIN  # pylint: disable=global-statement # noqa: PLW0603
+    with _plugin_lock:
+        if observability_plugin and _OBSERVABILITY_PLUGIN:
+            error_msg = "observability_plugin was already set!"
+            raise ValueError(error_msg)
+        _OBSERVABILITY_PLUGIN = observability_plugin
+
+
+def observability_init(observability_plugin: ObservabilityPlugin) -> None:
+    """Initialize observability with provided ObservabilityPlugin.
+
+    This method have to be called at the start of a program, before any
+    channels/servers are built.
+
+    Args:
+      observability_plugin: The ObservabilityPlugin to use.
+
+    Raises:
+      ValueError: If an ObservabilityPlugin was already registered at the
+    time of calling this method.
+    """
+    set_plugin(observability_plugin)
+
+
+def observability_deinit() -> None:
+    """Clear the observability context, including ObservabilityPlugin and
+    ServerCallTracerFactory
+
+    This method have to be called after exit observability context so that
+    it's possible to re-initialize again.
+    """
+    set_plugin(None)
+    _cygrpc.clear_server_call_tracer_factory()
+
+
+def maybe_record_rpc_latency(state: "_channel._RPCState") -> None:
+    """Record the latency of the RPC, if the plugin is registered and stats is enabled.
+
+    This method will be called at the end of each RPC.
+
+    Args:
+      state: a grpc._channel._RPCState object which contains the stats related to the
+    RPC.
+    """
+    # TODO(xuanwn): use channel args to exclude those metrics.
+    for exclude_prefix in _SERVICES_TO_EXCLUDE:
+        if exclude_prefix in state.method.encode("utf8"):
+            return
+    with get_plugin() as plugin:
+        if plugin and plugin.stats_enabled:
+            rpc_latency_s = state.rpc_end_time - state.rpc_start_time
+            rpc_latency_ms = rpc_latency_s * 1000
+            plugin.record_rpc_latency(
+                state.method, state.target, rpc_latency_ms, state.code
+            )
+
+
+def create_server_call_tracer_factory_option(
+    xds: bool,
+) -> Union[Tuple[ChannelArgumentType], Tuple[()]]:
+    with get_plugin() as plugin:
+        if plugin and plugin.stats_enabled:
+            server_call_tracer_factory_address = (
+                _cygrpc.get_server_call_tracer_factory_address(plugin, xds)
+            )
+            if server_call_tracer_factory_address:
+                return (
+                    (
+                        "grpc.experimental.server_call_tracer_factory",
+                        ServerCallTracerFactory(
+                            server_call_tracer_factory_address
+                        ),
+                    ),
+                )
+        return ()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_plugin_wrapping.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_plugin_wrapping.py
new file mode 100644
index 0000000000000000000000000000000000000000..6026a40c5b5b886c6d003f3c4f7b96037490c7f1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_plugin_wrapping.py
@@ -0,0 +1,136 @@
+# Copyright 2015 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import collections
+import logging
+import threading
+from typing import Callable, Optional, Type
+
+import grpc
+from grpc import _common
+from grpc._cython import cygrpc
+from grpc._typing import MetadataType
+
+_LOGGER = logging.getLogger(__name__)
+
+
+class _AuthMetadataContext(
+    collections.namedtuple(
+        "AuthMetadataContext",
+        (
+            "service_url",
+            "method_name",
+        ),
+    ),
+    grpc.AuthMetadataContext,
+):
+    pass
+
+
+class _CallbackState(object):
+    def __init__(self):
+        self.lock = threading.Lock()
+        self.called = False
+        self.exception = None
+
+
+class _AuthMetadataPluginCallback(grpc.AuthMetadataPluginCallback):
+    _state: _CallbackState
+    _callback: Callable
+
+    def __init__(self, state: _CallbackState, callback: Callable):
+        self._state = state
+        self._callback = callback
+
+    def __call__(
+        self, metadata: MetadataType, error: Optional[Type[BaseException]]
+    ):
+        with self._state.lock:
+            if self._state.exception is None:
+                if self._state.called:
+                    error_msg = (
+                        "AuthMetadataPluginCallback invoked more than once!"
+                    )
+                    raise RuntimeError(error_msg)
+                self._state.called = True
+            else:
+                error_msg = (
+                    "AuthMetadataPluginCallback"
+                    'raised exception "{self._state.exception}"!'
+                )
+                raise RuntimeError(error_msg)
+        if error is None:
+            self._callback(metadata, cygrpc.StatusCode.ok, None)
+        else:
+            self._callback(
+                None, cygrpc.StatusCode.internal, _common.encode(str(error))
+            )
+
+
+class _Plugin(object):
+    _metadata_plugin: grpc.AuthMetadataPlugin
+
+    def __init__(self, metadata_plugin: grpc.AuthMetadataPlugin):
+        self._metadata_plugin = metadata_plugin
+        self._stored_ctx = None
+
+        try:
+            import contextvars  # pylint: disable=wrong-import-position
+
+            # The plugin may be invoked on a thread created by Core, which will not
+            # have the context propagated. This context is stored and installed in
+            # the thread invoking the plugin.
+            self._stored_ctx = contextvars.copy_context()
+        except ImportError:
+            # Support versions predating contextvars.
+            pass
+
+    def __call__(self, service_url: str, method_name: str, callback: Callable):
+        context = _AuthMetadataContext(
+            _common.decode(service_url), _common.decode(method_name)
+        )
+        callback_state = _CallbackState()
+        try:
+            self._metadata_plugin(
+                context, _AuthMetadataPluginCallback(callback_state, callback)
+            )
+        except Exception as exception:  # pylint: disable=broad-except
+            _LOGGER.exception(
+                'AuthMetadataPluginCallback "%s" raised exception!',
+                self._metadata_plugin,
+            )
+            with callback_state.lock:
+                callback_state.exception = exception
+                if callback_state.called:
+                    return
+            callback(
+                None, cygrpc.StatusCode.internal, _common.encode(str(exception))
+            )
+
+
+def metadata_plugin_call_credentials(
+    metadata_plugin: grpc.AuthMetadataPlugin, name: Optional[str]
+) -> grpc.CallCredentials:
+    if name is None:
+        try:
+            effective_name = metadata_plugin.__name__
+        except AttributeError:
+            effective_name = metadata_plugin.__class__.__name__
+    else:
+        effective_name = name
+    return grpc.CallCredentials(
+        cygrpc.MetadataPluginCallCredentials(
+            _Plugin(metadata_plugin), _common.encode(effective_name)
+        )
+    )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_runtime_protos.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_runtime_protos.py
new file mode 100644
index 0000000000000000000000000000000000000000..571ee52a71e970ba279e415b4abb42946bee71f8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_runtime_protos.py
@@ -0,0 +1,163 @@
+# Copyright 2020 The gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import sys
+import types
+from typing import Tuple, Union
+
+_REQUIRED_SYMBOLS = ("_protos", "_services", "_protos_and_services")
+_MINIMUM_VERSION = (3, 5, 0)
+
+_UNINSTALLED_TEMPLATE = (
+    "Install the grpcio-tools package (1.32.0+) to use the {} function."
+)
+_VERSION_ERROR_TEMPLATE = (
+    "The {} function is only on available on Python 3.X interpreters."
+)
+
+
+def _has_runtime_proto_symbols(mod: types.ModuleType) -> bool:
+    return all(hasattr(mod, sym) for sym in _REQUIRED_SYMBOLS)
+
+
+def _is_grpc_tools_importable() -> bool:
+    try:
+        import grpc_tools  # pylint: disable=unused-import # pytype: disable=import-error
+
+        return True
+    except ImportError as e:
+        # NOTE: It's possible that we're encountering a transitive ImportError, so
+        # we check for that and re-raise if so.
+        if "grpc_tools" not in e.args[0]:
+            raise
+        return False
+
+
+def _call_with_lazy_import(
+    fn_name: str, protobuf_path: str
+) -> Union[types.ModuleType, Tuple[types.ModuleType, types.ModuleType]]:
+    """Calls one of the three functions, lazily importing grpc_tools.
+
+    Args:
+      fn_name: The name of the function to import from grpc_tools.protoc.
+      protobuf_path: The path to import.
+
+    Returns:
+      The appropriate module object.
+    """
+    if sys.version_info < _MINIMUM_VERSION:
+        raise NotImplementedError(_VERSION_ERROR_TEMPLATE.format(fn_name))
+    if not _is_grpc_tools_importable():
+        raise NotImplementedError(_UNINSTALLED_TEMPLATE.format(fn_name))
+    import grpc_tools.protoc  # pytype: disable=import-error
+
+    if _has_runtime_proto_symbols(grpc_tools.protoc):
+        fn = getattr(grpc_tools.protoc, "_" + fn_name)
+        return fn(protobuf_path)
+    raise NotImplementedError(_UNINSTALLED_TEMPLATE.format(fn_name))
+
+
+def protos(protobuf_path):  # pylint: disable=unused-argument
+    """Returns a module generated by the indicated .proto file.
+
+    THIS IS AN EXPERIMENTAL API.
+
+    Use this function to retrieve classes corresponding to message
+    definitions in the .proto file.
+
+    To inspect the contents of the returned module, use the dir function.
+    For example:
+
+    ```
+    protos = grpc.protos("foo.proto")
+    print(dir(protos))
+    ```
+
+    The returned module object corresponds to the _pb2.py file generated
+    by protoc. The path is expected to be relative to an entry on sys.path
+    and all transitive dependencies of the file should also be resolvable
+    from an entry on sys.path.
+
+    To completely disable the machinery behind this function, set the
+    GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true".
+
+    Args:
+      protobuf_path: The path to the .proto file on the filesystem. This path
+        must be resolvable from an entry on sys.path and so must all of its
+        transitive dependencies.
+
+    Returns:
+      A module object corresponding to the message code for the indicated
+      .proto file. Equivalent to a generated _pb2.py file.
+    """
+    return _call_with_lazy_import("protos", protobuf_path)
+
+
+def services(protobuf_path):  # pylint: disable=unused-argument
+    """Returns a module generated by the indicated .proto file.
+
+    THIS IS AN EXPERIMENTAL API.
+
+    Use this function to retrieve classes and functions corresponding to
+    service definitions in the .proto file, including both stub and servicer
+    definitions.
+
+    To inspect the contents of the returned module, use the dir function.
+    For example:
+
+    ```
+    services = grpc.services("foo.proto")
+    print(dir(services))
+    ```
+
+    The returned module object corresponds to the _pb2_grpc.py file generated
+    by protoc. The path is expected to be relative to an entry on sys.path
+    and all transitive dependencies of the file should also be resolvable
+    from an entry on sys.path.
+
+    To completely disable the machinery behind this function, set the
+    GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true".
+
+    Args:
+      protobuf_path: The path to the .proto file on the filesystem. This path
+        must be resolvable from an entry on sys.path and so must all of its
+        transitive dependencies.
+
+    Returns:
+      A module object corresponding to the stub/service code for the indicated
+      .proto file. Equivalent to a generated _pb2_grpc.py file.
+    """
+    return _call_with_lazy_import("services", protobuf_path)
+
+
+def protos_and_services(protobuf_path):  # pylint: disable=unused-argument
+    """Returns a 2-tuple of modules corresponding to protos and services.
+
+    THIS IS AN EXPERIMENTAL API.
+
+    The return value of this function is equivalent to a call to protos and a
+    call to services.
+
+    To completely disable the machinery behind this function, set the
+    GRPC_PYTHON_DISABLE_DYNAMIC_STUBS environment variable to "true".
+
+    Args:
+      protobuf_path: The path to the .proto file on the filesystem. This path
+        must be resolvable from an entry on sys.path and so must all of its
+        transitive dependencies.
+
+    Returns:
+      A 2-tuple of module objects corresponding to (protos(path), services(path)).
+    """
+    return _call_with_lazy_import("protos_and_services", protobuf_path)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_server.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_server.py
new file mode 100644
index 0000000000000000000000000000000000000000..44ff22a35d7aa7f4c4119e027d37f282a1bd8c9a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_server.py
@@ -0,0 +1,1515 @@
+# Copyright 2016 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Service-side implementation of gRPC Python."""
+
+from __future__ import annotations
+
+import abc
+import collections
+from concurrent import futures
+import contextvars
+import enum
+import logging
+import threading
+import time
+import traceback
+from typing import (
+    Any,
+    Callable,
+    Dict,
+    Iterable,
+    Iterator,
+    List,
+    Mapping,
+    Optional,
+    Sequence,
+    Set,
+    Tuple,
+    Union,
+)
+
+import grpc
+from grpc import _common
+from grpc import _compression
+from grpc import _interceptor
+from grpc import _observability
+from grpc._cython import cygrpc
+from grpc._typing import ArityAgnosticMethodHandler
+from grpc._typing import ChannelArgumentType
+from grpc._typing import DeserializingFunction
+from grpc._typing import MetadataType
+from grpc._typing import NullaryCallbackType
+from grpc._typing import ResponseType
+from grpc._typing import SerializingFunction
+from grpc._typing import ServerCallbackTag
+from grpc._typing import ServerTagCallbackType
+from typing_extensions import override
+
+_LOGGER = logging.getLogger(__name__)
+
+_SHUTDOWN_TAG = "shutdown"
+_REQUEST_CALL_TAG = "request_call"
+
+_RECEIVE_CLOSE_ON_SERVER_TOKEN = "receive_close_on_server"
+_SEND_INITIAL_METADATA_TOKEN = "send_initial_metadata"
+_RECEIVE_MESSAGE_TOKEN = "receive_message"
+_SEND_MESSAGE_TOKEN = "send_message"
+_SEND_INITIAL_METADATA_AND_SEND_MESSAGE_TOKEN = (
+    "send_initial_metadata * send_message"
+)
+_SEND_STATUS_FROM_SERVER_TOKEN = "send_status_from_server"
+_SEND_INITIAL_METADATA_AND_SEND_STATUS_FROM_SERVER_TOKEN = (
+    "send_initial_metadata * send_status_from_server"
+)
+
+_OPEN = "open"
+_CLOSED = "closed"
+_CANCELLED = "cancelled"
+
+_EMPTY_FLAGS = 0
+
+_DEALLOCATED_SERVER_CHECK_PERIOD_S = 1.0
+_INF_TIMEOUT = 1e9
+
+
+def _serialized_request(request_event: cygrpc.BaseEvent) -> bytes:
+    return request_event.batch_operations[0].message()
+
+
+def _application_code(code: grpc.StatusCode) -> cygrpc.StatusCode:
+    cygrpc_code = _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE.get(code)
+    return cygrpc.StatusCode.unknown if cygrpc_code is None else cygrpc_code
+
+
+def _completion_code(state: _RPCState) -> cygrpc.StatusCode:
+    if state.code is None:
+        return cygrpc.StatusCode.ok
+    return _application_code(state.code)
+
+
+def _abortion_code(
+    state: _RPCState, code: cygrpc.StatusCode
+) -> cygrpc.StatusCode:
+    if state.code is None:
+        return code
+    return _application_code(state.code)
+
+
+def _details(state: _RPCState) -> bytes:
+    return b"" if state.details is None else state.details
+
+
+class _HandlerCallDetails(
+    collections.namedtuple(
+        "_HandlerCallDetails",
+        (
+            "method",
+            "invocation_metadata",
+        ),
+    ),
+    grpc.HandlerCallDetails,
+):
+    pass
+
+
+class _Method(abc.ABC):
+    @abc.abstractmethod
+    def name(self) -> Optional[str]:
+        raise NotImplementedError()
+
+    @abc.abstractmethod
+    def handler(
+        self, handler_call_details: _HandlerCallDetails
+    ) -> Optional[grpc.RpcMethodHandler]:
+        raise NotImplementedError()
+
+
+class _RegisteredMethod(_Method):
+    def __init__(
+        self,
+        name: str,
+        registered_handler: Optional[grpc.RpcMethodHandler],
+    ):
+        self._name = name
+        self._registered_handler = registered_handler
+
+    @override
+    def name(self) -> Optional[str]:
+        return self._name
+
+    @override
+    def handler(
+        self, handler_call_details: _HandlerCallDetails
+    ) -> Optional[grpc.RpcMethodHandler]:
+        return self._registered_handler
+
+
+class _GenericMethod(_Method):
+    def __init__(
+        self,
+        generic_handlers: List[grpc.GenericRpcHandler],
+    ):
+        self._generic_handlers = generic_handlers
+
+    @override
+    def name(self) -> Optional[str]:
+        return None
+
+    @override
+    def handler(
+        self, handler_call_details: _HandlerCallDetails
+    ) -> Optional[grpc.RpcMethodHandler]:
+        # If the same method have both generic and registered handler,
+        # registered handler will take precedence.
+        for generic_handler in self._generic_handlers:
+            method_handler = generic_handler.service(handler_call_details)
+            if method_handler is not None:
+                return method_handler
+        return None
+
+
+class _RPCState(object):
+    context: contextvars.Context
+    condition: threading.Condition
+    due = Set[str]
+    request: Any
+    client: str
+    initial_metadata_allowed: bool
+    compression_algorithm: Optional[grpc.Compression]
+    disable_next_compression: bool
+    trailing_metadata: Optional[MetadataType]
+    code: Optional[grpc.StatusCode]
+    details: Optional[bytes]
+    statused: bool
+    rpc_errors: List[Exception]
+    callbacks: Optional[List[NullaryCallbackType]]
+    aborted: bool
+
+    def __init__(self):
+        self.context = contextvars.Context()
+        self.condition = threading.Condition()
+        self.due = set()
+        self.request = None
+        self.client = _OPEN
+        self.initial_metadata_allowed = True
+        self.compression_algorithm = None
+        self.disable_next_compression = False
+        self.trailing_metadata = None
+        self.code = None
+        self.details = None
+        self.statused = False
+        self.rpc_errors = []
+        self.callbacks = []
+        self.aborted = False
+
+
+def _raise_rpc_error(state: _RPCState) -> None:
+    rpc_error = grpc.RpcError()
+    state.rpc_errors.append(rpc_error)
+    raise rpc_error
+
+
+def _possibly_finish_call(
+    state: _RPCState, token: str
+) -> ServerTagCallbackType:
+    state.due.remove(token)
+    if not _is_rpc_state_active(state) and not state.due:
+        callbacks = state.callbacks
+        state.callbacks = None
+        return state, callbacks
+    return None, ()
+
+
+def _send_status_from_server(state: _RPCState, token: str) -> ServerCallbackTag:
+    def send_status_from_server(unused_send_status_from_server_event):
+        with state.condition:
+            return _possibly_finish_call(state, token)
+
+    return send_status_from_server
+
+
+def _get_initial_metadata(
+    state: _RPCState, metadata: Optional[MetadataType]
+) -> Optional[MetadataType]:
+    with state.condition:
+        if state.compression_algorithm:
+            compression_metadata = (
+                _compression.compression_algorithm_to_metadata(
+                    state.compression_algorithm
+                ),
+            )
+            if metadata is None:
+                return compression_metadata
+            return compression_metadata + tuple(metadata)
+        return metadata
+
+
+def _get_initial_metadata_operation(
+    state: _RPCState, metadata: Optional[MetadataType]
+) -> cygrpc.Operation:
+    operation = cygrpc.SendInitialMetadataOperation(
+        _get_initial_metadata(state, metadata), _EMPTY_FLAGS
+    )
+    return operation
+
+
+def _abort(
+    state: _RPCState, call: cygrpc.Call, code: cygrpc.StatusCode, details: bytes
+) -> None:
+    if state.client is not _CANCELLED:
+        effective_code = _abortion_code(state, code)
+        effective_details = details if state.details is None else state.details
+        if state.initial_metadata_allowed:
+            operations = (
+                _get_initial_metadata_operation(state, None),
+                cygrpc.SendStatusFromServerOperation(
+                    state.trailing_metadata,
+                    effective_code,
+                    effective_details,
+                    _EMPTY_FLAGS,
+                ),
+            )
+            token = _SEND_INITIAL_METADATA_AND_SEND_STATUS_FROM_SERVER_TOKEN
+        else:
+            operations = (
+                cygrpc.SendStatusFromServerOperation(
+                    state.trailing_metadata,
+                    effective_code,
+                    effective_details,
+                    _EMPTY_FLAGS,
+                ),
+            )
+            token = _SEND_STATUS_FROM_SERVER_TOKEN
+        call.start_server_batch(
+            operations, _send_status_from_server(state, token)
+        )
+        state.statused = True
+        state.due.add(token)
+
+
+def _receive_close_on_server(state: _RPCState) -> ServerCallbackTag:
+    def receive_close_on_server(receive_close_on_server_event):
+        with state.condition:
+            if receive_close_on_server_event.batch_operations[0].cancelled():
+                state.client = _CANCELLED
+            elif state.client is _OPEN:
+                state.client = _CLOSED
+            state.condition.notify_all()
+            return _possibly_finish_call(state, _RECEIVE_CLOSE_ON_SERVER_TOKEN)
+
+    return receive_close_on_server
+
+
+def _receive_message(
+    state: _RPCState,
+    call: cygrpc.Call,
+    request_deserializer: Optional[DeserializingFunction],
+) -> ServerCallbackTag:
+    def receive_message(receive_message_event):
+        serialized_request = _serialized_request(receive_message_event)
+        if serialized_request is None:
+            with state.condition:
+                if state.client is _OPEN:
+                    state.client = _CLOSED
+                state.condition.notify_all()
+                return _possibly_finish_call(state, _RECEIVE_MESSAGE_TOKEN)
+        else:
+            request = _common.deserialize(
+                serialized_request, request_deserializer
+            )
+            with state.condition:
+                if request is None:
+                    _abort(
+                        state,
+                        call,
+                        cygrpc.StatusCode.internal,
+                        b"Exception deserializing request!",
+                    )
+                else:
+                    state.request = request
+                state.condition.notify_all()
+                return _possibly_finish_call(state, _RECEIVE_MESSAGE_TOKEN)
+
+    return receive_message
+
+
+def _send_initial_metadata(state: _RPCState) -> ServerCallbackTag:
+    def send_initial_metadata(unused_send_initial_metadata_event):
+        with state.condition:
+            return _possibly_finish_call(state, _SEND_INITIAL_METADATA_TOKEN)
+
+    return send_initial_metadata
+
+
+def _send_message(state: _RPCState, token: str) -> ServerCallbackTag:
+    def send_message(unused_send_message_event):
+        with state.condition:
+            state.condition.notify_all()
+            return _possibly_finish_call(state, token)
+
+    return send_message
+
+
+class _Context(grpc.ServicerContext):
+    _rpc_event: cygrpc.BaseEvent
+    _state: _RPCState
+    request_deserializer: Optional[DeserializingFunction]
+
+    def __init__(
+        self,
+        rpc_event: cygrpc.BaseEvent,
+        state: _RPCState,
+        request_deserializer: Optional[DeserializingFunction],
+    ):
+        self._rpc_event = rpc_event
+        self._state = state
+        self._request_deserializer = request_deserializer
+
+    def is_active(self) -> bool:
+        with self._state.condition:
+            return _is_rpc_state_active(self._state)
+
+    def time_remaining(self) -> float:
+        return max(self._rpc_event.call_details.deadline - time.time(), 0)
+
+    def cancel(self) -> None:
+        self._rpc_event.call.cancel()
+
+    def add_callback(self, callback: NullaryCallbackType) -> bool:
+        with self._state.condition:
+            if self._state.callbacks is None:
+                return False
+            self._state.callbacks.append(callback)
+            return True
+
+    def disable_next_message_compression(self) -> None:
+        with self._state.condition:
+            self._state.disable_next_compression = True
+
+    def invocation_metadata(self) -> Optional[MetadataType]:
+        return self._rpc_event.invocation_metadata
+
+    def peer(self) -> str:
+        return _common.decode(self._rpc_event.call.peer())
+
+    def peer_identities(self) -> Optional[Sequence[bytes]]:
+        return cygrpc.peer_identities(self._rpc_event.call)
+
+    def peer_identity_key(self) -> Optional[str]:
+        id_key = cygrpc.peer_identity_key(self._rpc_event.call)
+        return id_key if id_key is None else _common.decode(id_key)
+
+    def auth_context(self) -> Mapping[str, Sequence[bytes]]:
+        auth_context = cygrpc.auth_context(self._rpc_event.call)
+        auth_context_dict = {} if auth_context is None else auth_context
+        return {
+            _common.decode(key): value
+            for key, value in auth_context_dict.items()
+        }
+
+    def set_compression(self, compression: grpc.Compression) -> None:
+        with self._state.condition:
+            self._state.compression_algorithm = compression
+
+    def send_initial_metadata(self, initial_metadata: MetadataType) -> None:
+        with self._state.condition:
+            if self._state.client is _CANCELLED:
+                _raise_rpc_error(self._state)
+            if self._state.initial_metadata_allowed:
+                operation = _get_initial_metadata_operation(
+                    self._state, initial_metadata
+                )
+                self._rpc_event.call.start_server_batch(
+                    (operation,), _send_initial_metadata(self._state)
+                )
+                self._state.initial_metadata_allowed = False
+                self._state.due.add(_SEND_INITIAL_METADATA_TOKEN)
+            else:
+                error_msg = "Initial metadata no longer allowed!"
+                raise ValueError(error_msg)
+
+    def set_trailing_metadata(self, trailing_metadata: MetadataType) -> None:
+        with self._state.condition:
+            self._state.trailing_metadata = trailing_metadata
+
+    def trailing_metadata(self) -> Optional[MetadataType]:
+        return self._state.trailing_metadata
+
+    def abort(self, code: grpc.StatusCode, details: str) -> None:
+        # treat OK like other invalid arguments: fail the RPC
+        if code == grpc.StatusCode.OK:
+            _LOGGER.error(
+                "abort() called with StatusCode.OK; returning UNKNOWN"
+            )
+            code = grpc.StatusCode.UNKNOWN
+            details = ""
+        with self._state.condition:
+            self._state.code = code
+            self._state.details = _common.encode(details)
+            self._state.aborted = True
+            raise Exception()  # noqa: TRY002
+
+    def abort_with_status(self, status: grpc.Status) -> None:
+        self._state.trailing_metadata = status.trailing_metadata
+        self.abort(status.code, status.details)
+
+    def set_code(self, code: grpc.StatusCode) -> None:
+        with self._state.condition:
+            self._state.code = code
+
+    def code(self) -> grpc.StatusCode:
+        return self._state.code
+
+    def set_details(self, details: str) -> None:
+        with self._state.condition:
+            self._state.details = _common.encode(details)
+
+    def details(self) -> bytes:
+        return self._state.details
+
+    def _finalize_state(self) -> None:
+        pass
+
+
+class _RequestIterator(object):
+    _state: _RPCState
+    _call: cygrpc.Call
+    _request_deserializer: Optional[DeserializingFunction]
+
+    def __init__(
+        self,
+        state: _RPCState,
+        call: cygrpc.Call,
+        request_deserializer: Optional[DeserializingFunction],
+    ):
+        self._state = state
+        self._call = call
+        self._request_deserializer = request_deserializer
+
+    def _raise_or_start_receive_message(self) -> None:
+        if self._state.client is _CANCELLED:
+            _raise_rpc_error(self._state)
+        elif not _is_rpc_state_active(self._state):
+            raise StopIteration()
+        else:
+            self._call.start_server_batch(
+                (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
+                _receive_message(
+                    self._state, self._call, self._request_deserializer
+                ),
+            )
+            self._state.due.add(_RECEIVE_MESSAGE_TOKEN)
+
+    def _look_for_request(self) -> Any:
+        if self._state.client is _CANCELLED:
+            _raise_rpc_error(self._state)
+        elif (
+            self._state.request is None
+            and _RECEIVE_MESSAGE_TOKEN not in self._state.due
+        ):
+            raise StopIteration()
+        else:
+            request = self._state.request
+            self._state.request = None
+            return request
+
+        raise AssertionError()  # should never run
+
+    def _next(self) -> Any:
+        with self._state.condition:
+            self._raise_or_start_receive_message()
+            while True:
+                self._state.condition.wait()
+                request = self._look_for_request()
+                if request is not None:
+                    return request
+
+    def __iter__(self) -> _RequestIterator:
+        return self
+
+    def __next__(self) -> Any:
+        return self._next()
+
+    def next(self) -> Any:
+        return self._next()
+
+
+def _unary_request(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    request_deserializer: Optional[DeserializingFunction],
+) -> Callable[[], Any]:
+    def unary_request():
+        with state.condition:
+            if not _is_rpc_state_active(state):
+                return None
+            rpc_event.call.start_server_batch(
+                (cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS),),
+                _receive_message(state, rpc_event.call, request_deserializer),
+            )
+            state.due.add(_RECEIVE_MESSAGE_TOKEN)
+            while True:
+                state.condition.wait()
+                if state.request is None:
+                    if state.client is _CLOSED:
+                        details = (
+                            '"{}" requires exactly one request message.'.format(
+                                rpc_event.call_details.method
+                            )
+                        )
+                        _abort(
+                            state,
+                            rpc_event.call,
+                            cygrpc.StatusCode.unimplemented,
+                            _common.encode(details),
+                        )
+                        return None
+                    if state.client is _CANCELLED:
+                        return None
+                else:
+                    request = state.request
+                    state.request = None
+                    return request
+
+    return unary_request
+
+
+def _call_behavior(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    behavior: ArityAgnosticMethodHandler,
+    argument: Any,
+    request_deserializer: Optional[DeserializingFunction],
+    send_response_callback: Optional[Callable[[ResponseType], None]] = None,
+) -> Tuple[Union[ResponseType, Iterator[ResponseType]], bool]:
+    from grpc import _create_servicer_context
+
+    with _create_servicer_context(
+        rpc_event, state, request_deserializer
+    ) as context:
+        try:
+            response_or_iterator = None
+            if send_response_callback is not None:
+                response_or_iterator = behavior(
+                    argument, context, send_response_callback
+                )
+            else:
+                response_or_iterator = behavior(argument, context)
+            return response_or_iterator, True
+        except Exception as exception:  # pylint: disable=broad-except
+            with state.condition:
+                if state.aborted:
+                    _abort(
+                        state,
+                        rpc_event.call,
+                        cygrpc.StatusCode.unknown,
+                        b"RPC Aborted",
+                    )
+                elif exception not in state.rpc_errors:
+                    try:
+                        details = "Exception calling application: {}".format(
+                            exception
+                        )
+                    except Exception:  # pylint: disable=broad-except
+                        details = (
+                            "Calling application raised unprintable Exception!"
+                        )
+                        _LOGGER.exception(
+                            traceback.format_exception(
+                                type(exception),
+                                exception,
+                                exception.__traceback__,
+                            )
+                        )
+                        traceback.print_exc()
+                    _LOGGER.exception(details)
+                    _abort(
+                        state,
+                        rpc_event.call,
+                        cygrpc.StatusCode.unknown,
+                        _common.encode(details),
+                    )
+            return None, False
+
+
+def _take_response_from_response_iterator(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    response_iterator: Iterator[ResponseType],
+) -> Tuple[ResponseType, bool]:
+    try:
+        return next(response_iterator), True
+    except StopIteration:
+        return None, True
+    except Exception as exception:  # pylint: disable=broad-except
+        with state.condition:
+            if state.aborted:
+                _abort(
+                    state,
+                    rpc_event.call,
+                    cygrpc.StatusCode.unknown,
+                    b"RPC Aborted",
+                )
+            elif exception not in state.rpc_errors:
+                details = "Exception iterating responses: {}".format(exception)
+                _LOGGER.exception(details)
+                _abort(
+                    state,
+                    rpc_event.call,
+                    cygrpc.StatusCode.unknown,
+                    _common.encode(details),
+                )
+        return None, False
+
+
+def _serialize_response(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    response: Any,
+    response_serializer: Optional[SerializingFunction],
+) -> Optional[bytes]:
+    serialized_response = _common.serialize(response, response_serializer)
+    if serialized_response is None:
+        with state.condition:
+            _abort(
+                state,
+                rpc_event.call,
+                cygrpc.StatusCode.internal,
+                b"Failed to serialize response!",
+            )
+        return None
+    return serialized_response
+
+
+def _get_send_message_op_flags_from_state(
+    state: _RPCState,
+) -> Union[int, cygrpc.WriteFlag]:
+    if state.disable_next_compression:
+        return cygrpc.WriteFlag.no_compress
+    return _EMPTY_FLAGS
+
+
+def _reset_per_message_state(state: _RPCState) -> None:
+    with state.condition:
+        state.disable_next_compression = False
+
+
+def _send_response(
+    rpc_event: cygrpc.BaseEvent, state: _RPCState, serialized_response: bytes
+) -> bool:
+    with state.condition:
+        if not _is_rpc_state_active(state):
+            return False
+        if state.initial_metadata_allowed:
+            operations = (
+                _get_initial_metadata_operation(state, None),
+                cygrpc.SendMessageOperation(
+                    serialized_response,
+                    _get_send_message_op_flags_from_state(state),
+                ),
+            )
+            state.initial_metadata_allowed = False
+            token = _SEND_INITIAL_METADATA_AND_SEND_MESSAGE_TOKEN
+        else:
+            operations = (
+                cygrpc.SendMessageOperation(
+                    serialized_response,
+                    _get_send_message_op_flags_from_state(state),
+                ),
+            )
+            token = _SEND_MESSAGE_TOKEN
+        rpc_event.call.start_server_batch(
+            operations, _send_message(state, token)
+        )
+        state.due.add(token)
+        _reset_per_message_state(state)
+        while True:
+            state.condition.wait()
+            if token not in state.due:
+                return _is_rpc_state_active(state)
+
+
+def _status(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    serialized_response: Optional[bytes],
+) -> None:
+    with state.condition:
+        if state.client is not _CANCELLED:
+            code = _completion_code(state)
+            details = _details(state)
+            operations = [
+                cygrpc.SendStatusFromServerOperation(
+                    state.trailing_metadata, code, details, _EMPTY_FLAGS
+                ),
+            ]
+            if state.initial_metadata_allowed:
+                operations.append(_get_initial_metadata_operation(state, None))
+            if serialized_response is not None:
+                operations.append(
+                    cygrpc.SendMessageOperation(
+                        serialized_response,
+                        _get_send_message_op_flags_from_state(state),
+                    )
+                )
+            rpc_event.call.start_server_batch(
+                operations,
+                _send_status_from_server(state, _SEND_STATUS_FROM_SERVER_TOKEN),
+            )
+            state.statused = True
+            _reset_per_message_state(state)
+            state.due.add(_SEND_STATUS_FROM_SERVER_TOKEN)
+
+
+def _unary_response_in_pool(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    behavior: ArityAgnosticMethodHandler,
+    argument_thunk: Callable[[], Any],
+    request_deserializer: Optional[SerializingFunction],
+    response_serializer: Optional[SerializingFunction],
+) -> None:
+    cygrpc.install_context_from_request_call_event(rpc_event)
+
+    try:
+        argument = argument_thunk()
+        if argument is not None:
+            response, proceed = _call_behavior(
+                rpc_event, state, behavior, argument, request_deserializer
+            )
+            if proceed:
+                serialized_response = _serialize_response(
+                    rpc_event, state, response, response_serializer
+                )
+                if serialized_response is not None:
+                    _status(rpc_event, state, serialized_response)
+    except Exception:  # pylint: disable=broad-except
+        traceback.print_exc()
+    finally:
+        cygrpc.uninstall_context()
+
+
+def _stream_response_in_pool(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    behavior: ArityAgnosticMethodHandler,
+    argument_thunk: Callable[[], Any],
+    request_deserializer: Optional[DeserializingFunction],
+    response_serializer: Optional[SerializingFunction],
+) -> None:
+    cygrpc.install_context_from_request_call_event(rpc_event)
+
+    def send_response(response: Any) -> None:
+        if response is None:
+            _status(rpc_event, state, None)
+        else:
+            serialized_response = _serialize_response(
+                rpc_event, state, response, response_serializer
+            )
+            if serialized_response is not None:
+                _send_response(rpc_event, state, serialized_response)
+
+    try:
+        argument = argument_thunk()
+        if argument is not None:
+            if (
+                hasattr(behavior, "experimental_non_blocking")
+                and behavior.experimental_non_blocking
+            ):
+                _call_behavior(
+                    rpc_event,
+                    state,
+                    behavior,
+                    argument,
+                    request_deserializer,
+                    send_response_callback=send_response,
+                )
+            else:
+                response_iterator, proceed = _call_behavior(
+                    rpc_event, state, behavior, argument, request_deserializer
+                )
+                if proceed:
+                    _send_message_callback_to_blocking_iterator_adapter(
+                        rpc_event, state, send_response, response_iterator
+                    )
+    except Exception:  # pylint: disable=broad-except
+        traceback.print_exc()
+    finally:
+        cygrpc.uninstall_context()
+
+
+def _is_rpc_state_active(state: _RPCState) -> bool:
+    return state.client is not _CANCELLED and not state.statused
+
+
+def _send_message_callback_to_blocking_iterator_adapter(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    send_response_callback: Callable[[ResponseType], None],
+    response_iterator: Iterator[ResponseType],
+) -> None:
+    while True:
+        response, proceed = _take_response_from_response_iterator(
+            rpc_event, state, response_iterator
+        )
+        if proceed:
+            send_response_callback(response)
+            if not _is_rpc_state_active(state):
+                break
+        else:
+            break
+
+
+def _select_thread_pool_for_behavior(
+    behavior: ArityAgnosticMethodHandler,
+    default_thread_pool: futures.ThreadPoolExecutor,
+) -> futures.ThreadPoolExecutor:
+    if hasattr(behavior, "experimental_thread_pool") and isinstance(
+        behavior.experimental_thread_pool, futures.ThreadPoolExecutor
+    ):
+        return behavior.experimental_thread_pool
+    return default_thread_pool
+
+
+def _handle_unary_unary(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    method_handler: grpc.RpcMethodHandler,
+    default_thread_pool: futures.ThreadPoolExecutor,
+) -> futures.Future:
+    unary_request = _unary_request(
+        rpc_event, state, method_handler.request_deserializer
+    )
+    thread_pool = _select_thread_pool_for_behavior(
+        method_handler.unary_unary, default_thread_pool
+    )
+    return thread_pool.submit(
+        state.context.run,
+        _unary_response_in_pool,
+        rpc_event,
+        state,
+        method_handler.unary_unary,
+        unary_request,
+        method_handler.request_deserializer,
+        method_handler.response_serializer,
+    )
+
+
+def _handle_unary_stream(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    method_handler: grpc.RpcMethodHandler,
+    default_thread_pool: futures.ThreadPoolExecutor,
+) -> futures.Future:
+    unary_request = _unary_request(
+        rpc_event, state, method_handler.request_deserializer
+    )
+    thread_pool = _select_thread_pool_for_behavior(
+        method_handler.unary_stream, default_thread_pool
+    )
+    return thread_pool.submit(
+        state.context.run,
+        _stream_response_in_pool,
+        rpc_event,
+        state,
+        method_handler.unary_stream,
+        unary_request,
+        method_handler.request_deserializer,
+        method_handler.response_serializer,
+    )
+
+
+def _handle_stream_unary(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    method_handler: grpc.RpcMethodHandler,
+    default_thread_pool: futures.ThreadPoolExecutor,
+) -> futures.Future:
+    request_iterator = _RequestIterator(
+        state, rpc_event.call, method_handler.request_deserializer
+    )
+    thread_pool = _select_thread_pool_for_behavior(
+        method_handler.stream_unary, default_thread_pool
+    )
+    return thread_pool.submit(
+        state.context.run,
+        _unary_response_in_pool,
+        rpc_event,
+        state,
+        method_handler.stream_unary,
+        lambda: request_iterator,
+        method_handler.request_deserializer,
+        method_handler.response_serializer,
+    )
+
+
+def _handle_stream_stream(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    method_handler: grpc.RpcMethodHandler,
+    default_thread_pool: futures.ThreadPoolExecutor,
+) -> futures.Future:
+    request_iterator = _RequestIterator(
+        state, rpc_event.call, method_handler.request_deserializer
+    )
+    thread_pool = _select_thread_pool_for_behavior(
+        method_handler.stream_stream, default_thread_pool
+    )
+    return thread_pool.submit(
+        state.context.run,
+        _stream_response_in_pool,
+        rpc_event,
+        state,
+        method_handler.stream_stream,
+        lambda: request_iterator,
+        method_handler.request_deserializer,
+        method_handler.response_serializer,
+    )
+
+
+def _find_method_handler(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    method_with_handler: _Method,
+    interceptor_pipeline: Optional[_interceptor._ServicePipeline],
+) -> Optional[grpc.RpcMethodHandler]:
+    def query_handlers(
+        handler_call_details: _HandlerCallDetails,
+    ) -> Optional[grpc.RpcMethodHandler]:
+        return method_with_handler.handler(handler_call_details)
+
+    method_name = method_with_handler.name()
+    if not method_name:
+        method_name = _common.decode(rpc_event.call_details.method)
+
+    handler_call_details = _HandlerCallDetails(
+        method_name,
+        rpc_event.invocation_metadata,
+    )
+
+    if interceptor_pipeline is not None:
+        return state.context.run(
+            interceptor_pipeline.execute, query_handlers, handler_call_details
+        )
+    return state.context.run(query_handlers, handler_call_details)
+
+
+def _reject_rpc(
+    rpc_event: cygrpc.BaseEvent,
+    rpc_state: _RPCState,
+    status: cygrpc.StatusCode,
+    details: bytes,
+):
+    operations = (
+        _get_initial_metadata_operation(rpc_state, None),
+        cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),
+        cygrpc.SendStatusFromServerOperation(
+            None, status, details, _EMPTY_FLAGS
+        ),
+    )
+    rpc_event.call.start_server_batch(
+        operations,
+        lambda _ignored_event: (
+            rpc_state,
+            (),
+        ),
+    )
+
+
+def _handle_with_method_handler(
+    rpc_event: cygrpc.BaseEvent,
+    state: _RPCState,
+    method_handler: grpc.RpcMethodHandler,
+    thread_pool: futures.ThreadPoolExecutor,
+) -> futures.Future:
+    with state.condition:
+        rpc_event.call.start_server_batch(
+            (cygrpc.ReceiveCloseOnServerOperation(_EMPTY_FLAGS),),
+            _receive_close_on_server(state),
+        )
+        state.due.add(_RECEIVE_CLOSE_ON_SERVER_TOKEN)
+        if method_handler.request_streaming:
+            if method_handler.response_streaming:
+                return _handle_stream_stream(
+                    rpc_event, state, method_handler, thread_pool
+                )
+            return _handle_stream_unary(
+                rpc_event, state, method_handler, thread_pool
+            )
+        if method_handler.response_streaming:
+            return _handle_unary_stream(
+                rpc_event, state, method_handler, thread_pool
+            )
+        return _handle_unary_unary(
+            rpc_event, state, method_handler, thread_pool
+        )
+
+
+def _handle_call(
+    rpc_event: cygrpc.BaseEvent,
+    method_with_handler: _Method,
+    interceptor_pipeline: Optional[_interceptor._ServicePipeline],
+    thread_pool: futures.ThreadPoolExecutor,
+    concurrency_exceeded: bool,
+) -> Tuple[Optional[_RPCState], Optional[futures.Future]]:
+    """Handles RPC based on provided handlers.
+
+      When receiving a call event from Core, registered method will have its
+    name as tag, we pass the tag as registered_method_name to this method,
+    then we can find the handler in registered_method_handlers based on
+    the method name.
+
+      For call event with unregistered method, the method name will be included
+    in rpc_event.call_details.method and we need to query the generics handlers
+    to find the actual handler.
+    """
+    if not rpc_event.success:
+        return None, None
+    if rpc_event.call_details.method or method_with_handler.name():
+        rpc_state = _RPCState()
+        try:
+            method_handler = _find_method_handler(
+                rpc_event,
+                rpc_state,
+                method_with_handler,
+                interceptor_pipeline,
+            )
+        except Exception as exception:  # pylint: disable=broad-except
+            details = "Exception servicing handler: {}".format(exception)
+            _LOGGER.exception(details)
+            _reject_rpc(
+                rpc_event,
+                rpc_state,
+                cygrpc.StatusCode.unknown,
+                b"Error in service handler!",
+            )
+            return rpc_state, None
+        if method_handler is None:
+            _reject_rpc(
+                rpc_event,
+                rpc_state,
+                cygrpc.StatusCode.unimplemented,
+                b"Method not found!",
+            )
+            return rpc_state, None
+        if concurrency_exceeded:
+            _reject_rpc(
+                rpc_event,
+                rpc_state,
+                cygrpc.StatusCode.resource_exhausted,
+                b"Concurrent RPC limit exceeded!",
+            )
+            return rpc_state, None
+        return (
+            rpc_state,
+            _handle_with_method_handler(
+                rpc_event, rpc_state, method_handler, thread_pool
+            ),
+        )
+    return None, None
+
+
+@enum.unique
+class _ServerStage(enum.Enum):
+    STOPPED = "stopped"
+    STARTED = "started"
+    GRACE = "grace"
+
+
+class _ServerState(object):
+    lock: threading.RLock
+    completion_queue: cygrpc.CompletionQueue
+    server: cygrpc.Server
+    generic_handlers: List[grpc.GenericRpcHandler]
+    registered_method_handlers: Dict[str, grpc.RpcMethodHandler]
+    interceptor_pipeline: Optional[_interceptor._ServicePipeline]
+    thread_pool: futures.ThreadPoolExecutor
+    stage: _ServerStage
+    termination_event: threading.Event
+    shutdown_events: List[threading.Event]
+    maximum_concurrent_rpcs: Optional[int]
+    active_rpc_count: int
+    rpc_states: Set[_RPCState]
+    due: Set[str]
+    server_deallocated: bool
+
+    # pylint: disable=too-many-arguments
+    def __init__(
+        self,
+        completion_queue: cygrpc.CompletionQueue,
+        server: cygrpc.Server,
+        generic_handlers: Sequence[grpc.GenericRpcHandler],
+        interceptor_pipeline: Optional[_interceptor._ServicePipeline],
+        thread_pool: futures.ThreadPoolExecutor,
+        maximum_concurrent_rpcs: Optional[int],
+    ):
+        self.lock = threading.RLock()
+        self.completion_queue = completion_queue
+        self.server = server
+        self.generic_handlers = list(generic_handlers)
+        self.interceptor_pipeline = interceptor_pipeline
+        self.thread_pool = thread_pool
+        self.stage = _ServerStage.STOPPED
+        self.termination_event = threading.Event()
+        self.shutdown_events = [self.termination_event]
+        self.maximum_concurrent_rpcs = maximum_concurrent_rpcs
+        self.active_rpc_count = 0
+        self.registered_method_handlers = {}
+
+        # TODO(https://github.com/grpc/grpc/issues/6597): eliminate these fields.
+        self.rpc_states = set()
+        self.due = set()
+
+        # A "volatile" flag to interrupt the daemon serving thread
+        self.server_deallocated = False
+
+
+def _add_generic_handlers(
+    state: _ServerState, generic_handlers: Iterable[grpc.GenericRpcHandler]
+) -> None:
+    with state.lock:
+        state.generic_handlers.extend(generic_handlers)
+
+
+def _add_registered_method_handlers(
+    state: _ServerState, method_handlers: Dict[str, grpc.RpcMethodHandler]
+) -> None:
+    with state.lock:
+        state.registered_method_handlers.update(method_handlers)
+
+
+def _add_insecure_port(state: _ServerState, address: bytes) -> int:
+    with state.lock:
+        return state.server.add_http2_port(address)
+
+
+def _add_secure_port(
+    state: _ServerState,
+    address: bytes,
+    server_credentials: grpc.ServerCredentials,
+) -> int:
+    with state.lock:
+        return state.server.add_http2_port(
+            address, server_credentials._credentials
+        )
+
+
+def _request_call(state: _ServerState) -> None:
+    state.server.request_call(
+        state.completion_queue, state.completion_queue, _REQUEST_CALL_TAG
+    )
+    state.due.add(_REQUEST_CALL_TAG)
+
+
+def _request_registered_call(state: _ServerState, method: str) -> None:
+    registered_call_tag = method
+    state.server.request_registered_call(
+        state.completion_queue,
+        state.completion_queue,
+        method,
+        registered_call_tag,
+    )
+    state.due.add(registered_call_tag)
+
+
+# TODO(https://github.com/grpc/grpc/issues/6597): delete this function.
+def _stop_serving(state: _ServerState) -> bool:
+    if not state.rpc_states and not state.due:
+        state.server.destroy()
+        for shutdown_event in state.shutdown_events:
+            shutdown_event.set()
+        state.stage = _ServerStage.STOPPED
+        return True
+    return False
+
+
+def _on_call_completed(state: _ServerState) -> None:
+    with state.lock:
+        state.active_rpc_count -= 1
+
+
+# pylint: disable=too-many-branches
+def _process_event_and_continue(
+    state: _ServerState, event: cygrpc.BaseEvent
+) -> bool:
+    should_continue = True
+    if event.tag is _SHUTDOWN_TAG:
+        with state.lock:
+            state.due.remove(_SHUTDOWN_TAG)
+            if _stop_serving(state):
+                should_continue = False
+    elif (
+        event.tag is _REQUEST_CALL_TAG
+        or event.tag in state.registered_method_handlers
+    ):
+        registered_method_name = None
+        if event.tag in state.registered_method_handlers:
+            registered_method_name = event.tag
+            method_with_handler = _RegisteredMethod(
+                registered_method_name,
+                state.registered_method_handlers.get(
+                    registered_method_name, None
+                ),
+            )
+        else:
+            method_with_handler = _GenericMethod(
+                state.generic_handlers,
+            )
+        with state.lock:
+            state.due.remove(event.tag)
+            concurrency_exceeded = (
+                state.maximum_concurrent_rpcs is not None
+                and state.active_rpc_count >= state.maximum_concurrent_rpcs
+            )
+            rpc_state, rpc_future = _handle_call(
+                event,
+                method_with_handler,
+                state.interceptor_pipeline,
+                state.thread_pool,
+                concurrency_exceeded,
+            )
+            if rpc_state is not None:
+                state.rpc_states.add(rpc_state)
+            if rpc_future is not None:
+                state.active_rpc_count += 1
+                rpc_future.add_done_callback(
+                    lambda _unused_future: _on_call_completed(state)
+                )
+            if state.stage is _ServerStage.STARTED:
+                if registered_method_name in state.registered_method_handlers:
+                    _request_registered_call(state, registered_method_name)
+                else:
+                    _request_call(state)
+            elif _stop_serving(state):
+                should_continue = False
+    else:
+        rpc_state, callbacks = event.tag(event)
+        for callback in callbacks:
+            try:
+                callback()
+            except Exception:  # pylint: disable=broad-except
+                _LOGGER.exception("Exception calling callback!")
+        if rpc_state is not None:
+            with state.lock:
+                state.rpc_states.remove(rpc_state)
+                if _stop_serving(state):
+                    should_continue = False
+    return should_continue
+
+
+def _serve(state: _ServerState) -> None:
+    while True:
+        timeout = time.time() + _DEALLOCATED_SERVER_CHECK_PERIOD_S
+        event = state.completion_queue.poll(timeout)
+        if state.server_deallocated:
+            _begin_shutdown_once(state)
+        is_timeout = (
+            event.completion_type == cygrpc.CompletionType.queue_timeout
+        )
+        if not is_timeout and not _process_event_and_continue(state, event):
+            return
+        # We want to force the deletion of the previous event
+        # ~before~ we poll again; if the event has a reference
+        # to a shutdown Call object, this can induce spinlock.
+        event = None
+
+
+def _begin_shutdown_once(state: _ServerState) -> None:
+    with state.lock:
+        if state.stage is _ServerStage.STARTED:
+            state.server.shutdown(state.completion_queue, _SHUTDOWN_TAG)
+            state.stage = _ServerStage.GRACE
+            state.due.add(_SHUTDOWN_TAG)
+
+
+def _stop(state: _ServerState, grace: Optional[float]) -> threading.Event:
+    with state.lock:
+        if state.stage is _ServerStage.STOPPED:
+            shutdown_event = threading.Event()
+            shutdown_event.set()
+            return shutdown_event
+        _begin_shutdown_once(state)
+        shutdown_event = threading.Event()
+        state.shutdown_events.append(shutdown_event)
+        if grace is None:
+            state.server.cancel_all_calls()
+        else:
+
+            def cancel_all_calls_after_grace():
+                shutdown_event.wait(timeout=grace)
+                with state.lock:
+                    state.server.cancel_all_calls()
+
+            thread = threading.Thread(target=cancel_all_calls_after_grace)
+            thread.start()
+            return shutdown_event
+    shutdown_event.wait()
+    return shutdown_event
+
+
+def _start(state: _ServerState) -> None:
+    with state.lock:
+        if state.stage is not _ServerStage.STOPPED:
+            error_msg = "Cannot start already-started server!"
+            raise ValueError(error_msg)
+        state.server.start()
+        state.stage = _ServerStage.STARTED
+        # Request a call for each registered method so we can handle any of them.
+        for method in state.registered_method_handlers:
+            _request_registered_call(state, method)
+        # Also request a call for non-registered method.
+        _request_call(state)
+        thread = threading.Thread(target=_serve, args=(state,))
+        thread.daemon = True
+        thread.start()
+
+
+def _validate_generic_rpc_handlers(
+    generic_rpc_handlers: Iterable[grpc.GenericRpcHandler],
+) -> None:
+    for generic_rpc_handler in generic_rpc_handlers:
+        service_attribute = getattr(generic_rpc_handler, "service", None)
+        if service_attribute is None:
+            error_msg = (
+                f'"{generic_rpc_handler}" must conform to'
+                'grpc.GenericRpcHandler type but does not have "service" method!'
+            )
+            raise AttributeError(error_msg)
+
+
+def _augment_options(
+    base_options: Sequence[ChannelArgumentType],
+    compression: Optional[grpc.Compression],
+    xds: bool,
+) -> Sequence[ChannelArgumentType]:
+    compression_option = _compression.create_channel_option(compression)
+    maybe_server_call_tracer_factory_option = (
+        _observability.create_server_call_tracer_factory_option(xds)
+    )
+    return (
+        tuple(base_options)
+        + compression_option
+        + maybe_server_call_tracer_factory_option
+    )
+
+
+class _Server(grpc.Server):
+    _state: _ServerState
+
+    # pylint: disable=too-many-arguments
+    def __init__(
+        self,
+        thread_pool: futures.ThreadPoolExecutor,
+        generic_handlers: Sequence[grpc.GenericRpcHandler],
+        interceptors: Sequence[grpc.ServerInterceptor],
+        options: Sequence[ChannelArgumentType],
+        maximum_concurrent_rpcs: Optional[int],
+        compression: Optional[grpc.Compression],
+        xds: bool,
+    ):
+        completion_queue = cygrpc.CompletionQueue()
+        server = cygrpc.Server(_augment_options(options, compression, xds), xds)
+        server.register_completion_queue(completion_queue)
+        self._state = _ServerState(
+            completion_queue,
+            server,
+            generic_handlers,
+            _interceptor.service_pipeline(interceptors),
+            thread_pool,
+            maximum_concurrent_rpcs,
+        )
+        self._cy_server = server
+
+    def add_generic_rpc_handlers(
+        self, generic_rpc_handlers: Iterable[grpc.GenericRpcHandler]
+    ) -> None:
+        _validate_generic_rpc_handlers(generic_rpc_handlers)
+        _add_generic_handlers(self._state, generic_rpc_handlers)
+
+    def add_registered_method_handlers(
+        self,
+        service_name: str,
+        method_handlers: Dict[str, grpc.RpcMethodHandler],
+    ) -> None:
+        # Can't register method once server started.
+        with self._state.lock:
+            if self._state.stage is _ServerStage.STARTED:
+                return
+
+        # TODO(xuanwn): We should validate method_handlers first.
+        method_to_handlers = {
+            _common.fully_qualified_method(service_name, method): method_handler
+            for method, method_handler in method_handlers.items()
+        }
+        for fully_qualified_method in method_to_handlers:
+            self._cy_server.register_method(fully_qualified_method)
+        _add_registered_method_handlers(self._state, method_to_handlers)
+
+    def add_insecure_port(self, address: str) -> int:
+        return _common.validate_port_binding_result(
+            address, _add_insecure_port(self._state, _common.encode(address))
+        )
+
+    def add_secure_port(
+        self, address: str, server_credentials: grpc.ServerCredentials
+    ) -> int:
+        return _common.validate_port_binding_result(
+            address,
+            _add_secure_port(
+                self._state, _common.encode(address), server_credentials
+            ),
+        )
+
+    def start(self) -> None:
+        _start(self._state)
+
+    def wait_for_termination(self, timeout: Optional[float] = None) -> bool:
+        # NOTE(https://bugs.python.org/issue35935)
+        # Remove this workaround once threading.Event.wait() is working with
+        # CTRL+C across platforms.
+        return _common.wait(
+            self._state.termination_event.wait,
+            self._state.termination_event.is_set,
+            timeout=timeout,
+        )
+
+    def stop(self, grace: Optional[float]) -> threading.Event:
+        return _stop(self._state, grace)
+
+    def __del__(self):
+        if hasattr(self, "_state"):
+            # We can not grab a lock in __del__(), so set a flag to signal the
+            # serving daemon thread (if it exists) to initiate shutdown.
+            self._state.server_deallocated = True
+
+
+def create_server(
+    thread_pool: futures.ThreadPoolExecutor,
+    generic_rpc_handlers: Sequence[grpc.GenericRpcHandler],
+    interceptors: Sequence[grpc.ServerInterceptor],
+    options: Sequence[ChannelArgumentType],
+    maximum_concurrent_rpcs: Optional[int],
+    compression: Optional[grpc.Compression],
+    xds: bool,
+) -> _Server:
+    _validate_generic_rpc_handlers(generic_rpc_handlers)
+    return _Server(
+        thread_pool,
+        generic_rpc_handlers,
+        interceptors,
+        options,
+        maximum_concurrent_rpcs,
+        compression,
+        xds,
+    )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_simple_stubs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_simple_stubs.py
new file mode 100644
index 0000000000000000000000000000000000000000..be4aea8d1483023b3fec7960bb7a7d746d983b30
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_simple_stubs.py
@@ -0,0 +1,587 @@
+# Copyright 2020 The gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Functions that obviate explicit stubs and explicit channels."""
+
+import collections
+import datetime
+import logging
+import os
+import threading
+from typing import (
+    Any,
+    AnyStr,
+    Callable,
+    Dict,
+    Iterator,
+    Optional,
+    Sequence,
+    Tuple,
+    TypeVar,
+    Union,
+)
+
+import grpc
+from grpc.experimental import experimental_api
+
+RequestType = TypeVar("RequestType")
+ResponseType = TypeVar("ResponseType")
+
+OptionsType = Sequence[Tuple[str, str]]
+CacheKey = Tuple[
+    str,
+    OptionsType,
+    Optional[grpc.ChannelCredentials],
+    Optional[grpc.Compression],
+]
+
+_LOGGER = logging.getLogger(__name__)
+
+_EVICTION_PERIOD_KEY = "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS"
+if _EVICTION_PERIOD_KEY in os.environ:
+    _EVICTION_PERIOD = datetime.timedelta(
+        seconds=float(os.environ[_EVICTION_PERIOD_KEY])
+    )
+    _LOGGER.debug(
+        "Setting managed channel eviction period to %s", _EVICTION_PERIOD
+    )
+else:
+    _EVICTION_PERIOD = datetime.timedelta(minutes=10)
+
+_MAXIMUM_CHANNELS_KEY = "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM"
+if _MAXIMUM_CHANNELS_KEY in os.environ:
+    _MAXIMUM_CHANNELS = int(os.environ[_MAXIMUM_CHANNELS_KEY])
+    _LOGGER.debug("Setting maximum managed channels to %d", _MAXIMUM_CHANNELS)
+else:
+    _MAXIMUM_CHANNELS = 2**8
+
+_DEFAULT_TIMEOUT_KEY = "GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS"
+if _DEFAULT_TIMEOUT_KEY in os.environ:
+    _DEFAULT_TIMEOUT = float(os.environ[_DEFAULT_TIMEOUT_KEY])
+    _LOGGER.debug("Setting default timeout seconds to %f", _DEFAULT_TIMEOUT)
+else:
+    _DEFAULT_TIMEOUT = 60.0
+
+
+def _create_channel(
+    target: str,
+    options: Sequence[Tuple[str, str]],
+    channel_credentials: Optional[grpc.ChannelCredentials],
+    compression: Optional[grpc.Compression],
+) -> grpc.Channel:
+    debug_msg = (
+        f"Creating secure channel with credentials '{channel_credentials}', "
+        f"options '{options}' and compression '{compression}'"
+    )
+    _LOGGER.debug(debug_msg)
+    return grpc.secure_channel(
+        target,
+        credentials=channel_credentials,
+        options=options,
+        compression=compression,
+    )
+
+
+class ChannelCache:
+    # NOTE(rbellevi): Untyped due to reference cycle.
+    _singleton = None
+    _lock: threading.RLock = threading.RLock()
+    _condition: threading.Condition = threading.Condition(lock=_lock)
+    _eviction_ready: threading.Event = threading.Event()
+
+    _mapping: Dict[CacheKey, Tuple[grpc.Channel, datetime.datetime]]
+    _eviction_thread: threading.Thread
+
+    def __init__(self):
+        self._mapping = collections.OrderedDict()
+        self._eviction_thread = threading.Thread(
+            target=ChannelCache._perform_evictions, daemon=True
+        )
+        self._eviction_thread.start()
+
+    @staticmethod
+    def get():
+        with ChannelCache._lock:
+            if ChannelCache._singleton is None:
+                ChannelCache._singleton = ChannelCache()
+        ChannelCache._eviction_ready.wait()
+        return ChannelCache._singleton
+
+    def _evict_locked(self, key: CacheKey):
+        channel, _ = self._mapping.pop(key)
+        _LOGGER.debug(
+            "Evicting channel %s with configuration %s.", channel, key
+        )
+        channel.close()
+        del channel
+
+    @staticmethod
+    def _perform_evictions():
+        while True:
+            with ChannelCache._lock:
+                ChannelCache._eviction_ready.set()
+                if not ChannelCache._singleton._mapping:
+                    ChannelCache._condition.wait()
+                elif len(ChannelCache._singleton._mapping) > _MAXIMUM_CHANNELS:
+                    key = next(iter(ChannelCache._singleton._mapping.keys()))
+                    ChannelCache._singleton._evict_locked(key)
+                    # And immediately reevaluate.
+                else:
+                    key, (_, eviction_time) = next(
+                        iter(ChannelCache._singleton._mapping.items())
+                    )
+                    now = datetime.datetime.now()
+                    if eviction_time <= now:
+                        ChannelCache._singleton._evict_locked(key)
+                        continue
+                    time_to_eviction = (eviction_time - now).total_seconds()
+                    # NOTE: We aim to *eventually* coalesce to a state in
+                    # which no overdue channels are in the cache and the
+                    # length of the cache is longer than _MAXIMUM_CHANNELS.
+                    # We tolerate momentary states in which these two
+                    # criteria are not met.
+                    ChannelCache._condition.wait(timeout=time_to_eviction)
+
+    def get_channel(
+        self,
+        target: str,
+        options: Sequence[Tuple[str, str]],
+        channel_credentials: Optional[grpc.ChannelCredentials],
+        insecure: bool,
+        compression: Optional[grpc.Compression],
+        method: str,
+        _registered_method: bool,
+    ) -> Tuple[grpc.Channel, Optional[int]]:
+        """Get a channel from cache or creates a new channel.
+
+        This method also takes care of register method for channel,
+          which means we'll register a new call handle if we're calling a
+          non-registered method for an existing channel.
+
+        Returns:
+            A tuple with two items. The first item is the channel, second item is
+              the call handle if the method is registered, None if it's not registered.
+        """
+        if insecure and channel_credentials:
+            raise ValueError(
+                "The insecure option is mutually exclusive with "
+                + "the channel_credentials option. Please use one "
+                + "or the other."
+            )
+        if insecure:
+            channel_credentials = (
+                grpc.experimental.insecure_channel_credentials()
+            )
+        elif channel_credentials is None:
+            _LOGGER.debug("Defaulting to SSL channel credentials.")
+            channel_credentials = grpc.ssl_channel_credentials()
+        key = (target, options, channel_credentials, compression)
+        with self._lock:
+            channel_data = self._mapping.get(key, None)
+            call_handle = None
+            if channel_data is not None:
+                channel = channel_data[0]
+                # Register a new call handle if we're calling a registered method for an
+                # existing channel and this method is not registered.
+                if _registered_method:
+                    call_handle = channel._get_registered_call_handle(method)
+                self._mapping.pop(key)
+                self._mapping[key] = (
+                    channel,
+                    datetime.datetime.now() + _EVICTION_PERIOD,
+                )
+                return channel, call_handle
+            channel = _create_channel(
+                target, options, channel_credentials, compression
+            )
+            if _registered_method:
+                call_handle = channel._get_registered_call_handle(method)
+            self._mapping[key] = (
+                channel,
+                datetime.datetime.now() + _EVICTION_PERIOD,
+            )
+            if (
+                len(self._mapping) == 1
+                or len(self._mapping) >= _MAXIMUM_CHANNELS
+            ):
+                self._condition.notify()
+            return channel, call_handle
+
+    def _test_only_channel_count(self) -> int:
+        with self._lock:
+            return len(self._mapping)
+
+
+@experimental_api
+# pylint: disable=too-many-locals
+def unary_unary(
+    request: RequestType,
+    target: str,
+    method: str,
+    request_serializer: Optional[Callable[[Any], bytes]] = None,
+    response_deserializer: Optional[Callable[[bytes], Any]] = None,
+    options: Sequence[Tuple[AnyStr, AnyStr]] = (),
+    channel_credentials: Optional[grpc.ChannelCredentials] = None,
+    insecure: bool = False,
+    call_credentials: Optional[grpc.CallCredentials] = None,
+    compression: Optional[grpc.Compression] = None,
+    wait_for_ready: Optional[bool] = None,
+    timeout: Optional[float] = _DEFAULT_TIMEOUT,
+    metadata: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None,
+    _registered_method: Optional[bool] = False,
+) -> ResponseType:
+    """Invokes a unary-unary RPC without an explicitly specified channel.
+
+    THIS IS AN EXPERIMENTAL API.
+
+    This is backed by a per-process cache of channels. Channels are evicted
+    from the cache after a fixed period by a background. Channels will also be
+    evicted if more than a configured maximum accumulate.
+
+    The default eviction period is 10 minutes. One may set the environment
+    variable "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" to configure this.
+
+    The default maximum number of channels is 256. One may set the
+    environment variable "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" to configure
+    this.
+
+    Args:
+      request: An iterator that yields request values for the RPC.
+      target: The server address.
+      method: The name of the RPC method.
+      request_serializer: Optional :term:`serializer` for serializing the request
+        message. Request goes unserialized in case None is passed.
+      response_deserializer: Optional :term:`deserializer` for deserializing the response
+        message. Response goes undeserialized in case None is passed.
+      options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC Core
+        runtime) to configure the channel.
+      channel_credentials: A credential applied to the whole channel, e.g. the
+        return value of grpc.ssl_channel_credentials() or
+        grpc.insecure_channel_credentials().
+      insecure: If True, specifies channel_credentials as
+        :term:`grpc.insecure_channel_credentials()`. This option is mutually
+        exclusive with the `channel_credentials` option.
+      call_credentials: A call credential applied to each call individually,
+        e.g. the output of grpc.metadata_call_credentials() or
+        grpc.access_token_call_credentials().
+      compression: An optional value indicating the compression method to be
+        used over the lifetime of the channel, e.g. grpc.Compression.Gzip.
+      wait_for_ready: An optional flag indicating whether the RPC should fail
+        immediately if the connection is not ready at the time the RPC is
+        invoked, or if it should wait until the connection to the server
+        becomes ready. When using this option, the user will likely also want
+        to set a timeout. Defaults to True.
+      timeout: An optional duration of time in seconds to allow for the RPC,
+        after which an exception will be raised. If timeout is unspecified,
+        defaults to a timeout controlled by the
+        GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS environment variable. If that is
+        unset, defaults to 60 seconds. Supply a value of None to indicate that
+        no timeout should be enforced.
+      metadata: Optional metadata to send to the server.
+
+    Returns:
+      The response to the RPC.
+    """
+    channel, method_handle = ChannelCache.get().get_channel(
+        target,
+        options,
+        channel_credentials,
+        insecure,
+        compression,
+        method,
+        _registered_method,
+    )
+    multicallable = channel.unary_unary(
+        method, request_serializer, response_deserializer, method_handle
+    )
+    wait_for_ready = wait_for_ready if wait_for_ready is not None else True
+    return multicallable(
+        request,
+        metadata=metadata,
+        wait_for_ready=wait_for_ready,
+        credentials=call_credentials,
+        timeout=timeout,
+    )
+
+
+@experimental_api
+# pylint: disable=too-many-locals
+def unary_stream(
+    request: RequestType,
+    target: str,
+    method: str,
+    request_serializer: Optional[Callable[[Any], bytes]] = None,
+    response_deserializer: Optional[Callable[[bytes], Any]] = None,
+    options: Sequence[Tuple[AnyStr, AnyStr]] = (),
+    channel_credentials: Optional[grpc.ChannelCredentials] = None,
+    insecure: bool = False,
+    call_credentials: Optional[grpc.CallCredentials] = None,
+    compression: Optional[grpc.Compression] = None,
+    wait_for_ready: Optional[bool] = None,
+    timeout: Optional[float] = _DEFAULT_TIMEOUT,
+    metadata: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None,
+    _registered_method: Optional[bool] = False,
+) -> Iterator[ResponseType]:
+    """Invokes a unary-stream RPC without an explicitly specified channel.
+
+    THIS IS AN EXPERIMENTAL API.
+
+    This is backed by a per-process cache of channels. Channels are evicted
+    from the cache after a fixed period by a background. Channels will also be
+    evicted if more than a configured maximum accumulate.
+
+    The default eviction period is 10 minutes. One may set the environment
+    variable "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" to configure this.
+
+    The default maximum number of channels is 256. One may set the
+    environment variable "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" to configure
+    this.
+
+    Args:
+      request: An iterator that yields request values for the RPC.
+      target: The server address.
+      method: The name of the RPC method.
+      request_serializer: Optional :term:`serializer` for serializing the request
+        message. Request goes unserialized in case None is passed.
+      response_deserializer: Optional :term:`deserializer` for deserializing the response
+        message. Response goes undeserialized in case None is passed.
+      options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC Core
+        runtime) to configure the channel.
+      channel_credentials: A credential applied to the whole channel, e.g. the
+        return value of grpc.ssl_channel_credentials().
+      insecure: If True, specifies channel_credentials as
+        :term:`grpc.insecure_channel_credentials()`. This option is mutually
+        exclusive with the `channel_credentials` option.
+      call_credentials: A call credential applied to each call individually,
+        e.g. the output of grpc.metadata_call_credentials() or
+        grpc.access_token_call_credentials().
+      compression: An optional value indicating the compression method to be
+        used over the lifetime of the channel, e.g. grpc.Compression.Gzip.
+      wait_for_ready: An optional flag indicating whether the RPC should fail
+        immediately if the connection is not ready at the time the RPC is
+        invoked, or if it should wait until the connection to the server
+        becomes ready. When using this option, the user will likely also want
+        to set a timeout. Defaults to True.
+      timeout: An optional duration of time in seconds to allow for the RPC,
+        after which an exception will be raised. If timeout is unspecified,
+        defaults to a timeout controlled by the
+        GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS environment variable. If that is
+        unset, defaults to 60 seconds. Supply a value of None to indicate that
+        no timeout should be enforced.
+      metadata: Optional metadata to send to the server.
+
+    Returns:
+      An iterator of responses.
+    """
+    channel, method_handle = ChannelCache.get().get_channel(
+        target,
+        options,
+        channel_credentials,
+        insecure,
+        compression,
+        method,
+        _registered_method,
+    )
+    multicallable = channel.unary_stream(
+        method, request_serializer, response_deserializer, method_handle
+    )
+    wait_for_ready = wait_for_ready if wait_for_ready is not None else True
+    return multicallable(
+        request,
+        metadata=metadata,
+        wait_for_ready=wait_for_ready,
+        credentials=call_credentials,
+        timeout=timeout,
+    )
+
+
+@experimental_api
+# pylint: disable=too-many-locals
+def stream_unary(
+    request_iterator: Iterator[RequestType],
+    target: str,
+    method: str,
+    request_serializer: Optional[Callable[[Any], bytes]] = None,
+    response_deserializer: Optional[Callable[[bytes], Any]] = None,
+    options: Sequence[Tuple[AnyStr, AnyStr]] = (),
+    channel_credentials: Optional[grpc.ChannelCredentials] = None,
+    insecure: bool = False,
+    call_credentials: Optional[grpc.CallCredentials] = None,
+    compression: Optional[grpc.Compression] = None,
+    wait_for_ready: Optional[bool] = None,
+    timeout: Optional[float] = _DEFAULT_TIMEOUT,
+    metadata: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None,
+    _registered_method: Optional[bool] = False,
+) -> ResponseType:
+    """Invokes a stream-unary RPC without an explicitly specified channel.
+
+    THIS IS AN EXPERIMENTAL API.
+
+    This is backed by a per-process cache of channels. Channels are evicted
+    from the cache after a fixed period by a background. Channels will also be
+    evicted if more than a configured maximum accumulate.
+
+    The default eviction period is 10 minutes. One may set the environment
+    variable "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" to configure this.
+
+    The default maximum number of channels is 256. One may set the
+    environment variable "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" to configure
+    this.
+
+    Args:
+      request_iterator: An iterator that yields request values for the RPC.
+      target: The server address.
+      method: The name of the RPC method.
+      request_serializer: Optional :term:`serializer` for serializing the request
+        message. Request goes unserialized in case None is passed.
+      response_deserializer: Optional :term:`deserializer` for deserializing the response
+        message. Response goes undeserialized in case None is passed.
+      options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC Core
+        runtime) to configure the channel.
+      channel_credentials: A credential applied to the whole channel, e.g. the
+        return value of grpc.ssl_channel_credentials().
+      call_credentials: A call credential applied to each call individually,
+        e.g. the output of grpc.metadata_call_credentials() or
+        grpc.access_token_call_credentials().
+      insecure: If True, specifies channel_credentials as
+        :term:`grpc.insecure_channel_credentials()`. This option is mutually
+        exclusive with the `channel_credentials` option.
+      compression: An optional value indicating the compression method to be
+        used over the lifetime of the channel, e.g. grpc.Compression.Gzip.
+      wait_for_ready: An optional flag indicating whether the RPC should fail
+        immediately if the connection is not ready at the time the RPC is
+        invoked, or if it should wait until the connection to the server
+        becomes ready. When using this option, the user will likely also want
+        to set a timeout. Defaults to True.
+      timeout: An optional duration of time in seconds to allow for the RPC,
+        after which an exception will be raised. If timeout is unspecified,
+        defaults to a timeout controlled by the
+        GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS environment variable. If that is
+        unset, defaults to 60 seconds. Supply a value of None to indicate that
+        no timeout should be enforced.
+      metadata: Optional metadata to send to the server.
+
+    Returns:
+      The response to the RPC.
+    """
+    channel, method_handle = ChannelCache.get().get_channel(
+        target,
+        options,
+        channel_credentials,
+        insecure,
+        compression,
+        method,
+        _registered_method,
+    )
+    multicallable = channel.stream_unary(
+        method, request_serializer, response_deserializer, method_handle
+    )
+    wait_for_ready = wait_for_ready if wait_for_ready is not None else True
+    return multicallable(
+        request_iterator,
+        metadata=metadata,
+        wait_for_ready=wait_for_ready,
+        credentials=call_credentials,
+        timeout=timeout,
+    )
+
+
+@experimental_api
+# pylint: disable=too-many-locals
+def stream_stream(
+    request_iterator: Iterator[RequestType],
+    target: str,
+    method: str,
+    request_serializer: Optional[Callable[[Any], bytes]] = None,
+    response_deserializer: Optional[Callable[[bytes], Any]] = None,
+    options: Sequence[Tuple[AnyStr, AnyStr]] = (),
+    channel_credentials: Optional[grpc.ChannelCredentials] = None,
+    insecure: bool = False,
+    call_credentials: Optional[grpc.CallCredentials] = None,
+    compression: Optional[grpc.Compression] = None,
+    wait_for_ready: Optional[bool] = None,
+    timeout: Optional[float] = _DEFAULT_TIMEOUT,
+    metadata: Optional[Sequence[Tuple[str, Union[str, bytes]]]] = None,
+    _registered_method: Optional[bool] = False,
+) -> Iterator[ResponseType]:
+    """Invokes a stream-stream RPC without an explicitly specified channel.
+
+    THIS IS AN EXPERIMENTAL API.
+
+    This is backed by a per-process cache of channels. Channels are evicted
+    from the cache after a fixed period by a background. Channels will also be
+    evicted if more than a configured maximum accumulate.
+
+    The default eviction period is 10 minutes. One may set the environment
+    variable "GRPC_PYTHON_MANAGED_CHANNEL_EVICTION_SECONDS" to configure this.
+
+    The default maximum number of channels is 256. One may set the
+    environment variable "GRPC_PYTHON_MANAGED_CHANNEL_MAXIMUM" to configure
+    this.
+
+    Args:
+      request_iterator: An iterator that yields request values for the RPC.
+      target: The server address.
+      method: The name of the RPC method.
+      request_serializer: Optional :term:`serializer` for serializing the request
+        message. Request goes unserialized in case None is passed.
+      response_deserializer: Optional :term:`deserializer` for deserializing the response
+        message. Response goes undeserialized in case None is passed.
+      options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC Core
+        runtime) to configure the channel.
+      channel_credentials: A credential applied to the whole channel, e.g. the
+        return value of grpc.ssl_channel_credentials().
+      call_credentials: A call credential applied to each call individually,
+        e.g. the output of grpc.metadata_call_credentials() or
+        grpc.access_token_call_credentials().
+      insecure: If True, specifies channel_credentials as
+        :term:`grpc.insecure_channel_credentials()`. This option is mutually
+        exclusive with the `channel_credentials` option.
+      compression: An optional value indicating the compression method to be
+        used over the lifetime of the channel, e.g. grpc.Compression.Gzip.
+      wait_for_ready: An optional flag indicating whether the RPC should fail
+        immediately if the connection is not ready at the time the RPC is
+        invoked, or if it should wait until the connection to the server
+        becomes ready. When using this option, the user will likely also want
+        to set a timeout. Defaults to True.
+      timeout: An optional duration of time in seconds to allow for the RPC,
+        after which an exception will be raised. If timeout is unspecified,
+        defaults to a timeout controlled by the
+        GRPC_PYTHON_DEFAULT_TIMEOUT_SECONDS environment variable. If that is
+        unset, defaults to 60 seconds. Supply a value of None to indicate that
+        no timeout should be enforced.
+      metadata: Optional metadata to send to the server.
+
+    Returns:
+      An iterator of responses.
+    """
+    channel, method_handle = ChannelCache.get().get_channel(
+        target,
+        options,
+        channel_credentials,
+        insecure,
+        compression,
+        method,
+        _registered_method,
+    )
+    multicallable = channel.stream_stream(
+        method, request_serializer, response_deserializer, method_handle
+    )
+    wait_for_ready = wait_for_ready if wait_for_ready is not None else True
+    return multicallable(
+        request_iterator,
+        metadata=metadata,
+        wait_for_ready=wait_for_ready,
+        credentials=call_credentials,
+        timeout=timeout,
+    )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_typing.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_typing.py
new file mode 100644
index 0000000000000000000000000000000000000000..3761c8d31b723934a8f78542bd6ec3e4fa398392
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_typing.py
@@ -0,0 +1,96 @@
+# Copyright 2022 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Common types for gRPC Sync API"""
+
+from typing import (
+    TYPE_CHECKING,
+    Any,
+    Callable,
+    Iterable,
+    Iterator,
+    Optional,
+    Sequence,
+    Tuple,
+    TypeVar,
+    Union,
+)
+
+from grpc._cython import cygrpc
+
+if TYPE_CHECKING:
+    from grpc import ServicerContext
+    from grpc._server import _RPCState
+
+RequestType = TypeVar("RequestType")
+ResponseType = TypeVar("ResponseType")
+SerializingFunction = Callable[[Any], bytes]
+DeserializingFunction = Callable[[bytes], Any]
+MetadataType = Sequence[Tuple[str, Union[str, bytes]]]
+ChannelArgumentType = Tuple[str, Any]
+DoneCallbackType = Callable[[Any], None]
+NullaryCallbackType = Callable[[], None]
+RequestIterableType = Iterable[Any]
+ResponseIterableType = Iterable[Any]
+UserTag = Callable[[cygrpc.BaseEvent], bool]
+IntegratedCallFactory = Callable[
+    [
+        int,
+        bytes,
+        Optional[str],
+        Optional[float],
+        Optional[MetadataType],
+        Optional[cygrpc.CallCredentials],
+        Sequence[Sequence[cygrpc.Operation]],
+        UserTag,
+        Any,
+        Optional[int],
+    ],
+    cygrpc.IntegratedCall,
+]
+ServerTagCallbackType = Tuple[
+    Optional["_RPCState"], Sequence[NullaryCallbackType]
+]
+ServerCallbackTag = Callable[[cygrpc.BaseEvent], ServerTagCallbackType]
+ArityAgnosticMethodHandler = Union[
+    Callable[
+        [RequestType, "ServicerContext", Callable[[ResponseType], None]],
+        ResponseType,
+    ],
+    Callable[
+        [RequestType, "ServicerContext", Callable[[ResponseType], None]],
+        Iterator[ResponseType],
+    ],
+    Callable[
+        [
+            Iterator[RequestType],
+            "ServicerContext",
+            Callable[[ResponseType], None],
+        ],
+        ResponseType,
+    ],
+    Callable[
+        [
+            Iterator[RequestType],
+            "ServicerContext",
+            Callable[[ResponseType], None],
+        ],
+        Iterator[ResponseType],
+    ],
+    Callable[[RequestType, "ServicerContext"], ResponseType],
+    Callable[[RequestType, "ServicerContext"], Iterator[ResponseType]],
+    Callable[[Iterator[RequestType], "ServicerContext"], ResponseType],
+    Callable[
+        [Iterator[RequestType], "ServicerContext"], Iterator[ResponseType]
+    ],
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_utilities.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_utilities.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ac7b57e71d26981eeb4708d552049440e78d930
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpc/_utilities.py
@@ -0,0 +1,220 @@
+# Copyright 2015 gRPC authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Internal utilities for gRPC Python."""
+
+import collections
+import logging
+import threading
+import time
+from typing import Callable, Dict, Optional, Sequence
+
+import grpc
+from grpc import _common
+from grpc._typing import DoneCallbackType
+
+_LOGGER = logging.getLogger(__name__)
+
+_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE = (
+    'Exception calling connectivity future "done" callback!'
+)
+
+
+class RpcMethodHandler(
+    collections.namedtuple(
+        "_RpcMethodHandler",
+        (
+            "request_streaming",
+            "response_streaming",
+            "request_deserializer",
+            "response_serializer",
+            "unary_unary",
+            "unary_stream",
+            "stream_unary",
+            "stream_stream",
+        ),
+    ),
+    grpc.RpcMethodHandler,
+):
+    pass
+
+
+class DictionaryGenericHandler(grpc.ServiceRpcHandler):
+    _name: str
+    _method_handlers: Dict[str, grpc.RpcMethodHandler]
+
+    def __init__(
+        self, service: str, method_handlers: Dict[str, grpc.RpcMethodHandler]
+    ):
+        self._name = service
+        self._method_handlers = {
+            _common.fully_qualified_method(service, method): method_handler
+            for method, method_handler in method_handlers.items()
+        }
+
+    def service_name(self) -> str:
+        return self._name
+
+    def service(
+        self, handler_call_details: grpc.HandlerCallDetails
+    ) -> Optional[grpc.RpcMethodHandler]:
+        details_method = handler_call_details.method
+        return self._method_handlers.get(
+            details_method
+        )  # pytype: disable=attribute-error
+
+
+class _ChannelReadyFuture(grpc.Future):
+    _condition: threading.Condition
+    _channel: grpc.Channel
+    _matured: bool
+    _cancelled: bool
+    _done_callbacks: Sequence[Callable]
+
+    def __init__(self, channel: grpc.Channel):
+        self._condition = threading.Condition()
+        self._channel = channel
+
+        self._matured = False
+        self._cancelled = False
+        self._done_callbacks = []
+
+    def _block(self, timeout: Optional[float]) -> None:
+        until = None if timeout is None else time.time() + timeout
+        with self._condition:
+            while True:
+                if self._cancelled:
+                    raise grpc.FutureCancelledError()
+                if self._matured:
+                    return
+                if until is None:
+                    self._condition.wait()
+                else:
+                    remaining = until - time.time()
+                    if remaining < 0:
+                        raise grpc.FutureTimeoutError()
+                    self._condition.wait(timeout=remaining)
+
+    def _update(self, connectivity: Optional[grpc.ChannelConnectivity]) -> None:
+        with self._condition:
+            if (
+                not self._cancelled
+                and connectivity is grpc.ChannelConnectivity.READY
+            ):
+                self._matured = True
+                self._channel.unsubscribe(self._update)
+                self._condition.notify_all()
+                done_callbacks = tuple(self._done_callbacks)
+                self._done_callbacks = None
+            else:
+                return
+
+        for done_callback in done_callbacks:
+            try:
+                done_callback(self)
+            except Exception:  # pylint: disable=broad-except
+                _LOGGER.exception(_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE)
+
+    def cancel(self) -> bool:
+        with self._condition:
+            if not self._matured:
+                self._cancelled = True
+                self._channel.unsubscribe(self._update)
+                self._condition.notify_all()
+                done_callbacks = tuple(self._done_callbacks)
+                self._done_callbacks = None
+            else:
+                return False
+
+        for done_callback in done_callbacks:
+            try:
+                done_callback(self)
+            except Exception:  # pylint: disable=broad-except
+                _LOGGER.exception(_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE)
+
+        return True
+
+    def cancelled(self) -> bool:
+        with self._condition:
+            return self._cancelled
+
+    def running(self) -> bool:
+        with self._condition:
+            return not self._cancelled and not self._matured
+
+    def done(self) -> bool:
+        with self._condition:
+            return self._cancelled or self._matured
+
+    def result(self, timeout: Optional[float] = None) -> None:
+        self._block(timeout)
+
+    def exception(self, timeout: Optional[float] = None) -> None:
+        self._block(timeout)
+
+    def traceback(self, timeout: Optional[float] = None) -> None:
+        self._block(timeout)
+
+    def add_done_callback(self, fn: DoneCallbackType):
+        with self._condition:
+            if not self._cancelled and not self._matured:
+                self._done_callbacks.append(fn)
+                return
+
+        fn(self)
+
+    def start(self):
+        with self._condition:
+            self._channel.subscribe(self._update, try_to_connect=True)
+
+    def __del__(self):
+        with self._condition:
+            if not self._cancelled and not self._matured:
+                self._channel.unsubscribe(self._update)
+
+
+def channel_ready_future(channel: grpc.Channel) -> _ChannelReadyFuture:
+    ready_future = _ChannelReadyFuture(channel)
+    ready_future.start()
+    return ready_future
+
+
+def first_version_is_lower(version1: str, version2: str) -> bool:
+    """
+    Compares two versions in the format '1.60.1' or '1.60.1.dev0'.
+
+    This method will be used in all stubs generated by grpcio-tools to check whether
+    the stub version is compatible with the runtime grpcio.
+
+    Args:
+        version1: The first version string.
+        version2: The second version string.
+
+    Returns:
+        True if version1 is lower, False otherwise.
+    """
+    version1_list = version1.split(".")
+    version2_list = version2.split(".")
+
+    try:
+        for i in range(3):
+            if int(version1_list[i]) < int(version2_list[i]):
+                return True
+            if int(version1_list[i]) > int(version2_list[i]):
+                return False
+    except ValueError:
+        # Return false in case we can't convert version to int.
+        return False
+
+    # The version without dev0 will be considered lower.
+    return len(version1_list) < len(version2_list)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..7da42f458d2ff572151e7b567f403d9077d90600
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/METADATA
@@ -0,0 +1,129 @@
+Metadata-Version: 2.4
+Name: grpcio
+Version: 1.80.0
+Summary: HTTP/2-based RPC framework
+Author-email: The gRPC Authors 
+License-Expression: Apache-2.0
+Project-URL: Homepage, https://grpc.io
+Project-URL: Source Code, https://github.com/grpc/grpc
+Project-URL: Bug Tracker, https://github.com/grpc/grpc/issues
+Project-URL: Documentation, https://grpc.github.io/grpc/python
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Requires-Python: >=3.9
+Description-Content-Type: text/x-rst
+License-File: LICENSE
+Requires-Dist: typing-extensions~=4.12
+Provides-Extra: protobuf
+Requires-Dist: grpcio-tools>=1.80.0; extra == "protobuf"
+Dynamic: classifier
+Dynamic: license-file
+Dynamic: provides-extra
+Dynamic: requires-dist
+Dynamic: requires-python
+
+gRPC Python
+===========
+
+Package for gRPC Python.
+
+
+Installation
+------------
+
+gRPC Python is available for Linux, macOS, and Windows.
+
+Installing From PyPI
+~~~~~~~~~~~~~~~~~~~~
+
+If you are installing locally...
+
+::
+
+  $ pip install grpcio
+
+Else system wide (on Ubuntu)...
+
+::
+
+  $ sudo pip install grpcio
+
+If you're on Windows make sure that you installed the :code:`pip.exe` component
+when you installed Python (if not go back and install it!) then invoke:
+
+::
+
+  $ pip.exe install grpcio
+
+Windows users may need to invoke :code:`pip.exe` from a command line ran as
+administrator.
+
+n.b. On Windows and on Mac OS X one *must* have a recent release of :code:`pip`
+to retrieve the proper wheel from PyPI. Be sure to upgrade to the latest
+version!
+
+Installing From Source
+~~~~~~~~~~~~~~~~~~~~~~
+
+Building from source requires that you have the Python headers (usually a
+package named :code:`python-dev`).
+
+::
+
+  $ export REPO_ROOT=grpc  # REPO_ROOT can be any directory of your choice
+  $ git clone -b RELEASE_TAG_HERE https://github.com/grpc/grpc $REPO_ROOT
+  $ cd $REPO_ROOT
+  $ git submodule update --init
+
+  # To include systemd socket-activation feature in the build,
+  # first install the `libsystemd-dev` package, then :
+  $ export GRPC_PYTHON_BUILD_WITH_SYSTEMD=1
+
+  # For the next two commands do `sudo pip install` if you get permission-denied errors
+  $ pip install -r requirements.txt
+  $ GRPC_PYTHON_BUILD_WITH_CYTHON=1 pip install .
+
+You cannot currently install Python from source on Windows. Things might work
+out for you in MSYS2 (follow the Linux instructions), but it isn't officially
+supported at the moment.
+
+Troubleshooting
+~~~~~~~~~~~~~~~
+
+Help, I ...
+
+* **... see the following error on some platforms**
+
+  ::
+
+    /tmp/pip-build-U8pSsr/cython/Cython/Plex/Scanners.c:4:20: fatal error: Python.h: No such file or directory
+    #include "Python.h"
+                    ^
+    compilation terminated.
+
+  You can fix it by installing `python-dev` package. i.e
+
+  ::
+
+    sudo apt-get install python-dev
+
+
+Versioning
+~~~~~~~~~~
+
+gRPC Python is developed in a monorepo shared with implementations of gRPC in
+other programming languages. While the minor versions are released in
+lock-step with other languages in the repo (e.g. 1.63.0 is guaranteed to exist
+for all languages), patch versions may be specific to only a single
+language. For example, if 1.63.1 is a C++-specific patch, 1.63.1 may not be
+uploaded to PyPi. As a result, it is __not__ a good assumption that the latest
+patch for a given minor version on Github is also the latest patch for that
+same minor version on PyPi.
+
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..5eb3f8b629bac8d318b1f68e1448affac7d8a558
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/RECORD
@@ -0,0 +1,122 @@
+grpc/__init__.py,sha256=FBhUsKt5SndyPAMJxmJkznS-0THDWkfn38RevkhhmU4,84672
+grpc/__pycache__/__init__.cpython-311.pyc,,
+grpc/__pycache__/_auth.cpython-311.pyc,,
+grpc/__pycache__/_channel.cpython-311.pyc,,
+grpc/__pycache__/_common.cpython-311.pyc,,
+grpc/__pycache__/_compression.cpython-311.pyc,,
+grpc/__pycache__/_grpcio_metadata.cpython-311.pyc,,
+grpc/__pycache__/_interceptor.cpython-311.pyc,,
+grpc/__pycache__/_observability.cpython-311.pyc,,
+grpc/__pycache__/_plugin_wrapping.cpython-311.pyc,,
+grpc/__pycache__/_runtime_protos.cpython-311.pyc,,
+grpc/__pycache__/_server.cpython-311.pyc,,
+grpc/__pycache__/_simple_stubs.cpython-311.pyc,,
+grpc/__pycache__/_typing.cpython-311.pyc,,
+grpc/__pycache__/_utilities.cpython-311.pyc,,
+grpc/_auth.py,sha256=uGbFEodfxjTU8TStcOVYlQMa0fBwYe0mf7pJU3co5UY,2730
+grpc/_channel.py,sha256=-lwfPC6mcw9pLrnxe1VSF3PIJcv2P3Nvz-IbxPzqBoQ,82267
+grpc/_common.py,sha256=VgAURBAOqquKA8Jqmsh0Q0bWMOHnQMv5gwludiph8aE,6906
+grpc/_compression.py,sha256=kGe7KzCYqoUm9yjYXQ5FjXmpmb5-FgyqdLgeYHVqaxM,2054
+grpc/_cython/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590
+grpc/_cython/__pycache__/__init__.cpython-311.pyc,,
+grpc/_cython/_credentials/roots.pem,sha256=iQrx6SIqWnawwL7sTFcKoy0a1ZIIj89WEN6VR4qN5jg,268777
+grpc/_cython/_cygrpc/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590
+grpc/_cython/_cygrpc/__pycache__/__init__.cpython-311.pyc,,
+grpc/_cython/_cygrpc/private_key_signing/private_key_signer_py_wrapper.cc,sha256=h-QjQKKQLTlwWOPj6wqMXHBLMWW8HVomWrOgdWJJW6o,3533
+grpc/_cython/_cygrpc/private_key_signing/private_key_signer_py_wrapper.h,sha256=FJ7ifduQ7TLWtb4owlV78M_WopRmTCHqBW7jJHJ-y5A,5612
+grpc/_cython/cygrpc.cp311-win_amd64.pyd,sha256=1Ndo6LJqMxime45omi88OtSrYhxO39iec6DtzWvBYiM,10764288
+grpc/_grpcio_metadata.py,sha256=ngni2EJyUFGdAD2KZzgMgXpACO-RxEs5emI_K241gIU,26
+grpc/_interceptor.py,sha256=7g1d9awl-gGtEs2L-3c62ioCro9v4W6Swb6xSloW0co,26613
+grpc/_observability.py,sha256=xuDEXrGJGB_4oM0_uemPcqTcf6GSHGsULa2SM1aPF5U,10863
+grpc/_plugin_wrapping.py,sha256=VyVorDAQTGvhxpmZFgBpKoXNnTWS-SsO1ryrjb_4za0,4543
+grpc/_runtime_protos.py,sha256=DU1IE-9IHcxhAP3GNG_Pix3fJF0rYPkSwIynkhshppY,5912
+grpc/_server.py,sha256=-y4rYTeYUIR4at5eE7BWuz_yLJzfc1YGRZ6e7xRKBbQ,51701
+grpc/_simple_stubs.py,sha256=KAzIPz8FQr-Ep3VW3zRUykfPy1t2Q0bD40cJlaz1xus,25091
+grpc/_typing.py,sha256=ZhI_OB7oXINC8y8mJLPuEpgmOmEB5qSQMngS05BII7I,2886
+grpc/_utilities.py,sha256=SkZ38dFxjJjXrjsRrbbxlg7BkVvoCEkSNo95qLLRtPQ,7117
+grpc/aio/__init__.py,sha256=LDB_hbdwzxFJ3HSKmlvnc_rI0DGie0d3FuDjQS3-DxU,3255
+grpc/aio/__pycache__/__init__.cpython-311.pyc,,
+grpc/aio/__pycache__/_base_call.cpython-311.pyc,,
+grpc/aio/__pycache__/_base_channel.cpython-311.pyc,,
+grpc/aio/__pycache__/_base_server.cpython-311.pyc,,
+grpc/aio/__pycache__/_call.cpython-311.pyc,,
+grpc/aio/__pycache__/_channel.cpython-311.pyc,,
+grpc/aio/__pycache__/_interceptor.cpython-311.pyc,,
+grpc/aio/__pycache__/_metadata.cpython-311.pyc,,
+grpc/aio/__pycache__/_server.cpython-311.pyc,,
+grpc/aio/__pycache__/_typing.cpython-311.pyc,,
+grpc/aio/__pycache__/_utils.cpython-311.pyc,,
+grpc/aio/_base_call.py,sha256=aIdDcZN38QKAfMkJD5qTsu_WssbSQtLZcj8mBgqOsKA,7817
+grpc/aio/_base_channel.py,sha256=p0A0fLNsWRhs_qfwRwlUBN569DnzV84KXYF1fqzkDMA,14257
+grpc/aio/_base_server.py,sha256=H34TurID0XYflliD2JgYhn3_XL0qtzyP6zYipH5WT_g,12970
+grpc/aio/_call.py,sha256=ya6Z4hAdG3V2_mwFIDaRu9BgAkZ6lccfSc_cfEnJCn0,26231
+grpc/aio/_channel.py,sha256=n-43DY3Cp9wtGhNsjl9mwf5tTJWFRJqeKTpflaculA0,22693
+grpc/aio/_interceptor.py,sha256=10p_5akVoOsilEcdDRtkL23v6nY_UX9wqbPcaAlcEQQ,42633
+grpc/aio/_metadata.py,sha256=KRnx7Co9HFf-eHQRrlXHPZ63vceWq7AYt8qFHLXljf8,6276
+grpc/aio/_server.py,sha256=74qgeNfD8lb-8QMf6MwD62n6_d3onk4PYDbQtVkZbVw,9284
+grpc/aio/_typing.py,sha256=k50mtmrFaGcDxB6R_vW9Fp8MSYJrZtw112EixmDps1k,1455
+grpc/aio/_utils.py,sha256=Fw8FpKtucE2a2VRNF3JyAMzh0BtgNQZKpE5jWlHlwQw,843
+grpc/beta/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590
+grpc/beta/__pycache__/__init__.cpython-311.pyc,,
+grpc/beta/__pycache__/_client_adaptations.cpython-311.pyc,,
+grpc/beta/__pycache__/_metadata.cpython-311.pyc,,
+grpc/beta/__pycache__/_server_adaptations.cpython-311.pyc,,
+grpc/beta/__pycache__/implementations.cpython-311.pyc,,
+grpc/beta/__pycache__/interfaces.cpython-311.pyc,,
+grpc/beta/__pycache__/utilities.cpython-311.pyc,,
+grpc/beta/_client_adaptations.py,sha256=R8RXCyJcSIryUoAwNiHqiHlqbMG1ndY1vYG2VrFXE3c,27890
+grpc/beta/_metadata.py,sha256=0QoPBL4LzI9Awow2MPQneceT93cF98iSR_8ryvJtNA8,1652
+grpc/beta/_server_adaptations.py,sha256=bVjE4cFQgdUZx5fKWvLPrSAB0wD1TrmOXMSmK4D6nLo,14943
+grpc/beta/implementations.py,sha256=fEpftVpElsOzHK3MxVVQqE21CZ5HdBUkSAbjLNvU1Ew,12403
+grpc/beta/interfaces.py,sha256=U5D3tvq7Z_t4fCYJD9RfFqqnpSvS9VmB4cYQTtari-Y,6245
+grpc/beta/utilities.py,sha256=iwNXJN0Gp-jPd7WqyrcM44hMucOcBPMExjzAPCuTkPg,5007
+grpc/experimental/__init__.py,sha256=AhoFDvlUDB4Y2yJBF5NeE_zCTV490MJc-NhdCXjB5hg,6614
+grpc/experimental/__pycache__/__init__.cpython-311.pyc,,
+grpc/experimental/__pycache__/gevent.cpython-311.pyc,,
+grpc/experimental/__pycache__/session_cache.cpython-311.pyc,,
+grpc/experimental/aio/__init__.py,sha256=QoEtaa5C408IeaaSMKvooYNJdWCqyX6X9UYF-maJcIY,676
+grpc/experimental/aio/__pycache__/__init__.cpython-311.pyc,,
+grpc/experimental/gevent.py,sha256=ZmFL0iK7irhC9JtTC2JJP23-IRG3_ZCohRQBhhVWuyM,1000
+grpc/experimental/session_cache.py,sha256=OdASXKtZYY8vP1Yo6GeRi4dfEaVuvyiOK5CknnROExE,1578
+grpc/framework/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590
+grpc/framework/__pycache__/__init__.cpython-311.pyc,,
+grpc/framework/common/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590
+grpc/framework/common/__pycache__/__init__.cpython-311.pyc,,
+grpc/framework/common/__pycache__/cardinality.cpython-311.pyc,,
+grpc/framework/common/__pycache__/style.cpython-311.pyc,,
+grpc/framework/common/cardinality.py,sha256=lhyS0Chc2kUCH84K069F2PgNLFJHpjfBjSdN79olL8E,1014
+grpc/framework/common/style.py,sha256=eFEX5mA2ynBzHFf8H2eKeAFp2mm-fR343MiGq9Xq_sI,848
+grpc/framework/foundation/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590
+grpc/framework/foundation/__pycache__/__init__.cpython-311.pyc,,
+grpc/framework/foundation/__pycache__/abandonment.cpython-311.pyc,,
+grpc/framework/foundation/__pycache__/callable_util.cpython-311.pyc,,
+grpc/framework/foundation/__pycache__/future.cpython-311.pyc,,
+grpc/framework/foundation/__pycache__/logging_pool.cpython-311.pyc,,
+grpc/framework/foundation/__pycache__/stream.cpython-311.pyc,,
+grpc/framework/foundation/__pycache__/stream_util.cpython-311.pyc,,
+grpc/framework/foundation/abandonment.py,sha256=lI3FSuizdQ85z8sxEKluhvYj9I64YeImvqWDuWu6JXs,900
+grpc/framework/foundation/callable_util.py,sha256=VGnmbsM_31Kk46fjyotBKqSyrCNSLpe7j1M51MHRyFI,3255
+grpc/framework/foundation/future.py,sha256=WGkqWv-4W0ahgE0iRsgsKdIuVNIBny22OrARQb4AMfc,8592
+grpc/framework/foundation/logging_pool.py,sha256=SDfgyCoEI10sJhw0a4ZWBMldd79r9VLvqu74a85i7_0,2314
+grpc/framework/foundation/stream.py,sha256=l2VMgFK5qhPMBT0yjM75ZppHMIf5Lzz6Iwnp6Wd9wAw,1420
+grpc/framework/foundation/stream_util.py,sha256=F2nRlVsQEJKiD_iBFT2FtmkbynQKEPjN0ChsUNY7FvU,4895
+grpc/framework/interfaces/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590
+grpc/framework/interfaces/__pycache__/__init__.cpython-311.pyc,,
+grpc/framework/interfaces/base/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590
+grpc/framework/interfaces/base/__pycache__/__init__.cpython-311.pyc,,
+grpc/framework/interfaces/base/__pycache__/base.cpython-311.pyc,,
+grpc/framework/interfaces/base/__pycache__/utilities.cpython-311.pyc,,
+grpc/framework/interfaces/base/base.py,sha256=5Bvs4SPEUAhJUQCvflvP4BqUx-UXs2SGBAXf2hAv9TA,12562
+grpc/framework/interfaces/base/utilities.py,sha256=fN-_DUGGZdbb8HwHmOmWYHcSRHZbWiPy1ScROb9zCzc,2445
+grpc/framework/interfaces/face/__init__.py,sha256=v-bMmhfnkYP7kR6Mw9wPLG_cCagk-ZKiUZi6pyap2GU,590
+grpc/framework/interfaces/face/__pycache__/__init__.cpython-311.pyc,,
+grpc/framework/interfaces/face/__pycache__/face.cpython-311.pyc,,
+grpc/framework/interfaces/face/__pycache__/utilities.cpython-311.pyc,,
+grpc/framework/interfaces/face/face.py,sha256=Ml3loDRLwrunMkCs_B9iE6uJEbV3QSCciWxLWykGaYo,40784
+grpc/framework/interfaces/face/utilities.py,sha256=i2hcUy2q1bGfZ2YGgz8vR1Hhjxd3VmqWQAN5G6Tel-0,7022
+grpcio-1.80.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+grpcio-1.80.0.dist-info/METADATA,sha256=rPtJchu7bXEA3CNT4-jzo9rNV27vbROHBoJpbRPLw-E,3893
+grpcio-1.80.0.dist-info/RECORD,,
+grpcio-1.80.0.dist-info/WHEEL,sha256=XHXMKJU3yoVh1ZanBXTJ5bDGb67oEYtF1S6bd8a4izI,101
+grpcio-1.80.0.dist-info/licenses/LICENSE,sha256=7Zq8SfH6PjzpYtisQuF2ElwKsAUexXg9_MgH3SpMHw8,30814
+grpcio-1.80.0.dist-info/top_level.txt,sha256=eEd2Jq_aVQFp38bWW8Pfwjz_5iibqeOFT-2zXlPAq_8,5
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..75a83ab128f69c4cd27d9a5be479a52a2597d3d1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (82.0.1)
+Root-Is-Purelib: false
+Tag: cp311-cp311-win_amd64
+
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..3b2fe54cba7bccaa783f551549920c8e8927cf1e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/grpcio-1.80.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+grpc
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..8a2f639061cc4a203f7109d8335d28076442c61d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/METADATA
@@ -0,0 +1,202 @@
+Metadata-Version: 2.4
+Name: h11
+Version: 0.16.0
+Summary: A pure-Python, bring-your-own-I/O implementation of HTTP/1.1
+Home-page: https://github.com/python-hyper/h11
+Author: Nathaniel J. Smith
+Author-email: njs@pobox.com
+License: MIT
+Classifier: Development Status :: 3 - Alpha
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Topic :: Internet :: WWW/HTTP
+Classifier: Topic :: System :: Networking
+Requires-Python: >=3.8
+License-File: LICENSE.txt
+Dynamic: author
+Dynamic: author-email
+Dynamic: classifier
+Dynamic: description
+Dynamic: home-page
+Dynamic: license
+Dynamic: license-file
+Dynamic: requires-python
+Dynamic: summary
+
+h11
+===
+
+.. image:: https://travis-ci.org/python-hyper/h11.svg?branch=master
+   :target: https://travis-ci.org/python-hyper/h11
+   :alt: Automated test status
+
+.. image:: https://codecov.io/gh/python-hyper/h11/branch/master/graph/badge.svg
+   :target: https://codecov.io/gh/python-hyper/h11
+   :alt: Test coverage
+
+.. image:: https://readthedocs.org/projects/h11/badge/?version=latest
+   :target: http://h11.readthedocs.io/en/latest/?badge=latest
+   :alt: Documentation Status
+
+This is a little HTTP/1.1 library written from scratch in Python,
+heavily inspired by `hyper-h2 `_.
+
+It's a "bring-your-own-I/O" library; h11 contains no IO code
+whatsoever. This means you can hook h11 up to your favorite network
+API, and that could be anything you want: synchronous, threaded,
+asynchronous, or your own implementation of `RFC 6214
+`_ -- h11 won't judge you.
+(Compare this to the current state of the art, where every time a `new
+network API `_ comes along then someone
+gets to start over reimplementing the entire HTTP protocol from
+scratch.) Cory Benfield made an `excellent blog post describing the
+benefits of this approach
+`_, or if you like video
+then here's his `PyCon 2016 talk on the same theme
+`_.
+
+This also means that h11 is not immediately useful out of the box:
+it's a toolkit for building programs that speak HTTP, not something
+that could directly replace ``requests`` or ``twisted.web`` or
+whatever. But h11 makes it much easier to implement something like
+``requests`` or ``twisted.web``.
+
+At a high level, working with h11 goes like this:
+
+1) First, create an ``h11.Connection`` object to track the state of a
+   single HTTP/1.1 connection.
+
+2) When you read data off the network, pass it to
+   ``conn.receive_data(...)``; you'll get back a list of objects
+   representing high-level HTTP "events".
+
+3) When you want to send a high-level HTTP event, create the
+   corresponding "event" object and pass it to ``conn.send(...)``;
+   this will give you back some bytes that you can then push out
+   through the network.
+
+For example, a client might instantiate and then send a
+``h11.Request`` object, then zero or more ``h11.Data`` objects for the
+request body (e.g., if this is a POST), and then a
+``h11.EndOfMessage`` to indicate the end of the message. Then the
+server would then send back a ``h11.Response``, some ``h11.Data``, and
+its own ``h11.EndOfMessage``. If either side violates the protocol,
+you'll get a ``h11.ProtocolError`` exception.
+
+h11 is suitable for implementing both servers and clients, and has a
+pleasantly symmetric API: the events you send as a client are exactly
+the ones that you receive as a server and vice-versa.
+
+`Here's an example of a tiny HTTP client
+`_
+
+It also has `a fine manual `_.
+
+FAQ
+---
+
+*Whyyyyy?*
+
+I wanted to play with HTTP in `Curio
+`__ and `Trio
+`__, which at the time didn't have any
+HTTP libraries. So I thought, no big deal, Python has, like, a dozen
+different implementations of HTTP, surely I can find one that's
+reusable. I didn't find one, but I did find Cory's call-to-arms
+blog-post. So I figured, well, fine, if I have to implement HTTP from
+scratch, at least I can make sure no-one *else* has to ever again.
+
+*Should I use it?*
+
+Maybe. You should be aware that it's a very young project. But, it's
+feature complete and has an exhaustive test-suite and complete docs,
+so the next step is for people to try using it and see how it goes
+:-). If you do then please let us know -- if nothing else we'll want
+to talk to you before making any incompatible changes!
+
+*What are the features/limitations?*
+
+Roughly speaking, it's trying to be a robust, complete, and non-hacky
+implementation of the first "chapter" of the HTTP/1.1 spec: `RFC 7230:
+HTTP/1.1 Message Syntax and Routing
+`_. That is, it mostly focuses on
+implementing HTTP at the level of taking bytes on and off the wire,
+and the headers related to that, and tries to be anal about spec
+conformance. It doesn't know about higher-level concerns like URL
+routing, conditional GETs, cross-origin cookie policies, or content
+negotiation. But it does know how to take care of framing,
+cross-version differences in keep-alive handling, and the "obsolete
+line folding" rule, so you can focus your energies on the hard /
+interesting parts for your application, and it tries to support the
+full specification in the sense that any useful HTTP/1.1 conformant
+application should be able to use h11.
+
+It's pure Python, and has no dependencies outside of the standard
+library.
+
+It has a test suite with 100.0% coverage for both statements and
+branches.
+
+Currently it supports Python 3 (testing on 3.8-3.12) and PyPy 3.
+The last Python 2-compatible version was h11 0.11.x.
+(Originally it had a Cython wrapper for `http-parser
+`_ and a beautiful nested state
+machine implemented with ``yield from`` to postprocess the output. But
+I had to take these out -- the new *parser* needs fewer lines-of-code
+than the old *parser wrapper*, is written in pure Python, uses no
+exotic language syntax, and has more features. It's sad, really; that
+old state machine was really slick. I just need a few sentences here
+to mourn that.)
+
+I don't know how fast it is. I haven't benchmarked or profiled it yet,
+so it's probably got a few pointless hot spots, and I've been trying
+to err on the side of simplicity and robustness instead of
+micro-optimization. But at the architectural level I tried hard to
+avoid fundamentally bad decisions, e.g., I believe that all the
+parsing algorithms remain linear-time even in the face of pathological
+input like slowloris, and there are no byte-by-byte loops. (I also
+believe that it maintains bounded memory usage in the face of
+arbitrary/pathological input.)
+
+The whole library is ~800 lines-of-code. You can read and understand
+the whole thing in less than an hour. Most of the energy invested in
+this so far has been spent on trying to keep things simple by
+minimizing special-cases and ad hoc state manipulation; even though it
+is now quite small and simple, I'm still annoyed that I haven't
+figured out how to make it even smaller and simpler. (Unfortunately,
+HTTP does not lend itself to simplicity.)
+
+The API is ~feature complete and I don't expect the general outlines
+to change much, but you can't judge an API's ergonomics until you
+actually document and use it, so I'd expect some changes in the
+details.
+
+*How do I try it?*
+
+.. code-block:: sh
+
+  $ pip install h11
+  $ git clone git@github.com:python-hyper/h11
+  $ cd h11/examples
+  $ python basic-client.py
+
+and go from there.
+
+*License?*
+
+MIT
+
+*Code of conduct?*
+
+Contributors are requested to follow our `code of conduct
+`_ in
+all project spaces.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/RECORD
new file mode 100644
index 0000000000000000000000000000000000000000..8768040c3cd11d4e09e697b8fc3b40c693c48cd4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/RECORD
@@ -0,0 +1,29 @@
+h11-0.16.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
+h11-0.16.0.dist-info/METADATA,sha256=KPMmCYrAn8unm48YD5YIfIQf4kViFct7hyqcfVzRnWQ,8348
+h11-0.16.0.dist-info/RECORD,,
+h11-0.16.0.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
+h11-0.16.0.dist-info/licenses/LICENSE.txt,sha256=N9tbuFkm2yikJ6JYZ_ELEjIAOuob5pzLhRE4rbjm82E,1124
+h11-0.16.0.dist-info/top_level.txt,sha256=F7dC4jl3zeh8TGHEPaWJrMbeuoWbS379Gwdi-Yvdcis,4
+h11/__init__.py,sha256=iO1KzkSO42yZ6ffg-VMgbx_ZVTWGUY00nRYEWn-s3kY,1507
+h11/__pycache__/__init__.cpython-311.pyc,,
+h11/__pycache__/_abnf.cpython-311.pyc,,
+h11/__pycache__/_connection.cpython-311.pyc,,
+h11/__pycache__/_events.cpython-311.pyc,,
+h11/__pycache__/_headers.cpython-311.pyc,,
+h11/__pycache__/_readers.cpython-311.pyc,,
+h11/__pycache__/_receivebuffer.cpython-311.pyc,,
+h11/__pycache__/_state.cpython-311.pyc,,
+h11/__pycache__/_util.cpython-311.pyc,,
+h11/__pycache__/_version.cpython-311.pyc,,
+h11/__pycache__/_writers.cpython-311.pyc,,
+h11/_abnf.py,sha256=ybixr0xsupnkA6GFAyMubuXF6Tc1lb_hF890NgCsfNc,4815
+h11/_connection.py,sha256=k9YRVf6koZqbttBW36xSWaJpWdZwa-xQVU9AHEo9DuI,26863
+h11/_events.py,sha256=I97aXoal1Wu7dkL548BANBUCkOIbe-x5CioYA9IBY14,11792
+h11/_headers.py,sha256=P7D-lBNxHwdLZPLimmYwrPG-9ZkjElvvJZJdZAgSP-4,10412
+h11/_readers.py,sha256=a4RypORUCC3d0q_kxPuBIM7jTD8iLt5X91TH0FsduN4,8590
+h11/_receivebuffer.py,sha256=xrspsdsNgWFxRfQcTXxR8RrdjRXXTK0Io5cQYWpJ1Ws,5252
+h11/_state.py,sha256=_5LG_BGR8FCcFQeBPH-TMHgm_-B-EUcWCnQof_9XjFE,13231
+h11/_util.py,sha256=LWkkjXyJaFlAy6Lt39w73UStklFT5ovcvo0TkY7RYuk,4888
+h11/_version.py,sha256=GVSsbPSPDcOuF6ptfIiXnVJoaEm3ygXbMnqlr_Giahw,686
+h11/_writers.py,sha256=oFKm6PtjeHfbj4RLX7VB7KDc1gIY53gXG3_HR9ltmTA,5081
+h11/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/WHEEL
new file mode 100644
index 0000000000000000000000000000000000000000..1eb3c49d99559863120cfb8433fc8738fba43ba9
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/WHEEL
@@ -0,0 +1,5 @@
+Wheel-Version: 1.0
+Generator: setuptools (78.1.0)
+Root-Is-Purelib: true
+Tag: py3-none-any
+
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0d24def711344ec6f4da2108f7d5c9261eb35f8b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11-0.16.0.dist-info/top_level.txt
@@ -0,0 +1 @@
+h11
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..989e92c3458681a6f0be72ae4105ea742750d328
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/__init__.py
@@ -0,0 +1,62 @@
+# A highish-level implementation of the HTTP/1.1 wire protocol (RFC 7230),
+# containing no networking code at all, loosely modelled on hyper-h2's generic
+# implementation of HTTP/2 (and in particular the h2.connection.H2Connection
+# class). There's still a bunch of subtle details you need to get right if you
+# want to make this actually useful, because it doesn't implement all the
+# semantics to check that what you're asking to write to the wire is sensible,
+# but at least it gets you out of dealing with the wire itself.
+
+from h11._connection import Connection, NEED_DATA, PAUSED
+from h11._events import (
+    ConnectionClosed,
+    Data,
+    EndOfMessage,
+    Event,
+    InformationalResponse,
+    Request,
+    Response,
+)
+from h11._state import (
+    CLIENT,
+    CLOSED,
+    DONE,
+    ERROR,
+    IDLE,
+    MIGHT_SWITCH_PROTOCOL,
+    MUST_CLOSE,
+    SEND_BODY,
+    SEND_RESPONSE,
+    SERVER,
+    SWITCHED_PROTOCOL,
+)
+from h11._util import LocalProtocolError, ProtocolError, RemoteProtocolError
+from h11._version import __version__
+
+PRODUCT_ID = "python-h11/" + __version__
+
+
+__all__ = (
+    "Connection",
+    "NEED_DATA",
+    "PAUSED",
+    "ConnectionClosed",
+    "Data",
+    "EndOfMessage",
+    "Event",
+    "InformationalResponse",
+    "Request",
+    "Response",
+    "CLIENT",
+    "CLOSED",
+    "DONE",
+    "ERROR",
+    "IDLE",
+    "MUST_CLOSE",
+    "SEND_BODY",
+    "SEND_RESPONSE",
+    "SERVER",
+    "SWITCHED_PROTOCOL",
+    "ProtocolError",
+    "LocalProtocolError",
+    "RemoteProtocolError",
+)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_abnf.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_abnf.py
new file mode 100644
index 0000000000000000000000000000000000000000..933587fba22290d7eb7df4c88e12f1e61702b8ce
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_abnf.py
@@ -0,0 +1,132 @@
+# We use native strings for all the re patterns, to take advantage of string
+# formatting, and then convert to bytestrings when compiling the final re
+# objects.
+
+# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#whitespace
+#  OWS            = *( SP / HTAB )
+#                 ; optional whitespace
+OWS = r"[ \t]*"
+
+# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.token.separators
+#   token          = 1*tchar
+#
+#   tchar          = "!" / "#" / "$" / "%" / "&" / "'" / "*"
+#                  / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
+#                  / DIGIT / ALPHA
+#                  ; any VCHAR, except delimiters
+token = r"[-!#$%&'*+.^_`|~0-9a-zA-Z]+"
+
+# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#header.fields
+#  field-name     = token
+field_name = token
+
+# The standard says:
+#
+#  field-value    = *( field-content / obs-fold )
+#  field-content  = field-vchar [ 1*( SP / HTAB ) field-vchar ]
+#  field-vchar    = VCHAR / obs-text
+#  obs-fold       = CRLF 1*( SP / HTAB )
+#                 ; obsolete line folding
+#                 ; see Section 3.2.4
+#
+# https://tools.ietf.org/html/rfc5234#appendix-B.1
+#
+#   VCHAR          =  %x21-7E
+#                  ; visible (printing) characters
+#
+# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#rule.quoted-string
+#   obs-text       = %x80-FF
+#
+# However, the standard definition of field-content is WRONG! It disallows
+# fields containing a single visible character surrounded by whitespace,
+# e.g. "foo a bar".
+#
+# See: https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189
+#
+# So our definition of field_content attempts to fix it up...
+#
+# Also, we allow lots of control characters, because apparently people assume
+# that they're legal in practice (e.g., google analytics makes cookies with
+# \x01 in them!):
+#   https://github.com/python-hyper/h11/issues/57
+# We still don't allow NUL or whitespace, because those are often treated as
+# meta-characters and letting them through can lead to nasty issues like SSRF.
+vchar = r"[\x21-\x7e]"
+vchar_or_obs_text = r"[^\x00\s]"
+field_vchar = vchar_or_obs_text
+field_content = r"{field_vchar}+(?:[ \t]+{field_vchar}+)*".format(**globals())
+
+# We handle obs-fold at a different level, and our fixed-up field_content
+# already grows to swallow the whole value, so ? instead of *
+field_value = r"({field_content})?".format(**globals())
+
+#  header-field   = field-name ":" OWS field-value OWS
+header_field = (
+    r"(?P{field_name})"
+    r":"
+    r"{OWS}"
+    r"(?P{field_value})"
+    r"{OWS}".format(**globals())
+)
+
+# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#request.line
+#
+#   request-line   = method SP request-target SP HTTP-version CRLF
+#   method         = token
+#   HTTP-version   = HTTP-name "/" DIGIT "." DIGIT
+#   HTTP-name      = %x48.54.54.50 ; "HTTP", case-sensitive
+#
+# request-target is complicated (see RFC 7230 sec 5.3) -- could be path, full
+# URL, host+port (for connect), or even "*", but in any case we are guaranteed
+# that it contists of the visible printing characters.
+method = token
+request_target = r"{vchar}+".format(**globals())
+http_version = r"HTTP/(?P[0-9]\.[0-9])"
+request_line = (
+    r"(?P{method})"
+    r" "
+    r"(?P{request_target})"
+    r" "
+    r"{http_version}".format(**globals())
+)
+
+# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#status.line
+#
+#   status-line = HTTP-version SP status-code SP reason-phrase CRLF
+#   status-code    = 3DIGIT
+#   reason-phrase  = *( HTAB / SP / VCHAR / obs-text )
+status_code = r"[0-9]{3}"
+reason_phrase = r"([ \t]|{vchar_or_obs_text})*".format(**globals())
+status_line = (
+    r"{http_version}"
+    r" "
+    r"(?P{status_code})"
+    # However, there are apparently a few too many servers out there that just
+    # leave out the reason phrase:
+    #   https://github.com/scrapy/scrapy/issues/345#issuecomment-281756036
+    #   https://github.com/seanmonstar/httparse/issues/29
+    # so make it optional. ?: is a non-capturing group.
+    r"(?: (?P{reason_phrase}))?".format(**globals())
+)
+
+HEXDIG = r"[0-9A-Fa-f]"
+# Actually
+#
+#      chunk-size     = 1*HEXDIG
+#
+# but we impose an upper-limit to avoid ridiculosity. len(str(2**64)) == 20
+chunk_size = r"({HEXDIG}){{1,20}}".format(**globals())
+# Actually
+#
+#     chunk-ext      = *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
+#
+# but we aren't parsing the things so we don't really care.
+chunk_ext = r";.*"
+chunk_header = (
+    r"(?P{chunk_size})"
+    r"(?P{chunk_ext})?"
+    r"{OWS}\r\n".format(
+        **globals()
+    )  # Even though the specification does not allow for extra whitespaces,
+    # we are lenient with trailing whitespaces because some servers on the wild use it.
+)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_connection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_connection.py
new file mode 100644
index 0000000000000000000000000000000000000000..e37d82a82a882c072cb938a90eb4486b51cdad99
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_connection.py
@@ -0,0 +1,659 @@
+# This contains the main Connection class. Everything in h11 revolves around
+# this.
+from typing import (
+    Any,
+    Callable,
+    cast,
+    Dict,
+    List,
+    Optional,
+    overload,
+    Tuple,
+    Type,
+    Union,
+)
+
+from ._events import (
+    ConnectionClosed,
+    Data,
+    EndOfMessage,
+    Event,
+    InformationalResponse,
+    Request,
+    Response,
+)
+from ._headers import get_comma_header, has_expect_100_continue, set_comma_header
+from ._readers import READERS, ReadersType
+from ._receivebuffer import ReceiveBuffer
+from ._state import (
+    _SWITCH_CONNECT,
+    _SWITCH_UPGRADE,
+    CLIENT,
+    ConnectionState,
+    DONE,
+    ERROR,
+    MIGHT_SWITCH_PROTOCOL,
+    SEND_BODY,
+    SERVER,
+    SWITCHED_PROTOCOL,
+)
+from ._util import (  # Import the internal things we need
+    LocalProtocolError,
+    RemoteProtocolError,
+    Sentinel,
+)
+from ._writers import WRITERS, WritersType
+
+# Everything in __all__ gets re-exported as part of the h11 public API.
+__all__ = ["Connection", "NEED_DATA", "PAUSED"]
+
+
+class NEED_DATA(Sentinel, metaclass=Sentinel):
+    pass
+
+
+class PAUSED(Sentinel, metaclass=Sentinel):
+    pass
+
+
+# If we ever have this much buffered without it making a complete parseable
+# event, we error out. The only time we really buffer is when reading the
+# request/response line + headers together, so this is effectively the limit on
+# the size of that.
+#
+# Some precedents for defaults:
+# - node.js: 80 * 1024
+# - tomcat: 8 * 1024
+# - IIS: 16 * 1024
+# - Apache: <8 KiB per line>
+DEFAULT_MAX_INCOMPLETE_EVENT_SIZE = 16 * 1024
+
+
+# RFC 7230's rules for connection lifecycles:
+# - If either side says they want to close the connection, then the connection
+#   must close.
+# - HTTP/1.1 defaults to keep-alive unless someone says Connection: close
+# - HTTP/1.0 defaults to close unless both sides say Connection: keep-alive
+#   (and even this is a mess -- e.g. if you're implementing a proxy then
+#   sending Connection: keep-alive is forbidden).
+#
+# We simplify life by simply not supporting keep-alive with HTTP/1.0 peers. So
+# our rule is:
+# - If someone says Connection: close, we will close
+# - If someone uses HTTP/1.0, we will close.
+def _keep_alive(event: Union[Request, Response]) -> bool:
+    connection = get_comma_header(event.headers, b"connection")
+    if b"close" in connection:
+        return False
+    if getattr(event, "http_version", b"1.1") < b"1.1":
+        return False
+    return True
+
+
+def _body_framing(
+    request_method: bytes, event: Union[Request, Response]
+) -> Tuple[str, Union[Tuple[()], Tuple[int]]]:
+    # Called when we enter SEND_BODY to figure out framing information for
+    # this body.
+    #
+    # These are the only two events that can trigger a SEND_BODY state:
+    assert type(event) in (Request, Response)
+    # Returns one of:
+    #
+    #    ("content-length", count)
+    #    ("chunked", ())
+    #    ("http/1.0", ())
+    #
+    # which are (lookup key, *args) for constructing body reader/writer
+    # objects.
+    #
+    # Reference: https://tools.ietf.org/html/rfc7230#section-3.3.3
+    #
+    # Step 1: some responses always have an empty body, regardless of what the
+    # headers say.
+    if type(event) is Response:
+        if (
+            event.status_code in (204, 304)
+            or request_method == b"HEAD"
+            or (request_method == b"CONNECT" and 200 <= event.status_code < 300)
+        ):
+            return ("content-length", (0,))
+        # Section 3.3.3 also lists another case -- responses with status_code
+        # < 200. For us these are InformationalResponses, not Responses, so
+        # they can't get into this function in the first place.
+        assert event.status_code >= 200
+
+    # Step 2: check for Transfer-Encoding (T-E beats C-L):
+    transfer_encodings = get_comma_header(event.headers, b"transfer-encoding")
+    if transfer_encodings:
+        assert transfer_encodings == [b"chunked"]
+        return ("chunked", ())
+
+    # Step 3: check for Content-Length
+    content_lengths = get_comma_header(event.headers, b"content-length")
+    if content_lengths:
+        return ("content-length", (int(content_lengths[0]),))
+
+    # Step 4: no applicable headers; fallback/default depends on type
+    if type(event) is Request:
+        return ("content-length", (0,))
+    else:
+        return ("http/1.0", ())
+
+
+################################################################
+#
+# The main Connection class
+#
+################################################################
+
+
+class Connection:
+    """An object encapsulating the state of an HTTP connection.
+
+    Args:
+        our_role: If you're implementing a client, pass :data:`h11.CLIENT`. If
+            you're implementing a server, pass :data:`h11.SERVER`.
+
+        max_incomplete_event_size (int):
+            The maximum number of bytes we're willing to buffer of an
+            incomplete event. In practice this mostly sets a limit on the
+            maximum size of the request/response line + headers. If this is
+            exceeded, then :meth:`next_event` will raise
+            :exc:`RemoteProtocolError`.
+
+    """
+
+    def __init__(
+        self,
+        our_role: Type[Sentinel],
+        max_incomplete_event_size: int = DEFAULT_MAX_INCOMPLETE_EVENT_SIZE,
+    ) -> None:
+        self._max_incomplete_event_size = max_incomplete_event_size
+        # State and role tracking
+        if our_role not in (CLIENT, SERVER):
+            raise ValueError(f"expected CLIENT or SERVER, not {our_role!r}")
+        self.our_role = our_role
+        self.their_role: Type[Sentinel]
+        if our_role is CLIENT:
+            self.their_role = SERVER
+        else:
+            self.their_role = CLIENT
+        self._cstate = ConnectionState()
+
+        # Callables for converting data->events or vice-versa given the
+        # current state
+        self._writer = self._get_io_object(self.our_role, None, WRITERS)
+        self._reader = self._get_io_object(self.their_role, None, READERS)
+
+        # Holds any unprocessed received data
+        self._receive_buffer = ReceiveBuffer()
+        # If this is true, then it indicates that the incoming connection was
+        # closed *after* the end of whatever's in self._receive_buffer:
+        self._receive_buffer_closed = False
+
+        # Extra bits of state that don't fit into the state machine.
+        #
+        # These two are only used to interpret framing headers for figuring
+        # out how to read/write response bodies. their_http_version is also
+        # made available as a convenient public API.
+        self.their_http_version: Optional[bytes] = None
+        self._request_method: Optional[bytes] = None
+        # This is pure flow-control and doesn't at all affect the set of legal
+        # transitions, so no need to bother ConnectionState with it:
+        self.client_is_waiting_for_100_continue = False
+
+    @property
+    def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]:
+        """A dictionary like::
+
+           {CLIENT: , SERVER: }
+
+        See :ref:`state-machine` for details.
+
+        """
+        return dict(self._cstate.states)
+
+    @property
+    def our_state(self) -> Type[Sentinel]:
+        """The current state of whichever role we are playing. See
+        :ref:`state-machine` for details.
+        """
+        return self._cstate.states[self.our_role]
+
+    @property
+    def their_state(self) -> Type[Sentinel]:
+        """The current state of whichever role we are NOT playing. See
+        :ref:`state-machine` for details.
+        """
+        return self._cstate.states[self.their_role]
+
+    @property
+    def they_are_waiting_for_100_continue(self) -> bool:
+        return self.their_role is CLIENT and self.client_is_waiting_for_100_continue
+
+    def start_next_cycle(self) -> None:
+        """Attempt to reset our connection state for a new request/response
+        cycle.
+
+        If both client and server are in :data:`DONE` state, then resets them
+        both to :data:`IDLE` state in preparation for a new request/response
+        cycle on this same connection. Otherwise, raises a
+        :exc:`LocalProtocolError`.
+
+        See :ref:`keepalive-and-pipelining`.
+
+        """
+        old_states = dict(self._cstate.states)
+        self._cstate.start_next_cycle()
+        self._request_method = None
+        # self.their_http_version gets left alone, since it presumably lasts
+        # beyond a single request/response cycle
+        assert not self.client_is_waiting_for_100_continue
+        self._respond_to_state_changes(old_states)
+
+    def _process_error(self, role: Type[Sentinel]) -> None:
+        old_states = dict(self._cstate.states)
+        self._cstate.process_error(role)
+        self._respond_to_state_changes(old_states)
+
+    def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]:
+        if type(event) is InformationalResponse and event.status_code == 101:
+            return _SWITCH_UPGRADE
+        if type(event) is Response:
+            if (
+                _SWITCH_CONNECT in self._cstate.pending_switch_proposals
+                and 200 <= event.status_code < 300
+            ):
+                return _SWITCH_CONNECT
+        return None
+
+    # All events go through here
+    def _process_event(self, role: Type[Sentinel], event: Event) -> None:
+        # First, pass the event through the state machine to make sure it
+        # succeeds.
+        old_states = dict(self._cstate.states)
+        if role is CLIENT and type(event) is Request:
+            if event.method == b"CONNECT":
+                self._cstate.process_client_switch_proposal(_SWITCH_CONNECT)
+            if get_comma_header(event.headers, b"upgrade"):
+                self._cstate.process_client_switch_proposal(_SWITCH_UPGRADE)
+        server_switch_event = None
+        if role is SERVER:
+            server_switch_event = self._server_switch_event(event)
+        self._cstate.process_event(role, type(event), server_switch_event)
+
+        # Then perform the updates triggered by it.
+
+        if type(event) is Request:
+            self._request_method = event.method
+
+        if role is self.their_role and type(event) in (
+            Request,
+            Response,
+            InformationalResponse,
+        ):
+            event = cast(Union[Request, Response, InformationalResponse], event)
+            self.their_http_version = event.http_version
+
+        # Keep alive handling
+        #
+        # RFC 7230 doesn't really say what one should do if Connection: close
+        # shows up on a 1xx InformationalResponse. I think the idea is that
+        # this is not supposed to happen. In any case, if it does happen, we
+        # ignore it.
+        if type(event) in (Request, Response) and not _keep_alive(
+            cast(Union[Request, Response], event)
+        ):
+            self._cstate.process_keep_alive_disabled()
+
+        # 100-continue
+        if type(event) is Request and has_expect_100_continue(event):
+            self.client_is_waiting_for_100_continue = True
+        if type(event) in (InformationalResponse, Response):
+            self.client_is_waiting_for_100_continue = False
+        if role is CLIENT and type(event) in (Data, EndOfMessage):
+            self.client_is_waiting_for_100_continue = False
+
+        self._respond_to_state_changes(old_states, event)
+
+    def _get_io_object(
+        self,
+        role: Type[Sentinel],
+        event: Optional[Event],
+        io_dict: Union[ReadersType, WritersType],
+    ) -> Optional[Callable[..., Any]]:
+        # event may be None; it's only used when entering SEND_BODY
+        state = self._cstate.states[role]
+        if state is SEND_BODY:
+            # Special case: the io_dict has a dict of reader/writer factories
+            # that depend on the request/response framing.
+            framing_type, args = _body_framing(
+                cast(bytes, self._request_method), cast(Union[Request, Response], event)
+            )
+            return io_dict[SEND_BODY][framing_type](*args)  # type: ignore[index]
+        else:
+            # General case: the io_dict just has the appropriate reader/writer
+            # for this state
+            return io_dict.get((role, state))  # type: ignore[return-value]
+
+    # This must be called after any action that might have caused
+    # self._cstate.states to change.
+    def _respond_to_state_changes(
+        self,
+        old_states: Dict[Type[Sentinel], Type[Sentinel]],
+        event: Optional[Event] = None,
+    ) -> None:
+        # Update reader/writer
+        if self.our_state != old_states[self.our_role]:
+            self._writer = self._get_io_object(self.our_role, event, WRITERS)
+        if self.their_state != old_states[self.their_role]:
+            self._reader = self._get_io_object(self.their_role, event, READERS)
+
+    @property
+    def trailing_data(self) -> Tuple[bytes, bool]:
+        """Data that has been received, but not yet processed, represented as
+        a tuple with two elements, where the first is a byte-string containing
+        the unprocessed data itself, and the second is a bool that is True if
+        the receive connection was closed.
+
+        See :ref:`switching-protocols` for discussion of why you'd want this.
+        """
+        return (bytes(self._receive_buffer), self._receive_buffer_closed)
+
+    def receive_data(self, data: bytes) -> None:
+        """Add data to our internal receive buffer.
+
+        This does not actually do any processing on the data, just stores
+        it. To trigger processing, you have to call :meth:`next_event`.
+
+        Args:
+            data (:term:`bytes-like object`):
+                The new data that was just received.
+
+                Special case: If *data* is an empty byte-string like ``b""``,
+                then this indicates that the remote side has closed the
+                connection (end of file). Normally this is convenient, because
+                standard Python APIs like :meth:`file.read` or
+                :meth:`socket.recv` use ``b""`` to indicate end-of-file, while
+                other failures to read are indicated using other mechanisms
+                like raising :exc:`TimeoutError`. When using such an API you
+                can just blindly pass through whatever you get from ``read``
+                to :meth:`receive_data`, and everything will work.
+
+                But, if you have an API where reading an empty string is a
+                valid non-EOF condition, then you need to be aware of this and
+                make sure to check for such strings and avoid passing them to
+                :meth:`receive_data`.
+
+        Returns:
+            Nothing, but after calling this you should call :meth:`next_event`
+            to parse the newly received data.
+
+        Raises:
+            RuntimeError:
+                Raised if you pass an empty *data*, indicating EOF, and then
+                pass a non-empty *data*, indicating more data that somehow
+                arrived after the EOF.
+
+                (Calling ``receive_data(b"")`` multiple times is fine,
+                and equivalent to calling it once.)
+
+        """
+        if data:
+            if self._receive_buffer_closed:
+                raise RuntimeError("received close, then received more data?")
+            self._receive_buffer += data
+        else:
+            self._receive_buffer_closed = True
+
+    def _extract_next_receive_event(
+        self,
+    ) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]:
+        state = self.their_state
+        # We don't pause immediately when they enter DONE, because even in
+        # DONE state we can still process a ConnectionClosed() event. But
+        # if we have data in our buffer, then we definitely aren't getting
+        # a ConnectionClosed() immediately and we need to pause.
+        if state is DONE and self._receive_buffer:
+            return PAUSED
+        if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL:
+            return PAUSED
+        assert self._reader is not None
+        event = self._reader(self._receive_buffer)
+        if event is None:
+            if not self._receive_buffer and self._receive_buffer_closed:
+                # In some unusual cases (basically just HTTP/1.0 bodies), EOF
+                # triggers an actual protocol event; in that case, we want to
+                # return that event, and then the state will change and we'll
+                # get called again to generate the actual ConnectionClosed().
+                if hasattr(self._reader, "read_eof"):
+                    event = self._reader.read_eof()
+                else:
+                    event = ConnectionClosed()
+        if event is None:
+            event = NEED_DATA
+        return event  # type: ignore[no-any-return]
+
+    def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]:
+        """Parse the next event out of our receive buffer, update our internal
+        state, and return it.
+
+        This is a mutating operation -- think of it like calling :func:`next`
+        on an iterator.
+
+        Returns:
+            : One of three things:
+
+            1) An event object -- see :ref:`events`.
+
+            2) The special constant :data:`NEED_DATA`, which indicates that
+               you need to read more data from your socket and pass it to
+               :meth:`receive_data` before this method will be able to return
+               any more events.
+
+            3) The special constant :data:`PAUSED`, which indicates that we
+               are not in a state where we can process incoming data (usually
+               because the peer has finished their part of the current
+               request/response cycle, and you have not yet called
+               :meth:`start_next_cycle`). See :ref:`flow-control` for details.
+
+        Raises:
+            RemoteProtocolError:
+                The peer has misbehaved. You should close the connection
+                (possibly after sending some kind of 4xx response).
+
+        Once this method returns :class:`ConnectionClosed` once, then all
+        subsequent calls will also return :class:`ConnectionClosed`.
+
+        If this method raises any exception besides :exc:`RemoteProtocolError`
+        then that's a bug -- if it happens please file a bug report!
+
+        If this method raises any exception then it also sets
+        :attr:`Connection.their_state` to :data:`ERROR` -- see
+        :ref:`error-handling` for discussion.
+
+        """
+
+        if self.their_state is ERROR:
+            raise RemoteProtocolError("Can't receive data when peer state is ERROR")
+        try:
+            event = self._extract_next_receive_event()
+            if event not in [NEED_DATA, PAUSED]:
+                self._process_event(self.their_role, cast(Event, event))
+            if event is NEED_DATA:
+                if len(self._receive_buffer) > self._max_incomplete_event_size:
+                    # 431 is "Request header fields too large" which is pretty
+                    # much the only situation where we can get here
+                    raise RemoteProtocolError(
+                        "Receive buffer too long", error_status_hint=431
+                    )
+                if self._receive_buffer_closed:
+                    # We're still trying to complete some event, but that's
+                    # never going to happen because no more data is coming
+                    raise RemoteProtocolError("peer unexpectedly closed connection")
+            return event
+        except BaseException as exc:
+            self._process_error(self.their_role)
+            if isinstance(exc, LocalProtocolError):
+                exc._reraise_as_remote_protocol_error()
+            else:
+                raise
+
+    @overload
+    def send(self, event: ConnectionClosed) -> None:
+        ...
+
+    @overload
+    def send(
+        self, event: Union[Request, InformationalResponse, Response, Data, EndOfMessage]
+    ) -> bytes:
+        ...
+
+    @overload
+    def send(self, event: Event) -> Optional[bytes]:
+        ...
+
+    def send(self, event: Event) -> Optional[bytes]:
+        """Convert a high-level event into bytes that can be sent to the peer,
+        while updating our internal state machine.
+
+        Args:
+            event: The :ref:`event ` to send.
+
+        Returns:
+            If ``type(event) is ConnectionClosed``, then returns
+            ``None``. Otherwise, returns a :term:`bytes-like object`.
+
+        Raises:
+            LocalProtocolError:
+                Sending this event at this time would violate our
+                understanding of the HTTP/1.1 protocol.
+
+        If this method raises any exception then it also sets
+        :attr:`Connection.our_state` to :data:`ERROR` -- see
+        :ref:`error-handling` for discussion.
+
+        """
+        data_list = self.send_with_data_passthrough(event)
+        if data_list is None:
+            return None
+        else:
+            return b"".join(data_list)
+
+    def send_with_data_passthrough(self, event: Event) -> Optional[List[bytes]]:
+        """Identical to :meth:`send`, except that in situations where
+        :meth:`send` returns a single :term:`bytes-like object`, this instead
+        returns a list of them -- and when sending a :class:`Data` event, this
+        list is guaranteed to contain the exact object you passed in as
+        :attr:`Data.data`. See :ref:`sendfile` for discussion.
+
+        """
+        if self.our_state is ERROR:
+            raise LocalProtocolError("Can't send data when our state is ERROR")
+        try:
+            if type(event) is Response:
+                event = self._clean_up_response_headers_for_sending(event)
+            # We want to call _process_event before calling the writer,
+            # because if someone tries to do something invalid then this will
+            # give a sensible error message, while our writers all just assume
+            # they will only receive valid events. But, _process_event might
+            # change self._writer. So we have to do a little dance:
+            writer = self._writer
+            self._process_event(self.our_role, event)
+            if type(event) is ConnectionClosed:
+                return None
+            else:
+                # In any situation where writer is None, process_event should
+                # have raised ProtocolError
+                assert writer is not None
+                data_list: List[bytes] = []
+                writer(event, data_list.append)
+                return data_list
+        except:
+            self._process_error(self.our_role)
+            raise
+
+    def send_failed(self) -> None:
+        """Notify the state machine that we failed to send the data it gave
+        us.
+
+        This causes :attr:`Connection.our_state` to immediately become
+        :data:`ERROR` -- see :ref:`error-handling` for discussion.
+
+        """
+        self._process_error(self.our_role)
+
+    # When sending a Response, we take responsibility for a few things:
+    #
+    # - Sometimes you MUST set Connection: close. We take care of those
+    #   times. (You can also set it yourself if you want, and if you do then
+    #   we'll respect that and close the connection at the right time. But you
+    #   don't have to worry about that unless you want to.)
+    #
+    # - The user has to set Content-Length if they want it. Otherwise, for
+    #   responses that have bodies (e.g. not HEAD), then we will automatically
+    #   select the right mechanism for streaming a body of unknown length,
+    #   which depends on depending on the peer's HTTP version.
+    #
+    # This function's *only* responsibility is making sure headers are set up
+    # right -- everything downstream just looks at the headers. There are no
+    # side channels.
+    def _clean_up_response_headers_for_sending(self, response: Response) -> Response:
+        assert type(response) is Response
+
+        headers = response.headers
+        need_close = False
+
+        # HEAD requests need some special handling: they always act like they
+        # have Content-Length: 0, and that's how _body_framing treats
+        # them. But their headers are supposed to match what we would send if
+        # the request was a GET. (Technically there is one deviation allowed:
+        # we're allowed to leave out the framing headers -- see
+        # https://tools.ietf.org/html/rfc7231#section-4.3.2 . But it's just as
+        # easy to get them right.)
+        method_for_choosing_headers = cast(bytes, self._request_method)
+        if method_for_choosing_headers == b"HEAD":
+            method_for_choosing_headers = b"GET"
+        framing_type, _ = _body_framing(method_for_choosing_headers, response)
+        if framing_type in ("chunked", "http/1.0"):
+            # This response has a body of unknown length.
+            # If our peer is HTTP/1.1, we use Transfer-Encoding: chunked
+            # If our peer is HTTP/1.0, we use no framing headers, and close the
+            # connection afterwards.
+            #
+            # Make sure to clear Content-Length (in principle user could have
+            # set both and then we ignored Content-Length b/c
+            # Transfer-Encoding overwrote it -- this would be naughty of them,
+            # but the HTTP spec says that if our peer does this then we have
+            # to fix it instead of erroring out, so we'll accord the user the
+            # same respect).
+            headers = set_comma_header(headers, b"content-length", [])
+            if self.their_http_version is None or self.their_http_version < b"1.1":
+                # Either we never got a valid request and are sending back an
+                # error (their_http_version is None), so we assume the worst;
+                # or else we did get a valid HTTP/1.0 request, so we know that
+                # they don't understand chunked encoding.
+                headers = set_comma_header(headers, b"transfer-encoding", [])
+                # This is actually redundant ATM, since currently we
+                # unconditionally disable keep-alive when talking to HTTP/1.0
+                # peers. But let's be defensive just in case we add
+                # Connection: keep-alive support later:
+                if self._request_method != b"HEAD":
+                    need_close = True
+            else:
+                headers = set_comma_header(headers, b"transfer-encoding", [b"chunked"])
+
+        if not self._cstate.keep_alive or need_close:
+            # Make sure Connection: close is set
+            connection = set(get_comma_header(headers, b"connection"))
+            connection.discard(b"keep-alive")
+            connection.add(b"close")
+            headers = set_comma_header(headers, b"connection", sorted(connection))
+
+        return Response(
+            headers=headers,
+            status_code=response.status_code,
+            http_version=response.http_version,
+            reason=response.reason,
+        )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_events.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_events.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca1c3adbde2c4e7710482a18e3471f91f1da610e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_events.py
@@ -0,0 +1,369 @@
+# High level events that make up HTTP/1.1 conversations. Loosely inspired by
+# the corresponding events in hyper-h2:
+#
+#     http://python-hyper.org/h2/en/stable/api.html#events
+#
+# Don't subclass these. Stuff will break.
+
+import re
+from abc import ABC
+from dataclasses import dataclass
+from typing import List, Tuple, Union
+
+from ._abnf import method, request_target
+from ._headers import Headers, normalize_and_validate
+from ._util import bytesify, LocalProtocolError, validate
+
+# Everything in __all__ gets re-exported as part of the h11 public API.
+__all__ = [
+    "Event",
+    "Request",
+    "InformationalResponse",
+    "Response",
+    "Data",
+    "EndOfMessage",
+    "ConnectionClosed",
+]
+
+method_re = re.compile(method.encode("ascii"))
+request_target_re = re.compile(request_target.encode("ascii"))
+
+
+class Event(ABC):
+    """
+    Base class for h11 events.
+    """
+
+    __slots__ = ()
+
+
+@dataclass(init=False, frozen=True)
+class Request(Event):
+    """The beginning of an HTTP request.
+
+    Fields:
+
+    .. attribute:: method
+
+       An HTTP method, e.g. ``b"GET"`` or ``b"POST"``. Always a byte
+       string. :term:`Bytes-like objects ` and native
+       strings containing only ascii characters will be automatically
+       converted to byte strings.
+
+    .. attribute:: target
+
+       The target of an HTTP request, e.g. ``b"/index.html"``, or one of the
+       more exotic formats described in `RFC 7320, section 5.3
+       `_. Always a byte
+       string. :term:`Bytes-like objects ` and native
+       strings containing only ascii characters will be automatically
+       converted to byte strings.
+
+    .. attribute:: headers
+
+       Request headers, represented as a list of (name, value) pairs. See
+       :ref:`the header normalization rules ` for details.
+
+    .. attribute:: http_version
+
+       The HTTP protocol version, represented as a byte string like
+       ``b"1.1"``. See :ref:`the HTTP version normalization rules
+       ` for details.
+
+    """
+
+    __slots__ = ("method", "headers", "target", "http_version")
+
+    method: bytes
+    headers: Headers
+    target: bytes
+    http_version: bytes
+
+    def __init__(
+        self,
+        *,
+        method: Union[bytes, str],
+        headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]],
+        target: Union[bytes, str],
+        http_version: Union[bytes, str] = b"1.1",
+        _parsed: bool = False,
+    ) -> None:
+        super().__init__()
+        if isinstance(headers, Headers):
+            object.__setattr__(self, "headers", headers)
+        else:
+            object.__setattr__(
+                self, "headers", normalize_and_validate(headers, _parsed=_parsed)
+            )
+        if not _parsed:
+            object.__setattr__(self, "method", bytesify(method))
+            object.__setattr__(self, "target", bytesify(target))
+            object.__setattr__(self, "http_version", bytesify(http_version))
+        else:
+            object.__setattr__(self, "method", method)
+            object.__setattr__(self, "target", target)
+            object.__setattr__(self, "http_version", http_version)
+
+        # "A server MUST respond with a 400 (Bad Request) status code to any
+        # HTTP/1.1 request message that lacks a Host header field and to any
+        # request message that contains more than one Host header field or a
+        # Host header field with an invalid field-value."
+        # -- https://tools.ietf.org/html/rfc7230#section-5.4
+        host_count = 0
+        for name, value in self.headers:
+            if name == b"host":
+                host_count += 1
+        if self.http_version == b"1.1" and host_count == 0:
+            raise LocalProtocolError("Missing mandatory Host: header")
+        if host_count > 1:
+            raise LocalProtocolError("Found multiple Host: headers")
+
+        validate(method_re, self.method, "Illegal method characters")
+        validate(request_target_re, self.target, "Illegal target characters")
+
+    # This is an unhashable type.
+    __hash__ = None  # type: ignore
+
+
+@dataclass(init=False, frozen=True)
+class _ResponseBase(Event):
+    __slots__ = ("headers", "http_version", "reason", "status_code")
+
+    headers: Headers
+    http_version: bytes
+    reason: bytes
+    status_code: int
+
+    def __init__(
+        self,
+        *,
+        headers: Union[Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]]],
+        status_code: int,
+        http_version: Union[bytes, str] = b"1.1",
+        reason: Union[bytes, str] = b"",
+        _parsed: bool = False,
+    ) -> None:
+        super().__init__()
+        if isinstance(headers, Headers):
+            object.__setattr__(self, "headers", headers)
+        else:
+            object.__setattr__(
+                self, "headers", normalize_and_validate(headers, _parsed=_parsed)
+            )
+        if not _parsed:
+            object.__setattr__(self, "reason", bytesify(reason))
+            object.__setattr__(self, "http_version", bytesify(http_version))
+            if not isinstance(status_code, int):
+                raise LocalProtocolError("status code must be integer")
+            # Because IntEnum objects are instances of int, but aren't
+            # duck-compatible (sigh), see gh-72.
+            object.__setattr__(self, "status_code", int(status_code))
+        else:
+            object.__setattr__(self, "reason", reason)
+            object.__setattr__(self, "http_version", http_version)
+            object.__setattr__(self, "status_code", status_code)
+
+        self.__post_init__()
+
+    def __post_init__(self) -> None:
+        pass
+
+    # This is an unhashable type.
+    __hash__ = None  # type: ignore
+
+
+@dataclass(init=False, frozen=True)
+class InformationalResponse(_ResponseBase):
+    """An HTTP informational response.
+
+    Fields:
+
+    .. attribute:: status_code
+
+       The status code of this response, as an integer. For an
+       :class:`InformationalResponse`, this is always in the range [100,
+       200).
+
+    .. attribute:: headers
+
+       Request headers, represented as a list of (name, value) pairs. See
+       :ref:`the header normalization rules ` for
+       details.
+
+    .. attribute:: http_version
+
+       The HTTP protocol version, represented as a byte string like
+       ``b"1.1"``. See :ref:`the HTTP version normalization rules
+       ` for details.
+
+    .. attribute:: reason
+
+       The reason phrase of this response, as a byte string. For example:
+       ``b"OK"``, or ``b"Not Found"``.
+
+    """
+
+    def __post_init__(self) -> None:
+        if not (100 <= self.status_code < 200):
+            raise LocalProtocolError(
+                "InformationalResponse status_code should be in range "
+                "[100, 200), not {}".format(self.status_code)
+            )
+
+    # This is an unhashable type.
+    __hash__ = None  # type: ignore
+
+
+@dataclass(init=False, frozen=True)
+class Response(_ResponseBase):
+    """The beginning of an HTTP response.
+
+    Fields:
+
+    .. attribute:: status_code
+
+       The status code of this response, as an integer. For an
+       :class:`Response`, this is always in the range [200,
+       1000).
+
+    .. attribute:: headers
+
+       Request headers, represented as a list of (name, value) pairs. See
+       :ref:`the header normalization rules ` for details.
+
+    .. attribute:: http_version
+
+       The HTTP protocol version, represented as a byte string like
+       ``b"1.1"``. See :ref:`the HTTP version normalization rules
+       ` for details.
+
+    .. attribute:: reason
+
+       The reason phrase of this response, as a byte string. For example:
+       ``b"OK"``, or ``b"Not Found"``.
+
+    """
+
+    def __post_init__(self) -> None:
+        if not (200 <= self.status_code < 1000):
+            raise LocalProtocolError(
+                "Response status_code should be in range [200, 1000), not {}".format(
+                    self.status_code
+                )
+            )
+
+    # This is an unhashable type.
+    __hash__ = None  # type: ignore
+
+
+@dataclass(init=False, frozen=True)
+class Data(Event):
+    """Part of an HTTP message body.
+
+    Fields:
+
+    .. attribute:: data
+
+       A :term:`bytes-like object` containing part of a message body. Or, if
+       using the ``combine=False`` argument to :meth:`Connection.send`, then
+       any object that your socket writing code knows what to do with, and for
+       which calling :func:`len` returns the number of bytes that will be
+       written -- see :ref:`sendfile` for details.
+
+    .. attribute:: chunk_start
+
+       A marker that indicates whether this data object is from the start of a
+       chunked transfer encoding chunk. This field is ignored when when a Data
+       event is provided to :meth:`Connection.send`: it is only valid on
+       events emitted from :meth:`Connection.next_event`. You probably
+       shouldn't use this attribute at all; see
+       :ref:`chunk-delimiters-are-bad` for details.
+
+    .. attribute:: chunk_end
+
+       A marker that indicates whether this data object is the last for a
+       given chunked transfer encoding chunk. This field is ignored when when
+       a Data event is provided to :meth:`Connection.send`: it is only valid
+       on events emitted from :meth:`Connection.next_event`. You probably
+       shouldn't use this attribute at all; see
+       :ref:`chunk-delimiters-are-bad` for details.
+
+    """
+
+    __slots__ = ("data", "chunk_start", "chunk_end")
+
+    data: bytes
+    chunk_start: bool
+    chunk_end: bool
+
+    def __init__(
+        self, data: bytes, chunk_start: bool = False, chunk_end: bool = False
+    ) -> None:
+        object.__setattr__(self, "data", data)
+        object.__setattr__(self, "chunk_start", chunk_start)
+        object.__setattr__(self, "chunk_end", chunk_end)
+
+    # This is an unhashable type.
+    __hash__ = None  # type: ignore
+
+
+# XX FIXME: "A recipient MUST ignore (or consider as an error) any fields that
+# are forbidden to be sent in a trailer, since processing them as if they were
+# present in the header section might bypass external security filters."
+# https://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7230.html#chunked.trailer.part
+# Unfortunately, the list of forbidden fields is long and vague :-/
+@dataclass(init=False, frozen=True)
+class EndOfMessage(Event):
+    """The end of an HTTP message.
+
+    Fields:
+
+    .. attribute:: headers
+
+       Default value: ``[]``
+
+       Any trailing headers attached to this message, represented as a list of
+       (name, value) pairs. See :ref:`the header normalization rules
+       ` for details.
+
+       Must be empty unless ``Transfer-Encoding: chunked`` is in use.
+
+    """
+
+    __slots__ = ("headers",)
+
+    headers: Headers
+
+    def __init__(
+        self,
+        *,
+        headers: Union[
+            Headers, List[Tuple[bytes, bytes]], List[Tuple[str, str]], None
+        ] = None,
+        _parsed: bool = False,
+    ) -> None:
+        super().__init__()
+        if headers is None:
+            headers = Headers([])
+        elif not isinstance(headers, Headers):
+            headers = normalize_and_validate(headers, _parsed=_parsed)
+
+        object.__setattr__(self, "headers", headers)
+
+    # This is an unhashable type.
+    __hash__ = None  # type: ignore
+
+
+@dataclass(frozen=True)
+class ConnectionClosed(Event):
+    """This event indicates that the sender has closed their outgoing
+    connection.
+
+    Note that this does not necessarily mean that they can't *receive* further
+    data, because TCP connections are composed to two one-way channels which
+    can be closed independently. See :ref:`closing` for details.
+
+    No fields.
+    """
+
+    pass
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_headers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_headers.py
new file mode 100644
index 0000000000000000000000000000000000000000..31da3e2b23b55a624b36f105e62a6902e63286aa
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_headers.py
@@ -0,0 +1,282 @@
+import re
+from typing import AnyStr, cast, List, overload, Sequence, Tuple, TYPE_CHECKING, Union
+
+from ._abnf import field_name, field_value
+from ._util import bytesify, LocalProtocolError, validate
+
+if TYPE_CHECKING:
+    from ._events import Request
+
+try:
+    from typing import Literal
+except ImportError:
+    from typing_extensions import Literal  # type: ignore
+
+CONTENT_LENGTH_MAX_DIGITS = 20  # allow up to 1 billion TB - 1
+
+
+# Facts
+# -----
+#
+# Headers are:
+#   keys: case-insensitive ascii
+#   values: mixture of ascii and raw bytes
+#
+# "Historically, HTTP has allowed field content with text in the ISO-8859-1
+# charset [ISO-8859-1], supporting other charsets only through use of
+# [RFC2047] encoding.  In practice, most HTTP header field values use only a
+# subset of the US-ASCII charset [USASCII]. Newly defined header fields SHOULD
+# limit their field values to US-ASCII octets.  A recipient SHOULD treat other
+# octets in field content (obs-text) as opaque data."
+# And it deprecates all non-ascii values
+#
+# Leading/trailing whitespace in header names is forbidden
+#
+# Values get leading/trailing whitespace stripped
+#
+# Content-Disposition actually needs to contain unicode semantically; to
+# accomplish this it has a terrifically weird way of encoding the filename
+# itself as ascii (and even this still has lots of cross-browser
+# incompatibilities)
+#
+# Order is important:
+# "a proxy MUST NOT change the order of these field values when forwarding a
+# message"
+# (and there are several headers where the order indicates a preference)
+#
+# Multiple occurences of the same header:
+# "A sender MUST NOT generate multiple header fields with the same field name
+# in a message unless either the entire field value for that header field is
+# defined as a comma-separated list [or the header is Set-Cookie which gets a
+# special exception]" - RFC 7230. (cookies are in RFC 6265)
+#
+# So every header aside from Set-Cookie can be merged by b", ".join if it
+# occurs repeatedly. But, of course, they can't necessarily be split by
+# .split(b","), because quoting.
+#
+# Given all this mess (case insensitive, duplicates allowed, order is
+# important, ...), there doesn't appear to be any standard way to handle
+# headers in Python -- they're almost like dicts, but... actually just
+# aren't. For now we punt and just use a super simple representation: headers
+# are a list of pairs
+#
+#   [(name1, value1), (name2, value2), ...]
+#
+# where all entries are bytestrings, names are lowercase and have no
+# leading/trailing whitespace, and values are bytestrings with no
+# leading/trailing whitespace. Searching and updating are done via naive O(n)
+# methods.
+#
+# Maybe a dict-of-lists would be better?
+
+_content_length_re = re.compile(rb"[0-9]+")
+_field_name_re = re.compile(field_name.encode("ascii"))
+_field_value_re = re.compile(field_value.encode("ascii"))
+
+
+class Headers(Sequence[Tuple[bytes, bytes]]):
+    """
+    A list-like interface that allows iterating over headers as byte-pairs
+    of (lowercased-name, value).
+
+    Internally we actually store the representation as three-tuples,
+    including both the raw original casing, in order to preserve casing
+    over-the-wire, and the lowercased name, for case-insensitive comparisions.
+
+    r = Request(
+        method="GET",
+        target="/",
+        headers=[("Host", "example.org"), ("Connection", "keep-alive")],
+        http_version="1.1",
+    )
+    assert r.headers == [
+        (b"host", b"example.org"),
+        (b"connection", b"keep-alive")
+    ]
+    assert r.headers.raw_items() == [
+        (b"Host", b"example.org"),
+        (b"Connection", b"keep-alive")
+    ]
+    """
+
+    __slots__ = "_full_items"
+
+    def __init__(self, full_items: List[Tuple[bytes, bytes, bytes]]) -> None:
+        self._full_items = full_items
+
+    def __bool__(self) -> bool:
+        return bool(self._full_items)
+
+    def __eq__(self, other: object) -> bool:
+        return list(self) == list(other)  # type: ignore
+
+    def __len__(self) -> int:
+        return len(self._full_items)
+
+    def __repr__(self) -> str:
+        return "" % repr(list(self))
+
+    def __getitem__(self, idx: int) -> Tuple[bytes, bytes]:  # type: ignore[override]
+        _, name, value = self._full_items[idx]
+        return (name, value)
+
+    def raw_items(self) -> List[Tuple[bytes, bytes]]:
+        return [(raw_name, value) for raw_name, _, value in self._full_items]
+
+
+HeaderTypes = Union[
+    List[Tuple[bytes, bytes]],
+    List[Tuple[bytes, str]],
+    List[Tuple[str, bytes]],
+    List[Tuple[str, str]],
+]
+
+
+@overload
+def normalize_and_validate(headers: Headers, _parsed: Literal[True]) -> Headers:
+    ...
+
+
+@overload
+def normalize_and_validate(headers: HeaderTypes, _parsed: Literal[False]) -> Headers:
+    ...
+
+
+@overload
+def normalize_and_validate(
+    headers: Union[Headers, HeaderTypes], _parsed: bool = False
+) -> Headers:
+    ...
+
+
+def normalize_and_validate(
+    headers: Union[Headers, HeaderTypes], _parsed: bool = False
+) -> Headers:
+    new_headers = []
+    seen_content_length = None
+    saw_transfer_encoding = False
+    for name, value in headers:
+        # For headers coming out of the parser, we can safely skip some steps,
+        # because it always returns bytes and has already run these regexes
+        # over the data:
+        if not _parsed:
+            name = bytesify(name)
+            value = bytesify(value)
+            validate(_field_name_re, name, "Illegal header name {!r}", name)
+            validate(_field_value_re, value, "Illegal header value {!r}", value)
+        assert isinstance(name, bytes)
+        assert isinstance(value, bytes)
+
+        raw_name = name
+        name = name.lower()
+        if name == b"content-length":
+            lengths = {length.strip() for length in value.split(b",")}
+            if len(lengths) != 1:
+                raise LocalProtocolError("conflicting Content-Length headers")
+            value = lengths.pop()
+            validate(_content_length_re, value, "bad Content-Length")
+            if len(value) > CONTENT_LENGTH_MAX_DIGITS:
+                raise LocalProtocolError("bad Content-Length")
+            if seen_content_length is None:
+                seen_content_length = value
+                new_headers.append((raw_name, name, value))
+            elif seen_content_length != value:
+                raise LocalProtocolError("conflicting Content-Length headers")
+        elif name == b"transfer-encoding":
+            # "A server that receives a request message with a transfer coding
+            # it does not understand SHOULD respond with 501 (Not
+            # Implemented)."
+            # https://tools.ietf.org/html/rfc7230#section-3.3.1
+            if saw_transfer_encoding:
+                raise LocalProtocolError(
+                    "multiple Transfer-Encoding headers", error_status_hint=501
+                )
+            # "All transfer-coding names are case-insensitive"
+            # -- https://tools.ietf.org/html/rfc7230#section-4
+            value = value.lower()
+            if value != b"chunked":
+                raise LocalProtocolError(
+                    "Only Transfer-Encoding: chunked is supported",
+                    error_status_hint=501,
+                )
+            saw_transfer_encoding = True
+            new_headers.append((raw_name, name, value))
+        else:
+            new_headers.append((raw_name, name, value))
+    return Headers(new_headers)
+
+
+def get_comma_header(headers: Headers, name: bytes) -> List[bytes]:
+    # Should only be used for headers whose value is a list of
+    # comma-separated, case-insensitive values.
+    #
+    # The header name `name` is expected to be lower-case bytes.
+    #
+    # Connection: meets these criteria (including cast insensitivity).
+    #
+    # Content-Length: technically is just a single value (1*DIGIT), but the
+    # standard makes reference to implementations that do multiple values, and
+    # using this doesn't hurt. Ditto, case insensitivity doesn't things either
+    # way.
+    #
+    # Transfer-Encoding: is more complex (allows for quoted strings), so
+    # splitting on , is actually wrong. For example, this is legal:
+    #
+    #    Transfer-Encoding: foo; options="1,2", chunked
+    #
+    # and should be parsed as
+    #
+    #    foo; options="1,2"
+    #    chunked
+    #
+    # but this naive function will parse it as
+    #
+    #    foo; options="1
+    #    2"
+    #    chunked
+    #
+    # However, this is okay because the only thing we are going to do with
+    # any Transfer-Encoding is reject ones that aren't just "chunked", so
+    # both of these will be treated the same anyway.
+    #
+    # Expect: the only legal value is the literal string
+    # "100-continue". Splitting on commas is harmless. Case insensitive.
+    #
+    out: List[bytes] = []
+    for _, found_name, found_raw_value in headers._full_items:
+        if found_name == name:
+            found_raw_value = found_raw_value.lower()
+            for found_split_value in found_raw_value.split(b","):
+                found_split_value = found_split_value.strip()
+                if found_split_value:
+                    out.append(found_split_value)
+    return out
+
+
+def set_comma_header(headers: Headers, name: bytes, new_values: List[bytes]) -> Headers:
+    # The header name `name` is expected to be lower-case bytes.
+    #
+    # Note that when we store the header we use title casing for the header
+    # names, in order to match the conventional HTTP header style.
+    #
+    # Simply calling `.title()` is a blunt approach, but it's correct
+    # here given the cases where we're using `set_comma_header`...
+    #
+    # Connection, Content-Length, Transfer-Encoding.
+    new_headers: List[Tuple[bytes, bytes]] = []
+    for found_raw_name, found_name, found_raw_value in headers._full_items:
+        if found_name != name:
+            new_headers.append((found_raw_name, found_raw_value))
+    for new_value in new_values:
+        new_headers.append((name.title(), new_value))
+    return normalize_and_validate(new_headers)
+
+
+def has_expect_100_continue(request: "Request") -> bool:
+    # https://tools.ietf.org/html/rfc7231#section-5.1.1
+    # "A server that receives a 100-continue expectation in an HTTP/1.0 request
+    # MUST ignore that expectation."
+    if request.http_version < b"1.1":
+        return False
+    expect = get_comma_header(request.headers, b"expect")
+    return b"100-continue" in expect
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_readers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_readers.py
new file mode 100644
index 0000000000000000000000000000000000000000..576804cc282032526e0a932c9853d586a094bad0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_readers.py
@@ -0,0 +1,250 @@
+# Code to read HTTP data
+#
+# Strategy: each reader is a callable which takes a ReceiveBuffer object, and
+# either:
+# 1) consumes some of it and returns an Event
+# 2) raises a LocalProtocolError (for consistency -- e.g. we call validate()
+#    and it might raise a LocalProtocolError, so simpler just to always use
+#    this)
+# 3) returns None, meaning "I need more data"
+#
+# If they have a .read_eof attribute, then this will be called if an EOF is
+# received -- but this is optional. Either way, the actual ConnectionClosed
+# event will be generated afterwards.
+#
+# READERS is a dict describing how to pick a reader. It maps states to either:
+# - a reader
+# - or, for body readers, a dict of per-framing reader factories
+
+import re
+from typing import Any, Callable, Dict, Iterable, NoReturn, Optional, Tuple, Type, Union
+
+from ._abnf import chunk_header, header_field, request_line, status_line
+from ._events import Data, EndOfMessage, InformationalResponse, Request, Response
+from ._receivebuffer import ReceiveBuffer
+from ._state import (
+    CLIENT,
+    CLOSED,
+    DONE,
+    IDLE,
+    MUST_CLOSE,
+    SEND_BODY,
+    SEND_RESPONSE,
+    SERVER,
+)
+from ._util import LocalProtocolError, RemoteProtocolError, Sentinel, validate
+
+__all__ = ["READERS"]
+
+header_field_re = re.compile(header_field.encode("ascii"))
+obs_fold_re = re.compile(rb"[ \t]+")
+
+
+def _obsolete_line_fold(lines: Iterable[bytes]) -> Iterable[bytes]:
+    it = iter(lines)
+    last: Optional[bytes] = None
+    for line in it:
+        match = obs_fold_re.match(line)
+        if match:
+            if last is None:
+                raise LocalProtocolError("continuation line at start of headers")
+            if not isinstance(last, bytearray):
+                # Cast to a mutable type, avoiding copy on append to ensure O(n) time
+                last = bytearray(last)
+            last += b" "
+            last += line[match.end() :]
+        else:
+            if last is not None:
+                yield last
+            last = line
+    if last is not None:
+        yield last
+
+
+def _decode_header_lines(
+    lines: Iterable[bytes],
+) -> Iterable[Tuple[bytes, bytes]]:
+    for line in _obsolete_line_fold(lines):
+        matches = validate(header_field_re, line, "illegal header line: {!r}", line)
+        yield (matches["field_name"], matches["field_value"])
+
+
+request_line_re = re.compile(request_line.encode("ascii"))
+
+
+def maybe_read_from_IDLE_client(buf: ReceiveBuffer) -> Optional[Request]:
+    lines = buf.maybe_extract_lines()
+    if lines is None:
+        if buf.is_next_line_obviously_invalid_request_line():
+            raise LocalProtocolError("illegal request line")
+        return None
+    if not lines:
+        raise LocalProtocolError("no request line received")
+    matches = validate(
+        request_line_re, lines[0], "illegal request line: {!r}", lines[0]
+    )
+    return Request(
+        headers=list(_decode_header_lines(lines[1:])), _parsed=True, **matches
+    )
+
+
+status_line_re = re.compile(status_line.encode("ascii"))
+
+
+def maybe_read_from_SEND_RESPONSE_server(
+    buf: ReceiveBuffer,
+) -> Union[InformationalResponse, Response, None]:
+    lines = buf.maybe_extract_lines()
+    if lines is None:
+        if buf.is_next_line_obviously_invalid_request_line():
+            raise LocalProtocolError("illegal request line")
+        return None
+    if not lines:
+        raise LocalProtocolError("no response line received")
+    matches = validate(status_line_re, lines[0], "illegal status line: {!r}", lines[0])
+    http_version = (
+        b"1.1" if matches["http_version"] is None else matches["http_version"]
+    )
+    reason = b"" if matches["reason"] is None else matches["reason"]
+    status_code = int(matches["status_code"])
+    class_: Union[Type[InformationalResponse], Type[Response]] = (
+        InformationalResponse if status_code < 200 else Response
+    )
+    return class_(
+        headers=list(_decode_header_lines(lines[1:])),
+        _parsed=True,
+        status_code=status_code,
+        reason=reason,
+        http_version=http_version,
+    )
+
+
+class ContentLengthReader:
+    def __init__(self, length: int) -> None:
+        self._length = length
+        self._remaining = length
+
+    def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]:
+        if self._remaining == 0:
+            return EndOfMessage()
+        data = buf.maybe_extract_at_most(self._remaining)
+        if data is None:
+            return None
+        self._remaining -= len(data)
+        return Data(data=data)
+
+    def read_eof(self) -> NoReturn:
+        raise RemoteProtocolError(
+            "peer closed connection without sending complete message body "
+            "(received {} bytes, expected {})".format(
+                self._length - self._remaining, self._length
+            )
+        )
+
+
+chunk_header_re = re.compile(chunk_header.encode("ascii"))
+
+
+class ChunkedReader:
+    def __init__(self) -> None:
+        self._bytes_in_chunk = 0
+        # After reading a chunk, we have to throw away the trailing \r\n.
+        # This tracks the bytes that we need to match and throw away.
+        self._bytes_to_discard = b""
+        self._reading_trailer = False
+
+    def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]:
+        if self._reading_trailer:
+            lines = buf.maybe_extract_lines()
+            if lines is None:
+                return None
+            return EndOfMessage(headers=list(_decode_header_lines(lines)))
+        if self._bytes_to_discard:
+            data = buf.maybe_extract_at_most(len(self._bytes_to_discard))
+            if data is None:
+                return None
+            if data != self._bytes_to_discard[: len(data)]:
+                raise LocalProtocolError(
+                    f"malformed chunk footer: {data!r} (expected {self._bytes_to_discard!r})"
+                )
+            self._bytes_to_discard = self._bytes_to_discard[len(data) :]
+            if self._bytes_to_discard:
+                return None
+            # else, fall through and read some more
+        assert self._bytes_to_discard == b""
+        if self._bytes_in_chunk == 0:
+            # We need to refill our chunk count
+            chunk_header = buf.maybe_extract_next_line()
+            if chunk_header is None:
+                return None
+            matches = validate(
+                chunk_header_re,
+                chunk_header,
+                "illegal chunk header: {!r}",
+                chunk_header,
+            )
+            # XX FIXME: we discard chunk extensions. Does anyone care?
+            self._bytes_in_chunk = int(matches["chunk_size"], base=16)
+            if self._bytes_in_chunk == 0:
+                self._reading_trailer = True
+                return self(buf)
+            chunk_start = True
+        else:
+            chunk_start = False
+        assert self._bytes_in_chunk > 0
+        data = buf.maybe_extract_at_most(self._bytes_in_chunk)
+        if data is None:
+            return None
+        self._bytes_in_chunk -= len(data)
+        if self._bytes_in_chunk == 0:
+            self._bytes_to_discard = b"\r\n"
+            chunk_end = True
+        else:
+            chunk_end = False
+        return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end)
+
+    def read_eof(self) -> NoReturn:
+        raise RemoteProtocolError(
+            "peer closed connection without sending complete message body "
+            "(incomplete chunked read)"
+        )
+
+
+class Http10Reader:
+    def __call__(self, buf: ReceiveBuffer) -> Optional[Data]:
+        data = buf.maybe_extract_at_most(999999999)
+        if data is None:
+            return None
+        return Data(data=data)
+
+    def read_eof(self) -> EndOfMessage:
+        return EndOfMessage()
+
+
+def expect_nothing(buf: ReceiveBuffer) -> None:
+    if buf:
+        raise LocalProtocolError("Got data when expecting EOF")
+    return None
+
+
+ReadersType = Dict[
+    Union[Type[Sentinel], Tuple[Type[Sentinel], Type[Sentinel]]],
+    Union[Callable[..., Any], Dict[str, Callable[..., Any]]],
+]
+
+READERS: ReadersType = {
+    (CLIENT, IDLE): maybe_read_from_IDLE_client,
+    (SERVER, IDLE): maybe_read_from_SEND_RESPONSE_server,
+    (SERVER, SEND_RESPONSE): maybe_read_from_SEND_RESPONSE_server,
+    (CLIENT, DONE): expect_nothing,
+    (CLIENT, MUST_CLOSE): expect_nothing,
+    (CLIENT, CLOSED): expect_nothing,
+    (SERVER, DONE): expect_nothing,
+    (SERVER, MUST_CLOSE): expect_nothing,
+    (SERVER, CLOSED): expect_nothing,
+    SEND_BODY: {
+        "chunked": ChunkedReader,
+        "content-length": ContentLengthReader,
+        "http/1.0": Http10Reader,
+    },
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_receivebuffer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_receivebuffer.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5c4e08a56f5081e87103f38b4add6ce1b730204
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_receivebuffer.py
@@ -0,0 +1,153 @@
+import re
+import sys
+from typing import List, Optional, Union
+
+__all__ = ["ReceiveBuffer"]
+
+
+# Operations we want to support:
+# - find next \r\n or \r\n\r\n (\n or \n\n are also acceptable),
+#   or wait until there is one
+# - read at-most-N bytes
+# Goals:
+# - on average, do this fast
+# - worst case, do this in O(n) where n is the number of bytes processed
+# Plan:
+# - store bytearray, offset, how far we've searched for a separator token
+# - use the how-far-we've-searched data to avoid rescanning
+# - while doing a stream of uninterrupted processing, advance offset instead
+#   of constantly copying
+# WARNING:
+# - I haven't benchmarked or profiled any of this yet.
+#
+# Note that starting in Python 3.4, deleting the initial n bytes from a
+# bytearray is amortized O(n), thanks to some excellent work by Antoine
+# Martin:
+#
+#     https://bugs.python.org/issue19087
+#
+# This means that if we only supported 3.4+, we could get rid of the code here
+# involving self._start and self.compress, because it's doing exactly the same
+# thing that bytearray now does internally.
+#
+# BUT unfortunately, we still support 2.7, and reading short segments out of a
+# long buffer MUST be O(bytes read) to avoid DoS issues, so we can't actually
+# delete this code. Yet:
+#
+#     https://pythonclock.org/
+#
+# (Two things to double-check first though: make sure PyPy also has the
+# optimization, and benchmark to make sure it's a win, since we do have a
+# slightly clever thing where we delay calling compress() until we've
+# processed a whole event, which could in theory be slightly more efficient
+# than the internal bytearray support.)
+blank_line_regex = re.compile(b"\n\r?\n", re.MULTILINE)
+
+
+class ReceiveBuffer:
+    def __init__(self) -> None:
+        self._data = bytearray()
+        self._next_line_search = 0
+        self._multiple_lines_search = 0
+
+    def __iadd__(self, byteslike: Union[bytes, bytearray]) -> "ReceiveBuffer":
+        self._data += byteslike
+        return self
+
+    def __bool__(self) -> bool:
+        return bool(len(self))
+
+    def __len__(self) -> int:
+        return len(self._data)
+
+    # for @property unprocessed_data
+    def __bytes__(self) -> bytes:
+        return bytes(self._data)
+
+    def _extract(self, count: int) -> bytearray:
+        # extracting an initial slice of the data buffer and return it
+        out = self._data[:count]
+        del self._data[:count]
+
+        self._next_line_search = 0
+        self._multiple_lines_search = 0
+
+        return out
+
+    def maybe_extract_at_most(self, count: int) -> Optional[bytearray]:
+        """
+        Extract a fixed number of bytes from the buffer.
+        """
+        out = self._data[:count]
+        if not out:
+            return None
+
+        return self._extract(count)
+
+    def maybe_extract_next_line(self) -> Optional[bytearray]:
+        """
+        Extract the first line, if it is completed in the buffer.
+        """
+        # Only search in buffer space that we've not already looked at.
+        search_start_index = max(0, self._next_line_search - 1)
+        partial_idx = self._data.find(b"\r\n", search_start_index)
+
+        if partial_idx == -1:
+            self._next_line_search = len(self._data)
+            return None
+
+        # + 2 is to compensate len(b"\r\n")
+        idx = partial_idx + 2
+
+        return self._extract(idx)
+
+    def maybe_extract_lines(self) -> Optional[List[bytearray]]:
+        """
+        Extract everything up to the first blank line, and return a list of lines.
+        """
+        # Handle the case where we have an immediate empty line.
+        if self._data[:1] == b"\n":
+            self._extract(1)
+            return []
+
+        if self._data[:2] == b"\r\n":
+            self._extract(2)
+            return []
+
+        # Only search in buffer space that we've not already looked at.
+        match = blank_line_regex.search(self._data, self._multiple_lines_search)
+        if match is None:
+            self._multiple_lines_search = max(0, len(self._data) - 2)
+            return None
+
+        # Truncate the buffer and return it.
+        idx = match.span(0)[-1]
+        out = self._extract(idx)
+        lines = out.split(b"\n")
+
+        for line in lines:
+            if line.endswith(b"\r"):
+                del line[-1]
+
+        assert lines[-2] == lines[-1] == b""
+
+        del lines[-2:]
+
+        return lines
+
+    # In theory we should wait until `\r\n` before starting to validate
+    # incoming data. However it's interesting to detect (very) invalid data
+    # early given they might not even contain `\r\n` at all (hence only
+    # timeout will get rid of them).
+    # This is not a 100% effective detection but more of a cheap sanity check
+    # allowing for early abort in some useful cases.
+    # This is especially interesting when peer is messing up with HTTPS and
+    # sent us a TLS stream where we were expecting plain HTTP given all
+    # versions of TLS so far start handshake with a 0x16 message type code.
+    def is_next_line_obviously_invalid_request_line(self) -> bool:
+        try:
+            # HTTP header line must not contain non-printable characters
+            # and should not start with a space
+            return self._data[0] < 0x21
+        except IndexError:
+            return False
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_state.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_state.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ad444b043e3f3d6c05c2d9d84d5119312bfaa34
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_state.py
@@ -0,0 +1,365 @@
+################################################################
+# The core state machine
+################################################################
+#
+# Rule 1: everything that affects the state machine and state transitions must
+# live here in this file. As much as possible goes into the table-based
+# representation, but for the bits that don't quite fit, the actual code and
+# state must nonetheless live here.
+#
+# Rule 2: this file does not know about what role we're playing; it only knows
+# about HTTP request/response cycles in the abstract. This ensures that we
+# don't cheat and apply different rules to local and remote parties.
+#
+#
+# Theory of operation
+# ===================
+#
+# Possibly the simplest way to think about this is that we actually have 5
+# different state machines here. Yes, 5. These are:
+#
+# 1) The client state, with its complicated automaton (see the docs)
+# 2) The server state, with its complicated automaton (see the docs)
+# 3) The keep-alive state, with possible states {True, False}
+# 4) The SWITCH_CONNECT state, with possible states {False, True}
+# 5) The SWITCH_UPGRADE state, with possible states {False, True}
+#
+# For (3)-(5), the first state listed is the initial state.
+#
+# (1)-(3) are stored explicitly in member variables. The last
+# two are stored implicitly in the pending_switch_proposals set as:
+#   (state of 4) == (_SWITCH_CONNECT in pending_switch_proposals)
+#   (state of 5) == (_SWITCH_UPGRADE in pending_switch_proposals)
+#
+# And each of these machines has two different kinds of transitions:
+#
+# a) Event-triggered
+# b) State-triggered
+#
+# Event triggered is the obvious thing that you'd think it is: some event
+# happens, and if it's the right event at the right time then a transition
+# happens. But there are somewhat complicated rules for which machines can
+# "see" which events. (As a rule of thumb, if a machine "sees" an event, this
+# means two things: the event can affect the machine, and if the machine is
+# not in a state where it expects that event then it's an error.) These rules
+# are:
+#
+# 1) The client machine sees all h11.events objects emitted by the client.
+#
+# 2) The server machine sees all h11.events objects emitted by the server.
+#
+#    It also sees the client's Request event.
+#
+#    And sometimes, server events are annotated with a _SWITCH_* event. For
+#    example, we can have a (Response, _SWITCH_CONNECT) event, which is
+#    different from a regular Response event.
+#
+# 3) The keep-alive machine sees the process_keep_alive_disabled() event
+#    (which is derived from Request/Response events), and this event
+#    transitions it from True -> False, or from False -> False. There's no way
+#    to transition back.
+#
+# 4&5) The _SWITCH_* machines transition from False->True when we get a
+#    Request that proposes the relevant type of switch (via
+#    process_client_switch_proposals), and they go from True->False when we
+#    get a Response that has no _SWITCH_* annotation.
+#
+# So that's event-triggered transitions.
+#
+# State-triggered transitions are less standard. What they do here is couple
+# the machines together. The way this works is, when certain *joint*
+# configurations of states are achieved, then we automatically transition to a
+# new *joint* state. So, for example, if we're ever in a joint state with
+#
+#   client: DONE
+#   keep-alive: False
+#
+# then the client state immediately transitions to:
+#
+#   client: MUST_CLOSE
+#
+# This is fundamentally different from an event-based transition, because it
+# doesn't matter how we arrived at the {client: DONE, keep-alive: False} state
+# -- maybe the client transitioned SEND_BODY -> DONE, or keep-alive
+# transitioned True -> False. Either way, once this precondition is satisfied,
+# this transition is immediately triggered.
+#
+# What if two conflicting state-based transitions get enabled at the same
+# time?  In practice there's only one case where this arises (client DONE ->
+# MIGHT_SWITCH_PROTOCOL versus DONE -> MUST_CLOSE), and we resolve it by
+# explicitly prioritizing the DONE -> MIGHT_SWITCH_PROTOCOL transition.
+#
+# Implementation
+# --------------
+#
+# The event-triggered transitions for the server and client machines are all
+# stored explicitly in a table. Ditto for the state-triggered transitions that
+# involve just the server and client state.
+#
+# The transitions for the other machines, and the state-triggered transitions
+# that involve the other machines, are written out as explicit Python code.
+#
+# It'd be nice if there were some cleaner way to do all this. This isn't
+# *too* terrible, but I feel like it could probably be better.
+#
+# WARNING
+# -------
+#
+# The script that generates the state machine diagrams for the docs knows how
+# to read out the EVENT_TRIGGERED_TRANSITIONS and STATE_TRIGGERED_TRANSITIONS
+# tables. But it can't automatically read the transitions that are written
+# directly in Python code. So if you touch those, you need to also update the
+# script to keep it in sync!
+from typing import cast, Dict, Optional, Set, Tuple, Type, Union
+
+from ._events import *
+from ._util import LocalProtocolError, Sentinel
+
+# Everything in __all__ gets re-exported as part of the h11 public API.
+__all__ = [
+    "CLIENT",
+    "SERVER",
+    "IDLE",
+    "SEND_RESPONSE",
+    "SEND_BODY",
+    "DONE",
+    "MUST_CLOSE",
+    "CLOSED",
+    "MIGHT_SWITCH_PROTOCOL",
+    "SWITCHED_PROTOCOL",
+    "ERROR",
+]
+
+
+class CLIENT(Sentinel, metaclass=Sentinel):
+    pass
+
+
+class SERVER(Sentinel, metaclass=Sentinel):
+    pass
+
+
+# States
+class IDLE(Sentinel, metaclass=Sentinel):
+    pass
+
+
+class SEND_RESPONSE(Sentinel, metaclass=Sentinel):
+    pass
+
+
+class SEND_BODY(Sentinel, metaclass=Sentinel):
+    pass
+
+
+class DONE(Sentinel, metaclass=Sentinel):
+    pass
+
+
+class MUST_CLOSE(Sentinel, metaclass=Sentinel):
+    pass
+
+
+class CLOSED(Sentinel, metaclass=Sentinel):
+    pass
+
+
+class ERROR(Sentinel, metaclass=Sentinel):
+    pass
+
+
+# Switch types
+class MIGHT_SWITCH_PROTOCOL(Sentinel, metaclass=Sentinel):
+    pass
+
+
+class SWITCHED_PROTOCOL(Sentinel, metaclass=Sentinel):
+    pass
+
+
+class _SWITCH_UPGRADE(Sentinel, metaclass=Sentinel):
+    pass
+
+
+class _SWITCH_CONNECT(Sentinel, metaclass=Sentinel):
+    pass
+
+
+EventTransitionType = Dict[
+    Type[Sentinel],
+    Dict[
+        Type[Sentinel],
+        Dict[Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]], Type[Sentinel]],
+    ],
+]
+
+EVENT_TRIGGERED_TRANSITIONS: EventTransitionType = {
+    CLIENT: {
+        IDLE: {Request: SEND_BODY, ConnectionClosed: CLOSED},
+        SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE},
+        DONE: {ConnectionClosed: CLOSED},
+        MUST_CLOSE: {ConnectionClosed: CLOSED},
+        CLOSED: {ConnectionClosed: CLOSED},
+        MIGHT_SWITCH_PROTOCOL: {},
+        SWITCHED_PROTOCOL: {},
+        ERROR: {},
+    },
+    SERVER: {
+        IDLE: {
+            ConnectionClosed: CLOSED,
+            Response: SEND_BODY,
+            # Special case: server sees client Request events, in this form
+            (Request, CLIENT): SEND_RESPONSE,
+        },
+        SEND_RESPONSE: {
+            InformationalResponse: SEND_RESPONSE,
+            Response: SEND_BODY,
+            (InformationalResponse, _SWITCH_UPGRADE): SWITCHED_PROTOCOL,
+            (Response, _SWITCH_CONNECT): SWITCHED_PROTOCOL,
+        },
+        SEND_BODY: {Data: SEND_BODY, EndOfMessage: DONE},
+        DONE: {ConnectionClosed: CLOSED},
+        MUST_CLOSE: {ConnectionClosed: CLOSED},
+        CLOSED: {ConnectionClosed: CLOSED},
+        SWITCHED_PROTOCOL: {},
+        ERROR: {},
+    },
+}
+
+StateTransitionType = Dict[
+    Tuple[Type[Sentinel], Type[Sentinel]], Dict[Type[Sentinel], Type[Sentinel]]
+]
+
+# NB: there are also some special-case state-triggered transitions hard-coded
+# into _fire_state_triggered_transitions below.
+STATE_TRIGGERED_TRANSITIONS: StateTransitionType = {
+    # (Client state, Server state) -> new states
+    # Protocol negotiation
+    (MIGHT_SWITCH_PROTOCOL, SWITCHED_PROTOCOL): {CLIENT: SWITCHED_PROTOCOL},
+    # Socket shutdown
+    (CLOSED, DONE): {SERVER: MUST_CLOSE},
+    (CLOSED, IDLE): {SERVER: MUST_CLOSE},
+    (ERROR, DONE): {SERVER: MUST_CLOSE},
+    (DONE, CLOSED): {CLIENT: MUST_CLOSE},
+    (IDLE, CLOSED): {CLIENT: MUST_CLOSE},
+    (DONE, ERROR): {CLIENT: MUST_CLOSE},
+}
+
+
+class ConnectionState:
+    def __init__(self) -> None:
+        # Extra bits of state that don't quite fit into the state model.
+
+        # If this is False then it enables the automatic DONE -> MUST_CLOSE
+        # transition. Don't set this directly; call .keep_alive_disabled()
+        self.keep_alive = True
+
+        # This is a subset of {UPGRADE, CONNECT}, containing the proposals
+        # made by the client for switching protocols.
+        self.pending_switch_proposals: Set[Type[Sentinel]] = set()
+
+        self.states: Dict[Type[Sentinel], Type[Sentinel]] = {CLIENT: IDLE, SERVER: IDLE}
+
+    def process_error(self, role: Type[Sentinel]) -> None:
+        self.states[role] = ERROR
+        self._fire_state_triggered_transitions()
+
+    def process_keep_alive_disabled(self) -> None:
+        self.keep_alive = False
+        self._fire_state_triggered_transitions()
+
+    def process_client_switch_proposal(self, switch_event: Type[Sentinel]) -> None:
+        self.pending_switch_proposals.add(switch_event)
+        self._fire_state_triggered_transitions()
+
+    def process_event(
+        self,
+        role: Type[Sentinel],
+        event_type: Type[Event],
+        server_switch_event: Optional[Type[Sentinel]] = None,
+    ) -> None:
+        _event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]] = event_type
+        if server_switch_event is not None:
+            assert role is SERVER
+            if server_switch_event not in self.pending_switch_proposals:
+                raise LocalProtocolError(
+                    "Received server _SWITCH_UPGRADE event without a pending proposal"
+                )
+            _event_type = (event_type, server_switch_event)
+        if server_switch_event is None and _event_type is Response:
+            self.pending_switch_proposals = set()
+        self._fire_event_triggered_transitions(role, _event_type)
+        # Special case: the server state does get to see Request
+        # events.
+        if _event_type is Request:
+            assert role is CLIENT
+            self._fire_event_triggered_transitions(SERVER, (Request, CLIENT))
+        self._fire_state_triggered_transitions()
+
+    def _fire_event_triggered_transitions(
+        self,
+        role: Type[Sentinel],
+        event_type: Union[Type[Event], Tuple[Type[Event], Type[Sentinel]]],
+    ) -> None:
+        state = self.states[role]
+        try:
+            new_state = EVENT_TRIGGERED_TRANSITIONS[role][state][event_type]
+        except KeyError:
+            event_type = cast(Type[Event], event_type)
+            raise LocalProtocolError(
+                "can't handle event type {} when role={} and state={}".format(
+                    event_type.__name__, role, self.states[role]
+                )
+            ) from None
+        self.states[role] = new_state
+
+    def _fire_state_triggered_transitions(self) -> None:
+        # We apply these rules repeatedly until converging on a fixed point
+        while True:
+            start_states = dict(self.states)
+
+            # It could happen that both these special-case transitions are
+            # enabled at the same time:
+            #
+            #    DONE -> MIGHT_SWITCH_PROTOCOL
+            #    DONE -> MUST_CLOSE
+            #
+            # For example, this will always be true of a HTTP/1.0 client
+            # requesting CONNECT.  If this happens, the protocol switch takes
+            # priority. From there the client will either go to
+            # SWITCHED_PROTOCOL, in which case it's none of our business when
+            # they close the connection, or else the server will deny the
+            # request, in which case the client will go back to DONE and then
+            # from there to MUST_CLOSE.
+            if self.pending_switch_proposals:
+                if self.states[CLIENT] is DONE:
+                    self.states[CLIENT] = MIGHT_SWITCH_PROTOCOL
+
+            if not self.pending_switch_proposals:
+                if self.states[CLIENT] is MIGHT_SWITCH_PROTOCOL:
+                    self.states[CLIENT] = DONE
+
+            if not self.keep_alive:
+                for role in (CLIENT, SERVER):
+                    if self.states[role] is DONE:
+                        self.states[role] = MUST_CLOSE
+
+            # Tabular state-triggered transitions
+            joint_state = (self.states[CLIENT], self.states[SERVER])
+            changes = STATE_TRIGGERED_TRANSITIONS.get(joint_state, {})
+            self.states.update(changes)
+
+            if self.states == start_states:
+                # Fixed point reached
+                return
+
+    def start_next_cycle(self) -> None:
+        if self.states != {CLIENT: DONE, SERVER: DONE}:
+            raise LocalProtocolError(
+                f"not in a reusable state. self.states={self.states}"
+            )
+        # Can't reach DONE/DONE with any of these active, but still, let's be
+        # sure.
+        assert self.keep_alive
+        assert not self.pending_switch_proposals
+        self.states = {CLIENT: IDLE, SERVER: IDLE}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_util.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..6718445290770e028ea2f1f662026c9a0b0991db
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_util.py
@@ -0,0 +1,135 @@
+from typing import Any, Dict, NoReturn, Pattern, Tuple, Type, TypeVar, Union
+
+__all__ = [
+    "ProtocolError",
+    "LocalProtocolError",
+    "RemoteProtocolError",
+    "validate",
+    "bytesify",
+]
+
+
+class ProtocolError(Exception):
+    """Exception indicating a violation of the HTTP/1.1 protocol.
+
+    This as an abstract base class, with two concrete base classes:
+    :exc:`LocalProtocolError`, which indicates that you tried to do something
+    that HTTP/1.1 says is illegal, and :exc:`RemoteProtocolError`, which
+    indicates that the remote peer tried to do something that HTTP/1.1 says is
+    illegal. See :ref:`error-handling` for details.
+
+    In addition to the normal :exc:`Exception` features, it has one attribute:
+
+    .. attribute:: error_status_hint
+
+       This gives a suggestion as to what status code a server might use if
+       this error occurred as part of a request.
+
+       For a :exc:`RemoteProtocolError`, this is useful as a suggestion for
+       how you might want to respond to a misbehaving peer, if you're
+       implementing a server.
+
+       For a :exc:`LocalProtocolError`, this can be taken as a suggestion for
+       how your peer might have responded to *you* if h11 had allowed you to
+       continue.
+
+       The default is 400 Bad Request, a generic catch-all for protocol
+       violations.
+
+    """
+
+    def __init__(self, msg: str, error_status_hint: int = 400) -> None:
+        if type(self) is ProtocolError:
+            raise TypeError("tried to directly instantiate ProtocolError")
+        Exception.__init__(self, msg)
+        self.error_status_hint = error_status_hint
+
+
+# Strategy: there are a number of public APIs where a LocalProtocolError can
+# be raised (send(), all the different event constructors, ...), and only one
+# public API where RemoteProtocolError can be raised
+# (receive_data()). Therefore we always raise LocalProtocolError internally,
+# and then receive_data will translate this into a RemoteProtocolError.
+#
+# Internally:
+#   LocalProtocolError is the generic "ProtocolError".
+# Externally:
+#   LocalProtocolError is for local errors and RemoteProtocolError is for
+#   remote errors.
+class LocalProtocolError(ProtocolError):
+    def _reraise_as_remote_protocol_error(self) -> NoReturn:
+        # After catching a LocalProtocolError, use this method to re-raise it
+        # as a RemoteProtocolError. This method must be called from inside an
+        # except: block.
+        #
+        # An easy way to get an equivalent RemoteProtocolError is just to
+        # modify 'self' in place.
+        self.__class__ = RemoteProtocolError  # type: ignore
+        # But the re-raising is somewhat non-trivial -- you might think that
+        # now that we've modified the in-flight exception object, that just
+        # doing 'raise' to re-raise it would be enough. But it turns out that
+        # this doesn't work, because Python tracks the exception type
+        # (exc_info[0]) separately from the exception object (exc_info[1]),
+        # and we only modified the latter. So we really do need to re-raise
+        # the new type explicitly.
+        # On py3, the traceback is part of the exception object, so our
+        # in-place modification preserved it and we can just re-raise:
+        raise self
+
+
+class RemoteProtocolError(ProtocolError):
+    pass
+
+
+def validate(
+    regex: Pattern[bytes], data: bytes, msg: str = "malformed data", *format_args: Any
+) -> Dict[str, bytes]:
+    match = regex.fullmatch(data)
+    if not match:
+        if format_args:
+            msg = msg.format(*format_args)
+        raise LocalProtocolError(msg)
+    return match.groupdict()
+
+
+# Sentinel values
+#
+# - Inherit identity-based comparison and hashing from object
+# - Have a nice repr
+# - Have a *bonus property*: type(sentinel) is sentinel
+#
+# The bonus property is useful if you want to take the return value from
+# next_event() and do some sort of dispatch based on type(event).
+
+_T_Sentinel = TypeVar("_T_Sentinel", bound="Sentinel")
+
+
+class Sentinel(type):
+    def __new__(
+        cls: Type[_T_Sentinel],
+        name: str,
+        bases: Tuple[type, ...],
+        namespace: Dict[str, Any],
+        **kwds: Any
+    ) -> _T_Sentinel:
+        assert bases == (Sentinel,)
+        v = super().__new__(cls, name, bases, namespace, **kwds)
+        v.__class__ = v  # type: ignore
+        return v
+
+    def __repr__(self) -> str:
+        return self.__name__
+
+
+# Used for methods, request targets, HTTP versions, header names, and header
+# values. Accepts ascii-strings, or bytes/bytearray/memoryview/..., and always
+# returns bytes.
+def bytesify(s: Union[bytes, bytearray, memoryview, int, str]) -> bytes:
+    # Fast-path:
+    if type(s) is bytes:
+        return s
+    if isinstance(s, str):
+        s = s.encode("ascii")
+    if isinstance(s, int):
+        raise TypeError("expected bytes-like object, not int")
+    return bytes(s)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_version.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..76e7327b8617c9d12236f511414d5eb58e98a44b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_version.py
@@ -0,0 +1,16 @@
+# This file must be kept very simple, because it is consumed from several
+# places -- it is imported by h11/__init__.py, execfile'd by setup.py, etc.
+
+# We use a simple scheme:
+#   1.0.0 -> 1.0.0+dev -> 1.1.0 -> 1.1.0+dev
+# where the +dev versions are never released into the wild, they're just what
+# we stick into the VCS in between releases.
+#
+# This is compatible with PEP 440:
+#   http://legacy.python.org/dev/peps/pep-0440/
+# via the use of the "local suffix" "+dev", which is disallowed on index
+# servers and causes 1.0.0+dev to sort after plain 1.0.0, which is what we
+# want. (Contrast with the special suffix 1.0.0.dev, which sorts *before*
+# 1.0.0.)
+
+__version__ = "0.16.0"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_writers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_writers.py
new file mode 100644
index 0000000000000000000000000000000000000000..939cdb912a9debaea07fbf3a9ac04549c44d077c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/_writers.py
@@ -0,0 +1,145 @@
+# Code to read HTTP data
+#
+# Strategy: each writer takes an event + a write-some-bytes function, which is
+# calls.
+#
+# WRITERS is a dict describing how to pick a reader. It maps states to either:
+# - a writer
+# - or, for body writers, a dict of framin-dependent writer factories
+
+from typing import Any, Callable, Dict, List, Tuple, Type, Union
+
+from ._events import Data, EndOfMessage, Event, InformationalResponse, Request, Response
+from ._headers import Headers
+from ._state import CLIENT, IDLE, SEND_BODY, SEND_RESPONSE, SERVER
+from ._util import LocalProtocolError, Sentinel
+
+__all__ = ["WRITERS"]
+
+Writer = Callable[[bytes], Any]
+
+
+def write_headers(headers: Headers, write: Writer) -> None:
+    # "Since the Host field-value is critical information for handling a
+    # request, a user agent SHOULD generate Host as the first header field
+    # following the request-line." - RFC 7230
+    raw_items = headers._full_items
+    for raw_name, name, value in raw_items:
+        if name == b"host":
+            write(b"%s: %s\r\n" % (raw_name, value))
+    for raw_name, name, value in raw_items:
+        if name != b"host":
+            write(b"%s: %s\r\n" % (raw_name, value))
+    write(b"\r\n")
+
+
+def write_request(request: Request, write: Writer) -> None:
+    if request.http_version != b"1.1":
+        raise LocalProtocolError("I only send HTTP/1.1")
+    write(b"%s %s HTTP/1.1\r\n" % (request.method, request.target))
+    write_headers(request.headers, write)
+
+
+# Shared between InformationalResponse and Response
+def write_any_response(
+    response: Union[InformationalResponse, Response], write: Writer
+) -> None:
+    if response.http_version != b"1.1":
+        raise LocalProtocolError("I only send HTTP/1.1")
+    status_bytes = str(response.status_code).encode("ascii")
+    # We don't bother sending ascii status messages like "OK"; they're
+    # optional and ignored by the protocol. (But the space after the numeric
+    # status code is mandatory.)
+    #
+    # XX FIXME: could at least make an effort to pull out the status message
+    # from stdlib's http.HTTPStatus table. Or maybe just steal their enums
+    # (either by import or copy/paste). We already accept them as status codes
+    # since they're of type IntEnum < int.
+    write(b"HTTP/1.1 %s %s\r\n" % (status_bytes, response.reason))
+    write_headers(response.headers, write)
+
+
+class BodyWriter:
+    def __call__(self, event: Event, write: Writer) -> None:
+        if type(event) is Data:
+            self.send_data(event.data, write)
+        elif type(event) is EndOfMessage:
+            self.send_eom(event.headers, write)
+        else:  # pragma: no cover
+            assert False
+
+    def send_data(self, data: bytes, write: Writer) -> None:
+        pass
+
+    def send_eom(self, headers: Headers, write: Writer) -> None:
+        pass
+
+
+#
+# These are all careful not to do anything to 'data' except call len(data) and
+# write(data). This allows us to transparently pass-through funny objects,
+# like placeholder objects referring to files on disk that will be sent via
+# sendfile(2).
+#
+class ContentLengthWriter(BodyWriter):
+    def __init__(self, length: int) -> None:
+        self._length = length
+
+    def send_data(self, data: bytes, write: Writer) -> None:
+        self._length -= len(data)
+        if self._length < 0:
+            raise LocalProtocolError("Too much data for declared Content-Length")
+        write(data)
+
+    def send_eom(self, headers: Headers, write: Writer) -> None:
+        if self._length != 0:
+            raise LocalProtocolError("Too little data for declared Content-Length")
+        if headers:
+            raise LocalProtocolError("Content-Length and trailers don't mix")
+
+
+class ChunkedWriter(BodyWriter):
+    def send_data(self, data: bytes, write: Writer) -> None:
+        # if we encoded 0-length data in the naive way, it would look like an
+        # end-of-message.
+        if not data:
+            return
+        write(b"%x\r\n" % len(data))
+        write(data)
+        write(b"\r\n")
+
+    def send_eom(self, headers: Headers, write: Writer) -> None:
+        write(b"0\r\n")
+        write_headers(headers, write)
+
+
+class Http10Writer(BodyWriter):
+    def send_data(self, data: bytes, write: Writer) -> None:
+        write(data)
+
+    def send_eom(self, headers: Headers, write: Writer) -> None:
+        if headers:
+            raise LocalProtocolError("can't send trailers to HTTP/1.0 client")
+        # no need to close the socket ourselves, that will be taken care of by
+        # Connection: close machinery
+
+
+WritersType = Dict[
+    Union[Tuple[Type[Sentinel], Type[Sentinel]], Type[Sentinel]],
+    Union[
+        Dict[str, Type[BodyWriter]],
+        Callable[[Union[InformationalResponse, Response], Writer], None],
+        Callable[[Request, Writer], None],
+    ],
+]
+
+WRITERS: WritersType = {
+    (CLIENT, IDLE): write_request,
+    (SERVER, IDLE): write_any_response,
+    (SERVER, SEND_RESPONSE): write_any_response,
+    SEND_BODY: {
+        "chunked": ChunkedWriter,
+        "content-length": ContentLengthWriter,
+        "http/1.0": Http10Writer,
+    },
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..f5642f79f21d872f010979dcf6f0c4a415acc19d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/h11/py.typed
@@ -0,0 +1 @@
+Marker
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet-1.5.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet-1.5.0.dist-info/INSTALLER
new file mode 100644
index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet-1.5.0.dist-info/INSTALLER
@@ -0,0 +1 @@
+pip
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet-1.5.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet-1.5.0.dist-info/METADATA
new file mode 100644
index 0000000000000000000000000000000000000000..4c3b7b2b92140fad2b6b301d5bac757d241d9f1b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet-1.5.0.dist-info/METADATA
@@ -0,0 +1,87 @@
+Metadata-Version: 2.4
+Name: hf-xet
+Version: 1.5.0
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: License :: OSI Approved :: Apache Software License
+Classifier: Programming Language :: Rust
+Classifier: Programming Language :: Python :: Implementation :: CPython
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Classifier: Programming Language :: Python :: Free Threading
+Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta
+Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
+Requires-Dist: pytest ; extra == 'tests'
+Provides-Extra: tests
+License-File: LICENSE
+Summary: Fast transfer of large files with the Hugging Face Hub.
+Maintainer-email: Rajat Arya , Jared Sulzdorf , Di Xiao , Assaf Vayner , Hoyt Koepke 
+License-Expression: Apache-2.0
+Requires-Python: >=3.8
+Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
+Project-URL: Documentation, https://huggingface.co/docs/hub/xet/index
+Project-URL: Homepage, https://github.com/huggingface/xet-core
+Project-URL: Issues, https://github.com/huggingface/xet-core/issues
+Project-URL: Repository, https://github.com/huggingface/xet-core.git
+
+
+

+ License + GitHub release + Contributor Covenant +

+ +

+

🤗 hf-xet - xet client tech, used in huggingface_hub

+

+ +## Welcome + +`hf-xet` enables `huggingface_hub` to utilize xet storage for uploading and downloading to HF Hub. Xet storage provides chunk-based deduplication, efficient storage/retrieval with local disk caching, and backwards compatibility with Git LFS. This library is not meant to be used directly, and is instead intended to be used from [huggingface_hub](https://pypi.org/project/huggingface-hub). + +## Key features + +♻ **chunk-based deduplication implementation**: avoid transferring and storing chunks that are shared across binary files (models, datasets, etc). + +🤗 **Python bindings**: bindings for [huggingface_hub](https://github.com/huggingface/huggingface_hub/) package. + +↔ **network communications**: concurrent communication to HF Hub Xet backend services (CAS). + +🔖 **local disk caching**: chunk-based cache that sits alongside the existing [huggingface_hub disk cache](https://huggingface.co/docs/huggingface_hub/guides/manage-cache). + +## Installation + +Install the `hf_xet` package with [pip](https://pypi.org/project/hf-xet/): + +```bash +pip install hf_xet +``` + +## Quick Start + +`hf_xet` is not intended to be run independently as it is expected to be used from `huggingface_hub`, so to get started with `huggingface_hub` check out the documentation [here]("https://hf.co/docs/huggingface_hub"). + +## Contributions (feature requests, bugs, etc.) are encouraged & appreciated 💙💚💛💜🧡❤️ + +Please join us in making hf-xet better. We value everyone's contributions. Code is not the only way to help. Answering questions, helping each other, improving documentation, filing issues all help immensely. If you are interested in contributing (please do!), check out the [contribution guide](https://github.com/huggingface/xet-core/blob/main/CONTRIBUTING.md) for this repository. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet-1.5.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet-1.5.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..0e479d0bd4b137faebd67f2af5e1d3006344f715 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet-1.5.0.dist-info/RECORD @@ -0,0 +1,9 @@ +hf_xet-1.5.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +hf_xet-1.5.0.dist-info/METADATA,sha256=hHOh6lfhvFI_VCaTTuU2rbgRV2n6ceAJdROGjlapvr0,4935 +hf_xet-1.5.0.dist-info/RECORD,, +hf_xet-1.5.0.dist-info/WHEEL,sha256=gXPnzSzx5vdYKHxhDYVt-C4eXbt3uxomOiEDn4ehIhw,95 +hf_xet-1.5.0.dist-info/licenses/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558 +hf_xet-1.5.0.dist-info/sboms/hf_xet.cyclonedx.json,sha256=a7PGAA92UPU4vriLVDk3nYsTO6IABSQi_yGmadkk6L0,317095 +hf_xet/__init__.py,sha256=E8UDdyQ8glZ_nve9hHEf22bPang8-RKx4VuApXYeQUo,107 +hf_xet/__pycache__/__init__.cpython-311.pyc,, +hf_xet/hf_xet.pyd,sha256=CheHHcKkO4bgozaRqRYJ8l0oFJcO-rIBzHQOPXAuD0I,9291776 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet-1.5.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet-1.5.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..7429e62c77202fd72ee3191d3f82a9757904f69e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet-1.5.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: maturin (1.13.1) +Root-Is-Purelib: false +Tag: cp37-abi3-win_amd64 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..96ed54a8a066d681e4973e5841a0f5577b619698 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/hf_xet/__init__.py @@ -0,0 +1,5 @@ +from .hf_xet import * + +__doc__ = hf_xet.__doc__ +if hasattr(hf_xet, "__all__"): + __all__ = hf_xet.__all__ \ No newline at end of file diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore-1.0.9.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore-1.0.9.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore-1.0.9.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore-1.0.9.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore-1.0.9.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..8056834e6714b089ef49847820064a1ae4b041fd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore-1.0.9.dist-info/METADATA @@ -0,0 +1,625 @@ +Metadata-Version: 2.4 +Name: httpcore +Version: 1.0.9 +Summary: A minimal low-level HTTP client. +Project-URL: Documentation, https://www.encode.io/httpcore +Project-URL: Homepage, https://www.encode.io/httpcore/ +Project-URL: Source, https://github.com/encode/httpcore +Author-email: Tom Christie +License-Expression: BSD-3-Clause +License-File: LICENSE.md +Classifier: Development Status :: 3 - Alpha +Classifier: Environment :: Web Environment +Classifier: Framework :: AsyncIO +Classifier: Framework :: Trio +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.8 +Requires-Dist: certifi +Requires-Dist: h11>=0.16 +Provides-Extra: asyncio +Requires-Dist: anyio<5.0,>=4.0; extra == 'asyncio' +Provides-Extra: http2 +Requires-Dist: h2<5,>=3; extra == 'http2' +Provides-Extra: socks +Requires-Dist: socksio==1.*; extra == 'socks' +Provides-Extra: trio +Requires-Dist: trio<1.0,>=0.22.0; extra == 'trio' +Description-Content-Type: text/markdown + +# HTTP Core + +[![Test Suite](https://github.com/encode/httpcore/workflows/Test%20Suite/badge.svg)](https://github.com/encode/httpcore/actions) +[![Package version](https://badge.fury.io/py/httpcore.svg)](https://pypi.org/project/httpcore/) + +> *Do one thing, and do it well.* + +The HTTP Core package provides a minimal low-level HTTP client, which does +one thing only. Sending HTTP requests. + +It does not provide any high level model abstractions over the API, +does not handle redirects, multipart uploads, building authentication headers, +transparent HTTP caching, URL parsing, session cookie handling, +content or charset decoding, handling JSON, environment based configuration +defaults, or any of that Jazz. + +Some things HTTP Core does do: + +* Sending HTTP requests. +* Thread-safe / task-safe connection pooling. +* HTTP(S) proxy & SOCKS proxy support. +* Supports HTTP/1.1 and HTTP/2. +* Provides both sync and async interfaces. +* Async backend support for `asyncio` and `trio`. + +## Requirements + +Python 3.8+ + +## Installation + +For HTTP/1.1 only support, install with: + +```shell +$ pip install httpcore +``` + +There are also a number of optional extras available... + +```shell +$ pip install httpcore['asyncio,trio,http2,socks'] +``` + +## Sending requests + +Send an HTTP request: + +```python +import httpcore + +response = httpcore.request("GET", "https://www.example.com/") + +print(response) +# +print(response.status) +# 200 +print(response.headers) +# [(b'Accept-Ranges', b'bytes'), (b'Age', b'557328'), (b'Cache-Control', b'max-age=604800'), ...] +print(response.content) +# b'\n\n\nExample Domain\n\n\n ...' +``` + +The top-level `httpcore.request()` function is provided for convenience. In practice whenever you're working with `httpcore` you'll want to use the connection pooling functionality that it provides. + +```python +import httpcore + +http = httpcore.ConnectionPool() +response = http.request("GET", "https://www.example.com/") +``` + +Once you're ready to get going, [head over to the documentation](https://www.encode.io/httpcore/). + +## Motivation + +You *probably* don't want to be using HTTP Core directly. It might make sense if +you're writing something like a proxy service in Python, and you just want +something at the lowest possible level, but more typically you'll want to use +a higher level client library, such as `httpx`. + +The motivation for `httpcore` is: + +* To provide a reusable low-level client library, that other packages can then build on top of. +* To provide a *really clear interface split* between the networking code and client logic, + so that each is easier to understand and reason about in isolation. + +## Dependencies + +The `httpcore` package has the following dependencies... + +* `h11` +* `certifi` + +And the following optional extras... + +* `anyio` - Required by `pip install httpcore['asyncio']`. +* `trio` - Required by `pip install httpcore['trio']`. +* `h2` - Required by `pip install httpcore['http2']`. +* `socksio` - Required by `pip install httpcore['socks']`. + +## Versioning + +We use [SEMVER for our versioning policy](https://semver.org/). + +For changes between package versions please see our [project changelog](CHANGELOG.md). + +We recommend pinning your requirements either the most current major version, or a more specific version range: + +```python +pip install 'httpcore==1.*' +``` +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## Version 1.0.9 (April 24th, 2025) + +- Resolve https://github.com/advisories/GHSA-vqfr-h8mv-ghfj with h11 dependency update. (#1008) + +## Version 1.0.8 (April 11th, 2025) + +- Fix `AttributeError` when importing on Python 3.14. (#1005) + +## Version 1.0.7 (November 15th, 2024) + +- Support `proxy=…` configuration on `ConnectionPool()`. (#974) + +## Version 1.0.6 (October 1st, 2024) + +- Relax `trio` dependency pinning. (#956) +- Handle `trio` raising `NotImplementedError` on unsupported platforms. (#955) +- Handle mapping `ssl.SSLError` to `httpcore.ConnectError`. (#918) + +## 1.0.5 (March 27th, 2024) + +- Handle `EndOfStream` exception for anyio backend. (#899) +- Allow trio `0.25.*` series in package dependancies. (#903) + +## 1.0.4 (February 21st, 2024) + +- Add `target` request extension. (#888) +- Fix support for connection `Upgrade` and `CONNECT` when some data in the stream has been read. (#882) + +## 1.0.3 (February 13th, 2024) + +- Fix support for async cancellations. (#880) +- Fix trace extension when used with socks proxy. (#849) +- Fix SSL context for connections using the "wss" scheme (#869) + +## 1.0.2 (November 10th, 2023) + +- Fix `float("inf")` timeouts in `Event.wait` function. (#846) + +## 1.0.1 (November 3rd, 2023) + +- Fix pool timeout to account for the total time spent retrying. (#823) +- Raise a neater RuntimeError when the correct async deps are not installed. (#826) +- Add support for synchronous TLS-in-TLS streams. (#840) + +## 1.0.0 (October 6th, 2023) + +From version 1.0 our async support is now optional, as the package has minimal dependencies by default. + +For async support use either `pip install 'httpcore[asyncio]'` or `pip install 'httpcore[trio]'`. + +The project versioning policy is now explicitly governed by SEMVER. See https://semver.org/. + +- Async support becomes fully optional. (#809) +- Add support for Python 3.12. (#807) + +## 0.18.0 (September 8th, 2023) + +- Add support for HTTPS proxies. (#745, #786) +- Drop Python 3.7 support. (#727) +- Handle `sni_hostname` extension with SOCKS proxy. (#774) +- Handle HTTP/1.1 half-closed connections gracefully. (#641) +- Change the type of `Extensions` from `Mapping[Str, Any]` to `MutableMapping[Str, Any]`. (#762) + +## 0.17.3 (July 5th, 2023) + +- Support async cancellations, ensuring that the connection pool is left in a clean state when cancellations occur. (#726) +- The networking backend interface has [been added to the public API](https://www.encode.io/httpcore/network-backends). Some classes which were previously private implementation detail are now part of the top-level public API. (#699) +- Graceful handling of HTTP/2 GoAway frames, with requests being transparently retried on a new connection. (#730) +- Add exceptions when a synchronous `trace callback` is passed to an asynchronous request or an asynchronous `trace callback` is passed to a synchronous request. (#717) +- Drop Python 3.7 support. (#727) + +## 0.17.2 (May 23th, 2023) + +- Add `socket_options` argument to `ConnectionPool` and `HTTProxy` classes. (#668) +- Improve logging with per-module logger names. (#690) +- Add `sni_hostname` request extension. (#696) +- Resolve race condition during import of `anyio` package. (#692) +- Enable TCP_NODELAY for all synchronous sockets. (#651) + +## 0.17.1 (May 17th, 2023) + +- If 'retries' is set, then allow retries if an SSL handshake error occurs. (#669) +- Improve correctness of tracebacks on network exceptions, by raising properly chained exceptions. (#678) +- Prevent connection-hanging behaviour when HTTP/2 connections are closed by a server-sent 'GoAway' frame. (#679) +- Fix edge-case exception when removing requests from the connection pool. (#680) +- Fix pool timeout edge-case. (#688) + +## 0.17.0 (March 16th, 2023) + +- Add DEBUG level logging. (#648) +- Respect HTTP/2 max concurrent streams when settings updates are sent by server. (#652) +- Increase the allowable HTTP header size to 100kB. (#647) +- Add `retries` option to SOCKS proxy classes. (#643) + +## 0.16.3 (December 20th, 2022) + +- Allow `ws` and `wss` schemes. Allows us to properly support websocket upgrade connections. (#625) +- Forwarding HTTP proxies use a connection-per-remote-host. Required by some proxy implementations. (#637) +- Don't raise `RuntimeError` when closing a connection pool with active connections. Removes some error cases when cancellations are used. (#631) +- Lazy import `anyio`, so that it's no longer a hard dependancy, and isn't imported if unused. (#639) + +## 0.16.2 (November 25th, 2022) + +- Revert 'Fix async cancellation behaviour', which introduced race conditions. (#627) +- Raise `RuntimeError` if attempting to us UNIX domain sockets on Windows. (#619) + +## 0.16.1 (November 17th, 2022) + +- Fix HTTP/1.1 interim informational responses, such as "100 Continue". (#605) + +## 0.16.0 (October 11th, 2022) + +- Support HTTP/1.1 informational responses. (#581) +- Fix async cancellation behaviour. (#580) +- Support `h11` 0.14. (#579) + +## 0.15.0 (May 17th, 2022) + +- Drop Python 3.6 support (#535) +- Ensure HTTP proxy CONNECT requests include `timeout` configuration. (#506) +- Switch to explicit `typing.Optional` for type hints. (#513) +- For `trio` map OSError exceptions to `ConnectError`. (#543) + +## 0.14.7 (February 4th, 2022) + +- Requests which raise a PoolTimeout need to be removed from the pool queue. (#502) +- Fix AttributeError that happened when Socks5Connection were terminated. (#501) + +## 0.14.6 (February 1st, 2022) + +- Fix SOCKS support for `http://` URLs. (#492) +- Resolve race condition around exceptions during streaming a response. (#491) + +## 0.14.5 (January 18th, 2022) + +- SOCKS proxy support. (#478) +- Add proxy_auth argument to HTTPProxy. (#481) +- Improve error message on 'RemoteProtocolError' exception when server disconnects without sending a response. (#479) + +## 0.14.4 (January 5th, 2022) + +- Support HTTP/2 on HTTPS tunnelling proxies. (#468) +- Fix proxy headers missing on HTTP forwarding. (#456) +- Only instantiate SSL context if required. (#457) +- More robust HTTP/2 handling. (#253, #439, #440, #441) + +## 0.14.3 (November 17th, 2021) + +- Fix race condition when removing closed connections from the pool. (#437) + +## 0.14.2 (November 16th, 2021) + +- Failed connections no longer remain in the pool. (Pull #433) + +## 0.14.1 (November 12th, 2021) + +- `max_connections` becomes optional. (Pull #429) +- `certifi` is now included in the install dependancies. (Pull #428) +- `h2` is now strictly optional. (Pull #428) + +## 0.14.0 (November 11th, 2021) + +The 0.14 release is a complete reworking of `httpcore`, comprehensively addressing some underlying issues in the connection pooling, as well as substantially redesigning the API to be more user friendly. + +Some of the lower-level API design also makes the components more easily testable in isolation, and the package now has 100% test coverage. + +See [discussion #419](https://github.com/encode/httpcore/discussions/419) for a little more background. + +There's some other neat bits in there too, such as the "trace" extension, which gives a hook into inspecting the internal events that occur during the request/response cycle. This extension is needed for the HTTPX cli, in order to... + +* Log the point at which the connection is established, and the IP/port on which it is made. +* Determine if the outgoing request should log as HTTP/1.1 or HTTP/2, rather than having to assume it's HTTP/2 if the --http2 flag was passed. (Which may not actually be true.) +* Log SSL version info / certificate info. + +Note that `curio` support is not currently available in 0.14.0. If you're using `httpcore` with `curio` please get in touch, so we can assess if we ought to prioritize it as a feature or not. + +## 0.13.7 (September 13th, 2021) + +- Fix broken error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #403) + +## 0.13.6 (June 15th, 2021) + +### Fixed + +- Close sockets when read or write timeouts occur. (Pull #365) + +## 0.13.5 (June 14th, 2021) + +### Fixed + +- Resolved niggles with AnyIO EOF behaviours. (Pull #358, #362) + +## 0.13.4 (June 9th, 2021) + +### Added + +- Improved error messaging when URL scheme is missing, or a non HTTP(S) scheme is used. (Pull #354) + +### Fixed + +- Switched to `anyio` as the default backend implementation when running with `asyncio`. Resolves some awkward [TLS timeout issues](https://github.com/encode/httpx/discussions/1511). + +## 0.13.3 (May 6th, 2021) + +### Added + +- Support HTTP/2 prior knowledge, using `httpcore.SyncConnectionPool(http1=False)`. (Pull #333) + +### Fixed + +- Handle cases where environment does not provide `select.poll` support. (Pull #331) + +## 0.13.2 (April 29th, 2021) + +### Added + +- Improve error message for specific case of `RemoteProtocolError` where server disconnects without sending a response. (Pull #313) + +## 0.13.1 (April 28th, 2021) + +### Fixed + +- More resiliant testing for closed connections. (Pull #311) +- Don't raise exceptions on ungraceful connection closes. (Pull #310) + +## 0.13.0 (April 21st, 2021) + +The 0.13 release updates the core API in order to match the HTTPX Transport API, +introduced in HTTPX 0.18 onwards. + +An example of making requests with the new interface is: + +```python +with httpcore.SyncConnectionPool() as http: + status_code, headers, stream, extensions = http.handle_request( + method=b'GET', + url=(b'https', b'example.org', 443, b'/'), + headers=[(b'host', b'example.org'), (b'user-agent', b'httpcore')] + stream=httpcore.ByteStream(b''), + extensions={} + ) + body = stream.read() + print(status_code, body) +``` + +### Changed + +- The `.request()` method is now `handle_request()`. (Pull #296) +- The `.arequest()` method is now `.handle_async_request()`. (Pull #296) +- The `headers` argument is no longer optional. (Pull #296) +- The `stream` argument is no longer optional. (Pull #296) +- The `ext` argument is now named `extensions`, and is no longer optional. (Pull #296) +- The `"reason"` extension keyword is now named `"reason_phrase"`. (Pull #296) +- The `"reason_phrase"` and `"http_version"` extensions now use byte strings for their values. (Pull #296) +- The `httpcore.PlainByteStream()` class becomes `httpcore.ByteStream()`. (Pull #296) + +### Added + +- Streams now support a `.read()` interface. (Pull #296) + +### Fixed + +- Task cancellation no longer leaks connections from the connection pool. (Pull #305) + +## 0.12.3 (December 7th, 2020) + +### Fixed + +- Abort SSL connections on close rather than waiting for remote EOF when using `asyncio`. (Pull #167) +- Fix exception raised in case of connect timeouts when using the `anyio` backend. (Pull #236) +- Fix `Host` header precedence for `:authority` in HTTP/2. (Pull #241, #243) +- Handle extra edge case when detecting for socket readability when using `asyncio`. (Pull #242, #244) +- Fix `asyncio` SSL warning when using proxy tunneling. (Pull #249) + +## 0.12.2 (November 20th, 2020) + +### Fixed + +- Properly wrap connect errors on the asyncio backend. (Pull #235) +- Fix `ImportError` occurring on Python 3.9 when using the HTTP/1.1 sync client in a multithreaded context. (Pull #237) + +## 0.12.1 (November 7th, 2020) + +### Added + +- Add connect retries. (Pull #221) + +### Fixed + +- Tweak detection of dropped connections, resolving an issue with open files limits on Linux. (Pull #185) +- Avoid leaking connections when establishing an HTTP tunnel to a proxy has failed. (Pull #223) +- Properly wrap OS errors when using `trio`. (Pull #225) + +## 0.12.0 (October 6th, 2020) + +### Changed + +- HTTP header casing is now preserved, rather than always sent in lowercase. (#216 and python-hyper/h11#104) + +### Added + +- Add Python 3.9 to officially supported versions. + +### Fixed + +- Gracefully handle a stdlib asyncio bug when a connection is closed while it is in a paused-for-reading state. (#201) + +## 0.11.1 (September 28nd, 2020) + +### Fixed + +- Add await to async semaphore release() coroutine (#197) +- Drop incorrect curio classifier (#192) + +## 0.11.0 (September 22nd, 2020) + +The Transport API with 0.11.0 has a couple of significant changes. + +Firstly we've moved changed the request interface in order to allow extensions, which will later enable us to support features +such as trailing headers, HTTP/2 server push, and CONNECT/Upgrade connections. + +The interface changes from: + +```python +def request(method, url, headers, stream, timeout): + return (http_version, status_code, reason, headers, stream) +``` + +To instead including an optional dictionary of extensions on the request and response: + +```python +def request(method, url, headers, stream, ext): + return (status_code, headers, stream, ext) +``` + +Having an open-ended extensions point will allow us to add later support for various optional features, that wouldn't otherwise be supported without these API changes. + +In particular: + +* Trailing headers support. +* HTTP/2 Server Push +* sendfile. +* Exposing raw connection on CONNECT, Upgrade, HTTP/2 bi-di streaming. +* Exposing debug information out of the API, including template name, template context. + +Currently extensions are limited to: + +* request: `timeout` - Optional. Timeout dictionary. +* response: `http_version` - Optional. Include the HTTP version used on the response. +* response: `reason` - Optional. Include the reason phrase used on the response. Only valid with HTTP/1.*. + +See https://github.com/encode/httpx/issues/1274#issuecomment-694884553 for the history behind this. + +Secondly, the async version of `request` is now namespaced as `arequest`. + +This allows concrete transports to support both sync and async implementations on the same class. + +### Added + +- Add curio support. (Pull #168) +- Add anyio support, with `backend="anyio"`. (Pull #169) + +### Changed + +- Update the Transport API to use 'ext' for optional extensions. (Pull #190) +- Update the Transport API to use `.request` and `.arequest` so implementations can support both sync and async. (Pull #189) + +## 0.10.2 (August 20th, 2020) + +### Added + +- Added Unix Domain Socket support. (Pull #139) + +### Fixed + +- Always include the port on proxy CONNECT requests. (Pull #154) +- Fix `max_keepalive_connections` configuration. (Pull #153) +- Fixes behaviour in HTTP/1.1 where server disconnects can be used to signal the end of the response body. (Pull #164) + +## 0.10.1 (August 7th, 2020) + +- Include `max_keepalive_connections` on `AsyncHTTPProxy`/`SyncHTTPProxy` classes. + +## 0.10.0 (August 7th, 2020) + +The most notable change in the 0.10.0 release is that HTTP/2 support is now fully optional. + +Use either `pip install httpcore` for HTTP/1.1 support only, or `pip install httpcore[http2]` for HTTP/1.1 and HTTP/2 support. + +### Added + +- HTTP/2 support becomes optional. (Pull #121, #130) +- Add `local_address=...` support. (Pull #100, #134) +- Add `PlainByteStream`, `IteratorByteStream`, `AsyncIteratorByteStream`. The `AsyncByteSteam` and `SyncByteStream` classes are now pure interface classes. (#133) +- Add `LocalProtocolError`, `RemoteProtocolError` exceptions. (Pull #129) +- Add `UnsupportedProtocol` exception. (Pull #128) +- Add `.get_connection_info()` method. (Pull #102, #137) +- Add better TRACE logs. (Pull #101) + +### Changed + +- `max_keepalive` is deprecated in favour of `max_keepalive_connections`. (Pull #140) + +### Fixed + +- Improve handling of server disconnects. (Pull #112) + +## 0.9.1 (May 27th, 2020) + +### Fixed + +- Proper host resolution for sync case, including IPv6 support. (Pull #97) +- Close outstanding connections when connection pool is closed. (Pull #98) + +## 0.9.0 (May 21th, 2020) + +### Changed + +- URL port becomes an `Optional[int]` instead of `int`. (Pull #92) + +### Fixed + +- Honor HTTP/2 max concurrent streams settings. (Pull #89, #90) +- Remove incorrect debug log. (Pull #83) + +## 0.8.4 (May 11th, 2020) + +### Added + +- Logging via HTTPCORE_LOG_LEVEL and HTTPX_LOG_LEVEL environment variables +and TRACE level logging. (Pull #79) + +### Fixed + +- Reuse of connections on HTTP/2 in close concurrency situations. (Pull #81) + +## 0.8.3 (May 6rd, 2020) + +### Fixed + +- Include `Host` and `Accept` headers on proxy "CONNECT" requests. +- De-duplicate any headers also contained in proxy_headers. +- HTTP/2 flag not being passed down to proxy connections. + +## 0.8.2 (May 3rd, 2020) + +### Fixed + +- Fix connections using proxy forwarding requests not being added to the +connection pool properly. (Pull #70) + +## 0.8.1 (April 30th, 2020) + +### Changed + +- Allow inherintance of both `httpcore.AsyncByteStream`, `httpcore.SyncByteStream` without type conflicts. + +## 0.8.0 (April 30th, 2020) + +### Fixed + +- Fixed tunnel proxy support. + +### Added + +- New `TimeoutException` base class. + +## 0.7.0 (March 5th, 2020) + +- First integration with HTTPX. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore-1.0.9.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore-1.0.9.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..106f7a5d89faa11360b3eb100411cab31ddbf35d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore-1.0.9.dist-info/RECORD @@ -0,0 +1,68 @@ +httpcore-1.0.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httpcore-1.0.9.dist-info/METADATA,sha256=_i1P2mGZEol4d54M8n88BFxTGGP83Zh-rMdPOhjUHCE,21529 +httpcore-1.0.9.dist-info/RECORD,, +httpcore-1.0.9.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +httpcore-1.0.9.dist-info/licenses/LICENSE.md,sha256=_ctZFUx0y6uhahEkL3dAvqnyPW_rVUeRfYxflKgDkqU,1518 +httpcore/__init__.py,sha256=9kT_kqChCCJUTHww24ZmR_ezcdbpRYWksD-gYNzkZP8,3445 +httpcore/__pycache__/__init__.cpython-311.pyc,, +httpcore/__pycache__/_api.cpython-311.pyc,, +httpcore/__pycache__/_exceptions.cpython-311.pyc,, +httpcore/__pycache__/_models.cpython-311.pyc,, +httpcore/__pycache__/_ssl.cpython-311.pyc,, +httpcore/__pycache__/_synchronization.cpython-311.pyc,, +httpcore/__pycache__/_trace.cpython-311.pyc,, +httpcore/__pycache__/_utils.cpython-311.pyc,, +httpcore/_api.py,sha256=unZmeDschBWCGCPCwkS3Wot9euK6bg_kKxLtGTxw214,3146 +httpcore/_async/__init__.py,sha256=EWdl2v4thnAHzJpqjU4h2a8DUiGAvNiWrkii9pfhTf0,1221 +httpcore/_async/__pycache__/__init__.cpython-311.pyc,, +httpcore/_async/__pycache__/connection.cpython-311.pyc,, +httpcore/_async/__pycache__/connection_pool.cpython-311.pyc,, +httpcore/_async/__pycache__/http11.cpython-311.pyc,, +httpcore/_async/__pycache__/http2.cpython-311.pyc,, +httpcore/_async/__pycache__/http_proxy.cpython-311.pyc,, +httpcore/_async/__pycache__/interfaces.cpython-311.pyc,, +httpcore/_async/__pycache__/socks_proxy.cpython-311.pyc,, +httpcore/_async/connection.py,sha256=6OcPXqMEfc0BU38_-iHUNDd1vKSTc2UVT09XqNb_BOk,8449 +httpcore/_async/connection_pool.py,sha256=DOIQ2s2ZCf9qfwxhzMprTPLqCL8OxGXiKF6qRHxvVyY,17307 +httpcore/_async/http11.py,sha256=-qM9bV7PjSQF5vxs37-eUXOIFwbIjPcZbNliuX9TtBw,13880 +httpcore/_async/http2.py,sha256=azX1fcmtXaIwjputFlZ4vd92J8xwjGOa9ax9QIv4394,23936 +httpcore/_async/http_proxy.py,sha256=2zVkrlv-Ds-rWGaqaXlrhEJiAQFPo23BT3Gq_sWoBXU,14701 +httpcore/_async/interfaces.py,sha256=jTiaWL83pgpGC9ziv90ZfwaKNMmHwmOalzaKiuTxATo,4455 +httpcore/_async/socks_proxy.py,sha256=lLKgLlggPfhFlqi0ODeBkOWvt9CghBBUyqsnsU1tx6Q,13841 +httpcore/_backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +httpcore/_backends/__pycache__/__init__.cpython-311.pyc,, +httpcore/_backends/__pycache__/anyio.cpython-311.pyc,, +httpcore/_backends/__pycache__/auto.cpython-311.pyc,, +httpcore/_backends/__pycache__/base.cpython-311.pyc,, +httpcore/_backends/__pycache__/mock.cpython-311.pyc,, +httpcore/_backends/__pycache__/sync.cpython-311.pyc,, +httpcore/_backends/__pycache__/trio.cpython-311.pyc,, +httpcore/_backends/anyio.py,sha256=x8PgEhXRC8bVqsdzk_YJx8Y6d9Tub06CuUSwnbmtqoY,5252 +httpcore/_backends/auto.py,sha256=zO136PKZmsaTDK-HRk84eA-MUg8_2wJf4NvmK432Aio,1662 +httpcore/_backends/base.py,sha256=aShgRdZnMmRhFWHetjumlM73f8Kz1YOAyCUP_4kHslA,3042 +httpcore/_backends/mock.py,sha256=er9T436uSe7NLrfiLa4x6Nuqg5ivQ693CxWYCWsgbH4,4077 +httpcore/_backends/sync.py,sha256=bhE4d9iK9Umxdsdsgm2EfKnXaBms2WggGYU-7jmUujU,7977 +httpcore/_backends/trio.py,sha256=LHu4_Mr5MswQmmT3yE4oLgf9b_JJfeVS4BjDxeJc7Ro,5996 +httpcore/_exceptions.py,sha256=looCKga3_YVYu3s-d3L9RMPRJyhsY7fiuuGxvkOD0c0,1184 +httpcore/_models.py,sha256=IO2CcXcdpovRcLTdGFGB6RyBZdEm2h_TOmoCc4rEKho,17623 +httpcore/_ssl.py,sha256=srqmSNU4iOUvWF-SrJvb8G_YEbHFELOXQOwdDIBTS9c,187 +httpcore/_sync/__init__.py,sha256=JBDIgXt5la1LCJ1sLQeKhjKFpLnpNr8Svs6z2ni3fgg,1141 +httpcore/_sync/__pycache__/__init__.cpython-311.pyc,, +httpcore/_sync/__pycache__/connection.cpython-311.pyc,, +httpcore/_sync/__pycache__/connection_pool.cpython-311.pyc,, +httpcore/_sync/__pycache__/http11.cpython-311.pyc,, +httpcore/_sync/__pycache__/http2.cpython-311.pyc,, +httpcore/_sync/__pycache__/http_proxy.cpython-311.pyc,, +httpcore/_sync/__pycache__/interfaces.cpython-311.pyc,, +httpcore/_sync/__pycache__/socks_proxy.cpython-311.pyc,, +httpcore/_sync/connection.py,sha256=9exGOb3PB-Mp2T1-sckSeL2t-tJ_9-NXomV8ihmWCgU,8238 +httpcore/_sync/connection_pool.py,sha256=a-T8LTsUxc7r0Ww1atfHSDoWPjQ0fA8Ul7S3-F0Mj70,16955 +httpcore/_sync/http11.py,sha256=IFobD1Md5JFlJGKWnh1_Q3epikUryI8qo09v8MiJIEA,13476 +httpcore/_sync/http2.py,sha256=AxU4yhcq68Bn5vqdJYtiXKYUj7nvhYbxz3v4rT4xnvA,23400 +httpcore/_sync/http_proxy.py,sha256=_al_6crKuEZu2wyvu493RZImJdBJnj5oGKNjLOJL2Zo,14463 +httpcore/_sync/interfaces.py,sha256=snXON42vUDHO5JBJvo8D4VWk2Wat44z2OXXHDrjbl94,4344 +httpcore/_sync/socks_proxy.py,sha256=zegZW9Snqj2_992DFJa8_CppOVBkVL4AgwduRkStakQ,13614 +httpcore/_synchronization.py,sha256=zSi13mAColBnknjZBknUC6hKNDQT4C6ijnezZ-r0T2s,9434 +httpcore/_trace.py,sha256=ck6ZoIzYTkdNAIfq5MGeKqBXDtqjOX-qfYwmZFbrGco,3952 +httpcore/_utils.py,sha256=_RLgXYOAYC350ikALV59GZ68IJrdocRZxPs9PjmzdFY,1537 +httpcore/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore-1.0.9.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore-1.0.9.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore-1.0.9.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9a92dc4a440bdf6f259ec1083c89c817eb7b631b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/__init__.py @@ -0,0 +1,141 @@ +from ._api import request, stream +from ._async import ( + AsyncConnectionInterface, + AsyncConnectionPool, + AsyncHTTP2Connection, + AsyncHTTP11Connection, + AsyncHTTPConnection, + AsyncHTTPProxy, + AsyncSOCKSProxy, +) +from ._backends.base import ( + SOCKET_OPTION, + AsyncNetworkBackend, + AsyncNetworkStream, + NetworkBackend, + NetworkStream, +) +from ._backends.mock import AsyncMockBackend, AsyncMockStream, MockBackend, MockStream +from ._backends.sync import SyncBackend +from ._exceptions import ( + ConnectError, + ConnectionNotAvailable, + ConnectTimeout, + LocalProtocolError, + NetworkError, + PoolTimeout, + ProtocolError, + ProxyError, + ReadError, + ReadTimeout, + RemoteProtocolError, + TimeoutException, + UnsupportedProtocol, + WriteError, + WriteTimeout, +) +from ._models import URL, Origin, Proxy, Request, Response +from ._ssl import default_ssl_context +from ._sync import ( + ConnectionInterface, + ConnectionPool, + HTTP2Connection, + HTTP11Connection, + HTTPConnection, + HTTPProxy, + SOCKSProxy, +) + +# The 'httpcore.AnyIOBackend' class is conditional on 'anyio' being installed. +try: + from ._backends.anyio import AnyIOBackend +except ImportError: # pragma: nocover + + class AnyIOBackend: # type: ignore + def __init__(self, *args, **kwargs): # type: ignore + msg = ( + "Attempted to use 'httpcore.AnyIOBackend' but 'anyio' is not installed." + ) + raise RuntimeError(msg) + + +# The 'httpcore.TrioBackend' class is conditional on 'trio' being installed. +try: + from ._backends.trio import TrioBackend +except ImportError: # pragma: nocover + + class TrioBackend: # type: ignore + def __init__(self, *args, **kwargs): # type: ignore + msg = "Attempted to use 'httpcore.TrioBackend' but 'trio' is not installed." + raise RuntimeError(msg) + + +__all__ = [ + # top-level requests + "request", + "stream", + # models + "Origin", + "URL", + "Request", + "Response", + "Proxy", + # async + "AsyncHTTPConnection", + "AsyncConnectionPool", + "AsyncHTTPProxy", + "AsyncHTTP11Connection", + "AsyncHTTP2Connection", + "AsyncConnectionInterface", + "AsyncSOCKSProxy", + # sync + "HTTPConnection", + "ConnectionPool", + "HTTPProxy", + "HTTP11Connection", + "HTTP2Connection", + "ConnectionInterface", + "SOCKSProxy", + # network backends, implementations + "SyncBackend", + "AnyIOBackend", + "TrioBackend", + # network backends, mock implementations + "AsyncMockBackend", + "AsyncMockStream", + "MockBackend", + "MockStream", + # network backends, interface + "AsyncNetworkStream", + "AsyncNetworkBackend", + "NetworkStream", + "NetworkBackend", + # util + "default_ssl_context", + "SOCKET_OPTION", + # exceptions + "ConnectionNotAvailable", + "ProxyError", + "ProtocolError", + "LocalProtocolError", + "RemoteProtocolError", + "UnsupportedProtocol", + "TimeoutException", + "PoolTimeout", + "ConnectTimeout", + "ReadTimeout", + "WriteTimeout", + "NetworkError", + "ConnectError", + "ReadError", + "WriteError", +] + +__version__ = "1.0.9" + + +__locals = locals() +for __name in __all__: + # Exclude SOCKET_OPTION, it causes AttributeError on Python 3.14 + if not __name.startswith(("__", "SOCKET_OPTION")): + setattr(__locals[__name], "__module__", "httpcore") # noqa diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..38b961d10de88bebc98c758d0d1f14af1e7c0370 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_api.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import contextlib +import typing + +from ._models import URL, Extensions, HeaderTypes, Response +from ._sync.connection_pool import ConnectionPool + + +def request( + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes | typing.Iterator[bytes] | None = None, + extensions: Extensions | None = None, +) -> Response: + """ + Sends an HTTP request, returning the response. + + ``` + response = httpcore.request("GET", "https://www.example.com/") + ``` + + Arguments: + method: The HTTP method for the request. Typically one of `"GET"`, + `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. + url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, + or as str/bytes. + headers: The HTTP request headers. Either as a dictionary of str/bytes, + or as a list of two-tuples of str/bytes. + content: The content of the request body. Either as bytes, + or as a bytes iterator. + extensions: A dictionary of optional extra information included on the request. + Possible keys include `"timeout"`. + + Returns: + An instance of `httpcore.Response`. + """ + with ConnectionPool() as pool: + return pool.request( + method=method, + url=url, + headers=headers, + content=content, + extensions=extensions, + ) + + +@contextlib.contextmanager +def stream( + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes | typing.Iterator[bytes] | None = None, + extensions: Extensions | None = None, +) -> typing.Iterator[Response]: + """ + Sends an HTTP request, returning the response within a content manager. + + ``` + with httpcore.stream("GET", "https://www.example.com/") as response: + ... + ``` + + When using the `stream()` function, the body of the response will not be + automatically read. If you want to access the response body you should + either use `content = response.read()`, or `for chunk in response.iter_content()`. + + Arguments: + method: The HTTP method for the request. Typically one of `"GET"`, + `"OPTIONS"`, `"HEAD"`, `"POST"`, `"PUT"`, `"PATCH"`, or `"DELETE"`. + url: The URL of the HTTP request. Either as an instance of `httpcore.URL`, + or as str/bytes. + headers: The HTTP request headers. Either as a dictionary of str/bytes, + or as a list of two-tuples of str/bytes. + content: The content of the request body. Either as bytes, + or as a bytes iterator. + extensions: A dictionary of optional extra information included on the request. + Possible keys include `"timeout"`. + + Returns: + An instance of `httpcore.Response`. + """ + with ConnectionPool() as pool: + with pool.stream( + method=method, + url=url, + headers=headers, + content=content, + extensions=extensions, + ) as response: + yield response diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_exceptions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..bc28d44f55bdc4b872951a74780469a3999d9ab4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_exceptions.py @@ -0,0 +1,81 @@ +import contextlib +import typing + +ExceptionMapping = typing.Mapping[typing.Type[Exception], typing.Type[Exception]] + + +@contextlib.contextmanager +def map_exceptions(map: ExceptionMapping) -> typing.Iterator[None]: + try: + yield + except Exception as exc: # noqa: PIE786 + for from_exc, to_exc in map.items(): + if isinstance(exc, from_exc): + raise to_exc(exc) from exc + raise # pragma: nocover + + +class ConnectionNotAvailable(Exception): + pass + + +class ProxyError(Exception): + pass + + +class UnsupportedProtocol(Exception): + pass + + +class ProtocolError(Exception): + pass + + +class RemoteProtocolError(ProtocolError): + pass + + +class LocalProtocolError(ProtocolError): + pass + + +# Timeout errors + + +class TimeoutException(Exception): + pass + + +class PoolTimeout(TimeoutException): + pass + + +class ConnectTimeout(TimeoutException): + pass + + +class ReadTimeout(TimeoutException): + pass + + +class WriteTimeout(TimeoutException): + pass + + +# Network errors + + +class NetworkError(Exception): + pass + + +class ConnectError(NetworkError): + pass + + +class ReadError(NetworkError): + pass + + +class WriteError(NetworkError): + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_models.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..8a65f13347d6621289a166d08123cbc8e1ad0157 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_models.py @@ -0,0 +1,516 @@ +from __future__ import annotations + +import base64 +import ssl +import typing +import urllib.parse + +# Functions for typechecking... + + +ByteOrStr = typing.Union[bytes, str] +HeadersAsSequence = typing.Sequence[typing.Tuple[ByteOrStr, ByteOrStr]] +HeadersAsMapping = typing.Mapping[ByteOrStr, ByteOrStr] +HeaderTypes = typing.Union[HeadersAsSequence, HeadersAsMapping, None] + +Extensions = typing.MutableMapping[str, typing.Any] + + +def enforce_bytes(value: bytes | str, *, name: str) -> bytes: + """ + Any arguments that are ultimately represented as bytes can be specified + either as bytes or as strings. + + However we enforce that any string arguments must only contain characters in + the plain ASCII range. chr(0)...chr(127). If you need to use characters + outside that range then be precise, and use a byte-wise argument. + """ + if isinstance(value, str): + try: + return value.encode("ascii") + except UnicodeEncodeError: + raise TypeError(f"{name} strings may not include unicode characters.") + elif isinstance(value, bytes): + return value + + seen_type = type(value).__name__ + raise TypeError(f"{name} must be bytes or str, but got {seen_type}.") + + +def enforce_url(value: URL | bytes | str, *, name: str) -> URL: + """ + Type check for URL parameters. + """ + if isinstance(value, (bytes, str)): + return URL(value) + elif isinstance(value, URL): + return value + + seen_type = type(value).__name__ + raise TypeError(f"{name} must be a URL, bytes, or str, but got {seen_type}.") + + +def enforce_headers( + value: HeadersAsMapping | HeadersAsSequence | None = None, *, name: str +) -> list[tuple[bytes, bytes]]: + """ + Convienence function that ensure all items in request or response headers + are either bytes or strings in the plain ASCII range. + """ + if value is None: + return [] + elif isinstance(value, typing.Mapping): + return [ + ( + enforce_bytes(k, name="header name"), + enforce_bytes(v, name="header value"), + ) + for k, v in value.items() + ] + elif isinstance(value, typing.Sequence): + return [ + ( + enforce_bytes(k, name="header name"), + enforce_bytes(v, name="header value"), + ) + for k, v in value + ] + + seen_type = type(value).__name__ + raise TypeError( + f"{name} must be a mapping or sequence of two-tuples, but got {seen_type}." + ) + + +def enforce_stream( + value: bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes] | None, + *, + name: str, +) -> typing.Iterable[bytes] | typing.AsyncIterable[bytes]: + if value is None: + return ByteStream(b"") + elif isinstance(value, bytes): + return ByteStream(value) + return value + + +# * https://tools.ietf.org/html/rfc3986#section-3.2.3 +# * https://url.spec.whatwg.org/#url-miscellaneous +# * https://url.spec.whatwg.org/#scheme-state +DEFAULT_PORTS = { + b"ftp": 21, + b"http": 80, + b"https": 443, + b"ws": 80, + b"wss": 443, +} + + +def include_request_headers( + headers: list[tuple[bytes, bytes]], + *, + url: "URL", + content: None | bytes | typing.Iterable[bytes] | typing.AsyncIterable[bytes], +) -> list[tuple[bytes, bytes]]: + headers_set = set(k.lower() for k, v in headers) + + if b"host" not in headers_set: + default_port = DEFAULT_PORTS.get(url.scheme) + if url.port is None or url.port == default_port: + header_value = url.host + else: + header_value = b"%b:%d" % (url.host, url.port) + headers = [(b"Host", header_value)] + headers + + if ( + content is not None + and b"content-length" not in headers_set + and b"transfer-encoding" not in headers_set + ): + if isinstance(content, bytes): + content_length = str(len(content)).encode("ascii") + headers += [(b"Content-Length", content_length)] + else: + headers += [(b"Transfer-Encoding", b"chunked")] # pragma: nocover + + return headers + + +# Interfaces for byte streams... + + +class ByteStream: + """ + A container for non-streaming content, and that supports both sync and async + stream iteration. + """ + + def __init__(self, content: bytes) -> None: + self._content = content + + def __iter__(self) -> typing.Iterator[bytes]: + yield self._content + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + yield self._content + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{len(self._content)} bytes]>" + + +class Origin: + def __init__(self, scheme: bytes, host: bytes, port: int) -> None: + self.scheme = scheme + self.host = host + self.port = port + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, Origin) + and self.scheme == other.scheme + and self.host == other.host + and self.port == other.port + ) + + def __str__(self) -> str: + scheme = self.scheme.decode("ascii") + host = self.host.decode("ascii") + port = str(self.port) + return f"{scheme}://{host}:{port}" + + +class URL: + """ + Represents the URL against which an HTTP request may be made. + + The URL may either be specified as a plain string, for convienence: + + ```python + url = httpcore.URL("https://www.example.com/") + ``` + + Or be constructed with explicitily pre-parsed components: + + ```python + url = httpcore.URL(scheme=b'https', host=b'www.example.com', port=None, target=b'/') + ``` + + Using this second more explicit style allows integrations that are using + `httpcore` to pass through URLs that have already been parsed in order to use + libraries such as `rfc-3986` rather than relying on the stdlib. It also ensures + that URL parsing is treated identically at both the networking level and at any + higher layers of abstraction. + + The four components are important here, as they allow the URL to be precisely + specified in a pre-parsed format. They also allow certain types of request to + be created that could not otherwise be expressed. + + For example, an HTTP request to `http://www.example.com/` forwarded via a proxy + at `http://localhost:8080`... + + ```python + # Constructs an HTTP request with a complete URL as the target: + # GET https://www.example.com/ HTTP/1.1 + url = httpcore.URL( + scheme=b'http', + host=b'localhost', + port=8080, + target=b'https://www.example.com/' + ) + request = httpcore.Request( + method="GET", + url=url + ) + ``` + + Another example is constructing an `OPTIONS *` request... + + ```python + # Constructs an 'OPTIONS *' HTTP request: + # OPTIONS * HTTP/1.1 + url = httpcore.URL(scheme=b'https', host=b'www.example.com', target=b'*') + request = httpcore.Request(method="OPTIONS", url=url) + ``` + + This kind of request is not possible to formulate with a URL string, + because the `/` delimiter is always used to demark the target from the + host/port portion of the URL. + + For convenience, string-like arguments may be specified either as strings or + as bytes. However, once a request is being issue over-the-wire, the URL + components are always ultimately required to be a bytewise representation. + + In order to avoid any ambiguity over character encodings, when strings are used + as arguments, they must be strictly limited to the ASCII range `chr(0)`-`chr(127)`. + If you require a bytewise representation that is outside this range you must + handle the character encoding directly, and pass a bytes instance. + """ + + def __init__( + self, + url: bytes | str = "", + *, + scheme: bytes | str = b"", + host: bytes | str = b"", + port: int | None = None, + target: bytes | str = b"", + ) -> None: + """ + Parameters: + url: The complete URL as a string or bytes. + scheme: The URL scheme as a string or bytes. + Typically either `"http"` or `"https"`. + host: The URL host as a string or bytes. Such as `"www.example.com"`. + port: The port to connect to. Either an integer or `None`. + target: The target of the HTTP request. Such as `"/items?search=red"`. + """ + if url: + parsed = urllib.parse.urlparse(enforce_bytes(url, name="url")) + self.scheme = parsed.scheme + self.host = parsed.hostname or b"" + self.port = parsed.port + self.target = (parsed.path or b"/") + ( + b"?" + parsed.query if parsed.query else b"" + ) + else: + self.scheme = enforce_bytes(scheme, name="scheme") + self.host = enforce_bytes(host, name="host") + self.port = port + self.target = enforce_bytes(target, name="target") + + @property + def origin(self) -> Origin: + default_port = { + b"http": 80, + b"https": 443, + b"ws": 80, + b"wss": 443, + b"socks5": 1080, + b"socks5h": 1080, + }[self.scheme] + return Origin( + scheme=self.scheme, host=self.host, port=self.port or default_port + ) + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, URL) + and other.scheme == self.scheme + and other.host == self.host + and other.port == self.port + and other.target == self.target + ) + + def __bytes__(self) -> bytes: + if self.port is None: + return b"%b://%b%b" % (self.scheme, self.host, self.target) + return b"%b://%b:%d%b" % (self.scheme, self.host, self.port, self.target) + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(scheme={self.scheme!r}, " + f"host={self.host!r}, port={self.port!r}, target={self.target!r})" + ) + + +class Request: + """ + An HTTP request. + """ + + def __init__( + self, + method: bytes | str, + url: URL | bytes | str, + *, + headers: HeaderTypes = None, + content: bytes + | typing.Iterable[bytes] + | typing.AsyncIterable[bytes] + | None = None, + extensions: Extensions | None = None, + ) -> None: + """ + Parameters: + method: The HTTP request method, either as a string or bytes. + For example: `GET`. + url: The request URL, either as a `URL` instance, or as a string or bytes. + For example: `"https://www.example.com".` + headers: The HTTP request headers. + content: The content of the request body. + extensions: A dictionary of optional extra information included on + the request. Possible keys include `"timeout"`, and `"trace"`. + """ + self.method: bytes = enforce_bytes(method, name="method") + self.url: URL = enforce_url(url, name="url") + self.headers: list[tuple[bytes, bytes]] = enforce_headers( + headers, name="headers" + ) + self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = ( + enforce_stream(content, name="content") + ) + self.extensions = {} if extensions is None else extensions + + if "target" in self.extensions: + self.url = URL( + scheme=self.url.scheme, + host=self.url.host, + port=self.url.port, + target=self.extensions["target"], + ) + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.method!r}]>" + + +class Response: + """ + An HTTP response. + """ + + def __init__( + self, + status: int, + *, + headers: HeaderTypes = None, + content: bytes + | typing.Iterable[bytes] + | typing.AsyncIterable[bytes] + | None = None, + extensions: Extensions | None = None, + ) -> None: + """ + Parameters: + status: The HTTP status code of the response. For example `200`. + headers: The HTTP response headers. + content: The content of the response body. + extensions: A dictionary of optional extra information included on + the responseself.Possible keys include `"http_version"`, + `"reason_phrase"`, and `"network_stream"`. + """ + self.status: int = status + self.headers: list[tuple[bytes, bytes]] = enforce_headers( + headers, name="headers" + ) + self.stream: typing.Iterable[bytes] | typing.AsyncIterable[bytes] = ( + enforce_stream(content, name="content") + ) + self.extensions = {} if extensions is None else extensions + + self._stream_consumed = False + + @property + def content(self) -> bytes: + if not hasattr(self, "_content"): + if isinstance(self.stream, typing.Iterable): + raise RuntimeError( + "Attempted to access 'response.content' on a streaming response. " + "Call 'response.read()' first." + ) + else: + raise RuntimeError( + "Attempted to access 'response.content' on a streaming response. " + "Call 'await response.aread()' first." + ) + return self._content + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} [{self.status}]>" + + # Sync interface... + + def read(self) -> bytes: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover + raise RuntimeError( + "Attempted to read an asynchronous response using 'response.read()'. " + "You should use 'await response.aread()' instead." + ) + if not hasattr(self, "_content"): + self._content = b"".join([part for part in self.iter_stream()]) + return self._content + + def iter_stream(self) -> typing.Iterator[bytes]: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover + raise RuntimeError( + "Attempted to stream an asynchronous response using 'for ... in " + "response.iter_stream()'. " + "You should use 'async for ... in response.aiter_stream()' instead." + ) + if self._stream_consumed: + raise RuntimeError( + "Attempted to call 'for ... in response.iter_stream()' more than once." + ) + self._stream_consumed = True + for chunk in self.stream: + yield chunk + + def close(self) -> None: + if not isinstance(self.stream, typing.Iterable): # pragma: nocover + raise RuntimeError( + "Attempted to close an asynchronous response using 'response.close()'. " + "You should use 'await response.aclose()' instead." + ) + if hasattr(self.stream, "close"): + self.stream.close() + + # Async interface... + + async def aread(self) -> bytes: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover + raise RuntimeError( + "Attempted to read an synchronous response using " + "'await response.aread()'. " + "You should use 'response.read()' instead." + ) + if not hasattr(self, "_content"): + self._content = b"".join([part async for part in self.aiter_stream()]) + return self._content + + async def aiter_stream(self) -> typing.AsyncIterator[bytes]: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover + raise RuntimeError( + "Attempted to stream an synchronous response using 'async for ... in " + "response.aiter_stream()'. " + "You should use 'for ... in response.iter_stream()' instead." + ) + if self._stream_consumed: + raise RuntimeError( + "Attempted to call 'async for ... in response.aiter_stream()' " + "more than once." + ) + self._stream_consumed = True + async for chunk in self.stream: + yield chunk + + async def aclose(self) -> None: + if not isinstance(self.stream, typing.AsyncIterable): # pragma: nocover + raise RuntimeError( + "Attempted to close a synchronous response using " + "'await response.aclose()'. " + "You should use 'response.close()' instead." + ) + if hasattr(self.stream, "aclose"): + await self.stream.aclose() + + +class Proxy: + def __init__( + self, + url: URL | bytes | str, + auth: tuple[bytes | str, bytes | str] | None = None, + headers: HeadersAsMapping | HeadersAsSequence | None = None, + ssl_context: ssl.SSLContext | None = None, + ): + self.url = enforce_url(url, name="url") + self.headers = enforce_headers(headers, name="headers") + self.ssl_context = ssl_context + + if auth is not None: + username = enforce_bytes(auth[0], name="auth") + password = enforce_bytes(auth[1], name="auth") + userpass = username + b":" + password + authorization = b"Basic " + base64.b64encode(userpass) + self.auth: tuple[bytes, bytes] | None = (username, password) + self.headers = [(b"Proxy-Authorization", authorization)] + self.headers + else: + self.auth = None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_ssl.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_ssl.py new file mode 100644 index 0000000000000000000000000000000000000000..c99c5a67945b8a3a3544d481e979c791ab45fe23 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_ssl.py @@ -0,0 +1,9 @@ +import ssl + +import certifi + + +def default_ssl_context() -> ssl.SSLContext: + context = ssl.create_default_context() + context.load_verify_locations(certifi.where()) + return context diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_synchronization.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_synchronization.py new file mode 100644 index 0000000000000000000000000000000000000000..2ecc9e9c363e2f16c4f934cf41cf871826d6a495 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_synchronization.py @@ -0,0 +1,318 @@ +from __future__ import annotations + +import threading +import types + +from ._exceptions import ExceptionMapping, PoolTimeout, map_exceptions + +# Our async synchronization primatives use either 'anyio' or 'trio' depending +# on if they're running under asyncio or trio. + +try: + import trio +except (ImportError, NotImplementedError): # pragma: nocover + trio = None # type: ignore + +try: + import anyio +except ImportError: # pragma: nocover + anyio = None # type: ignore + + +def current_async_library() -> str: + # Determine if we're running under trio or asyncio. + # See https://sniffio.readthedocs.io/en/latest/ + try: + import sniffio + except ImportError: # pragma: nocover + environment = "asyncio" + else: + environment = sniffio.current_async_library() + + if environment not in ("asyncio", "trio"): # pragma: nocover + raise RuntimeError("Running under an unsupported async environment.") + + if environment == "asyncio" and anyio is None: # pragma: nocover + raise RuntimeError( + "Running with asyncio requires installation of 'httpcore[asyncio]'." + ) + + if environment == "trio" and trio is None: # pragma: nocover + raise RuntimeError( + "Running with trio requires installation of 'httpcore[trio]'." + ) + + return environment + + +class AsyncLock: + """ + This is a standard lock. + + In the sync case `Lock` provides thread locking. + In the async case `AsyncLock` provides async locking. + """ + + def __init__(self) -> None: + self._backend = "" + + def setup(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a lock with the correct implementation. + """ + self._backend = current_async_library() + if self._backend == "trio": + self._trio_lock = trio.Lock() + elif self._backend == "asyncio": + self._anyio_lock = anyio.Lock() + + async def __aenter__(self) -> AsyncLock: + if not self._backend: + self.setup() + + if self._backend == "trio": + await self._trio_lock.acquire() + elif self._backend == "asyncio": + await self._anyio_lock.acquire() + + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self._backend == "trio": + self._trio_lock.release() + elif self._backend == "asyncio": + self._anyio_lock.release() + + +class AsyncThreadLock: + """ + This is a threading-only lock for no-I/O contexts. + + In the sync case `ThreadLock` provides thread locking. + In the async case `AsyncThreadLock` is a no-op. + """ + + def __enter__(self) -> AsyncThreadLock: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + pass + + +class AsyncEvent: + def __init__(self) -> None: + self._backend = "" + + def setup(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a lock with the correct implementation. + """ + self._backend = current_async_library() + if self._backend == "trio": + self._trio_event = trio.Event() + elif self._backend == "asyncio": + self._anyio_event = anyio.Event() + + def set(self) -> None: + if not self._backend: + self.setup() + + if self._backend == "trio": + self._trio_event.set() + elif self._backend == "asyncio": + self._anyio_event.set() + + async def wait(self, timeout: float | None = None) -> None: + if not self._backend: + self.setup() + + if self._backend == "trio": + trio_exc_map: ExceptionMapping = {trio.TooSlowError: PoolTimeout} + timeout_or_inf = float("inf") if timeout is None else timeout + with map_exceptions(trio_exc_map): + with trio.fail_after(timeout_or_inf): + await self._trio_event.wait() + elif self._backend == "asyncio": + anyio_exc_map: ExceptionMapping = {TimeoutError: PoolTimeout} + with map_exceptions(anyio_exc_map): + with anyio.fail_after(timeout): + await self._anyio_event.wait() + + +class AsyncSemaphore: + def __init__(self, bound: int) -> None: + self._bound = bound + self._backend = "" + + def setup(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a semaphore with the correct implementation. + """ + self._backend = current_async_library() + if self._backend == "trio": + self._trio_semaphore = trio.Semaphore( + initial_value=self._bound, max_value=self._bound + ) + elif self._backend == "asyncio": + self._anyio_semaphore = anyio.Semaphore( + initial_value=self._bound, max_value=self._bound + ) + + async def acquire(self) -> None: + if not self._backend: + self.setup() + + if self._backend == "trio": + await self._trio_semaphore.acquire() + elif self._backend == "asyncio": + await self._anyio_semaphore.acquire() + + async def release(self) -> None: + if self._backend == "trio": + self._trio_semaphore.release() + elif self._backend == "asyncio": + self._anyio_semaphore.release() + + +class AsyncShieldCancellation: + # For certain portions of our codebase where we're dealing with + # closing connections during exception handling we want to shield + # the operation from being cancelled. + # + # with AsyncShieldCancellation(): + # ... # clean-up operations, shielded from cancellation. + + def __init__(self) -> None: + """ + Detect if we're running under 'asyncio' or 'trio' and create + a shielded scope with the correct implementation. + """ + self._backend = current_async_library() + + if self._backend == "trio": + self._trio_shield = trio.CancelScope(shield=True) + elif self._backend == "asyncio": + self._anyio_shield = anyio.CancelScope(shield=True) + + def __enter__(self) -> AsyncShieldCancellation: + if self._backend == "trio": + self._trio_shield.__enter__() + elif self._backend == "asyncio": + self._anyio_shield.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self._backend == "trio": + self._trio_shield.__exit__(exc_type, exc_value, traceback) + elif self._backend == "asyncio": + self._anyio_shield.__exit__(exc_type, exc_value, traceback) + + +# Our thread-based synchronization primitives... + + +class Lock: + """ + This is a standard lock. + + In the sync case `Lock` provides thread locking. + In the async case `AsyncLock` provides async locking. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + + def __enter__(self) -> Lock: + self._lock.acquire() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + self._lock.release() + + +class ThreadLock: + """ + This is a threading-only lock for no-I/O contexts. + + In the sync case `ThreadLock` provides thread locking. + In the async case `AsyncThreadLock` is a no-op. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + + def __enter__(self) -> ThreadLock: + self._lock.acquire() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + self._lock.release() + + +class Event: + def __init__(self) -> None: + self._event = threading.Event() + + def set(self) -> None: + self._event.set() + + def wait(self, timeout: float | None = None) -> None: + if timeout == float("inf"): # pragma: no cover + timeout = None + if not self._event.wait(timeout=timeout): + raise PoolTimeout() # pragma: nocover + + +class Semaphore: + def __init__(self, bound: int) -> None: + self._semaphore = threading.Semaphore(value=bound) + + def acquire(self) -> None: + self._semaphore.acquire() + + def release(self) -> None: + self._semaphore.release() + + +class ShieldCancellation: + # Thread-synchronous codebases don't support cancellation semantics. + # We have this class because we need to mirror the async and sync + # cases within our package, but it's just a no-op. + def __enter__(self) -> ShieldCancellation: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_trace.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_trace.py new file mode 100644 index 0000000000000000000000000000000000000000..5f1cd7c47829ce17dbcf651ab56b4ffdce04a485 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_trace.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import inspect +import logging +import types +import typing + +from ._models import Request + + +class Trace: + def __init__( + self, + name: str, + logger: logging.Logger, + request: Request | None = None, + kwargs: dict[str, typing.Any] | None = None, + ) -> None: + self.name = name + self.logger = logger + self.trace_extension = ( + None if request is None else request.extensions.get("trace") + ) + self.debug = self.logger.isEnabledFor(logging.DEBUG) + self.kwargs = kwargs or {} + self.return_value: typing.Any = None + self.should_trace = self.debug or self.trace_extension is not None + self.prefix = self.logger.name.split(".")[-1] + + def trace(self, name: str, info: dict[str, typing.Any]) -> None: + if self.trace_extension is not None: + prefix_and_name = f"{self.prefix}.{name}" + ret = self.trace_extension(prefix_and_name, info) + if inspect.iscoroutine(ret): # pragma: no cover + raise TypeError( + "If you are using a synchronous interface, " + "the callback of the `trace` extension should " + "be a normal function instead of an asynchronous function." + ) + + if self.debug: + if not info or "return_value" in info and info["return_value"] is None: + message = name + else: + args = " ".join([f"{key}={value!r}" for key, value in info.items()]) + message = f"{name} {args}" + self.logger.debug(message) + + def __enter__(self) -> Trace: + if self.should_trace: + info = self.kwargs + self.trace(f"{self.name}.started", info) + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self.should_trace: + if exc_value is None: + info = {"return_value": self.return_value} + self.trace(f"{self.name}.complete", info) + else: + info = {"exception": exc_value} + self.trace(f"{self.name}.failed", info) + + async def atrace(self, name: str, info: dict[str, typing.Any]) -> None: + if self.trace_extension is not None: + prefix_and_name = f"{self.prefix}.{name}" + coro = self.trace_extension(prefix_and_name, info) + if not inspect.iscoroutine(coro): # pragma: no cover + raise TypeError( + "If you're using an asynchronous interface, " + "the callback of the `trace` extension should " + "be an asynchronous function rather than a normal function." + ) + await coro + + if self.debug: + if not info or "return_value" in info and info["return_value"] is None: + message = name + else: + args = " ".join([f"{key}={value!r}" for key, value in info.items()]) + message = f"{name} {args}" + self.logger.debug(message) + + async def __aenter__(self) -> Trace: + if self.should_trace: + info = self.kwargs + await self.atrace(f"{self.name}.started", info) + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: types.TracebackType | None = None, + ) -> None: + if self.should_trace: + if exc_value is None: + info = {"return_value": self.return_value} + await self.atrace(f"{self.name}.complete", info) + else: + info = {"exception": exc_value} + await self.atrace(f"{self.name}.failed", info) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c44ff93cb2f572afc6e679308024b744b65c3b0a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/_utils.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +import select +import socket +import sys + + +def is_socket_readable(sock: socket.socket | None) -> bool: + """ + Return whether a socket, as identifed by its file descriptor, is readable. + "A socket is readable" means that the read buffer isn't empty, i.e. that calling + .recv() on it would immediately return some data. + """ + # NOTE: we want check for readability without actually attempting to read, because + # we don't want to block forever if it's not readable. + + # In the case that the socket no longer exists, or cannot return a file + # descriptor, we treat it as being readable, as if it the next read operation + # on it is ready to return the terminating `b""`. + sock_fd = None if sock is None else sock.fileno() + if sock_fd is None or sock_fd < 0: # pragma: nocover + return True + + # The implementation below was stolen from: + # https://github.com/python-trio/trio/blob/20ee2b1b7376db637435d80e266212a35837ddcc/trio/_socket.py#L471-L478 + # See also: https://github.com/encode/httpcore/pull/193#issuecomment-703129316 + + # Use select.select on Windows, and when poll is unavailable and select.poll + # everywhere else. (E.g. When eventlet is in use. See #327) + if ( + sys.platform == "win32" or getattr(select, "poll", None) is None + ): # pragma: nocover + rready, _, _ = select.select([sock_fd], [], [], 0) + return bool(rready) + p = select.poll() + p.register(sock_fd, select.POLLIN) + return bool(p.poll(0)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpcore/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..99c39a349115d3d40cd99b0b78f54fb664ffdbe2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/METADATA @@ -0,0 +1,130 @@ +Metadata-Version: 2.4 +Name: httptools +Version: 0.7.1 +Summary: A collection of framework independent HTTP protocol utils. +Author-email: Yury Selivanov +License-Expression: MIT +Project-URL: Homepage, https://github.com/MagicStack/httptools +Platform: macOS +Platform: POSIX +Platform: Windows +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Operating System :: POSIX +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Environment :: Web Environment +Classifier: Development Status :: 5 - Production/Stable +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: test +Dynamic: license-file +Dynamic: platform + +![Tests](https://github.com/MagicStack/httptools/workflows/Tests/badge.svg) + +httptools is a Python binding for the nodejs HTTP parser. + +The package is available on PyPI: `pip install httptools`. + + +# APIs + +httptools contains two classes `httptools.HttpRequestParser`, +`httptools.HttpResponseParser` (fulfilled through +[llhttp](https://github.com/nodejs/llhttp)) and a function for +parsing URLs `httptools.parse_url` (through +[http-parse](https://github.com/nodejs/http-parser) for now). +See unittests for examples. + + +```python + +class HttpRequestParser: + + def __init__(self, protocol): + """HttpRequestParser + + protocol -- a Python object with the following methods + (all optional): + + - on_message_begin() + - on_url(url: bytes) + - on_header(name: bytes, value: bytes) + - on_headers_complete() + - on_body(body: bytes) + - on_message_complete() + - on_chunk_header() + - on_chunk_complete() + - on_status(status: bytes) + """ + + def get_http_version(self) -> str: + """Return an HTTP protocol version.""" + + def should_keep_alive(self) -> bool: + """Return ``True`` if keep-alive mode is preferred.""" + + def should_upgrade(self) -> bool: + """Return ``True`` if the parsed request is a valid Upgrade request. + The method exposes a flag set just before on_headers_complete. + Calling this method earlier will only yield `False`. + """ + + def feed_data(self, data: bytes): + """Feed data to the parser. + + Will eventually trigger callbacks on the ``protocol`` + object. + + On HTTP upgrade, this method will raise an + ``HttpParserUpgrade`` exception, with its sole argument + set to the offset of the non-HTTP data in ``data``. + """ + + def get_method(self) -> bytes: + """Return HTTP request method (GET, HEAD, etc)""" + + +class HttpResponseParser: + + """Has all methods except ``get_method()`` that + HttpRequestParser has.""" + + def get_status_code(self) -> int: + """Return the status code of the HTTP response""" + + +def parse_url(url: bytes): + """Parse URL strings into a structured Python object. + + Returns an instance of ``httptools.URL`` class with the + following attributes: + + - schema: bytes + - host: bytes + - port: int + - path: bytes + - query: bytes + - fragment: bytes + - userinfo: bytes + """ +``` + + +# Development + +1. Clone this repository with + `git clone --recursive git@github.com:MagicStack/httptools.git` + +2. Create a virtual environment with Python 3: + `python3 -m venv envname` + +3. Activate the environment with `source envname/bin/activate` + +4. Run `make` and `make test`. + + +# License + +MIT. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..178989fc6eedbb5d6f06a0852b8504d67647141d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/RECORD @@ -0,0 +1,25 @@ +httptools-0.7.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httptools-0.7.1.dist-info/METADATA,sha256=SDOnsarDrAxgLgiOHmAxC9OnA4Ca9XEeI6DB1McUYKU,3602 +httptools-0.7.1.dist-info/RECORD,, +httptools-0.7.1.dist-info/WHEEL,sha256=JLOMsP7F5qtkAkINx5UnzbFguf8CqZeraV8o04b0I8I,101 +httptools-0.7.1.dist-info/licenses/LICENSE,sha256=HAKLBZ16WOFMzaOMq87WmMWR_mFP--T3IUMERuhsjWk,1114 +httptools-0.7.1.dist-info/top_level.txt,sha256=APjJKTbZcj0OQ4fdgf2eTCk82nK1n2BFXOD7ky41MPY,10 +httptools/__init__.py,sha256=uWLIa0nghlhLGoS8My_6YVhUlFbv3FhYsvxYpZHecS8,153 +httptools/__pycache__/__init__.cpython-311.pyc,, +httptools/__pycache__/_version.cpython-311.pyc,, +httptools/_version.py,sha256=L1qOIEGz2abHAuE9FSwFU6Q3tDr3nhuABOTtgE9ISv0,588 +httptools/parser/__init__.py,sha256=mXOisHGQtSCaaFE1RNgTtEhEnqhMqi9jFWaAGSIUktY,207 +httptools/parser/__pycache__/__init__.cpython-311.pyc,, +httptools/parser/__pycache__/errors.cpython-311.pyc,, +httptools/parser/__pycache__/protocol.cpython-311.pyc,, +httptools/parser/cparser.pxd,sha256=XOczyt3PFtYc1r-GVKecEkN5zvBD78NXfd2JhyKOKBg,5144 +httptools/parser/errors.py,sha256=fQeEGiZ6AQH7SIa-7uzMs5QggoXr0A8YBPVHmafSw5Q,596 +httptools/parser/parser.cp311-win_amd64.pyd,sha256=os7oiaUzd7meuH0nmw-R0wao-ww2iOz1-MJKxxRLId8,123392 +httptools/parser/parser.pyi,sha256=ipY5DWsoBI-XSUw_GONH2l1WkG97vQlB6aSnE4ilmcI,1918 +httptools/parser/parser.pyx,sha256=jgDH58PbHrXpT4wGDptP02tGsceOo9qHYSJBdpK5ZEs,15576 +httptools/parser/protocol.py,sha256=tGhmbKw2mlmwWmfo400sugh9F6ghjBSG4R84OJEpR-4,557 +httptools/parser/python.pxd,sha256=-pIXNLe1u3u3X51ORUUoHRBMsntzRlQa3z2iBqljTHU,144 +httptools/parser/url_cparser.pxd,sha256=rvPJV7S96tTqKMT0Bk4jHgMy2U0rNY5_NsPa7KG5lio,810 +httptools/parser/url_parser.cp311-win_amd64.pyd,sha256=xeTF3iqNMSZucJgnUpuE_t3ALKjjlS0dmdak5tZYfgo,50688 +httptools/parser/url_parser.pyi,sha256=YFt6ooO5GGv_IG7-Mq1vZHi3jBIMWAquUv87TPyMTBU,592 +httptools/parser/url_parser.pyx,sha256=_ZmJwXC2kh6Rh6FLQTy3nGBiZBBPAX9O-pWtGlgS-44,3866 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8f98e0aeebdc2c0a3b9b5f83d43db0ef8dbc186b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp311-cp311-win_amd64 + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..bef3b40b2f33a46ae13d46456df480f77ab712e3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools-0.7.1.dist-info/top_level.txt @@ -0,0 +1 @@ +httptools diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aaa1902aaeb55fc4b6d86e8e3616c4d4961b8874 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools/__init__.py @@ -0,0 +1,6 @@ +from . import parser +from .parser import * # NOQA + +from ._version import __version__ # NOQA + +__all__ = parser.__all__ + ('__version__',) # NOQA diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools/_version.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab8e27aea11ea96d1be9ca45749334fb4259f45 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httptools/_version.py @@ -0,0 +1,13 @@ +# This file MUST NOT contain anything but the __version__ assignment. +# +# When making a release, change the value of __version__ +# to an appropriate value, and open a pull request against +# the correct branch (master if making a new feature release). +# The commit message MUST contain a properly formatted release +# log, and the commit must be signed. +# +# The release automation will: build and test the packages for the +# supported platforms, publish the packages on PyPI, merge the PR +# to the target branch, create a Git tag pointing to the commit. + +__version__ = '0.7.1' diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b0d2b196385e98259971519793447c1fd7a9a643 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/METADATA @@ -0,0 +1,203 @@ +Metadata-Version: 2.3 +Name: httpx +Version: 0.28.1 +Summary: The next generation HTTP client. +Project-URL: Changelog, https://github.com/encode/httpx/blob/master/CHANGELOG.md +Project-URL: Documentation, https://www.python-httpx.org +Project-URL: Homepage, https://github.com/encode/httpx +Project-URL: Source, https://github.com/encode/httpx +Author-email: Tom Christie +License: BSD-3-Clause +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Web Environment +Classifier: Framework :: AsyncIO +Classifier: Framework :: Trio +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.8 +Requires-Dist: anyio +Requires-Dist: certifi +Requires-Dist: httpcore==1.* +Requires-Dist: idna +Provides-Extra: brotli +Requires-Dist: brotli; (platform_python_implementation == 'CPython') and extra == 'brotli' +Requires-Dist: brotlicffi; (platform_python_implementation != 'CPython') and extra == 'brotli' +Provides-Extra: cli +Requires-Dist: click==8.*; extra == 'cli' +Requires-Dist: pygments==2.*; extra == 'cli' +Requires-Dist: rich<14,>=10; extra == 'cli' +Provides-Extra: http2 +Requires-Dist: h2<5,>=3; extra == 'http2' +Provides-Extra: socks +Requires-Dist: socksio==1.*; extra == 'socks' +Provides-Extra: zstd +Requires-Dist: zstandard>=0.18.0; extra == 'zstd' +Description-Content-Type: text/markdown + +

+ HTTPX +

+ +

HTTPX - A next-generation HTTP client for Python.

+ +

+ + Test Suite + + + Package version + +

+ +HTTPX is a fully featured HTTP client library for Python 3. It includes **an integrated command line client**, has support for both **HTTP/1.1 and HTTP/2**, and provides both **sync and async APIs**. + +--- + +Install HTTPX using pip: + +```shell +$ pip install httpx +``` + +Now, let's get started: + +```pycon +>>> import httpx +>>> r = httpx.get('https://www.example.org/') +>>> r + +>>> r.status_code +200 +>>> r.headers['content-type'] +'text/html; charset=UTF-8' +>>> r.text +'\n\n\nExample Domain...' +``` + +Or, using the command-line client. + +```shell +$ pip install 'httpx[cli]' # The command line client is an optional dependency. +``` + +Which now allows us to use HTTPX directly from the command-line... + +

+ httpx --help +

+ +Sending a request... + +

+ httpx http://httpbin.org/json +

+ +## Features + +HTTPX builds on the well-established usability of `requests`, and gives you: + +* A broadly [requests-compatible API](https://www.python-httpx.org/compatibility/). +* An integrated command-line client. +* HTTP/1.1 [and HTTP/2 support](https://www.python-httpx.org/http2/). +* Standard synchronous interface, but with [async support if you need it](https://www.python-httpx.org/async/). +* Ability to make requests directly to [WSGI applications](https://www.python-httpx.org/advanced/transports/#wsgi-transport) or [ASGI applications](https://www.python-httpx.org/advanced/transports/#asgi-transport). +* Strict timeouts everywhere. +* Fully type annotated. +* 100% test coverage. + +Plus all the standard features of `requests`... + +* International Domains and URLs +* Keep-Alive & Connection Pooling +* Sessions with Cookie Persistence +* Browser-style SSL Verification +* Basic/Digest Authentication +* Elegant Key/Value Cookies +* Automatic Decompression +* Automatic Content Decoding +* Unicode Response Bodies +* Multipart File Uploads +* HTTP(S) Proxy Support +* Connection Timeouts +* Streaming Downloads +* .netrc Support +* Chunked Requests + +## Installation + +Install with pip: + +```shell +$ pip install httpx +``` + +Or, to include the optional HTTP/2 support, use: + +```shell +$ pip install httpx[http2] +``` + +HTTPX requires Python 3.8+. + +## Documentation + +Project documentation is available at [https://www.python-httpx.org/](https://www.python-httpx.org/). + +For a run-through of all the basics, head over to the [QuickStart](https://www.python-httpx.org/quickstart/). + +For more advanced topics, see the [Advanced Usage](https://www.python-httpx.org/advanced/) section, the [async support](https://www.python-httpx.org/async/) section, or the [HTTP/2](https://www.python-httpx.org/http2/) section. + +The [Developer Interface](https://www.python-httpx.org/api/) provides a comprehensive API reference. + +To find out about tools that integrate with HTTPX, see [Third Party Packages](https://www.python-httpx.org/third_party_packages/). + +## Contribute + +If you want to contribute with HTTPX check out the [Contributing Guide](https://www.python-httpx.org/contributing/) to learn how to start. + +## Dependencies + +The HTTPX project relies on these excellent libraries: + +* `httpcore` - The underlying transport implementation for `httpx`. + * `h11` - HTTP/1.1 support. +* `certifi` - SSL certificates. +* `idna` - Internationalized domain name support. +* `sniffio` - Async library autodetection. + +As well as these optional installs: + +* `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)* +* `socksio` - SOCKS proxy support. *(Optional, with `httpx[socks]`)* +* `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)* +* `click` - Command line client support. *(Optional, with `httpx[cli]`)* +* `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx[brotli]`)* +* `zstandard` - Decoding for "zstd" compressed responses. *(Optional, with `httpx[zstd]`)* + +A huge amount of credit is due to `requests` for the API layout that +much of this work follows, as well as to `urllib3` for plenty of design +inspiration around the lower-level networking details. + +--- + +

HTTPX is BSD licensed code.
Designed & crafted with care.

— 🦋 —

+ +## Release Information + +### Fixed + +* Reintroduced supposedly-private `URLTypes` shortcut. (#2673) + + +--- + +[Full changelog](https://github.com/encode/httpx/blob/master/CHANGELOG.md) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..84f4ac7948733ad95e5e36cae09e009bff5f5dbe --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/RECORD @@ -0,0 +1,54 @@ +../../Scripts/httpx.exe,sha256=ORavrYUsToSvChBxX3wQuv0iHlEOLgl55a8vx5YpNHA,108353 +httpx-0.28.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httpx-0.28.1.dist-info/METADATA,sha256=_rubD48-gNV8gZnDBPNcQzboWB0dGNeYPJJ2a4J5OyU,7052 +httpx-0.28.1.dist-info/RECORD,, +httpx-0.28.1.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87 +httpx-0.28.1.dist-info/entry_points.txt,sha256=2lVkdQmxLA1pNMgSN2eV89o90HCZezhmNwsy6ryKDSA,37 +httpx-0.28.1.dist-info/licenses/LICENSE.md,sha256=TsWdVE8StfU5o6cW_TIaxYzNgDC0ZSIfLIgCAM3yjY0,1508 +httpx/__init__.py,sha256=CsaZe6yZj0rHg6322AWKWHGTMVr9txgEfD5P3_Rrz60,2171 +httpx/__pycache__/__init__.cpython-311.pyc,, +httpx/__pycache__/__version__.cpython-311.pyc,, +httpx/__pycache__/_api.cpython-311.pyc,, +httpx/__pycache__/_auth.cpython-311.pyc,, +httpx/__pycache__/_client.cpython-311.pyc,, +httpx/__pycache__/_config.cpython-311.pyc,, +httpx/__pycache__/_content.cpython-311.pyc,, +httpx/__pycache__/_decoders.cpython-311.pyc,, +httpx/__pycache__/_exceptions.cpython-311.pyc,, +httpx/__pycache__/_main.cpython-311.pyc,, +httpx/__pycache__/_models.cpython-311.pyc,, +httpx/__pycache__/_multipart.cpython-311.pyc,, +httpx/__pycache__/_status_codes.cpython-311.pyc,, +httpx/__pycache__/_types.cpython-311.pyc,, +httpx/__pycache__/_urlparse.cpython-311.pyc,, +httpx/__pycache__/_urls.cpython-311.pyc,, +httpx/__pycache__/_utils.cpython-311.pyc,, +httpx/__version__.py,sha256=LoUyYeOXTieGzuP_64UL0wxdtxjuu_QbOvE7NOg-IqU,108 +httpx/_api.py,sha256=r_Zgs4jIpcPJLqK5dbbSayqo_iVMKFaxZCd-oOHxLEs,11743 +httpx/_auth.py,sha256=Yr3QwaUSK17rGYx-7j-FdicFIzz4Y9FFV-1F4-7RXX4,11891 +httpx/_client.py,sha256=xD-UG67-WMkeltAAOeGGj-cZ2RRTAm19sWRxlFY7_40,65714 +httpx/_config.py,sha256=pPp2U-wicfcKsF-KYRE1LYdt3e6ERGeIoXZ8Gjo3LWc,8547 +httpx/_content.py,sha256=LGGzrJTR3OvN4Mb1GVVNLXkXJH-6oKlwAttO9p5w_yg,8161 +httpx/_decoders.py,sha256=p0dX8I0NEHexs3UGp4SsZutiMhsXrrWl6-GnqVb0iKM,12041 +httpx/_exceptions.py,sha256=bxW7fxzgVMAdNTbwT0Vnq04gJDW1_gI_GFiQPuMyjL0,8527 +httpx/_main.py,sha256=Cg9GMabiTT_swaDfUgIRitSwxLRMSwUDOm7LdSGqlA4,15626 +httpx/_models.py,sha256=4__Guyv1gLxuZChwim8kfQNiIOcJ9acreFOSurvZfms,44700 +httpx/_multipart.py,sha256=KOHEZZl6oohg9mPaKyyu345qq1rJLg35TUG3YAzXB3Y,9843 +httpx/_status_codes.py,sha256=DYn-2ufBgMeXy5s8x3_TB7wjAuAAMewTakPrm5rXEsc,5639 +httpx/_transports/__init__.py,sha256=GbUoBSAOp7z-l-9j5YhMhR3DMIcn6FVLhj072O3Nnno,275 +httpx/_transports/__pycache__/__init__.cpython-311.pyc,, +httpx/_transports/__pycache__/asgi.cpython-311.pyc,, +httpx/_transports/__pycache__/base.cpython-311.pyc,, +httpx/_transports/__pycache__/default.cpython-311.pyc,, +httpx/_transports/__pycache__/mock.cpython-311.pyc,, +httpx/_transports/__pycache__/wsgi.cpython-311.pyc,, +httpx/_transports/asgi.py,sha256=HRfiDYMPt4wQH2gFgHZg4c-i3sblo6bL5GTqcET-xz8,5501 +httpx/_transports/base.py,sha256=kZS_VMbViYfF570pogUCJ1bulz-ybfL51Pqs9yktebU,2523 +httpx/_transports/default.py,sha256=AzeaRUyVwCccTyyNJexDf0n1dFfzzydpdIQgvw7PLnk,13983 +httpx/_transports/mock.py,sha256=PTo0d567RITXxGrki6kN7_67wwAxfwiMDcuXJiZCjEo,1232 +httpx/_transports/wsgi.py,sha256=NcPX3Xap_EwCFZWO_OaSyQNuInCYx1QMNbO8GAei6jY,4825 +httpx/_types.py,sha256=Jyh41GQq7AOev8IOWKDAg7zCbvHAfufmW5g_PiTtErY,2965 +httpx/_urlparse.py,sha256=ZAmH47ONfkxrrj-PPYhGeiHjb6AjKCS-ANWIN4OL_KY,18546 +httpx/_urls.py,sha256=dX99VR1DSOHpgo9Aq7PzYO4FKdxqKjwyNp8grf8dHN0,21550 +httpx/_utils.py,sha256=_TVeqAKvxJkKHdz7dFeb4s0LZqQXgeFkXSgfiHBK_1o,8285 +httpx/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..21aaa72961a8af71c17d2cb3b76d5f7f567100e4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.26.3 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/entry_points.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..8ae96007f7d725813fd02dc1d06d3834ee1939e4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx-0.28.1.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +httpx = httpx:main diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e9addde071f81758baf350c4ab6bde2556340131 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/__init__.py @@ -0,0 +1,105 @@ +from .__version__ import __description__, __title__, __version__ +from ._api import * +from ._auth import * +from ._client import * +from ._config import * +from ._content import * +from ._exceptions import * +from ._models import * +from ._status_codes import * +from ._transports import * +from ._types import * +from ._urls import * + +try: + from ._main import main +except ImportError: # pragma: no cover + + def main() -> None: # type: ignore + import sys + + print( + "The httpx command line client could not run because the required " + "dependencies were not installed.\nMake sure you've installed " + "everything with: pip install 'httpx[cli]'" + ) + sys.exit(1) + + +__all__ = [ + "__description__", + "__title__", + "__version__", + "ASGITransport", + "AsyncBaseTransport", + "AsyncByteStream", + "AsyncClient", + "AsyncHTTPTransport", + "Auth", + "BaseTransport", + "BasicAuth", + "ByteStream", + "Client", + "CloseError", + "codes", + "ConnectError", + "ConnectTimeout", + "CookieConflict", + "Cookies", + "create_ssl_context", + "DecodingError", + "delete", + "DigestAuth", + "get", + "head", + "Headers", + "HTTPError", + "HTTPStatusError", + "HTTPTransport", + "InvalidURL", + "Limits", + "LocalProtocolError", + "main", + "MockTransport", + "NetRCAuth", + "NetworkError", + "options", + "patch", + "PoolTimeout", + "post", + "ProtocolError", + "Proxy", + "ProxyError", + "put", + "QueryParams", + "ReadError", + "ReadTimeout", + "RemoteProtocolError", + "request", + "Request", + "RequestError", + "RequestNotRead", + "Response", + "ResponseNotRead", + "stream", + "StreamClosed", + "StreamConsumed", + "StreamError", + "SyncByteStream", + "Timeout", + "TimeoutException", + "TooManyRedirects", + "TransportError", + "UnsupportedProtocol", + "URL", + "USE_CLIENT_DEFAULT", + "WriteError", + "WriteTimeout", + "WSGITransport", +] + + +__locals = locals() +for __name in __all__: + if not __name.startswith("__"): + setattr(__locals[__name], "__module__", "httpx") # noqa diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/__version__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..801bfacf671017cfbebf1ac26ec385daa02ed260 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/__version__.py @@ -0,0 +1,3 @@ +__title__ = "httpx" +__description__ = "A next generation HTTP client, for Python 3." +__version__ = "0.28.1" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..c3cda1ecda8629edbdca2e3bc04bc51dba5e1430 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_api.py @@ -0,0 +1,438 @@ +from __future__ import annotations + +import typing +from contextlib import contextmanager + +from ._client import Client +from ._config import DEFAULT_TIMEOUT_CONFIG +from ._models import Response +from ._types import ( + AuthTypes, + CookieTypes, + HeaderTypes, + ProxyTypes, + QueryParamTypes, + RequestContent, + RequestData, + RequestFiles, + TimeoutTypes, +) +from ._urls import URL + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + + +__all__ = [ + "delete", + "get", + "head", + "options", + "patch", + "post", + "put", + "request", + "stream", +] + + +def request( + method: str, + url: URL | str, + *, + params: QueryParamTypes | None = None, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + trust_env: bool = True, +) -> Response: + """ + Sends an HTTP request. + + **Parameters:** + + * **method** - HTTP method for the new `Request` object: `GET`, `OPTIONS`, + `HEAD`, `POST`, `PUT`, `PATCH`, or `DELETE`. + * **url** - URL for the new `Request` object. + * **params** - *(optional)* Query parameters to include in the URL, as a + string, dictionary, or sequence of two-tuples. + * **content** - *(optional)* Binary content to include in the body of the + request, as bytes or a byte iterator. + * **data** - *(optional)* Form data to include in the body of the request, + as a dictionary. + * **files** - *(optional)* A dictionary of upload files to include in the + body of the request. + * **json** - *(optional)* A JSON serializable object to include in the body + of the request. + * **headers** - *(optional)* Dictionary of HTTP headers to include in the + request. + * **cookies** - *(optional)* Dictionary of Cookie items to include in the + request. + * **auth** - *(optional)* An authentication class to use when sending the + request. + * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. + * **timeout** - *(optional)* The timeout configuration to use when sending + the request. + * **follow_redirects** - *(optional)* Enables or disables HTTP redirects. + * **verify** - *(optional)* Either `True` to use an SSL context with the + default CA bundle, `False` to disable verification, or an instance of + `ssl.SSLContext` to use a custom context. + * **trust_env** - *(optional)* Enables or disables usage of environment + variables for configuration. + + **Returns:** `Response` + + Usage: + + ``` + >>> import httpx + >>> response = httpx.request('GET', 'https://httpbin.org/get') + >>> response + + ``` + """ + with Client( + cookies=cookies, + proxy=proxy, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) as client: + return client.request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + auth=auth, + follow_redirects=follow_redirects, + ) + + +@contextmanager +def stream( + method: str, + url: URL | str, + *, + params: QueryParamTypes | None = None, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + trust_env: bool = True, +) -> typing.Iterator[Response]: + """ + Alternative to `httpx.request()` that streams the response body + instead of loading it into memory at once. + + **Parameters**: See `httpx.request`. + + See also: [Streaming Responses][0] + + [0]: /quickstart#streaming-responses + """ + with Client( + cookies=cookies, + proxy=proxy, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) as client: + with client.stream( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + auth=auth, + follow_redirects=follow_redirects, + ) as response: + yield response + + +def get( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `GET` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `GET` requests should not include a request body. + """ + return request( + "GET", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def options( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends an `OPTIONS` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `OPTIONS` requests should not include a request body. + """ + return request( + "OPTIONS", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def head( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `HEAD` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `HEAD` requests should not include a request body. + """ + return request( + "HEAD", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def post( + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `POST` request. + + **Parameters**: See `httpx.request`. + """ + return request( + "POST", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def put( + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `PUT` request. + + **Parameters**: See `httpx.request`. + """ + return request( + "PUT", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def patch( + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + verify: ssl.SSLContext | str | bool = True, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + trust_env: bool = True, +) -> Response: + """ + Sends a `PATCH` request. + + **Parameters**: See `httpx.request`. + """ + return request( + "PATCH", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) + + +def delete( + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | None = None, + proxy: ProxyTypes | None = None, + follow_redirects: bool = False, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + verify: ssl.SSLContext | str | bool = True, + trust_env: bool = True, +) -> Response: + """ + Sends a `DELETE` request. + + **Parameters**: See `httpx.request`. + + Note that the `data`, `files`, `json` and `content` parameters are not available + on this function, as `DELETE` requests should not include a request body. + """ + return request( + "DELETE", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + proxy=proxy, + follow_redirects=follow_redirects, + verify=verify, + timeout=timeout, + trust_env=trust_env, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_auth.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..b03971ab4b311d60790dc22ca24d9966426ec0a4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_auth.py @@ -0,0 +1,348 @@ +from __future__ import annotations + +import hashlib +import os +import re +import time +import typing +from base64 import b64encode +from urllib.request import parse_http_list + +from ._exceptions import ProtocolError +from ._models import Cookies, Request, Response +from ._utils import to_bytes, to_str, unquote + +if typing.TYPE_CHECKING: # pragma: no cover + from hashlib import _Hash + + +__all__ = ["Auth", "BasicAuth", "DigestAuth", "NetRCAuth"] + + +class Auth: + """ + Base class for all authentication schemes. + + To implement a custom authentication scheme, subclass `Auth` and override + the `.auth_flow()` method. + + If the authentication scheme does I/O such as disk access or network calls, or uses + synchronization primitives such as locks, you should override `.sync_auth_flow()` + and/or `.async_auth_flow()` instead of `.auth_flow()` to provide specialized + implementations that will be used by `Client` and `AsyncClient` respectively. + """ + + requires_request_body = False + requires_response_body = False + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + """ + Execute the authentication flow. + + To dispatch a request, `yield` it: + + ``` + yield request + ``` + + The client will `.send()` the response back into the flow generator. You can + access it like so: + + ``` + response = yield request + ``` + + A `return` (or reaching the end of the generator) will result in the + client returning the last response obtained from the server. + + You can dispatch as many requests as is necessary. + """ + yield request + + def sync_auth_flow( + self, request: Request + ) -> typing.Generator[Request, Response, None]: + """ + Execute the authentication flow synchronously. + + By default, this defers to `.auth_flow()`. You should override this method + when the authentication scheme does I/O and/or uses concurrency primitives. + """ + if self.requires_request_body: + request.read() + + flow = self.auth_flow(request) + request = next(flow) + + while True: + response = yield request + if self.requires_response_body: + response.read() + + try: + request = flow.send(response) + except StopIteration: + break + + async def async_auth_flow( + self, request: Request + ) -> typing.AsyncGenerator[Request, Response]: + """ + Execute the authentication flow asynchronously. + + By default, this defers to `.auth_flow()`. You should override this method + when the authentication scheme does I/O and/or uses concurrency primitives. + """ + if self.requires_request_body: + await request.aread() + + flow = self.auth_flow(request) + request = next(flow) + + while True: + response = yield request + if self.requires_response_body: + await response.aread() + + try: + request = flow.send(response) + except StopIteration: + break + + +class FunctionAuth(Auth): + """ + Allows the 'auth' argument to be passed as a simple callable function, + that takes the request, and returns a new, modified request. + """ + + def __init__(self, func: typing.Callable[[Request], Request]) -> None: + self._func = func + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + yield self._func(request) + + +class BasicAuth(Auth): + """ + Allows the 'auth' argument to be passed as a (username, password) pair, + and uses HTTP Basic authentication. + """ + + def __init__(self, username: str | bytes, password: str | bytes) -> None: + self._auth_header = self._build_auth_header(username, password) + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + request.headers["Authorization"] = self._auth_header + yield request + + def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str: + userpass = b":".join((to_bytes(username), to_bytes(password))) + token = b64encode(userpass).decode() + return f"Basic {token}" + + +class NetRCAuth(Auth): + """ + Use a 'netrc' file to lookup basic auth credentials based on the url host. + """ + + def __init__(self, file: str | None = None) -> None: + # Lazily import 'netrc'. + # There's no need for us to load this module unless 'NetRCAuth' is being used. + import netrc + + self._netrc_info = netrc.netrc(file) + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + auth_info = self._netrc_info.authenticators(request.url.host) + if auth_info is None or not auth_info[2]: + # The netrc file did not have authentication credentials for this host. + yield request + else: + # Build a basic auth header with credentials from the netrc file. + request.headers["Authorization"] = self._build_auth_header( + username=auth_info[0], password=auth_info[2] + ) + yield request + + def _build_auth_header(self, username: str | bytes, password: str | bytes) -> str: + userpass = b":".join((to_bytes(username), to_bytes(password))) + token = b64encode(userpass).decode() + return f"Basic {token}" + + +class DigestAuth(Auth): + _ALGORITHM_TO_HASH_FUNCTION: dict[str, typing.Callable[[bytes], _Hash]] = { + "MD5": hashlib.md5, + "MD5-SESS": hashlib.md5, + "SHA": hashlib.sha1, + "SHA-SESS": hashlib.sha1, + "SHA-256": hashlib.sha256, + "SHA-256-SESS": hashlib.sha256, + "SHA-512": hashlib.sha512, + "SHA-512-SESS": hashlib.sha512, + } + + def __init__(self, username: str | bytes, password: str | bytes) -> None: + self._username = to_bytes(username) + self._password = to_bytes(password) + self._last_challenge: _DigestAuthChallenge | None = None + self._nonce_count = 1 + + def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]: + if self._last_challenge: + request.headers["Authorization"] = self._build_auth_header( + request, self._last_challenge + ) + + response = yield request + + if response.status_code != 401 or "www-authenticate" not in response.headers: + # If the response is not a 401 then we don't + # need to build an authenticated request. + return + + for auth_header in response.headers.get_list("www-authenticate"): + if auth_header.lower().startswith("digest "): + break + else: + # If the response does not include a 'WWW-Authenticate: Digest ...' + # header, then we don't need to build an authenticated request. + return + + self._last_challenge = self._parse_challenge(request, response, auth_header) + self._nonce_count = 1 + + request.headers["Authorization"] = self._build_auth_header( + request, self._last_challenge + ) + if response.cookies: + Cookies(response.cookies).set_cookie_header(request=request) + yield request + + def _parse_challenge( + self, request: Request, response: Response, auth_header: str + ) -> _DigestAuthChallenge: + """ + Returns a challenge from a Digest WWW-Authenticate header. + These take the form of: + `Digest realm="realm@host.com",qop="auth,auth-int",nonce="abc",opaque="xyz"` + """ + scheme, _, fields = auth_header.partition(" ") + + # This method should only ever have been called with a Digest auth header. + assert scheme.lower() == "digest" + + header_dict: dict[str, str] = {} + for field in parse_http_list(fields): + key, value = field.strip().split("=", 1) + header_dict[key] = unquote(value) + + try: + realm = header_dict["realm"].encode() + nonce = header_dict["nonce"].encode() + algorithm = header_dict.get("algorithm", "MD5") + opaque = header_dict["opaque"].encode() if "opaque" in header_dict else None + qop = header_dict["qop"].encode() if "qop" in header_dict else None + return _DigestAuthChallenge( + realm=realm, nonce=nonce, algorithm=algorithm, opaque=opaque, qop=qop + ) + except KeyError as exc: + message = "Malformed Digest WWW-Authenticate header" + raise ProtocolError(message, request=request) from exc + + def _build_auth_header( + self, request: Request, challenge: _DigestAuthChallenge + ) -> str: + hash_func = self._ALGORITHM_TO_HASH_FUNCTION[challenge.algorithm.upper()] + + def digest(data: bytes) -> bytes: + return hash_func(data).hexdigest().encode() + + A1 = b":".join((self._username, challenge.realm, self._password)) + + path = request.url.raw_path + A2 = b":".join((request.method.encode(), path)) + # TODO: implement auth-int + HA2 = digest(A2) + + nc_value = b"%08x" % self._nonce_count + cnonce = self._get_client_nonce(self._nonce_count, challenge.nonce) + self._nonce_count += 1 + + HA1 = digest(A1) + if challenge.algorithm.lower().endswith("-sess"): + HA1 = digest(b":".join((HA1, challenge.nonce, cnonce))) + + qop = self._resolve_qop(challenge.qop, request=request) + if qop is None: + # Following RFC 2069 + digest_data = [HA1, challenge.nonce, HA2] + else: + # Following RFC 2617/7616 + digest_data = [HA1, challenge.nonce, nc_value, cnonce, qop, HA2] + + format_args = { + "username": self._username, + "realm": challenge.realm, + "nonce": challenge.nonce, + "uri": path, + "response": digest(b":".join(digest_data)), + "algorithm": challenge.algorithm.encode(), + } + if challenge.opaque: + format_args["opaque"] = challenge.opaque + if qop: + format_args["qop"] = b"auth" + format_args["nc"] = nc_value + format_args["cnonce"] = cnonce + + return "Digest " + self._get_header_value(format_args) + + def _get_client_nonce(self, nonce_count: int, nonce: bytes) -> bytes: + s = str(nonce_count).encode() + s += nonce + s += time.ctime().encode() + s += os.urandom(8) + + return hashlib.sha1(s).hexdigest()[:16].encode() + + def _get_header_value(self, header_fields: dict[str, bytes]) -> str: + NON_QUOTED_FIELDS = ("algorithm", "qop", "nc") + QUOTED_TEMPLATE = '{}="{}"' + NON_QUOTED_TEMPLATE = "{}={}" + + header_value = "" + for i, (field, value) in enumerate(header_fields.items()): + if i > 0: + header_value += ", " + template = ( + QUOTED_TEMPLATE + if field not in NON_QUOTED_FIELDS + else NON_QUOTED_TEMPLATE + ) + header_value += template.format(field, to_str(value)) + + return header_value + + def _resolve_qop(self, qop: bytes | None, request: Request) -> bytes | None: + if qop is None: + return None + qops = re.split(b", ?", qop) + if b"auth" in qops: + return b"auth" + + if qops == [b"auth-int"]: + raise NotImplementedError("Digest auth-int support is not yet implemented") + + message = f'Unexpected qop value "{qop!r}" in digest auth' + raise ProtocolError(message, request=request) + + +class _DigestAuthChallenge(typing.NamedTuple): + realm: bytes + nonce: bytes + algorithm: str + opaque: bytes | None + qop: bytes | None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_client.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_client.py new file mode 100644 index 0000000000000000000000000000000000000000..2249231f8c3b912c731ff160344d3672e2f11738 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_client.py @@ -0,0 +1,2019 @@ +from __future__ import annotations + +import datetime +import enum +import logging +import time +import typing +import warnings +from contextlib import asynccontextmanager, contextmanager +from types import TracebackType + +from .__version__ import __version__ +from ._auth import Auth, BasicAuth, FunctionAuth +from ._config import ( + DEFAULT_LIMITS, + DEFAULT_MAX_REDIRECTS, + DEFAULT_TIMEOUT_CONFIG, + Limits, + Proxy, + Timeout, +) +from ._decoders import SUPPORTED_DECODERS +from ._exceptions import ( + InvalidURL, + RemoteProtocolError, + TooManyRedirects, + request_context, +) +from ._models import Cookies, Headers, Request, Response +from ._status_codes import codes +from ._transports.base import AsyncBaseTransport, BaseTransport +from ._transports.default import AsyncHTTPTransport, HTTPTransport +from ._types import ( + AsyncByteStream, + AuthTypes, + CertTypes, + CookieTypes, + HeaderTypes, + ProxyTypes, + QueryParamTypes, + RequestContent, + RequestData, + RequestExtensions, + RequestFiles, + SyncByteStream, + TimeoutTypes, +) +from ._urls import URL, QueryParams +from ._utils import URLPattern, get_environment_proxies + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + +__all__ = ["USE_CLIENT_DEFAULT", "AsyncClient", "Client"] + +# The type annotation for @classmethod and context managers here follows PEP 484 +# https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods +T = typing.TypeVar("T", bound="Client") +U = typing.TypeVar("U", bound="AsyncClient") + + +def _is_https_redirect(url: URL, location: URL) -> bool: + """ + Return 'True' if 'location' is a HTTPS upgrade of 'url' + """ + if url.host != location.host: + return False + + return ( + url.scheme == "http" + and _port_or_default(url) == 80 + and location.scheme == "https" + and _port_or_default(location) == 443 + ) + + +def _port_or_default(url: URL) -> int | None: + if url.port is not None: + return url.port + return {"http": 80, "https": 443}.get(url.scheme) + + +def _same_origin(url: URL, other: URL) -> bool: + """ + Return 'True' if the given URLs share the same origin. + """ + return ( + url.scheme == other.scheme + and url.host == other.host + and _port_or_default(url) == _port_or_default(other) + ) + + +class UseClientDefault: + """ + For some parameters such as `auth=...` and `timeout=...` we need to be able + to indicate the default "unset" state, in a way that is distinctly different + to using `None`. + + The default "unset" state indicates that whatever default is set on the + client should be used. This is different to setting `None`, which + explicitly disables the parameter, possibly overriding a client default. + + For example we use `timeout=USE_CLIENT_DEFAULT` in the `request()` signature. + Omitting the `timeout` parameter will send a request using whatever default + timeout has been configured on the client. Including `timeout=None` will + ensure no timeout is used. + + Note that user code shouldn't need to use the `USE_CLIENT_DEFAULT` constant, + but it is used internally when a parameter is not included. + """ + + +USE_CLIENT_DEFAULT = UseClientDefault() + + +logger = logging.getLogger("httpx") + +USER_AGENT = f"python-httpx/{__version__}" +ACCEPT_ENCODING = ", ".join( + [key for key in SUPPORTED_DECODERS.keys() if key != "identity"] +) + + +class ClientState(enum.Enum): + # UNOPENED: + # The client has been instantiated, but has not been used to send a request, + # or been opened by entering the context of a `with` block. + UNOPENED = 1 + # OPENED: + # The client has either sent a request, or is within a `with` block. + OPENED = 2 + # CLOSED: + # The client has either exited the `with` block, or `close()` has + # been called explicitly. + CLOSED = 3 + + +class BoundSyncStream(SyncByteStream): + """ + A byte stream that is bound to a given response instance, and that + ensures the `response.elapsed` is set once the response is closed. + """ + + def __init__( + self, stream: SyncByteStream, response: Response, start: float + ) -> None: + self._stream = stream + self._response = response + self._start = start + + def __iter__(self) -> typing.Iterator[bytes]: + for chunk in self._stream: + yield chunk + + def close(self) -> None: + elapsed = time.perf_counter() - self._start + self._response.elapsed = datetime.timedelta(seconds=elapsed) + self._stream.close() + + +class BoundAsyncStream(AsyncByteStream): + """ + An async byte stream that is bound to a given response instance, and that + ensures the `response.elapsed` is set once the response is closed. + """ + + def __init__( + self, stream: AsyncByteStream, response: Response, start: float + ) -> None: + self._stream = stream + self._response = response + self._start = start + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + async for chunk in self._stream: + yield chunk + + async def aclose(self) -> None: + elapsed = time.perf_counter() - self._start + self._response.elapsed = datetime.timedelta(seconds=elapsed) + await self._stream.aclose() + + +EventHook = typing.Callable[..., typing.Any] + + +class BaseClient: + def __init__( + self, + *, + auth: AuthTypes | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + max_redirects: int = DEFAULT_MAX_REDIRECTS, + event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, + base_url: URL | str = "", + trust_env: bool = True, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + event_hooks = {} if event_hooks is None else event_hooks + + self._base_url = self._enforce_trailing_slash(URL(base_url)) + + self._auth = self._build_auth(auth) + self._params = QueryParams(params) + self.headers = Headers(headers) + self._cookies = Cookies(cookies) + self._timeout = Timeout(timeout) + self.follow_redirects = follow_redirects + self.max_redirects = max_redirects + self._event_hooks = { + "request": list(event_hooks.get("request", [])), + "response": list(event_hooks.get("response", [])), + } + self._trust_env = trust_env + self._default_encoding = default_encoding + self._state = ClientState.UNOPENED + + @property + def is_closed(self) -> bool: + """ + Check if the client being closed + """ + return self._state == ClientState.CLOSED + + @property + def trust_env(self) -> bool: + return self._trust_env + + def _enforce_trailing_slash(self, url: URL) -> URL: + if url.raw_path.endswith(b"/"): + return url + return url.copy_with(raw_path=url.raw_path + b"/") + + def _get_proxy_map( + self, proxy: ProxyTypes | None, allow_env_proxies: bool + ) -> dict[str, Proxy | None]: + if proxy is None: + if allow_env_proxies: + return { + key: None if url is None else Proxy(url=url) + for key, url in get_environment_proxies().items() + } + return {} + else: + proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy + return {"all://": proxy} + + @property + def timeout(self) -> Timeout: + return self._timeout + + @timeout.setter + def timeout(self, timeout: TimeoutTypes) -> None: + self._timeout = Timeout(timeout) + + @property + def event_hooks(self) -> dict[str, list[EventHook]]: + return self._event_hooks + + @event_hooks.setter + def event_hooks(self, event_hooks: dict[str, list[EventHook]]) -> None: + self._event_hooks = { + "request": list(event_hooks.get("request", [])), + "response": list(event_hooks.get("response", [])), + } + + @property + def auth(self) -> Auth | None: + """ + Authentication class used when none is passed at the request-level. + + See also [Authentication][0]. + + [0]: /quickstart/#authentication + """ + return self._auth + + @auth.setter + def auth(self, auth: AuthTypes) -> None: + self._auth = self._build_auth(auth) + + @property + def base_url(self) -> URL: + """ + Base URL to use when sending requests with relative URLs. + """ + return self._base_url + + @base_url.setter + def base_url(self, url: URL | str) -> None: + self._base_url = self._enforce_trailing_slash(URL(url)) + + @property + def headers(self) -> Headers: + """ + HTTP headers to include when sending requests. + """ + return self._headers + + @headers.setter + def headers(self, headers: HeaderTypes) -> None: + client_headers = Headers( + { + b"Accept": b"*/*", + b"Accept-Encoding": ACCEPT_ENCODING.encode("ascii"), + b"Connection": b"keep-alive", + b"User-Agent": USER_AGENT.encode("ascii"), + } + ) + client_headers.update(headers) + self._headers = client_headers + + @property + def cookies(self) -> Cookies: + """ + Cookie values to include when sending requests. + """ + return self._cookies + + @cookies.setter + def cookies(self, cookies: CookieTypes) -> None: + self._cookies = Cookies(cookies) + + @property + def params(self) -> QueryParams: + """ + Query parameters to include in the URL when sending requests. + """ + return self._params + + @params.setter + def params(self, params: QueryParamTypes) -> None: + self._params = QueryParams(params) + + def build_request( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Request: + """ + Build and return a request instance. + + * The `params`, `headers` and `cookies` arguments + are merged with any values set on the client. + * The `url` argument is merged with any `base_url` set on the client. + + See also: [Request instances][0] + + [0]: /advanced/clients/#request-instances + """ + url = self._merge_url(url) + headers = self._merge_headers(headers) + cookies = self._merge_cookies(cookies) + params = self._merge_queryparams(params) + extensions = {} if extensions is None else extensions + if "timeout" not in extensions: + timeout = ( + self.timeout + if isinstance(timeout, UseClientDefault) + else Timeout(timeout) + ) + extensions = dict(**extensions, timeout=timeout.as_dict()) + return Request( + method, + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + extensions=extensions, + ) + + def _merge_url(self, url: URL | str) -> URL: + """ + Merge a URL argument together with any 'base_url' on the client, + to create the URL used for the outgoing request. + """ + merge_url = URL(url) + if merge_url.is_relative_url: + # To merge URLs we always append to the base URL. To get this + # behaviour correct we always ensure the base URL ends in a '/' + # separator, and strip any leading '/' from the merge URL. + # + # So, eg... + # + # >>> client = Client(base_url="https://www.example.com/subpath") + # >>> client.base_url + # URL('https://www.example.com/subpath/') + # >>> client.build_request("GET", "/path").url + # URL('https://www.example.com/subpath/path') + merge_raw_path = self.base_url.raw_path + merge_url.raw_path.lstrip(b"/") + return self.base_url.copy_with(raw_path=merge_raw_path) + return merge_url + + def _merge_cookies(self, cookies: CookieTypes | None = None) -> CookieTypes | None: + """ + Merge a cookies argument together with any cookies on the client, + to create the cookies used for the outgoing request. + """ + if cookies or self.cookies: + merged_cookies = Cookies(self.cookies) + merged_cookies.update(cookies) + return merged_cookies + return cookies + + def _merge_headers(self, headers: HeaderTypes | None = None) -> HeaderTypes | None: + """ + Merge a headers argument together with any headers on the client, + to create the headers used for the outgoing request. + """ + merged_headers = Headers(self.headers) + merged_headers.update(headers) + return merged_headers + + def _merge_queryparams( + self, params: QueryParamTypes | None = None + ) -> QueryParamTypes | None: + """ + Merge a queryparams argument together with any queryparams on the client, + to create the queryparams used for the outgoing request. + """ + if params or self.params: + merged_queryparams = QueryParams(self.params) + return merged_queryparams.merge(params) + return params + + def _build_auth(self, auth: AuthTypes | None) -> Auth | None: + if auth is None: + return None + elif isinstance(auth, tuple): + return BasicAuth(username=auth[0], password=auth[1]) + elif isinstance(auth, Auth): + return auth + elif callable(auth): + return FunctionAuth(func=auth) + else: + raise TypeError(f'Invalid "auth" argument: {auth!r}') + + def _build_request_auth( + self, + request: Request, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + ) -> Auth: + auth = ( + self._auth if isinstance(auth, UseClientDefault) else self._build_auth(auth) + ) + + if auth is not None: + return auth + + username, password = request.url.username, request.url.password + if username or password: + return BasicAuth(username=username, password=password) + + return Auth() + + def _build_redirect_request(self, request: Request, response: Response) -> Request: + """ + Given a request and a redirect response, return a new request that + should be used to effect the redirect. + """ + method = self._redirect_method(request, response) + url = self._redirect_url(request, response) + headers = self._redirect_headers(request, url, method) + stream = self._redirect_stream(request, method) + cookies = Cookies(self.cookies) + return Request( + method=method, + url=url, + headers=headers, + cookies=cookies, + stream=stream, + extensions=request.extensions, + ) + + def _redirect_method(self, request: Request, response: Response) -> str: + """ + When being redirected we may want to change the method of the request + based on certain specs or browser behavior. + """ + method = request.method + + # https://tools.ietf.org/html/rfc7231#section-6.4.4 + if response.status_code == codes.SEE_OTHER and method != "HEAD": + method = "GET" + + # Do what the browsers do, despite standards... + # Turn 302s into GETs. + if response.status_code == codes.FOUND and method != "HEAD": + method = "GET" + + # If a POST is responded to with a 301, turn it into a GET. + # This bizarre behaviour is explained in 'requests' issue 1704. + if response.status_code == codes.MOVED_PERMANENTLY and method == "POST": + method = "GET" + + return method + + def _redirect_url(self, request: Request, response: Response) -> URL: + """ + Return the URL for the redirect to follow. + """ + location = response.headers["Location"] + + try: + url = URL(location) + except InvalidURL as exc: + raise RemoteProtocolError( + f"Invalid URL in location header: {exc}.", request=request + ) from None + + # Handle malformed 'Location' headers that are "absolute" form, have no host. + # See: https://github.com/encode/httpx/issues/771 + if url.scheme and not url.host: + url = url.copy_with(host=request.url.host) + + # Facilitate relative 'Location' headers, as allowed by RFC 7231. + # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource') + if url.is_relative_url: + url = request.url.join(url) + + # Attach previous fragment if needed (RFC 7231 7.1.2) + if request.url.fragment and not url.fragment: + url = url.copy_with(fragment=request.url.fragment) + + return url + + def _redirect_headers(self, request: Request, url: URL, method: str) -> Headers: + """ + Return the headers that should be used for the redirect request. + """ + headers = Headers(request.headers) + + if not _same_origin(url, request.url): + if not _is_https_redirect(request.url, url): + # Strip Authorization headers when responses are redirected + # away from the origin. (Except for direct HTTP to HTTPS redirects.) + headers.pop("Authorization", None) + + # Update the Host header. + headers["Host"] = url.netloc.decode("ascii") + + if method != request.method and method == "GET": + # If we've switch to a 'GET' request, then strip any headers which + # are only relevant to the request body. + headers.pop("Content-Length", None) + headers.pop("Transfer-Encoding", None) + + # We should use the client cookie store to determine any cookie header, + # rather than whatever was on the original outgoing request. + headers.pop("Cookie", None) + + return headers + + def _redirect_stream( + self, request: Request, method: str + ) -> SyncByteStream | AsyncByteStream | None: + """ + Return the body that should be used for the redirect request. + """ + if method != request.method and method == "GET": + return None + + return request.stream + + def _set_timeout(self, request: Request) -> None: + if "timeout" not in request.extensions: + timeout = ( + self.timeout + if isinstance(self.timeout, UseClientDefault) + else Timeout(self.timeout) + ) + request.extensions = dict(**request.extensions, timeout=timeout.as_dict()) + + +class Client(BaseClient): + """ + An HTTP client, with connection pooling, HTTP/2, redirects, cookie persistence, etc. + + It can be shared between threads. + + Usage: + + ```python + >>> client = httpx.Client() + >>> response = client.get('https://example.org') + ``` + + **Parameters:** + + * **auth** - *(optional)* An authentication class to use when sending + requests. + * **params** - *(optional)* Query parameters to include in request URLs, as + a string, dictionary, or sequence of two-tuples. + * **headers** - *(optional)* Dictionary of HTTP headers to include when + sending requests. + * **cookies** - *(optional)* Dictionary of Cookie items to include when + sending requests. + * **verify** - *(optional)* Either `True` to use an SSL context with the + default CA bundle, `False` to disable verification, or an instance of + `ssl.SSLContext` to use a custom context. + * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be + enabled. Defaults to `False`. + * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. + * **timeout** - *(optional)* The timeout configuration to use when sending + requests. + * **limits** - *(optional)* The limits configuration to use. + * **max_redirects** - *(optional)* The maximum number of redirect responses + that should be followed. + * **base_url** - *(optional)* A URL to use as the base when building + request URLs. + * **transport** - *(optional)* A transport class to use for sending requests + over the network. + * **trust_env** - *(optional)* Enables or disables usage of environment + variables for configuration. + * **default_encoding** - *(optional)* The default encoding to use for decoding + response text, if no charset information is included in a response Content-Type + header. Set to a callable for automatic character set detection. Default: "utf-8". + """ + + def __init__( + self, + *, + auth: AuthTypes | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + proxy: ProxyTypes | None = None, + mounts: None | (typing.Mapping[str, BaseTransport | None]) = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + limits: Limits = DEFAULT_LIMITS, + max_redirects: int = DEFAULT_MAX_REDIRECTS, + event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, + base_url: URL | str = "", + transport: BaseTransport | None = None, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + super().__init__( + auth=auth, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + follow_redirects=follow_redirects, + max_redirects=max_redirects, + event_hooks=event_hooks, + base_url=base_url, + trust_env=trust_env, + default_encoding=default_encoding, + ) + + if http2: + try: + import h2 # noqa + except ImportError: # pragma: no cover + raise ImportError( + "Using http2=True, but the 'h2' package is not installed. " + "Make sure to install httpx using `pip install httpx[http2]`." + ) from None + + allow_env_proxies = trust_env and transport is None + proxy_map = self._get_proxy_map(proxy, allow_env_proxies) + + self._transport = self._init_transport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + transport=transport, + ) + self._mounts: dict[URLPattern, BaseTransport | None] = { + URLPattern(key): None + if proxy is None + else self._init_proxy_transport( + proxy, + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + for key, proxy in proxy_map.items() + } + if mounts is not None: + self._mounts.update( + {URLPattern(key): transport for key, transport in mounts.items()} + ) + + self._mounts = dict(sorted(self._mounts.items())) + + def _init_transport( + self, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + transport: BaseTransport | None = None, + ) -> BaseTransport: + if transport is not None: + return transport + + return HTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + + def _init_proxy_transport( + self, + proxy: Proxy, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + ) -> BaseTransport: + return HTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + proxy=proxy, + ) + + def _transport_for_url(self, url: URL) -> BaseTransport: + """ + Returns the transport instance that should be used for a given URL. + This will either be the standard connection pool, or a proxy. + """ + for pattern, transport in self._mounts.items(): + if pattern.matches(url): + return self._transport if transport is None else transport + + return self._transport + + def request( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Build and send a request. + + Equivalent to: + + ```python + request = client.build_request(...) + response = client.send(request, ...) + ``` + + See `Client.build_request()`, `Client.send()` and + [Merging of configuration][0] for how the various parameters + are merged with client-level configuration. + + [0]: /advanced/clients/#merging-of-configuration + """ + if cookies is not None: + message = ( + "Setting per-request cookies=<...> is being deprecated, because " + "the expected behaviour on cookie persistence is ambiguous. Set " + "cookies directly on the client instance instead." + ) + warnings.warn(message, DeprecationWarning, stacklevel=2) + + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + return self.send(request, auth=auth, follow_redirects=follow_redirects) + + @contextmanager + def stream( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> typing.Iterator[Response]: + """ + Alternative to `httpx.request()` that streams the response body + instead of loading it into memory at once. + + **Parameters**: See `httpx.request`. + + See also: [Streaming Responses][0] + + [0]: /quickstart#streaming-responses + """ + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + response = self.send( + request=request, + auth=auth, + follow_redirects=follow_redirects, + stream=True, + ) + try: + yield response + finally: + response.close() + + def send( + self, + request: Request, + *, + stream: bool = False, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + ) -> Response: + """ + Send a request. + + The request is sent as-is, unmodified. + + Typically you'll want to build one with `Client.build_request()` + so that any client-level configuration is merged into the request, + but passing an explicit `httpx.Request()` is supported as well. + + See also: [Request instances][0] + + [0]: /advanced/clients/#request-instances + """ + if self._state == ClientState.CLOSED: + raise RuntimeError("Cannot send a request, as the client has been closed.") + + self._state = ClientState.OPENED + follow_redirects = ( + self.follow_redirects + if isinstance(follow_redirects, UseClientDefault) + else follow_redirects + ) + + self._set_timeout(request) + + auth = self._build_request_auth(request, auth) + + response = self._send_handling_auth( + request, + auth=auth, + follow_redirects=follow_redirects, + history=[], + ) + try: + if not stream: + response.read() + + return response + + except BaseException as exc: + response.close() + raise exc + + def _send_handling_auth( + self, + request: Request, + auth: Auth, + follow_redirects: bool, + history: list[Response], + ) -> Response: + auth_flow = auth.sync_auth_flow(request) + try: + request = next(auth_flow) + + while True: + response = self._send_handling_redirects( + request, + follow_redirects=follow_redirects, + history=history, + ) + try: + try: + next_request = auth_flow.send(response) + except StopIteration: + return response + + response.history = list(history) + response.read() + request = next_request + history.append(response) + + except BaseException as exc: + response.close() + raise exc + finally: + auth_flow.close() + + def _send_handling_redirects( + self, + request: Request, + follow_redirects: bool, + history: list[Response], + ) -> Response: + while True: + if len(history) > self.max_redirects: + raise TooManyRedirects( + "Exceeded maximum allowed redirects.", request=request + ) + + for hook in self._event_hooks["request"]: + hook(request) + + response = self._send_single_request(request) + try: + for hook in self._event_hooks["response"]: + hook(response) + response.history = list(history) + + if not response.has_redirect_location: + return response + + request = self._build_redirect_request(request, response) + history = history + [response] + + if follow_redirects: + response.read() + else: + response.next_request = request + return response + + except BaseException as exc: + response.close() + raise exc + + def _send_single_request(self, request: Request) -> Response: + """ + Sends a single request, without handling any redirections. + """ + transport = self._transport_for_url(request.url) + start = time.perf_counter() + + if not isinstance(request.stream, SyncByteStream): + raise RuntimeError( + "Attempted to send an async request with a sync Client instance." + ) + + with request_context(request=request): + response = transport.handle_request(request) + + assert isinstance(response.stream, SyncByteStream) + + response.request = request + response.stream = BoundSyncStream( + response.stream, response=response, start=start + ) + self.cookies.extract_cookies(response) + response.default_encoding = self._default_encoding + + logger.info( + 'HTTP Request: %s %s "%s %d %s"', + request.method, + request.url, + response.http_version, + response.status_code, + response.reason_phrase, + ) + + return response + + def get( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `GET` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "GET", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def options( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send an `OPTIONS` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "OPTIONS", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def head( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `HEAD` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "HEAD", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def post( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `POST` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "POST", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def put( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PUT` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "PUT", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def patch( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PATCH` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "PATCH", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def delete( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `DELETE` request. + + **Parameters**: See `httpx.request`. + """ + return self.request( + "DELETE", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + def close(self) -> None: + """ + Close transport and proxies. + """ + if self._state != ClientState.CLOSED: + self._state = ClientState.CLOSED + + self._transport.close() + for transport in self._mounts.values(): + if transport is not None: + transport.close() + + def __enter__(self: T) -> T: + if self._state != ClientState.UNOPENED: + msg = { + ClientState.OPENED: "Cannot open a client instance more than once.", + ClientState.CLOSED: ( + "Cannot reopen a client instance, once it has been closed." + ), + }[self._state] + raise RuntimeError(msg) + + self._state = ClientState.OPENED + + self._transport.__enter__() + for transport in self._mounts.values(): + if transport is not None: + transport.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + self._state = ClientState.CLOSED + + self._transport.__exit__(exc_type, exc_value, traceback) + for transport in self._mounts.values(): + if transport is not None: + transport.__exit__(exc_type, exc_value, traceback) + + +class AsyncClient(BaseClient): + """ + An asynchronous HTTP client, with connection pooling, HTTP/2, redirects, + cookie persistence, etc. + + It can be shared between tasks. + + Usage: + + ```python + >>> async with httpx.AsyncClient() as client: + >>> response = await client.get('https://example.org') + ``` + + **Parameters:** + + * **auth** - *(optional)* An authentication class to use when sending + requests. + * **params** - *(optional)* Query parameters to include in request URLs, as + a string, dictionary, or sequence of two-tuples. + * **headers** - *(optional)* Dictionary of HTTP headers to include when + sending requests. + * **cookies** - *(optional)* Dictionary of Cookie items to include when + sending requests. + * **verify** - *(optional)* Either `True` to use an SSL context with the + default CA bundle, `False` to disable verification, or an instance of + `ssl.SSLContext` to use a custom context. + * **http2** - *(optional)* A boolean indicating if HTTP/2 support should be + enabled. Defaults to `False`. + * **proxy** - *(optional)* A proxy URL where all the traffic should be routed. + * **timeout** - *(optional)* The timeout configuration to use when sending + requests. + * **limits** - *(optional)* The limits configuration to use. + * **max_redirects** - *(optional)* The maximum number of redirect responses + that should be followed. + * **base_url** - *(optional)* A URL to use as the base when building + request URLs. + * **transport** - *(optional)* A transport class to use for sending requests + over the network. + * **trust_env** - *(optional)* Enables or disables usage of environment + variables for configuration. + * **default_encoding** - *(optional)* The default encoding to use for decoding + response text, if no charset information is included in a response Content-Type + header. Set to a callable for automatic character set detection. Default: "utf-8". + """ + + def __init__( + self, + *, + auth: AuthTypes | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + http1: bool = True, + http2: bool = False, + proxy: ProxyTypes | None = None, + mounts: None | (typing.Mapping[str, AsyncBaseTransport | None]) = None, + timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG, + follow_redirects: bool = False, + limits: Limits = DEFAULT_LIMITS, + max_redirects: int = DEFAULT_MAX_REDIRECTS, + event_hooks: None | (typing.Mapping[str, list[EventHook]]) = None, + base_url: URL | str = "", + transport: AsyncBaseTransport | None = None, + trust_env: bool = True, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + super().__init__( + auth=auth, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + follow_redirects=follow_redirects, + max_redirects=max_redirects, + event_hooks=event_hooks, + base_url=base_url, + trust_env=trust_env, + default_encoding=default_encoding, + ) + + if http2: + try: + import h2 # noqa + except ImportError: # pragma: no cover + raise ImportError( + "Using http2=True, but the 'h2' package is not installed. " + "Make sure to install httpx using `pip install httpx[http2]`." + ) from None + + allow_env_proxies = trust_env and transport is None + proxy_map = self._get_proxy_map(proxy, allow_env_proxies) + + self._transport = self._init_transport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + transport=transport, + ) + + self._mounts: dict[URLPattern, AsyncBaseTransport | None] = { + URLPattern(key): None + if proxy is None + else self._init_proxy_transport( + proxy, + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + for key, proxy in proxy_map.items() + } + if mounts is not None: + self._mounts.update( + {URLPattern(key): transport for key, transport in mounts.items()} + ) + self._mounts = dict(sorted(self._mounts.items())) + + def _init_transport( + self, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + transport: AsyncBaseTransport | None = None, + ) -> AsyncBaseTransport: + if transport is not None: + return transport + + return AsyncHTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + ) + + def _init_proxy_transport( + self, + proxy: Proxy, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + ) -> AsyncBaseTransport: + return AsyncHTTPTransport( + verify=verify, + cert=cert, + trust_env=trust_env, + http1=http1, + http2=http2, + limits=limits, + proxy=proxy, + ) + + def _transport_for_url(self, url: URL) -> AsyncBaseTransport: + """ + Returns the transport instance that should be used for a given URL. + This will either be the standard connection pool, or a proxy. + """ + for pattern, transport in self._mounts.items(): + if pattern.matches(url): + return self._transport if transport is None else transport + + return self._transport + + async def request( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Build and send a request. + + Equivalent to: + + ```python + request = client.build_request(...) + response = await client.send(request, ...) + ``` + + See `AsyncClient.build_request()`, `AsyncClient.send()` + and [Merging of configuration][0] for how the various parameters + are merged with client-level configuration. + + [0]: /advanced/clients/#merging-of-configuration + """ + + if cookies is not None: # pragma: no cover + message = ( + "Setting per-request cookies=<...> is being deprecated, because " + "the expected behaviour on cookie persistence is ambiguous. Set " + "cookies directly on the client instance instead." + ) + warnings.warn(message, DeprecationWarning, stacklevel=2) + + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + return await self.send(request, auth=auth, follow_redirects=follow_redirects) + + @asynccontextmanager + async def stream( + self, + method: str, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> typing.AsyncIterator[Response]: + """ + Alternative to `httpx.request()` that streams the response body + instead of loading it into memory at once. + + **Parameters**: See `httpx.request`. + + See also: [Streaming Responses][0] + + [0]: /quickstart#streaming-responses + """ + request = self.build_request( + method=method, + url=url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + timeout=timeout, + extensions=extensions, + ) + response = await self.send( + request=request, + auth=auth, + follow_redirects=follow_redirects, + stream=True, + ) + try: + yield response + finally: + await response.aclose() + + async def send( + self, + request: Request, + *, + stream: bool = False, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + ) -> Response: + """ + Send a request. + + The request is sent as-is, unmodified. + + Typically you'll want to build one with `AsyncClient.build_request()` + so that any client-level configuration is merged into the request, + but passing an explicit `httpx.Request()` is supported as well. + + See also: [Request instances][0] + + [0]: /advanced/clients/#request-instances + """ + if self._state == ClientState.CLOSED: + raise RuntimeError("Cannot send a request, as the client has been closed.") + + self._state = ClientState.OPENED + follow_redirects = ( + self.follow_redirects + if isinstance(follow_redirects, UseClientDefault) + else follow_redirects + ) + + self._set_timeout(request) + + auth = self._build_request_auth(request, auth) + + response = await self._send_handling_auth( + request, + auth=auth, + follow_redirects=follow_redirects, + history=[], + ) + try: + if not stream: + await response.aread() + + return response + + except BaseException as exc: + await response.aclose() + raise exc + + async def _send_handling_auth( + self, + request: Request, + auth: Auth, + follow_redirects: bool, + history: list[Response], + ) -> Response: + auth_flow = auth.async_auth_flow(request) + try: + request = await auth_flow.__anext__() + + while True: + response = await self._send_handling_redirects( + request, + follow_redirects=follow_redirects, + history=history, + ) + try: + try: + next_request = await auth_flow.asend(response) + except StopAsyncIteration: + return response + + response.history = list(history) + await response.aread() + request = next_request + history.append(response) + + except BaseException as exc: + await response.aclose() + raise exc + finally: + await auth_flow.aclose() + + async def _send_handling_redirects( + self, + request: Request, + follow_redirects: bool, + history: list[Response], + ) -> Response: + while True: + if len(history) > self.max_redirects: + raise TooManyRedirects( + "Exceeded maximum allowed redirects.", request=request + ) + + for hook in self._event_hooks["request"]: + await hook(request) + + response = await self._send_single_request(request) + try: + for hook in self._event_hooks["response"]: + await hook(response) + + response.history = list(history) + + if not response.has_redirect_location: + return response + + request = self._build_redirect_request(request, response) + history = history + [response] + + if follow_redirects: + await response.aread() + else: + response.next_request = request + return response + + except BaseException as exc: + await response.aclose() + raise exc + + async def _send_single_request(self, request: Request) -> Response: + """ + Sends a single request, without handling any redirections. + """ + transport = self._transport_for_url(request.url) + start = time.perf_counter() + + if not isinstance(request.stream, AsyncByteStream): + raise RuntimeError( + "Attempted to send an sync request with an AsyncClient instance." + ) + + with request_context(request=request): + response = await transport.handle_async_request(request) + + assert isinstance(response.stream, AsyncByteStream) + response.request = request + response.stream = BoundAsyncStream( + response.stream, response=response, start=start + ) + self.cookies.extract_cookies(response) + response.default_encoding = self._default_encoding + + logger.info( + 'HTTP Request: %s %s "%s %d %s"', + request.method, + request.url, + response.http_version, + response.status_code, + response.reason_phrase, + ) + + return response + + async def get( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault | None = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `GET` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "GET", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def options( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send an `OPTIONS` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "OPTIONS", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def head( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `HEAD` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "HEAD", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def post( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `POST` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "POST", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def put( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PUT` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "PUT", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def patch( + self, + url: URL | str, + *, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `PATCH` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "PATCH", + url, + content=content, + data=data, + files=files, + json=json, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def delete( + self, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + auth: AuthTypes | UseClientDefault = USE_CLIENT_DEFAULT, + follow_redirects: bool | UseClientDefault = USE_CLIENT_DEFAULT, + timeout: TimeoutTypes | UseClientDefault = USE_CLIENT_DEFAULT, + extensions: RequestExtensions | None = None, + ) -> Response: + """ + Send a `DELETE` request. + + **Parameters**: See `httpx.request`. + """ + return await self.request( + "DELETE", + url, + params=params, + headers=headers, + cookies=cookies, + auth=auth, + follow_redirects=follow_redirects, + timeout=timeout, + extensions=extensions, + ) + + async def aclose(self) -> None: + """ + Close transport and proxies. + """ + if self._state != ClientState.CLOSED: + self._state = ClientState.CLOSED + + await self._transport.aclose() + for proxy in self._mounts.values(): + if proxy is not None: + await proxy.aclose() + + async def __aenter__(self: U) -> U: + if self._state != ClientState.UNOPENED: + msg = { + ClientState.OPENED: "Cannot open a client instance more than once.", + ClientState.CLOSED: ( + "Cannot reopen a client instance, once it has been closed." + ), + }[self._state] + raise RuntimeError(msg) + + self._state = ClientState.OPENED + + await self._transport.__aenter__() + for proxy in self._mounts.values(): + if proxy is not None: + await proxy.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + self._state = ClientState.CLOSED + + await self._transport.__aexit__(exc_type, exc_value, traceback) + for proxy in self._mounts.values(): + if proxy is not None: + await proxy.__aexit__(exc_type, exc_value, traceback) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_config.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..467a6c90ae269babe3af7963d9d7c78b9f012268 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_config.py @@ -0,0 +1,248 @@ +from __future__ import annotations + +import os +import typing + +from ._models import Headers +from ._types import CertTypes, HeaderTypes, TimeoutTypes +from ._urls import URL + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + +__all__ = ["Limits", "Proxy", "Timeout", "create_ssl_context"] + + +class UnsetType: + pass # pragma: no cover + + +UNSET = UnsetType() + + +def create_ssl_context( + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, +) -> ssl.SSLContext: + import ssl + import warnings + + import certifi + + if verify is True: + if trust_env and os.environ.get("SSL_CERT_FILE"): # pragma: nocover + ctx = ssl.create_default_context(cafile=os.environ["SSL_CERT_FILE"]) + elif trust_env and os.environ.get("SSL_CERT_DIR"): # pragma: nocover + ctx = ssl.create_default_context(capath=os.environ["SSL_CERT_DIR"]) + else: + # Default case... + ctx = ssl.create_default_context(cafile=certifi.where()) + elif verify is False: + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ctx.check_hostname = False + ctx.verify_mode = ssl.CERT_NONE + elif isinstance(verify, str): # pragma: nocover + message = ( + "`verify=` is deprecated. " + "Use `verify=ssl.create_default_context(cafile=...)` " + "or `verify=ssl.create_default_context(capath=...)` instead." + ) + warnings.warn(message, DeprecationWarning) + if os.path.isdir(verify): + return ssl.create_default_context(capath=verify) + return ssl.create_default_context(cafile=verify) + else: + ctx = verify + + if cert: # pragma: nocover + message = ( + "`cert=...` is deprecated. Use `verify=` instead," + "with `.load_cert_chain()` to configure the certificate chain." + ) + warnings.warn(message, DeprecationWarning) + if isinstance(cert, str): + ctx.load_cert_chain(cert) + else: + ctx.load_cert_chain(*cert) + + return ctx + + +class Timeout: + """ + Timeout configuration. + + **Usage**: + + Timeout(None) # No timeouts. + Timeout(5.0) # 5s timeout on all operations. + Timeout(None, connect=5.0) # 5s timeout on connect, no other timeouts. + Timeout(5.0, connect=10.0) # 10s timeout on connect. 5s timeout elsewhere. + Timeout(5.0, pool=None) # No timeout on acquiring connection from pool. + # 5s timeout elsewhere. + """ + + def __init__( + self, + timeout: TimeoutTypes | UnsetType = UNSET, + *, + connect: None | float | UnsetType = UNSET, + read: None | float | UnsetType = UNSET, + write: None | float | UnsetType = UNSET, + pool: None | float | UnsetType = UNSET, + ) -> None: + if isinstance(timeout, Timeout): + # Passed as a single explicit Timeout. + assert connect is UNSET + assert read is UNSET + assert write is UNSET + assert pool is UNSET + self.connect = timeout.connect # type: typing.Optional[float] + self.read = timeout.read # type: typing.Optional[float] + self.write = timeout.write # type: typing.Optional[float] + self.pool = timeout.pool # type: typing.Optional[float] + elif isinstance(timeout, tuple): + # Passed as a tuple. + self.connect = timeout[0] + self.read = timeout[1] + self.write = None if len(timeout) < 3 else timeout[2] + self.pool = None if len(timeout) < 4 else timeout[3] + elif not ( + isinstance(connect, UnsetType) + or isinstance(read, UnsetType) + or isinstance(write, UnsetType) + or isinstance(pool, UnsetType) + ): + self.connect = connect + self.read = read + self.write = write + self.pool = pool + else: + if isinstance(timeout, UnsetType): + raise ValueError( + "httpx.Timeout must either include a default, or set all " + "four parameters explicitly." + ) + self.connect = timeout if isinstance(connect, UnsetType) else connect + self.read = timeout if isinstance(read, UnsetType) else read + self.write = timeout if isinstance(write, UnsetType) else write + self.pool = timeout if isinstance(pool, UnsetType) else pool + + def as_dict(self) -> dict[str, float | None]: + return { + "connect": self.connect, + "read": self.read, + "write": self.write, + "pool": self.pool, + } + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, self.__class__) + and self.connect == other.connect + and self.read == other.read + and self.write == other.write + and self.pool == other.pool + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + if len({self.connect, self.read, self.write, self.pool}) == 1: + return f"{class_name}(timeout={self.connect})" + return ( + f"{class_name}(connect={self.connect}, " + f"read={self.read}, write={self.write}, pool={self.pool})" + ) + + +class Limits: + """ + Configuration for limits to various client behaviors. + + **Parameters:** + + * **max_connections** - The maximum number of concurrent connections that may be + established. + * **max_keepalive_connections** - Allow the connection pool to maintain + keep-alive connections below this point. Should be less than or equal + to `max_connections`. + * **keepalive_expiry** - Time limit on idle keep-alive connections in seconds. + """ + + def __init__( + self, + *, + max_connections: int | None = None, + max_keepalive_connections: int | None = None, + keepalive_expiry: float | None = 5.0, + ) -> None: + self.max_connections = max_connections + self.max_keepalive_connections = max_keepalive_connections + self.keepalive_expiry = keepalive_expiry + + def __eq__(self, other: typing.Any) -> bool: + return ( + isinstance(other, self.__class__) + and self.max_connections == other.max_connections + and self.max_keepalive_connections == other.max_keepalive_connections + and self.keepalive_expiry == other.keepalive_expiry + ) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + return ( + f"{class_name}(max_connections={self.max_connections}, " + f"max_keepalive_connections={self.max_keepalive_connections}, " + f"keepalive_expiry={self.keepalive_expiry})" + ) + + +class Proxy: + def __init__( + self, + url: URL | str, + *, + ssl_context: ssl.SSLContext | None = None, + auth: tuple[str, str] | None = None, + headers: HeaderTypes | None = None, + ) -> None: + url = URL(url) + headers = Headers(headers) + + if url.scheme not in ("http", "https", "socks5", "socks5h"): + raise ValueError(f"Unknown scheme for proxy URL {url!r}") + + if url.username or url.password: + # Remove any auth credentials from the URL. + auth = (url.username, url.password) + url = url.copy_with(username=None, password=None) + + self.url = url + self.auth = auth + self.headers = headers + self.ssl_context = ssl_context + + @property + def raw_auth(self) -> tuple[bytes, bytes] | None: + # The proxy authentication as raw bytes. + return ( + None + if self.auth is None + else (self.auth[0].encode("utf-8"), self.auth[1].encode("utf-8")) + ) + + def __repr__(self) -> str: + # The authentication is represented with the password component masked. + auth = (self.auth[0], "********") if self.auth else None + + # Build a nice concise representation. + url_str = f"{str(self.url)!r}" + auth_str = f", auth={auth!r}" if auth else "" + headers_str = f", headers={dict(self.headers)!r}" if self.headers else "" + return f"Proxy({url_str}{auth_str}{headers_str})" + + +DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0) +DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20) +DEFAULT_MAX_REDIRECTS = 20 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_content.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_content.py new file mode 100644 index 0000000000000000000000000000000000000000..6f479a0885f723b7395843d41164a87041820776 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_content.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +import inspect +import warnings +from json import dumps as json_dumps +from typing import ( + Any, + AsyncIterable, + AsyncIterator, + Iterable, + Iterator, + Mapping, +) +from urllib.parse import urlencode + +from ._exceptions import StreamClosed, StreamConsumed +from ._multipart import MultipartStream +from ._types import ( + AsyncByteStream, + RequestContent, + RequestData, + RequestFiles, + ResponseContent, + SyncByteStream, +) +from ._utils import peek_filelike_length, primitive_value_to_str + +__all__ = ["ByteStream"] + + +class ByteStream(AsyncByteStream, SyncByteStream): + def __init__(self, stream: bytes) -> None: + self._stream = stream + + def __iter__(self) -> Iterator[bytes]: + yield self._stream + + async def __aiter__(self) -> AsyncIterator[bytes]: + yield self._stream + + +class IteratorByteStream(SyncByteStream): + CHUNK_SIZE = 65_536 + + def __init__(self, stream: Iterable[bytes]) -> None: + self._stream = stream + self._is_stream_consumed = False + self._is_generator = inspect.isgenerator(stream) + + def __iter__(self) -> Iterator[bytes]: + if self._is_stream_consumed and self._is_generator: + raise StreamConsumed() + + self._is_stream_consumed = True + if hasattr(self._stream, "read"): + # File-like interfaces should use 'read' directly. + chunk = self._stream.read(self.CHUNK_SIZE) + while chunk: + yield chunk + chunk = self._stream.read(self.CHUNK_SIZE) + else: + # Otherwise iterate. + for part in self._stream: + yield part + + +class AsyncIteratorByteStream(AsyncByteStream): + CHUNK_SIZE = 65_536 + + def __init__(self, stream: AsyncIterable[bytes]) -> None: + self._stream = stream + self._is_stream_consumed = False + self._is_generator = inspect.isasyncgen(stream) + + async def __aiter__(self) -> AsyncIterator[bytes]: + if self._is_stream_consumed and self._is_generator: + raise StreamConsumed() + + self._is_stream_consumed = True + if hasattr(self._stream, "aread"): + # File-like interfaces should use 'aread' directly. + chunk = await self._stream.aread(self.CHUNK_SIZE) + while chunk: + yield chunk + chunk = await self._stream.aread(self.CHUNK_SIZE) + else: + # Otherwise iterate. + async for part in self._stream: + yield part + + +class UnattachedStream(AsyncByteStream, SyncByteStream): + """ + If a request or response is serialized using pickle, then it is no longer + attached to a stream for I/O purposes. Any stream operations should result + in `httpx.StreamClosed`. + """ + + def __iter__(self) -> Iterator[bytes]: + raise StreamClosed() + + async def __aiter__(self) -> AsyncIterator[bytes]: + raise StreamClosed() + yield b"" # pragma: no cover + + +def encode_content( + content: str | bytes | Iterable[bytes] | AsyncIterable[bytes], +) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: + if isinstance(content, (bytes, str)): + body = content.encode("utf-8") if isinstance(content, str) else content + content_length = len(body) + headers = {"Content-Length": str(content_length)} if body else {} + return headers, ByteStream(body) + + elif isinstance(content, Iterable) and not isinstance(content, dict): + # `not isinstance(content, dict)` is a bit oddly specific, but it + # catches a case that's easy for users to make in error, and would + # otherwise pass through here, like any other bytes-iterable, + # because `dict` happens to be iterable. See issue #2491. + content_length_or_none = peek_filelike_length(content) + + if content_length_or_none is None: + headers = {"Transfer-Encoding": "chunked"} + else: + headers = {"Content-Length": str(content_length_or_none)} + return headers, IteratorByteStream(content) # type: ignore + + elif isinstance(content, AsyncIterable): + headers = {"Transfer-Encoding": "chunked"} + return headers, AsyncIteratorByteStream(content) + + raise TypeError(f"Unexpected type for 'content', {type(content)!r}") + + +def encode_urlencoded_data( + data: RequestData, +) -> tuple[dict[str, str], ByteStream]: + plain_data = [] + for key, value in data.items(): + if isinstance(value, (list, tuple)): + plain_data.extend([(key, primitive_value_to_str(item)) for item in value]) + else: + plain_data.append((key, primitive_value_to_str(value))) + body = urlencode(plain_data, doseq=True).encode("utf-8") + content_length = str(len(body)) + content_type = "application/x-www-form-urlencoded" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_multipart_data( + data: RequestData, files: RequestFiles, boundary: bytes | None +) -> tuple[dict[str, str], MultipartStream]: + multipart = MultipartStream(data=data, files=files, boundary=boundary) + headers = multipart.get_headers() + return headers, multipart + + +def encode_text(text: str) -> tuple[dict[str, str], ByteStream]: + body = text.encode("utf-8") + content_length = str(len(body)) + content_type = "text/plain; charset=utf-8" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_html(html: str) -> tuple[dict[str, str], ByteStream]: + body = html.encode("utf-8") + content_length = str(len(body)) + content_type = "text/html; charset=utf-8" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_json(json: Any) -> tuple[dict[str, str], ByteStream]: + body = json_dumps( + json, ensure_ascii=False, separators=(",", ":"), allow_nan=False + ).encode("utf-8") + content_length = str(len(body)) + content_type = "application/json" + headers = {"Content-Length": content_length, "Content-Type": content_type} + return headers, ByteStream(body) + + +def encode_request( + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: Any | None = None, + boundary: bytes | None = None, +) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: + """ + Handles encoding the given `content`, `data`, `files`, and `json`, + returning a two-tuple of (, ). + """ + if data is not None and not isinstance(data, Mapping): + # We prefer to separate `content=` + # for raw request content, and `data=
` for url encoded or + # multipart form content. + # + # However for compat with requests, we *do* still support + # `data=` usages. We deal with that case here, treating it + # as if `content=<...>` had been supplied instead. + message = "Use 'content=<...>' to upload raw bytes/text content." + warnings.warn(message, DeprecationWarning, stacklevel=2) + return encode_content(data) + + if content is not None: + return encode_content(content) + elif files: + return encode_multipart_data(data or {}, files, boundary) + elif data: + return encode_urlencoded_data(data) + elif json is not None: + return encode_json(json) + + return {}, ByteStream(b"") + + +def encode_response( + content: ResponseContent | None = None, + text: str | None = None, + html: str | None = None, + json: Any | None = None, +) -> tuple[dict[str, str], SyncByteStream | AsyncByteStream]: + """ + Handles encoding the given `content`, returning a two-tuple of + (, ). + """ + if content is not None: + return encode_content(content) + elif text is not None: + return encode_text(text) + elif html is not None: + return encode_html(html) + elif json is not None: + return encode_json(json) + + return {}, ByteStream(b"") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_decoders.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_decoders.py new file mode 100644 index 0000000000000000000000000000000000000000..899dfada878e1181fca6d3c75a79526a076abb9e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_decoders.py @@ -0,0 +1,393 @@ +""" +Handlers for Content-Encoding. + +See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding +""" + +from __future__ import annotations + +import codecs +import io +import typing +import zlib + +from ._exceptions import DecodingError + +# Brotli support is optional +try: + # The C bindings in `brotli` are recommended for CPython. + import brotli +except ImportError: # pragma: no cover + try: + # The CFFI bindings in `brotlicffi` are recommended for PyPy + # and other environments. + import brotlicffi as brotli + except ImportError: + brotli = None + + +# Zstandard support is optional +try: + import zstandard +except ImportError: # pragma: no cover + zstandard = None # type: ignore + + +class ContentDecoder: + def decode(self, data: bytes) -> bytes: + raise NotImplementedError() # pragma: no cover + + def flush(self) -> bytes: + raise NotImplementedError() # pragma: no cover + + +class IdentityDecoder(ContentDecoder): + """ + Handle unencoded data. + """ + + def decode(self, data: bytes) -> bytes: + return data + + def flush(self) -> bytes: + return b"" + + +class DeflateDecoder(ContentDecoder): + """ + Handle 'deflate' decoding. + + See: https://stackoverflow.com/questions/1838699 + """ + + def __init__(self) -> None: + self.first_attempt = True + self.decompressor = zlib.decompressobj() + + def decode(self, data: bytes) -> bytes: + was_first_attempt = self.first_attempt + self.first_attempt = False + try: + return self.decompressor.decompress(data) + except zlib.error as exc: + if was_first_attempt: + self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS) + return self.decode(data) + raise DecodingError(str(exc)) from exc + + def flush(self) -> bytes: + try: + return self.decompressor.flush() + except zlib.error as exc: # pragma: no cover + raise DecodingError(str(exc)) from exc + + +class GZipDecoder(ContentDecoder): + """ + Handle 'gzip' decoding. + + See: https://stackoverflow.com/questions/1838699 + """ + + def __init__(self) -> None: + self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16) + + def decode(self, data: bytes) -> bytes: + try: + return self.decompressor.decompress(data) + except zlib.error as exc: + raise DecodingError(str(exc)) from exc + + def flush(self) -> bytes: + try: + return self.decompressor.flush() + except zlib.error as exc: # pragma: no cover + raise DecodingError(str(exc)) from exc + + +class BrotliDecoder(ContentDecoder): + """ + Handle 'brotli' decoding. + + Requires `pip install brotlipy`. See: https://brotlipy.readthedocs.io/ + or `pip install brotli`. See https://github.com/google/brotli + Supports both 'brotlipy' and 'Brotli' packages since they share an import + name. The top branches are for 'brotlipy' and bottom branches for 'Brotli' + """ + + def __init__(self) -> None: + if brotli is None: # pragma: no cover + raise ImportError( + "Using 'BrotliDecoder', but neither of the 'brotlicffi' or 'brotli' " + "packages have been installed. " + "Make sure to install httpx using `pip install httpx[brotli]`." + ) from None + + self.decompressor = brotli.Decompressor() + self.seen_data = False + self._decompress: typing.Callable[[bytes], bytes] + if hasattr(self.decompressor, "decompress"): + # The 'brotlicffi' package. + self._decompress = self.decompressor.decompress # pragma: no cover + else: + # The 'brotli' package. + self._decompress = self.decompressor.process # pragma: no cover + + def decode(self, data: bytes) -> bytes: + if not data: + return b"" + self.seen_data = True + try: + return self._decompress(data) + except brotli.error as exc: + raise DecodingError(str(exc)) from exc + + def flush(self) -> bytes: + if not self.seen_data: + return b"" + try: + if hasattr(self.decompressor, "finish"): + # Only available in the 'brotlicffi' package. + + # As the decompressor decompresses eagerly, this + # will never actually emit any data. However, it will potentially throw + # errors if a truncated or damaged data stream has been used. + self.decompressor.finish() # pragma: no cover + return b"" + except brotli.error as exc: # pragma: no cover + raise DecodingError(str(exc)) from exc + + +class ZStandardDecoder(ContentDecoder): + """ + Handle 'zstd' RFC 8878 decoding. + + Requires `pip install zstandard`. + Can be installed as a dependency of httpx using `pip install httpx[zstd]`. + """ + + # inspired by the ZstdDecoder implementation in urllib3 + def __init__(self) -> None: + if zstandard is None: # pragma: no cover + raise ImportError( + "Using 'ZStandardDecoder', ..." + "Make sure to install httpx using `pip install httpx[zstd]`." + ) from None + + self.decompressor = zstandard.ZstdDecompressor().decompressobj() + self.seen_data = False + + def decode(self, data: bytes) -> bytes: + assert zstandard is not None + self.seen_data = True + output = io.BytesIO() + try: + output.write(self.decompressor.decompress(data)) + while self.decompressor.eof and self.decompressor.unused_data: + unused_data = self.decompressor.unused_data + self.decompressor = zstandard.ZstdDecompressor().decompressobj() + output.write(self.decompressor.decompress(unused_data)) + except zstandard.ZstdError as exc: + raise DecodingError(str(exc)) from exc + return output.getvalue() + + def flush(self) -> bytes: + if not self.seen_data: + return b"" + ret = self.decompressor.flush() # note: this is a no-op + if not self.decompressor.eof: + raise DecodingError("Zstandard data is incomplete") # pragma: no cover + return bytes(ret) + + +class MultiDecoder(ContentDecoder): + """ + Handle the case where multiple encodings have been applied. + """ + + def __init__(self, children: typing.Sequence[ContentDecoder]) -> None: + """ + 'children' should be a sequence of decoders in the order in which + each was applied. + """ + # Note that we reverse the order for decoding. + self.children = list(reversed(children)) + + def decode(self, data: bytes) -> bytes: + for child in self.children: + data = child.decode(data) + return data + + def flush(self) -> bytes: + data = b"" + for child in self.children: + data = child.decode(data) + child.flush() + return data + + +class ByteChunker: + """ + Handles returning byte content in fixed-size chunks. + """ + + def __init__(self, chunk_size: int | None = None) -> None: + self._buffer = io.BytesIO() + self._chunk_size = chunk_size + + def decode(self, content: bytes) -> list[bytes]: + if self._chunk_size is None: + return [content] if content else [] + + self._buffer.write(content) + if self._buffer.tell() >= self._chunk_size: + value = self._buffer.getvalue() + chunks = [ + value[i : i + self._chunk_size] + for i in range(0, len(value), self._chunk_size) + ] + if len(chunks[-1]) == self._chunk_size: + self._buffer.seek(0) + self._buffer.truncate() + return chunks + else: + self._buffer.seek(0) + self._buffer.write(chunks[-1]) + self._buffer.truncate() + return chunks[:-1] + else: + return [] + + def flush(self) -> list[bytes]: + value = self._buffer.getvalue() + self._buffer.seek(0) + self._buffer.truncate() + return [value] if value else [] + + +class TextChunker: + """ + Handles returning text content in fixed-size chunks. + """ + + def __init__(self, chunk_size: int | None = None) -> None: + self._buffer = io.StringIO() + self._chunk_size = chunk_size + + def decode(self, content: str) -> list[str]: + if self._chunk_size is None: + return [content] if content else [] + + self._buffer.write(content) + if self._buffer.tell() >= self._chunk_size: + value = self._buffer.getvalue() + chunks = [ + value[i : i + self._chunk_size] + for i in range(0, len(value), self._chunk_size) + ] + if len(chunks[-1]) == self._chunk_size: + self._buffer.seek(0) + self._buffer.truncate() + return chunks + else: + self._buffer.seek(0) + self._buffer.write(chunks[-1]) + self._buffer.truncate() + return chunks[:-1] + else: + return [] + + def flush(self) -> list[str]: + value = self._buffer.getvalue() + self._buffer.seek(0) + self._buffer.truncate() + return [value] if value else [] + + +class TextDecoder: + """ + Handles incrementally decoding bytes into text + """ + + def __init__(self, encoding: str = "utf-8") -> None: + self.decoder = codecs.getincrementaldecoder(encoding)(errors="replace") + + def decode(self, data: bytes) -> str: + return self.decoder.decode(data) + + def flush(self) -> str: + return self.decoder.decode(b"", True) + + +class LineDecoder: + """ + Handles incrementally reading lines from text. + + Has the same behaviour as the stdllib splitlines, + but handling the input iteratively. + """ + + def __init__(self) -> None: + self.buffer: list[str] = [] + self.trailing_cr: bool = False + + def decode(self, text: str) -> list[str]: + # See https://docs.python.org/3/library/stdtypes.html#str.splitlines + NEWLINE_CHARS = "\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029" + + # We always push a trailing `\r` into the next decode iteration. + if self.trailing_cr: + text = "\r" + text + self.trailing_cr = False + if text.endswith("\r"): + self.trailing_cr = True + text = text[:-1] + + if not text: + # NOTE: the edge case input of empty text doesn't occur in practice, + # because other httpx internals filter out this value + return [] # pragma: no cover + + trailing_newline = text[-1] in NEWLINE_CHARS + lines = text.splitlines() + + if len(lines) == 1 and not trailing_newline: + # No new lines, buffer the input and continue. + self.buffer.append(lines[0]) + return [] + + if self.buffer: + # Include any existing buffer in the first portion of the + # splitlines result. + lines = ["".join(self.buffer) + lines[0]] + lines[1:] + self.buffer = [] + + if not trailing_newline: + # If the last segment of splitlines is not newline terminated, + # then drop it from our output and start a new buffer. + self.buffer = [lines.pop()] + + return lines + + def flush(self) -> list[str]: + if not self.buffer and not self.trailing_cr: + return [] + + lines = ["".join(self.buffer)] + self.buffer = [] + self.trailing_cr = False + return lines + + +SUPPORTED_DECODERS = { + "identity": IdentityDecoder, + "gzip": GZipDecoder, + "deflate": DeflateDecoder, + "br": BrotliDecoder, + "zstd": ZStandardDecoder, +} + + +if brotli is None: + SUPPORTED_DECODERS.pop("br") # pragma: no cover +if zstandard is None: + SUPPORTED_DECODERS.pop("zstd") # pragma: no cover diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_exceptions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..77f45a6d3986d15626fc8a5fd459d6a3e0fbe466 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_exceptions.py @@ -0,0 +1,379 @@ +""" +Our exception hierarchy: + +* HTTPError + x RequestError + + TransportError + - TimeoutException + · ConnectTimeout + · ReadTimeout + · WriteTimeout + · PoolTimeout + - NetworkError + · ConnectError + · ReadError + · WriteError + · CloseError + - ProtocolError + · LocalProtocolError + · RemoteProtocolError + - ProxyError + - UnsupportedProtocol + + DecodingError + + TooManyRedirects + x HTTPStatusError +* InvalidURL +* CookieConflict +* StreamError + x StreamConsumed + x StreamClosed + x ResponseNotRead + x RequestNotRead +""" + +from __future__ import annotations + +import contextlib +import typing + +if typing.TYPE_CHECKING: + from ._models import Request, Response # pragma: no cover + +__all__ = [ + "CloseError", + "ConnectError", + "ConnectTimeout", + "CookieConflict", + "DecodingError", + "HTTPError", + "HTTPStatusError", + "InvalidURL", + "LocalProtocolError", + "NetworkError", + "PoolTimeout", + "ProtocolError", + "ProxyError", + "ReadError", + "ReadTimeout", + "RemoteProtocolError", + "RequestError", + "RequestNotRead", + "ResponseNotRead", + "StreamClosed", + "StreamConsumed", + "StreamError", + "TimeoutException", + "TooManyRedirects", + "TransportError", + "UnsupportedProtocol", + "WriteError", + "WriteTimeout", +] + + +class HTTPError(Exception): + """ + Base class for `RequestError` and `HTTPStatusError`. + + Useful for `try...except` blocks when issuing a request, + and then calling `.raise_for_status()`. + + For example: + + ``` + try: + response = httpx.get("https://www.example.com") + response.raise_for_status() + except httpx.HTTPError as exc: + print(f"HTTP Exception for {exc.request.url} - {exc}") + ``` + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + self._request: Request | None = None + + @property + def request(self) -> Request: + if self._request is None: + raise RuntimeError("The .request property has not been set.") + return self._request + + @request.setter + def request(self, request: Request) -> None: + self._request = request + + +class RequestError(HTTPError): + """ + Base class for all exceptions that may occur when issuing a `.request()`. + """ + + def __init__(self, message: str, *, request: Request | None = None) -> None: + super().__init__(message) + # At the point an exception is raised we won't typically have a request + # instance to associate it with. + # + # The 'request_context' context manager is used within the Client and + # Response methods in order to ensure that any raised exceptions + # have a `.request` property set on them. + self._request = request + + +class TransportError(RequestError): + """ + Base class for all exceptions that occur at the level of the Transport API. + """ + + +# Timeout exceptions... + + +class TimeoutException(TransportError): + """ + The base class for timeout errors. + + An operation has timed out. + """ + + +class ConnectTimeout(TimeoutException): + """ + Timed out while connecting to the host. + """ + + +class ReadTimeout(TimeoutException): + """ + Timed out while receiving data from the host. + """ + + +class WriteTimeout(TimeoutException): + """ + Timed out while sending data to the host. + """ + + +class PoolTimeout(TimeoutException): + """ + Timed out waiting to acquire a connection from the pool. + """ + + +# Core networking exceptions... + + +class NetworkError(TransportError): + """ + The base class for network-related errors. + + An error occurred while interacting with the network. + """ + + +class ReadError(NetworkError): + """ + Failed to receive data from the network. + """ + + +class WriteError(NetworkError): + """ + Failed to send data through the network. + """ + + +class ConnectError(NetworkError): + """ + Failed to establish a connection. + """ + + +class CloseError(NetworkError): + """ + Failed to close a connection. + """ + + +# Other transport exceptions... + + +class ProxyError(TransportError): + """ + An error occurred while establishing a proxy connection. + """ + + +class UnsupportedProtocol(TransportError): + """ + Attempted to make a request to an unsupported protocol. + + For example issuing a request to `ftp://www.example.com`. + """ + + +class ProtocolError(TransportError): + """ + The protocol was violated. + """ + + +class LocalProtocolError(ProtocolError): + """ + A protocol was violated by the client. + + For example if the user instantiated a `Request` instance explicitly, + failed to include the mandatory `Host:` header, and then issued it directly + using `client.send()`. + """ + + +class RemoteProtocolError(ProtocolError): + """ + The protocol was violated by the server. + + For example, returning malformed HTTP. + """ + + +# Other request exceptions... + + +class DecodingError(RequestError): + """ + Decoding of the response failed, due to a malformed encoding. + """ + + +class TooManyRedirects(RequestError): + """ + Too many redirects. + """ + + +# Client errors + + +class HTTPStatusError(HTTPError): + """ + The response had an error HTTP status of 4xx or 5xx. + + May be raised when calling `response.raise_for_status()` + """ + + def __init__(self, message: str, *, request: Request, response: Response) -> None: + super().__init__(message) + self.request = request + self.response = response + + +class InvalidURL(Exception): + """ + URL is improperly formed or cannot be parsed. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +class CookieConflict(Exception): + """ + Attempted to lookup a cookie by name, but multiple cookies existed. + + Can occur when calling `response.cookies.get(...)`. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +# Stream exceptions... + +# These may occur as the result of a programming error, by accessing +# the request/response stream in an invalid manner. + + +class StreamError(RuntimeError): + """ + The base class for stream exceptions. + + The developer made an error in accessing the request stream in + an invalid way. + """ + + def __init__(self, message: str) -> None: + super().__init__(message) + + +class StreamConsumed(StreamError): + """ + Attempted to read or stream content, but the content has already + been streamed. + """ + + def __init__(self) -> None: + message = ( + "Attempted to read or stream some content, but the content has " + "already been streamed. For requests, this could be due to passing " + "a generator as request content, and then receiving a redirect " + "response or a secondary request as part of an authentication flow." + "For responses, this could be due to attempting to stream the response " + "content more than once." + ) + super().__init__(message) + + +class StreamClosed(StreamError): + """ + Attempted to read or stream response content, but the request has been + closed. + """ + + def __init__(self) -> None: + message = ( + "Attempted to read or stream content, but the stream has " "been closed." + ) + super().__init__(message) + + +class ResponseNotRead(StreamError): + """ + Attempted to access streaming response content, without having called `read()`. + """ + + def __init__(self) -> None: + message = ( + "Attempted to access streaming response content," + " without having called `read()`." + ) + super().__init__(message) + + +class RequestNotRead(StreamError): + """ + Attempted to access streaming request content, without having called `read()`. + """ + + def __init__(self) -> None: + message = ( + "Attempted to access streaming request content," + " without having called `read()`." + ) + super().__init__(message) + + +@contextlib.contextmanager +def request_context( + request: Request | None = None, +) -> typing.Iterator[None]: + """ + A context manager that can be used to attach the given request context + to any `RequestError` exceptions that are raised within the block. + """ + try: + yield + except RequestError as exc: + if request is not None: + exc.request = request + raise exc diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_main.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_main.py new file mode 100644 index 0000000000000000000000000000000000000000..cffa4bb7db0f930f4db56653a061c4d7400ba4e6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_main.py @@ -0,0 +1,506 @@ +from __future__ import annotations + +import functools +import json +import sys +import typing + +import click +import pygments.lexers +import pygments.util +import rich.console +import rich.markup +import rich.progress +import rich.syntax +import rich.table + +from ._client import Client +from ._exceptions import RequestError +from ._models import Response +from ._status_codes import codes + +if typing.TYPE_CHECKING: + import httpcore # pragma: no cover + + +def print_help() -> None: + console = rich.console.Console() + + console.print("[bold]HTTPX :butterfly:", justify="center") + console.print() + console.print("A next generation HTTP client.", justify="center") + console.print() + console.print( + "Usage: [bold]httpx[/bold] [cyan] [OPTIONS][/cyan] ", justify="left" + ) + console.print() + + table = rich.table.Table.grid(padding=1, pad_edge=True) + table.add_column("Parameter", no_wrap=True, justify="left", style="bold") + table.add_column("Description") + table.add_row( + "-m, --method [cyan]METHOD", + "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD.\n" + "[Default: GET, or POST if a request body is included]", + ) + table.add_row( + "-p, --params [cyan] ...", + "Query parameters to include in the request URL.", + ) + table.add_row( + "-c, --content [cyan]TEXT", "Byte content to include in the request body." + ) + table.add_row( + "-d, --data [cyan] ...", "Form data to include in the request body." + ) + table.add_row( + "-f, --files [cyan] ...", + "Form files to include in the request body.", + ) + table.add_row("-j, --json [cyan]TEXT", "JSON data to include in the request body.") + table.add_row( + "-h, --headers [cyan] ...", + "Include additional HTTP headers in the request.", + ) + table.add_row( + "--cookies [cyan] ...", "Cookies to include in the request." + ) + table.add_row( + "--auth [cyan]", + "Username and password to include in the request. Specify '-' for the password" + " to use a password prompt. Note that using --verbose/-v will expose" + " the Authorization header, including the password encoding" + " in a trivially reversible format.", + ) + + table.add_row( + "--proxy [cyan]URL", + "Send the request via a proxy. Should be the URL giving the proxy address.", + ) + + table.add_row( + "--timeout [cyan]FLOAT", + "Timeout value to use for network operations, such as establishing the" + " connection, reading some data, etc... [Default: 5.0]", + ) + + table.add_row("--follow-redirects", "Automatically follow redirects.") + table.add_row("--no-verify", "Disable SSL verification.") + table.add_row( + "--http2", "Send the request using HTTP/2, if the remote server supports it." + ) + + table.add_row( + "--download [cyan]FILE", + "Save the response content as a file, rather than displaying it.", + ) + + table.add_row("-v, --verbose", "Verbose output. Show request as well as response.") + table.add_row("--help", "Show this message and exit.") + console.print(table) + + +def get_lexer_for_response(response: Response) -> str: + content_type = response.headers.get("Content-Type") + if content_type is not None: + mime_type, _, _ = content_type.partition(";") + try: + return typing.cast( + str, pygments.lexers.get_lexer_for_mimetype(mime_type.strip()).name + ) + except pygments.util.ClassNotFound: # pragma: no cover + pass + return "" # pragma: no cover + + +def format_request_headers(request: httpcore.Request, http2: bool = False) -> str: + version = "HTTP/2" if http2 else "HTTP/1.1" + headers = [ + (name.lower() if http2 else name, value) for name, value in request.headers + ] + method = request.method.decode("ascii") + target = request.url.target.decode("ascii") + lines = [f"{method} {target} {version}"] + [ + f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers + ] + return "\n".join(lines) + + +def format_response_headers( + http_version: bytes, + status: int, + reason_phrase: bytes | None, + headers: list[tuple[bytes, bytes]], +) -> str: + version = http_version.decode("ascii") + reason = ( + codes.get_reason_phrase(status) + if reason_phrase is None + else reason_phrase.decode("ascii") + ) + lines = [f"{version} {status} {reason}"] + [ + f"{name.decode('ascii')}: {value.decode('ascii')}" for name, value in headers + ] + return "\n".join(lines) + + +def print_request_headers(request: httpcore.Request, http2: bool = False) -> None: + console = rich.console.Console() + http_text = format_request_headers(request, http2=http2) + syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + + +def print_response_headers( + http_version: bytes, + status: int, + reason_phrase: bytes | None, + headers: list[tuple[bytes, bytes]], +) -> None: + console = rich.console.Console() + http_text = format_response_headers(http_version, status, reason_phrase, headers) + syntax = rich.syntax.Syntax(http_text, "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + syntax = rich.syntax.Syntax("", "http", theme="ansi_dark", word_wrap=True) + console.print(syntax) + + +def print_response(response: Response) -> None: + console = rich.console.Console() + lexer_name = get_lexer_for_response(response) + if lexer_name: + if lexer_name.lower() == "json": + try: + data = response.json() + text = json.dumps(data, indent=4) + except ValueError: # pragma: no cover + text = response.text + else: + text = response.text + + syntax = rich.syntax.Syntax(text, lexer_name, theme="ansi_dark", word_wrap=True) + console.print(syntax) + else: + console.print(f"<{len(response.content)} bytes of binary data>") + + +_PCTRTT = typing.Tuple[typing.Tuple[str, str], ...] +_PCTRTTT = typing.Tuple[_PCTRTT, ...] +_PeerCertRetDictType = typing.Dict[str, typing.Union[str, _PCTRTTT, _PCTRTT]] + + +def format_certificate(cert: _PeerCertRetDictType) -> str: # pragma: no cover + lines = [] + for key, value in cert.items(): + if isinstance(value, (list, tuple)): + lines.append(f"* {key}:") + for item in value: + if key in ("subject", "issuer"): + for sub_item in item: + lines.append(f"* {sub_item[0]}: {sub_item[1]!r}") + elif isinstance(item, tuple) and len(item) == 2: + lines.append(f"* {item[0]}: {item[1]!r}") + else: + lines.append(f"* {item!r}") + else: + lines.append(f"* {key}: {value!r}") + return "\n".join(lines) + + +def trace( + name: str, info: typing.Mapping[str, typing.Any], verbose: bool = False +) -> None: + console = rich.console.Console() + if name == "connection.connect_tcp.started" and verbose: + host = info["host"] + console.print(f"* Connecting to {host!r}") + elif name == "connection.connect_tcp.complete" and verbose: + stream = info["return_value"] + server_addr = stream.get_extra_info("server_addr") + console.print(f"* Connected to {server_addr[0]!r} on port {server_addr[1]}") + elif name == "connection.start_tls.complete" and verbose: # pragma: no cover + stream = info["return_value"] + ssl_object = stream.get_extra_info("ssl_object") + version = ssl_object.version() + cipher = ssl_object.cipher() + server_cert = ssl_object.getpeercert() + alpn = ssl_object.selected_alpn_protocol() + console.print(f"* SSL established using {version!r} / {cipher[0]!r}") + console.print(f"* Selected ALPN protocol: {alpn!r}") + if server_cert: + console.print("* Server certificate:") + console.print(format_certificate(server_cert)) + elif name == "http11.send_request_headers.started" and verbose: + request = info["request"] + print_request_headers(request, http2=False) + elif name == "http2.send_request_headers.started" and verbose: # pragma: no cover + request = info["request"] + print_request_headers(request, http2=True) + elif name == "http11.receive_response_headers.complete": + http_version, status, reason_phrase, headers = info["return_value"] + print_response_headers(http_version, status, reason_phrase, headers) + elif name == "http2.receive_response_headers.complete": # pragma: no cover + status, headers = info["return_value"] + http_version = b"HTTP/2" + reason_phrase = None + print_response_headers(http_version, status, reason_phrase, headers) + + +def download_response(response: Response, download: typing.BinaryIO) -> None: + console = rich.console.Console() + console.print() + content_length = response.headers.get("Content-Length") + with rich.progress.Progress( + "[progress.description]{task.description}", + "[progress.percentage]{task.percentage:>3.0f}%", + rich.progress.BarColumn(bar_width=None), + rich.progress.DownloadColumn(), + rich.progress.TransferSpeedColumn(), + ) as progress: + description = f"Downloading [bold]{rich.markup.escape(download.name)}" + download_task = progress.add_task( + description, + total=int(content_length or 0), + start=content_length is not None, + ) + for chunk in response.iter_bytes(): + download.write(chunk) + progress.update(download_task, completed=response.num_bytes_downloaded) + + +def validate_json( + ctx: click.Context, + param: click.Option | click.Parameter, + value: typing.Any, +) -> typing.Any: + if value is None: + return None + + try: + return json.loads(value) + except json.JSONDecodeError: # pragma: no cover + raise click.BadParameter("Not valid JSON") + + +def validate_auth( + ctx: click.Context, + param: click.Option | click.Parameter, + value: typing.Any, +) -> typing.Any: + if value == (None, None): + return None + + username, password = value + if password == "-": # pragma: no cover + password = click.prompt("Password", hide_input=True) + return (username, password) + + +def handle_help( + ctx: click.Context, + param: click.Option | click.Parameter, + value: typing.Any, +) -> None: + if not value or ctx.resilient_parsing: + return + + print_help() + ctx.exit() + + +@click.command(add_help_option=False) +@click.argument("url", type=str) +@click.option( + "--method", + "-m", + "method", + type=str, + help=( + "Request method, such as GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD. " + "[Default: GET, or POST if a request body is included]" + ), +) +@click.option( + "--params", + "-p", + "params", + type=(str, str), + multiple=True, + help="Query parameters to include in the request URL.", +) +@click.option( + "--content", + "-c", + "content", + type=str, + help="Byte content to include in the request body.", +) +@click.option( + "--data", + "-d", + "data", + type=(str, str), + multiple=True, + help="Form data to include in the request body.", +) +@click.option( + "--files", + "-f", + "files", + type=(str, click.File(mode="rb")), + multiple=True, + help="Form files to include in the request body.", +) +@click.option( + "--json", + "-j", + "json", + type=str, + callback=validate_json, + help="JSON data to include in the request body.", +) +@click.option( + "--headers", + "-h", + "headers", + type=(str, str), + multiple=True, + help="Include additional HTTP headers in the request.", +) +@click.option( + "--cookies", + "cookies", + type=(str, str), + multiple=True, + help="Cookies to include in the request.", +) +@click.option( + "--auth", + "auth", + type=(str, str), + default=(None, None), + callback=validate_auth, + help=( + "Username and password to include in the request. " + "Specify '-' for the password to use a password prompt. " + "Note that using --verbose/-v will expose the Authorization header, " + "including the password encoding in a trivially reversible format." + ), +) +@click.option( + "--proxy", + "proxy", + type=str, + default=None, + help="Send the request via a proxy. Should be the URL giving the proxy address.", +) +@click.option( + "--timeout", + "timeout", + type=float, + default=5.0, + help=( + "Timeout value to use for network operations, such as establishing the " + "connection, reading some data, etc... [Default: 5.0]" + ), +) +@click.option( + "--follow-redirects", + "follow_redirects", + is_flag=True, + default=False, + help="Automatically follow redirects.", +) +@click.option( + "--no-verify", + "verify", + is_flag=True, + default=True, + help="Disable SSL verification.", +) +@click.option( + "--http2", + "http2", + type=bool, + is_flag=True, + default=False, + help="Send the request using HTTP/2, if the remote server supports it.", +) +@click.option( + "--download", + type=click.File("wb"), + help="Save the response content as a file, rather than displaying it.", +) +@click.option( + "--verbose", + "-v", + type=bool, + is_flag=True, + default=False, + help="Verbose. Show request as well as response.", +) +@click.option( + "--help", + is_flag=True, + is_eager=True, + expose_value=False, + callback=handle_help, + help="Show this message and exit.", +) +def main( + url: str, + method: str, + params: list[tuple[str, str]], + content: str, + data: list[tuple[str, str]], + files: list[tuple[str, click.File]], + json: str, + headers: list[tuple[str, str]], + cookies: list[tuple[str, str]], + auth: tuple[str, str] | None, + proxy: str, + timeout: float, + follow_redirects: bool, + verify: bool, + http2: bool, + download: typing.BinaryIO | None, + verbose: bool, +) -> None: + """ + An HTTP command line client. + Sends a request and displays the response. + """ + if not method: + method = "POST" if content or data or files or json else "GET" + + try: + with Client(proxy=proxy, timeout=timeout, http2=http2, verify=verify) as client: + with client.stream( + method, + url, + params=list(params), + content=content, + data=dict(data), + files=files, # type: ignore + json=json, + headers=headers, + cookies=dict(cookies), + auth=auth, + follow_redirects=follow_redirects, + extensions={"trace": functools.partial(trace, verbose=verbose)}, + ) as response: + if download is not None: + download_response(response, download) + else: + response.read() + if response.content: + print_response(response) + + except RequestError as exc: + console = rich.console.Console() + console.print(f"[red]{type(exc).__name__}[/red]: {exc}") + sys.exit(1) + + sys.exit(0 if response.is_success else 1) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_models.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..67d74bf86bfc80e22d9a4a3153572845accd9039 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_models.py @@ -0,0 +1,1277 @@ +from __future__ import annotations + +import codecs +import datetime +import email.message +import json as jsonlib +import re +import typing +import urllib.request +from collections.abc import Mapping +from http.cookiejar import Cookie, CookieJar + +from ._content import ByteStream, UnattachedStream, encode_request, encode_response +from ._decoders import ( + SUPPORTED_DECODERS, + ByteChunker, + ContentDecoder, + IdentityDecoder, + LineDecoder, + MultiDecoder, + TextChunker, + TextDecoder, +) +from ._exceptions import ( + CookieConflict, + HTTPStatusError, + RequestNotRead, + ResponseNotRead, + StreamClosed, + StreamConsumed, + request_context, +) +from ._multipart import get_multipart_boundary_from_content_type +from ._status_codes import codes +from ._types import ( + AsyncByteStream, + CookieTypes, + HeaderTypes, + QueryParamTypes, + RequestContent, + RequestData, + RequestExtensions, + RequestFiles, + ResponseContent, + ResponseExtensions, + SyncByteStream, +) +from ._urls import URL +from ._utils import to_bytes_or_str, to_str + +__all__ = ["Cookies", "Headers", "Request", "Response"] + +SENSITIVE_HEADERS = {"authorization", "proxy-authorization"} + + +def _is_known_encoding(encoding: str) -> bool: + """ + Return `True` if `encoding` is a known codec. + """ + try: + codecs.lookup(encoding) + except LookupError: + return False + return True + + +def _normalize_header_key(key: str | bytes, encoding: str | None = None) -> bytes: + """ + Coerce str/bytes into a strictly byte-wise HTTP header key. + """ + return key if isinstance(key, bytes) else key.encode(encoding or "ascii") + + +def _normalize_header_value(value: str | bytes, encoding: str | None = None) -> bytes: + """ + Coerce str/bytes into a strictly byte-wise HTTP header value. + """ + if isinstance(value, bytes): + return value + if not isinstance(value, str): + raise TypeError(f"Header value must be str or bytes, not {type(value)}") + return value.encode(encoding or "ascii") + + +def _parse_content_type_charset(content_type: str) -> str | None: + # We used to use `cgi.parse_header()` here, but `cgi` became a dead battery. + # See: https://peps.python.org/pep-0594/#cgi + msg = email.message.Message() + msg["content-type"] = content_type + return msg.get_content_charset(failobj=None) + + +def _parse_header_links(value: str) -> list[dict[str, str]]: + """ + Returns a list of parsed link headers, for more info see: + https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link + The generic syntax of those is: + Link: < uri-reference >; param1=value1; param2="value2" + So for instance: + Link; '; type="image/jpeg",;' + would return + [ + {"url": "http:/.../front.jpeg", "type": "image/jpeg"}, + {"url": "http://.../back.jpeg"}, + ] + :param value: HTTP Link entity-header field + :return: list of parsed link headers + """ + links: list[dict[str, str]] = [] + replace_chars = " '\"" + value = value.strip(replace_chars) + if not value: + return links + for val in re.split(", *<", value): + try: + url, params = val.split(";", 1) + except ValueError: + url, params = val, "" + link = {"url": url.strip("<> '\"")} + for param in params.split(";"): + try: + key, value = param.split("=") + except ValueError: + break + link[key.strip(replace_chars)] = value.strip(replace_chars) + links.append(link) + return links + + +def _obfuscate_sensitive_headers( + items: typing.Iterable[tuple[typing.AnyStr, typing.AnyStr]], +) -> typing.Iterator[tuple[typing.AnyStr, typing.AnyStr]]: + for k, v in items: + if to_str(k.lower()) in SENSITIVE_HEADERS: + v = to_bytes_or_str("[secure]", match_type_of=v) + yield k, v + + +class Headers(typing.MutableMapping[str, str]): + """ + HTTP headers, as a case-insensitive multi-dict. + """ + + def __init__( + self, + headers: HeaderTypes | None = None, + encoding: str | None = None, + ) -> None: + self._list = [] # type: typing.List[typing.Tuple[bytes, bytes, bytes]] + + if isinstance(headers, Headers): + self._list = list(headers._list) + elif isinstance(headers, Mapping): + for k, v in headers.items(): + bytes_key = _normalize_header_key(k, encoding) + bytes_value = _normalize_header_value(v, encoding) + self._list.append((bytes_key, bytes_key.lower(), bytes_value)) + elif headers is not None: + for k, v in headers: + bytes_key = _normalize_header_key(k, encoding) + bytes_value = _normalize_header_value(v, encoding) + self._list.append((bytes_key, bytes_key.lower(), bytes_value)) + + self._encoding = encoding + + @property + def encoding(self) -> str: + """ + Header encoding is mandated as ascii, but we allow fallbacks to utf-8 + or iso-8859-1. + """ + if self._encoding is None: + for encoding in ["ascii", "utf-8"]: + for key, value in self.raw: + try: + key.decode(encoding) + value.decode(encoding) + except UnicodeDecodeError: + break + else: + # The else block runs if 'break' did not occur, meaning + # all values fitted the encoding. + self._encoding = encoding + break + else: + # The ISO-8859-1 encoding covers all 256 code points in a byte, + # so will never raise decode errors. + self._encoding = "iso-8859-1" + return self._encoding + + @encoding.setter + def encoding(self, value: str) -> None: + self._encoding = value + + @property + def raw(self) -> list[tuple[bytes, bytes]]: + """ + Returns a list of the raw header items, as byte pairs. + """ + return [(raw_key, value) for raw_key, _, value in self._list] + + def keys(self) -> typing.KeysView[str]: + return {key.decode(self.encoding): None for _, key, value in self._list}.keys() + + def values(self) -> typing.ValuesView[str]: + values_dict: dict[str, str] = {} + for _, key, value in self._list: + str_key = key.decode(self.encoding) + str_value = value.decode(self.encoding) + if str_key in values_dict: + values_dict[str_key] += f", {str_value}" + else: + values_dict[str_key] = str_value + return values_dict.values() + + def items(self) -> typing.ItemsView[str, str]: + """ + Return `(key, value)` items of headers. Concatenate headers + into a single comma separated value when a key occurs multiple times. + """ + values_dict: dict[str, str] = {} + for _, key, value in self._list: + str_key = key.decode(self.encoding) + str_value = value.decode(self.encoding) + if str_key in values_dict: + values_dict[str_key] += f", {str_value}" + else: + values_dict[str_key] = str_value + return values_dict.items() + + def multi_items(self) -> list[tuple[str, str]]: + """ + Return a list of `(key, value)` pairs of headers. Allow multiple + occurrences of the same key without concatenating into a single + comma separated value. + """ + return [ + (key.decode(self.encoding), value.decode(self.encoding)) + for _, key, value in self._list + ] + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Return a header value. If multiple occurrences of the header occur + then concatenate them together with commas. + """ + try: + return self[key] + except KeyError: + return default + + def get_list(self, key: str, split_commas: bool = False) -> list[str]: + """ + Return a list of all header values for a given key. + If `split_commas=True` is passed, then any comma separated header + values are split into multiple return strings. + """ + get_header_key = key.lower().encode(self.encoding) + + values = [ + item_value.decode(self.encoding) + for _, item_key, item_value in self._list + if item_key.lower() == get_header_key + ] + + if not split_commas: + return values + + split_values = [] + for value in values: + split_values.extend([item.strip() for item in value.split(",")]) + return split_values + + def update(self, headers: HeaderTypes | None = None) -> None: # type: ignore + headers = Headers(headers) + for key in headers.keys(): + if key in self: + self.pop(key) + self._list.extend(headers._list) + + def copy(self) -> Headers: + return Headers(self, encoding=self.encoding) + + def __getitem__(self, key: str) -> str: + """ + Return a single header value. + + If there are multiple headers with the same key, then we concatenate + them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2 + """ + normalized_key = key.lower().encode(self.encoding) + + items = [ + header_value.decode(self.encoding) + for _, header_key, header_value in self._list + if header_key == normalized_key + ] + + if items: + return ", ".join(items) + + raise KeyError(key) + + def __setitem__(self, key: str, value: str) -> None: + """ + Set the header `key` to `value`, removing any duplicate entries. + Retains insertion order. + """ + set_key = key.encode(self._encoding or "utf-8") + set_value = value.encode(self._encoding or "utf-8") + lookup_key = set_key.lower() + + found_indexes = [ + idx + for idx, (_, item_key, _) in enumerate(self._list) + if item_key == lookup_key + ] + + for idx in reversed(found_indexes[1:]): + del self._list[idx] + + if found_indexes: + idx = found_indexes[0] + self._list[idx] = (set_key, lookup_key, set_value) + else: + self._list.append((set_key, lookup_key, set_value)) + + def __delitem__(self, key: str) -> None: + """ + Remove the header `key`. + """ + del_key = key.lower().encode(self.encoding) + + pop_indexes = [ + idx + for idx, (_, item_key, _) in enumerate(self._list) + if item_key.lower() == del_key + ] + + if not pop_indexes: + raise KeyError(key) + + for idx in reversed(pop_indexes): + del self._list[idx] + + def __contains__(self, key: typing.Any) -> bool: + header_key = key.lower().encode(self.encoding) + return header_key in [key for _, key, _ in self._list] + + def __iter__(self) -> typing.Iterator[typing.Any]: + return iter(self.keys()) + + def __len__(self) -> int: + return len(self._list) + + def __eq__(self, other: typing.Any) -> bool: + try: + other_headers = Headers(other) + except ValueError: + return False + + self_list = [(key, value) for _, key, value in self._list] + other_list = [(key, value) for _, key, value in other_headers._list] + return sorted(self_list) == sorted(other_list) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + + encoding_str = "" + if self.encoding != "ascii": + encoding_str = f", encoding={self.encoding!r}" + + as_list = list(_obfuscate_sensitive_headers(self.multi_items())) + as_dict = dict(as_list) + + no_duplicate_keys = len(as_dict) == len(as_list) + if no_duplicate_keys: + return f"{class_name}({as_dict!r}{encoding_str})" + return f"{class_name}({as_list!r}{encoding_str})" + + +class Request: + def __init__( + self, + method: str, + url: URL | str, + *, + params: QueryParamTypes | None = None, + headers: HeaderTypes | None = None, + cookies: CookieTypes | None = None, + content: RequestContent | None = None, + data: RequestData | None = None, + files: RequestFiles | None = None, + json: typing.Any | None = None, + stream: SyncByteStream | AsyncByteStream | None = None, + extensions: RequestExtensions | None = None, + ) -> None: + self.method = method.upper() + self.url = URL(url) if params is None else URL(url, params=params) + self.headers = Headers(headers) + self.extensions = {} if extensions is None else dict(extensions) + + if cookies: + Cookies(cookies).set_cookie_header(self) + + if stream is None: + content_type: str | None = self.headers.get("content-type") + headers, stream = encode_request( + content=content, + data=data, + files=files, + json=json, + boundary=get_multipart_boundary_from_content_type( + content_type=content_type.encode(self.headers.encoding) + if content_type + else None + ), + ) + self._prepare(headers) + self.stream = stream + # Load the request body, except for streaming content. + if isinstance(stream, ByteStream): + self.read() + else: + # There's an important distinction between `Request(content=...)`, + # and `Request(stream=...)`. + # + # Using `content=...` implies automatically populated `Host` and content + # headers, of either `Content-Length: ...` or `Transfer-Encoding: chunked`. + # + # Using `stream=...` will not automatically include *any* + # auto-populated headers. + # + # As an end-user you don't really need `stream=...`. It's only + # useful when: + # + # * Preserving the request stream when copying requests, eg for redirects. + # * Creating request instances on the *server-side* of the transport API. + self.stream = stream + + def _prepare(self, default_headers: dict[str, str]) -> None: + for key, value in default_headers.items(): + # Ignore Transfer-Encoding if the Content-Length has been set explicitly. + if key.lower() == "transfer-encoding" and "Content-Length" in self.headers: + continue + self.headers.setdefault(key, value) + + auto_headers: list[tuple[bytes, bytes]] = [] + + has_host = "Host" in self.headers + has_content_length = ( + "Content-Length" in self.headers or "Transfer-Encoding" in self.headers + ) + + if not has_host and self.url.host: + auto_headers.append((b"Host", self.url.netloc)) + if not has_content_length and self.method in ("POST", "PUT", "PATCH"): + auto_headers.append((b"Content-Length", b"0")) + + self.headers = Headers(auto_headers + self.headers.raw) + + @property + def content(self) -> bytes: + if not hasattr(self, "_content"): + raise RequestNotRead() + return self._content + + def read(self) -> bytes: + """ + Read and return the request content. + """ + if not hasattr(self, "_content"): + assert isinstance(self.stream, typing.Iterable) + self._content = b"".join(self.stream) + if not isinstance(self.stream, ByteStream): + # If a streaming request has been read entirely into memory, then + # we can replace the stream with a raw bytes implementation, + # to ensure that any non-replayable streams can still be used. + self.stream = ByteStream(self._content) + return self._content + + async def aread(self) -> bytes: + """ + Read and return the request content. + """ + if not hasattr(self, "_content"): + assert isinstance(self.stream, typing.AsyncIterable) + self._content = b"".join([part async for part in self.stream]) + if not isinstance(self.stream, ByteStream): + # If a streaming request has been read entirely into memory, then + # we can replace the stream with a raw bytes implementation, + # to ensure that any non-replayable streams can still be used. + self.stream = ByteStream(self._content) + return self._content + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + url = str(self.url) + return f"<{class_name}({self.method!r}, {url!r})>" + + def __getstate__(self) -> dict[str, typing.Any]: + return { + name: value + for name, value in self.__dict__.items() + if name not in ["extensions", "stream"] + } + + def __setstate__(self, state: dict[str, typing.Any]) -> None: + for name, value in state.items(): + setattr(self, name, value) + self.extensions = {} + self.stream = UnattachedStream() + + +class Response: + def __init__( + self, + status_code: int, + *, + headers: HeaderTypes | None = None, + content: ResponseContent | None = None, + text: str | None = None, + html: str | None = None, + json: typing.Any = None, + stream: SyncByteStream | AsyncByteStream | None = None, + request: Request | None = None, + extensions: ResponseExtensions | None = None, + history: list[Response] | None = None, + default_encoding: str | typing.Callable[[bytes], str] = "utf-8", + ) -> None: + self.status_code = status_code + self.headers = Headers(headers) + + self._request: Request | None = request + + # When follow_redirects=False and a redirect is received, + # the client will set `response.next_request`. + self.next_request: Request | None = None + + self.extensions = {} if extensions is None else dict(extensions) + self.history = [] if history is None else list(history) + + self.is_closed = False + self.is_stream_consumed = False + + self.default_encoding = default_encoding + + if stream is None: + headers, stream = encode_response(content, text, html, json) + self._prepare(headers) + self.stream = stream + if isinstance(stream, ByteStream): + # Load the response body, except for streaming content. + self.read() + else: + # There's an important distinction between `Response(content=...)`, + # and `Response(stream=...)`. + # + # Using `content=...` implies automatically populated content headers, + # of either `Content-Length: ...` or `Transfer-Encoding: chunked`. + # + # Using `stream=...` will not automatically include any content headers. + # + # As an end-user you don't really need `stream=...`. It's only + # useful when creating response instances having received a stream + # from the transport API. + self.stream = stream + + self._num_bytes_downloaded = 0 + + def _prepare(self, default_headers: dict[str, str]) -> None: + for key, value in default_headers.items(): + # Ignore Transfer-Encoding if the Content-Length has been set explicitly. + if key.lower() == "transfer-encoding" and "content-length" in self.headers: + continue + self.headers.setdefault(key, value) + + @property + def elapsed(self) -> datetime.timedelta: + """ + Returns the time taken for the complete request/response + cycle to complete. + """ + if not hasattr(self, "_elapsed"): + raise RuntimeError( + "'.elapsed' may only be accessed after the response " + "has been read or closed." + ) + return self._elapsed + + @elapsed.setter + def elapsed(self, elapsed: datetime.timedelta) -> None: + self._elapsed = elapsed + + @property + def request(self) -> Request: + """ + Returns the request instance associated to the current response. + """ + if self._request is None: + raise RuntimeError( + "The request instance has not been set on this response." + ) + return self._request + + @request.setter + def request(self, value: Request) -> None: + self._request = value + + @property + def http_version(self) -> str: + try: + http_version: bytes = self.extensions["http_version"] + except KeyError: + return "HTTP/1.1" + else: + return http_version.decode("ascii", errors="ignore") + + @property + def reason_phrase(self) -> str: + try: + reason_phrase: bytes = self.extensions["reason_phrase"] + except KeyError: + return codes.get_reason_phrase(self.status_code) + else: + return reason_phrase.decode("ascii", errors="ignore") + + @property + def url(self) -> URL: + """ + Returns the URL for which the request was made. + """ + return self.request.url + + @property + def content(self) -> bytes: + if not hasattr(self, "_content"): + raise ResponseNotRead() + return self._content + + @property + def text(self) -> str: + if not hasattr(self, "_text"): + content = self.content + if not content: + self._text = "" + else: + decoder = TextDecoder(encoding=self.encoding or "utf-8") + self._text = "".join([decoder.decode(self.content), decoder.flush()]) + return self._text + + @property + def encoding(self) -> str | None: + """ + Return an encoding to use for decoding the byte content into text. + The priority for determining this is given by... + + * `.encoding = <>` has been set explicitly. + * The encoding as specified by the charset parameter in the Content-Type header. + * The encoding as determined by `default_encoding`, which may either be + a string like "utf-8" indicating the encoding to use, or may be a callable + which enables charset autodetection. + """ + if not hasattr(self, "_encoding"): + encoding = self.charset_encoding + if encoding is None or not _is_known_encoding(encoding): + if isinstance(self.default_encoding, str): + encoding = self.default_encoding + elif hasattr(self, "_content"): + encoding = self.default_encoding(self._content) + self._encoding = encoding or "utf-8" + return self._encoding + + @encoding.setter + def encoding(self, value: str) -> None: + """ + Set the encoding to use for decoding the byte content into text. + + If the `text` attribute has been accessed, attempting to set the + encoding will throw a ValueError. + """ + if hasattr(self, "_text"): + raise ValueError( + "Setting encoding after `text` has been accessed is not allowed." + ) + self._encoding = value + + @property + def charset_encoding(self) -> str | None: + """ + Return the encoding, as specified by the Content-Type header. + """ + content_type = self.headers.get("Content-Type") + if content_type is None: + return None + + return _parse_content_type_charset(content_type) + + def _get_content_decoder(self) -> ContentDecoder: + """ + Returns a decoder instance which can be used to decode the raw byte + content, depending on the Content-Encoding used in the response. + """ + if not hasattr(self, "_decoder"): + decoders: list[ContentDecoder] = [] + values = self.headers.get_list("content-encoding", split_commas=True) + for value in values: + value = value.strip().lower() + try: + decoder_cls = SUPPORTED_DECODERS[value] + decoders.append(decoder_cls()) + except KeyError: + continue + + if len(decoders) == 1: + self._decoder = decoders[0] + elif len(decoders) > 1: + self._decoder = MultiDecoder(children=decoders) + else: + self._decoder = IdentityDecoder() + + return self._decoder + + @property + def is_informational(self) -> bool: + """ + A property which is `True` for 1xx status codes, `False` otherwise. + """ + return codes.is_informational(self.status_code) + + @property + def is_success(self) -> bool: + """ + A property which is `True` for 2xx status codes, `False` otherwise. + """ + return codes.is_success(self.status_code) + + @property + def is_redirect(self) -> bool: + """ + A property which is `True` for 3xx status codes, `False` otherwise. + + Note that not all responses with a 3xx status code indicate a URL redirect. + + Use `response.has_redirect_location` to determine responses with a properly + formed URL redirection. + """ + return codes.is_redirect(self.status_code) + + @property + def is_client_error(self) -> bool: + """ + A property which is `True` for 4xx status codes, `False` otherwise. + """ + return codes.is_client_error(self.status_code) + + @property + def is_server_error(self) -> bool: + """ + A property which is `True` for 5xx status codes, `False` otherwise. + """ + return codes.is_server_error(self.status_code) + + @property + def is_error(self) -> bool: + """ + A property which is `True` for 4xx and 5xx status codes, `False` otherwise. + """ + return codes.is_error(self.status_code) + + @property + def has_redirect_location(self) -> bool: + """ + Returns True for 3xx responses with a properly formed URL redirection, + `False` otherwise. + """ + return ( + self.status_code + in ( + # 301 (Cacheable redirect. Method may change to GET.) + codes.MOVED_PERMANENTLY, + # 302 (Uncacheable redirect. Method may change to GET.) + codes.FOUND, + # 303 (Client should make a GET or HEAD request.) + codes.SEE_OTHER, + # 307 (Equiv. 302, but retain method) + codes.TEMPORARY_REDIRECT, + # 308 (Equiv. 301, but retain method) + codes.PERMANENT_REDIRECT, + ) + and "Location" in self.headers + ) + + def raise_for_status(self) -> Response: + """ + Raise the `HTTPStatusError` if one occurred. + """ + request = self._request + if request is None: + raise RuntimeError( + "Cannot call `raise_for_status` as the request " + "instance has not been set on this response." + ) + + if self.is_success: + return self + + if self.has_redirect_location: + message = ( + "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" + "Redirect location: '{0.headers[location]}'\n" + "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" + ) + else: + message = ( + "{error_type} '{0.status_code} {0.reason_phrase}' for url '{0.url}'\n" + "For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/{0.status_code}" + ) + + status_class = self.status_code // 100 + error_types = { + 1: "Informational response", + 3: "Redirect response", + 4: "Client error", + 5: "Server error", + } + error_type = error_types.get(status_class, "Invalid status code") + message = message.format(self, error_type=error_type) + raise HTTPStatusError(message, request=request, response=self) + + def json(self, **kwargs: typing.Any) -> typing.Any: + return jsonlib.loads(self.content, **kwargs) + + @property + def cookies(self) -> Cookies: + if not hasattr(self, "_cookies"): + self._cookies = Cookies() + self._cookies.extract_cookies(self) + return self._cookies + + @property + def links(self) -> dict[str | None, dict[str, str]]: + """ + Returns the parsed header links of the response, if any + """ + header = self.headers.get("link") + if header is None: + return {} + + return { + (link.get("rel") or link.get("url")): link + for link in _parse_header_links(header) + } + + @property + def num_bytes_downloaded(self) -> int: + return self._num_bytes_downloaded + + def __repr__(self) -> str: + return f"" + + def __getstate__(self) -> dict[str, typing.Any]: + return { + name: value + for name, value in self.__dict__.items() + if name not in ["extensions", "stream", "is_closed", "_decoder"] + } + + def __setstate__(self, state: dict[str, typing.Any]) -> None: + for name, value in state.items(): + setattr(self, name, value) + self.is_closed = True + self.extensions = {} + self.stream = UnattachedStream() + + def read(self) -> bytes: + """ + Read and return the response content. + """ + if not hasattr(self, "_content"): + self._content = b"".join(self.iter_bytes()) + return self._content + + def iter_bytes(self, chunk_size: int | None = None) -> typing.Iterator[bytes]: + """ + A byte-iterator over the decoded response content. + This allows us to handle gzip, deflate, brotli, and zstd encoded responses. + """ + if hasattr(self, "_content"): + chunk_size = len(self._content) if chunk_size is None else chunk_size + for i in range(0, len(self._content), max(chunk_size, 1)): + yield self._content[i : i + chunk_size] + else: + decoder = self._get_content_decoder() + chunker = ByteChunker(chunk_size=chunk_size) + with request_context(request=self._request): + for raw_bytes in self.iter_raw(): + decoded = decoder.decode(raw_bytes) + for chunk in chunker.decode(decoded): + yield chunk + decoded = decoder.flush() + for chunk in chunker.decode(decoded): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + def iter_text(self, chunk_size: int | None = None) -> typing.Iterator[str]: + """ + A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + decoder = TextDecoder(encoding=self.encoding or "utf-8") + chunker = TextChunker(chunk_size=chunk_size) + with request_context(request=self._request): + for byte_content in self.iter_bytes(): + text_content = decoder.decode(byte_content) + for chunk in chunker.decode(text_content): + yield chunk + text_content = decoder.flush() + for chunk in chunker.decode(text_content): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + def iter_lines(self) -> typing.Iterator[str]: + decoder = LineDecoder() + with request_context(request=self._request): + for text in self.iter_text(): + for line in decoder.decode(text): + yield line + for line in decoder.flush(): + yield line + + def iter_raw(self, chunk_size: int | None = None) -> typing.Iterator[bytes]: + """ + A byte-iterator over the raw response content. + """ + if self.is_stream_consumed: + raise StreamConsumed() + if self.is_closed: + raise StreamClosed() + if not isinstance(self.stream, SyncByteStream): + raise RuntimeError("Attempted to call a sync iterator on an async stream.") + + self.is_stream_consumed = True + self._num_bytes_downloaded = 0 + chunker = ByteChunker(chunk_size=chunk_size) + + with request_context(request=self._request): + for raw_stream_bytes in self.stream: + self._num_bytes_downloaded += len(raw_stream_bytes) + for chunk in chunker.decode(raw_stream_bytes): + yield chunk + + for chunk in chunker.flush(): + yield chunk + + self.close() + + def close(self) -> None: + """ + Close the response and release the connection. + Automatically called if the response body is read to completion. + """ + if not isinstance(self.stream, SyncByteStream): + raise RuntimeError("Attempted to call an sync close on an async stream.") + + if not self.is_closed: + self.is_closed = True + with request_context(request=self._request): + self.stream.close() + + async def aread(self) -> bytes: + """ + Read and return the response content. + """ + if not hasattr(self, "_content"): + self._content = b"".join([part async for part in self.aiter_bytes()]) + return self._content + + async def aiter_bytes( + self, chunk_size: int | None = None + ) -> typing.AsyncIterator[bytes]: + """ + A byte-iterator over the decoded response content. + This allows us to handle gzip, deflate, brotli, and zstd encoded responses. + """ + if hasattr(self, "_content"): + chunk_size = len(self._content) if chunk_size is None else chunk_size + for i in range(0, len(self._content), max(chunk_size, 1)): + yield self._content[i : i + chunk_size] + else: + decoder = self._get_content_decoder() + chunker = ByteChunker(chunk_size=chunk_size) + with request_context(request=self._request): + async for raw_bytes in self.aiter_raw(): + decoded = decoder.decode(raw_bytes) + for chunk in chunker.decode(decoded): + yield chunk + decoded = decoder.flush() + for chunk in chunker.decode(decoded): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + async def aiter_text( + self, chunk_size: int | None = None + ) -> typing.AsyncIterator[str]: + """ + A str-iterator over the decoded response content + that handles both gzip, deflate, etc but also detects the content's + string encoding. + """ + decoder = TextDecoder(encoding=self.encoding or "utf-8") + chunker = TextChunker(chunk_size=chunk_size) + with request_context(request=self._request): + async for byte_content in self.aiter_bytes(): + text_content = decoder.decode(byte_content) + for chunk in chunker.decode(text_content): + yield chunk + text_content = decoder.flush() + for chunk in chunker.decode(text_content): + yield chunk # pragma: no cover + for chunk in chunker.flush(): + yield chunk + + async def aiter_lines(self) -> typing.AsyncIterator[str]: + decoder = LineDecoder() + with request_context(request=self._request): + async for text in self.aiter_text(): + for line in decoder.decode(text): + yield line + for line in decoder.flush(): + yield line + + async def aiter_raw( + self, chunk_size: int | None = None + ) -> typing.AsyncIterator[bytes]: + """ + A byte-iterator over the raw response content. + """ + if self.is_stream_consumed: + raise StreamConsumed() + if self.is_closed: + raise StreamClosed() + if not isinstance(self.stream, AsyncByteStream): + raise RuntimeError("Attempted to call an async iterator on an sync stream.") + + self.is_stream_consumed = True + self._num_bytes_downloaded = 0 + chunker = ByteChunker(chunk_size=chunk_size) + + with request_context(request=self._request): + async for raw_stream_bytes in self.stream: + self._num_bytes_downloaded += len(raw_stream_bytes) + for chunk in chunker.decode(raw_stream_bytes): + yield chunk + + for chunk in chunker.flush(): + yield chunk + + await self.aclose() + + async def aclose(self) -> None: + """ + Close the response and release the connection. + Automatically called if the response body is read to completion. + """ + if not isinstance(self.stream, AsyncByteStream): + raise RuntimeError("Attempted to call an async close on an sync stream.") + + if not self.is_closed: + self.is_closed = True + with request_context(request=self._request): + await self.stream.aclose() + + +class Cookies(typing.MutableMapping[str, str]): + """ + HTTP Cookies, as a mutable mapping. + """ + + def __init__(self, cookies: CookieTypes | None = None) -> None: + if cookies is None or isinstance(cookies, dict): + self.jar = CookieJar() + if isinstance(cookies, dict): + for key, value in cookies.items(): + self.set(key, value) + elif isinstance(cookies, list): + self.jar = CookieJar() + for key, value in cookies: + self.set(key, value) + elif isinstance(cookies, Cookies): + self.jar = CookieJar() + for cookie in cookies.jar: + self.jar.set_cookie(cookie) + else: + self.jar = cookies + + def extract_cookies(self, response: Response) -> None: + """ + Loads any cookies based on the response `Set-Cookie` headers. + """ + urllib_response = self._CookieCompatResponse(response) + urllib_request = self._CookieCompatRequest(response.request) + + self.jar.extract_cookies(urllib_response, urllib_request) # type: ignore + + def set_cookie_header(self, request: Request) -> None: + """ + Sets an appropriate 'Cookie:' HTTP header on the `Request`. + """ + urllib_request = self._CookieCompatRequest(request) + self.jar.add_cookie_header(urllib_request) + + def set(self, name: str, value: str, domain: str = "", path: str = "/") -> None: + """ + Set a cookie value by name. May optionally include domain and path. + """ + kwargs = { + "version": 0, + "name": name, + "value": value, + "port": None, + "port_specified": False, + "domain": domain, + "domain_specified": bool(domain), + "domain_initial_dot": domain.startswith("."), + "path": path, + "path_specified": bool(path), + "secure": False, + "expires": None, + "discard": True, + "comment": None, + "comment_url": None, + "rest": {"HttpOnly": None}, + "rfc2109": False, + } + cookie = Cookie(**kwargs) # type: ignore + self.jar.set_cookie(cookie) + + def get( # type: ignore + self, + name: str, + default: str | None = None, + domain: str | None = None, + path: str | None = None, + ) -> str | None: + """ + Get a cookie by name. May optionally include domain and path + in order to specify exactly which cookie to retrieve. + """ + value = None + for cookie in self.jar: + if cookie.name == name: + if domain is None or cookie.domain == domain: + if path is None or cookie.path == path: + if value is not None: + message = f"Multiple cookies exist with name={name}" + raise CookieConflict(message) + value = cookie.value + + if value is None: + return default + return value + + def delete( + self, + name: str, + domain: str | None = None, + path: str | None = None, + ) -> None: + """ + Delete a cookie by name. May optionally include domain and path + in order to specify exactly which cookie to delete. + """ + if domain is not None and path is not None: + return self.jar.clear(domain, path, name) + + remove = [ + cookie + for cookie in self.jar + if cookie.name == name + and (domain is None or cookie.domain == domain) + and (path is None or cookie.path == path) + ] + + for cookie in remove: + self.jar.clear(cookie.domain, cookie.path, cookie.name) + + def clear(self, domain: str | None = None, path: str | None = None) -> None: + """ + Delete all cookies. Optionally include a domain and path in + order to only delete a subset of all the cookies. + """ + args = [] + if domain is not None: + args.append(domain) + if path is not None: + assert domain is not None + args.append(path) + self.jar.clear(*args) + + def update(self, cookies: CookieTypes | None = None) -> None: # type: ignore + cookies = Cookies(cookies) + for cookie in cookies.jar: + self.jar.set_cookie(cookie) + + def __setitem__(self, name: str, value: str) -> None: + return self.set(name, value) + + def __getitem__(self, name: str) -> str: + value = self.get(name) + if value is None: + raise KeyError(name) + return value + + def __delitem__(self, name: str) -> None: + return self.delete(name) + + def __len__(self) -> int: + return len(self.jar) + + def __iter__(self) -> typing.Iterator[str]: + return (cookie.name for cookie in self.jar) + + def __bool__(self) -> bool: + for _ in self.jar: + return True + return False + + def __repr__(self) -> str: + cookies_repr = ", ".join( + [ + f"" + for cookie in self.jar + ] + ) + + return f"" + + class _CookieCompatRequest(urllib.request.Request): + """ + Wraps a `Request` instance up in a compatibility interface suitable + for use with `CookieJar` operations. + """ + + def __init__(self, request: Request) -> None: + super().__init__( + url=str(request.url), + headers=dict(request.headers), + method=request.method, + ) + self.request = request + + def add_unredirected_header(self, key: str, value: str) -> None: + super().add_unredirected_header(key, value) + self.request.headers[key] = value + + class _CookieCompatResponse: + """ + Wraps a `Request` instance up in a compatibility interface suitable + for use with `CookieJar` operations. + """ + + def __init__(self, response: Response) -> None: + self.response = response + + def info(self) -> email.message.Message: + info = email.message.Message() + for key, value in self.response.headers.multi_items(): + # Note that setting `info[key]` here is an "append" operation, + # not a "replace" operation. + # https://docs.python.org/3/library/email.compat32-message.html#email.message.Message.__setitem__ + info[key] = value + return info diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_multipart.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_multipart.py new file mode 100644 index 0000000000000000000000000000000000000000..b4761af9b2cf384de5189269927d781a700dbe46 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_multipart.py @@ -0,0 +1,300 @@ +from __future__ import annotations + +import io +import mimetypes +import os +import re +import typing +from pathlib import Path + +from ._types import ( + AsyncByteStream, + FileContent, + FileTypes, + RequestData, + RequestFiles, + SyncByteStream, +) +from ._utils import ( + peek_filelike_length, + primitive_value_to_str, + to_bytes, +) + +_HTML5_FORM_ENCODING_REPLACEMENTS = {'"': "%22", "\\": "\\\\"} +_HTML5_FORM_ENCODING_REPLACEMENTS.update( + {chr(c): "%{:02X}".format(c) for c in range(0x1F + 1) if c != 0x1B} +) +_HTML5_FORM_ENCODING_RE = re.compile( + r"|".join([re.escape(c) for c in _HTML5_FORM_ENCODING_REPLACEMENTS.keys()]) +) + + +def _format_form_param(name: str, value: str) -> bytes: + """ + Encode a name/value pair within a multipart form. + """ + + def replacer(match: typing.Match[str]) -> str: + return _HTML5_FORM_ENCODING_REPLACEMENTS[match.group(0)] + + value = _HTML5_FORM_ENCODING_RE.sub(replacer, value) + return f'{name}="{value}"'.encode() + + +def _guess_content_type(filename: str | None) -> str | None: + """ + Guesses the mimetype based on a filename. Defaults to `application/octet-stream`. + + Returns `None` if `filename` is `None` or empty. + """ + if filename: + return mimetypes.guess_type(filename)[0] or "application/octet-stream" + return None + + +def get_multipart_boundary_from_content_type( + content_type: bytes | None, +) -> bytes | None: + if not content_type or not content_type.startswith(b"multipart/form-data"): + return None + # parse boundary according to + # https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1 + if b";" in content_type: + for section in content_type.split(b";"): + if section.strip().lower().startswith(b"boundary="): + return section.strip()[len(b"boundary=") :].strip(b'"') + return None + + +class DataField: + """ + A single form field item, within a multipart form field. + """ + + def __init__(self, name: str, value: str | bytes | int | float | None) -> None: + if not isinstance(name, str): + raise TypeError( + f"Invalid type for name. Expected str, got {type(name)}: {name!r}" + ) + if value is not None and not isinstance(value, (str, bytes, int, float)): + raise TypeError( + "Invalid type for value. Expected primitive type," + f" got {type(value)}: {value!r}" + ) + self.name = name + self.value: str | bytes = ( + value if isinstance(value, bytes) else primitive_value_to_str(value) + ) + + def render_headers(self) -> bytes: + if not hasattr(self, "_headers"): + name = _format_form_param("name", self.name) + self._headers = b"".join( + [b"Content-Disposition: form-data; ", name, b"\r\n\r\n"] + ) + + return self._headers + + def render_data(self) -> bytes: + if not hasattr(self, "_data"): + self._data = to_bytes(self.value) + + return self._data + + def get_length(self) -> int: + headers = self.render_headers() + data = self.render_data() + return len(headers) + len(data) + + def render(self) -> typing.Iterator[bytes]: + yield self.render_headers() + yield self.render_data() + + +class FileField: + """ + A single file field item, within a multipart form field. + """ + + CHUNK_SIZE = 64 * 1024 + + def __init__(self, name: str, value: FileTypes) -> None: + self.name = name + + fileobj: FileContent + + headers: dict[str, str] = {} + content_type: str | None = None + + # This large tuple based API largely mirror's requests' API + # It would be good to think of better APIs for this that we could + # include in httpx 2.0 since variable length tuples(especially of 4 elements) + # are quite unwieldly + if isinstance(value, tuple): + if len(value) == 2: + # neither the 3rd parameter (content_type) nor the 4th (headers) + # was included + filename, fileobj = value + elif len(value) == 3: + filename, fileobj, content_type = value + else: + # all 4 parameters included + filename, fileobj, content_type, headers = value # type: ignore + else: + filename = Path(str(getattr(value, "name", "upload"))).name + fileobj = value + + if content_type is None: + content_type = _guess_content_type(filename) + + has_content_type_header = any("content-type" in key.lower() for key in headers) + if content_type is not None and not has_content_type_header: + # note that unlike requests, we ignore the content_type provided in the 3rd + # tuple element if it is also included in the headers requests does + # the opposite (it overwrites the headerwith the 3rd tuple element) + headers["Content-Type"] = content_type + + if isinstance(fileobj, io.StringIO): + raise TypeError( + "Multipart file uploads require 'io.BytesIO', not 'io.StringIO'." + ) + if isinstance(fileobj, io.TextIOBase): + raise TypeError( + "Multipart file uploads must be opened in binary mode, not text mode." + ) + + self.filename = filename + self.file = fileobj + self.headers = headers + + def get_length(self) -> int | None: + headers = self.render_headers() + + if isinstance(self.file, (str, bytes)): + return len(headers) + len(to_bytes(self.file)) + + file_length = peek_filelike_length(self.file) + + # If we can't determine the filesize without reading it into memory, + # then return `None` here, to indicate an unknown file length. + if file_length is None: + return None + + return len(headers) + file_length + + def render_headers(self) -> bytes: + if not hasattr(self, "_headers"): + parts = [ + b"Content-Disposition: form-data; ", + _format_form_param("name", self.name), + ] + if self.filename: + filename = _format_form_param("filename", self.filename) + parts.extend([b"; ", filename]) + for header_name, header_value in self.headers.items(): + key, val = f"\r\n{header_name}: ".encode(), header_value.encode() + parts.extend([key, val]) + parts.append(b"\r\n\r\n") + self._headers = b"".join(parts) + + return self._headers + + def render_data(self) -> typing.Iterator[bytes]: + if isinstance(self.file, (str, bytes)): + yield to_bytes(self.file) + return + + if hasattr(self.file, "seek"): + try: + self.file.seek(0) + except io.UnsupportedOperation: + pass + + chunk = self.file.read(self.CHUNK_SIZE) + while chunk: + yield to_bytes(chunk) + chunk = self.file.read(self.CHUNK_SIZE) + + def render(self) -> typing.Iterator[bytes]: + yield self.render_headers() + yield from self.render_data() + + +class MultipartStream(SyncByteStream, AsyncByteStream): + """ + Request content as streaming multipart encoded form data. + """ + + def __init__( + self, + data: RequestData, + files: RequestFiles, + boundary: bytes | None = None, + ) -> None: + if boundary is None: + boundary = os.urandom(16).hex().encode("ascii") + + self.boundary = boundary + self.content_type = "multipart/form-data; boundary=%s" % boundary.decode( + "ascii" + ) + self.fields = list(self._iter_fields(data, files)) + + def _iter_fields( + self, data: RequestData, files: RequestFiles + ) -> typing.Iterator[FileField | DataField]: + for name, value in data.items(): + if isinstance(value, (tuple, list)): + for item in value: + yield DataField(name=name, value=item) + else: + yield DataField(name=name, value=value) + + file_items = files.items() if isinstance(files, typing.Mapping) else files + for name, value in file_items: + yield FileField(name=name, value=value) + + def iter_chunks(self) -> typing.Iterator[bytes]: + for field in self.fields: + yield b"--%s\r\n" % self.boundary + yield from field.render() + yield b"\r\n" + yield b"--%s--\r\n" % self.boundary + + def get_content_length(self) -> int | None: + """ + Return the length of the multipart encoded content, or `None` if + any of the files have a length that cannot be determined upfront. + """ + boundary_length = len(self.boundary) + length = 0 + + for field in self.fields: + field_length = field.get_length() + if field_length is None: + return None + + length += 2 + boundary_length + 2 # b"--{boundary}\r\n" + length += field_length + length += 2 # b"\r\n" + + length += 2 + boundary_length + 4 # b"--{boundary}--\r\n" + return length + + # Content stream interface. + + def get_headers(self) -> dict[str, str]: + content_length = self.get_content_length() + content_type = self.content_type + if content_length is None: + return {"Transfer-Encoding": "chunked", "Content-Type": content_type} + return {"Content-Length": str(content_length), "Content-Type": content_type} + + def __iter__(self) -> typing.Iterator[bytes]: + for chunk in self.iter_chunks(): + yield chunk + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + for chunk in self.iter_chunks(): + yield chunk diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_status_codes.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_status_codes.py new file mode 100644 index 0000000000000000000000000000000000000000..133a6231a5b53fd2f073799ca1bd07c50abe40ae --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_status_codes.py @@ -0,0 +1,162 @@ +from __future__ import annotations + +from enum import IntEnum + +__all__ = ["codes"] + + +class codes(IntEnum): + """HTTP status codes and reason phrases + + Status codes from the following RFCs are all observed: + + * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616 + * RFC 6585: Additional HTTP Status Codes + * RFC 3229: Delta encoding in HTTP + * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518 + * RFC 5842: Binding Extensions to WebDAV + * RFC 7238: Permanent Redirect + * RFC 2295: Transparent Content Negotiation in HTTP + * RFC 2774: An HTTP Extension Framework + * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2) + * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0) + * RFC 7725: An HTTP Status Code to Report Legal Obstacles + * RFC 8297: An HTTP Status Code for Indicating Hints + * RFC 8470: Using Early Data in HTTP + """ + + def __new__(cls, value: int, phrase: str = "") -> codes: + obj = int.__new__(cls, value) + obj._value_ = value + + obj.phrase = phrase # type: ignore[attr-defined] + return obj + + def __str__(self) -> str: + return str(self.value) + + @classmethod + def get_reason_phrase(cls, value: int) -> str: + try: + return codes(value).phrase # type: ignore + except ValueError: + return "" + + @classmethod + def is_informational(cls, value: int) -> bool: + """ + Returns `True` for 1xx status codes, `False` otherwise. + """ + return 100 <= value <= 199 + + @classmethod + def is_success(cls, value: int) -> bool: + """ + Returns `True` for 2xx status codes, `False` otherwise. + """ + return 200 <= value <= 299 + + @classmethod + def is_redirect(cls, value: int) -> bool: + """ + Returns `True` for 3xx status codes, `False` otherwise. + """ + return 300 <= value <= 399 + + @classmethod + def is_client_error(cls, value: int) -> bool: + """ + Returns `True` for 4xx status codes, `False` otherwise. + """ + return 400 <= value <= 499 + + @classmethod + def is_server_error(cls, value: int) -> bool: + """ + Returns `True` for 5xx status codes, `False` otherwise. + """ + return 500 <= value <= 599 + + @classmethod + def is_error(cls, value: int) -> bool: + """ + Returns `True` for 4xx or 5xx status codes, `False` otherwise. + """ + return 400 <= value <= 599 + + # informational + CONTINUE = 100, "Continue" + SWITCHING_PROTOCOLS = 101, "Switching Protocols" + PROCESSING = 102, "Processing" + EARLY_HINTS = 103, "Early Hints" + + # success + OK = 200, "OK" + CREATED = 201, "Created" + ACCEPTED = 202, "Accepted" + NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information" + NO_CONTENT = 204, "No Content" + RESET_CONTENT = 205, "Reset Content" + PARTIAL_CONTENT = 206, "Partial Content" + MULTI_STATUS = 207, "Multi-Status" + ALREADY_REPORTED = 208, "Already Reported" + IM_USED = 226, "IM Used" + + # redirection + MULTIPLE_CHOICES = 300, "Multiple Choices" + MOVED_PERMANENTLY = 301, "Moved Permanently" + FOUND = 302, "Found" + SEE_OTHER = 303, "See Other" + NOT_MODIFIED = 304, "Not Modified" + USE_PROXY = 305, "Use Proxy" + TEMPORARY_REDIRECT = 307, "Temporary Redirect" + PERMANENT_REDIRECT = 308, "Permanent Redirect" + + # client error + BAD_REQUEST = 400, "Bad Request" + UNAUTHORIZED = 401, "Unauthorized" + PAYMENT_REQUIRED = 402, "Payment Required" + FORBIDDEN = 403, "Forbidden" + NOT_FOUND = 404, "Not Found" + METHOD_NOT_ALLOWED = 405, "Method Not Allowed" + NOT_ACCEPTABLE = 406, "Not Acceptable" + PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required" + REQUEST_TIMEOUT = 408, "Request Timeout" + CONFLICT = 409, "Conflict" + GONE = 410, "Gone" + LENGTH_REQUIRED = 411, "Length Required" + PRECONDITION_FAILED = 412, "Precondition Failed" + REQUEST_ENTITY_TOO_LARGE = 413, "Request Entity Too Large" + REQUEST_URI_TOO_LONG = 414, "Request-URI Too Long" + UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type" + REQUESTED_RANGE_NOT_SATISFIABLE = 416, "Requested Range Not Satisfiable" + EXPECTATION_FAILED = 417, "Expectation Failed" + IM_A_TEAPOT = 418, "I'm a teapot" + MISDIRECTED_REQUEST = 421, "Misdirected Request" + UNPROCESSABLE_ENTITY = 422, "Unprocessable Entity" + LOCKED = 423, "Locked" + FAILED_DEPENDENCY = 424, "Failed Dependency" + TOO_EARLY = 425, "Too Early" + UPGRADE_REQUIRED = 426, "Upgrade Required" + PRECONDITION_REQUIRED = 428, "Precondition Required" + TOO_MANY_REQUESTS = 429, "Too Many Requests" + REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large" + UNAVAILABLE_FOR_LEGAL_REASONS = 451, "Unavailable For Legal Reasons" + + # server errors + INTERNAL_SERVER_ERROR = 500, "Internal Server Error" + NOT_IMPLEMENTED = 501, "Not Implemented" + BAD_GATEWAY = 502, "Bad Gateway" + SERVICE_UNAVAILABLE = 503, "Service Unavailable" + GATEWAY_TIMEOUT = 504, "Gateway Timeout" + HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported" + VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates" + INSUFFICIENT_STORAGE = 507, "Insufficient Storage" + LOOP_DETECTED = 508, "Loop Detected" + NOT_EXTENDED = 510, "Not Extended" + NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required" + + +# Include lower-case styles for `requests` compatibility. +for code in codes: + setattr(codes, code._name_.lower(), int(code)) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_types.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_types.py new file mode 100644 index 0000000000000000000000000000000000000000..704dfdffc8ba61eb913fa918072381e410b23c00 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_types.py @@ -0,0 +1,114 @@ +""" +Type definitions for type checking purposes. +""" + +from http.cookiejar import CookieJar +from typing import ( + IO, + TYPE_CHECKING, + Any, + AsyncIterable, + AsyncIterator, + Callable, + Dict, + Iterable, + Iterator, + List, + Mapping, + Optional, + Sequence, + Tuple, + Union, +) + +if TYPE_CHECKING: # pragma: no cover + from ._auth import Auth # noqa: F401 + from ._config import Proxy, Timeout # noqa: F401 + from ._models import Cookies, Headers, Request # noqa: F401 + from ._urls import URL, QueryParams # noqa: F401 + + +PrimitiveData = Optional[Union[str, int, float, bool]] + +URLTypes = Union["URL", str] + +QueryParamTypes = Union[ + "QueryParams", + Mapping[str, Union[PrimitiveData, Sequence[PrimitiveData]]], + List[Tuple[str, PrimitiveData]], + Tuple[Tuple[str, PrimitiveData], ...], + str, + bytes, +] + +HeaderTypes = Union[ + "Headers", + Mapping[str, str], + Mapping[bytes, bytes], + Sequence[Tuple[str, str]], + Sequence[Tuple[bytes, bytes]], +] + +CookieTypes = Union["Cookies", CookieJar, Dict[str, str], List[Tuple[str, str]]] + +TimeoutTypes = Union[ + Optional[float], + Tuple[Optional[float], Optional[float], Optional[float], Optional[float]], + "Timeout", +] +ProxyTypes = Union["URL", str, "Proxy"] +CertTypes = Union[str, Tuple[str, str], Tuple[str, str, str]] + +AuthTypes = Union[ + Tuple[Union[str, bytes], Union[str, bytes]], + Callable[["Request"], "Request"], + "Auth", +] + +RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] +ResponseContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]] +ResponseExtensions = Mapping[str, Any] + +RequestData = Mapping[str, Any] + +FileContent = Union[IO[bytes], bytes, str] +FileTypes = Union[ + # file (or bytes) + FileContent, + # (filename, file (or bytes)) + Tuple[Optional[str], FileContent], + # (filename, file (or bytes), content_type) + Tuple[Optional[str], FileContent, Optional[str]], + # (filename, file (or bytes), content_type, headers) + Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], +] +RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]] + +RequestExtensions = Mapping[str, Any] + +__all__ = ["AsyncByteStream", "SyncByteStream"] + + +class SyncByteStream: + def __iter__(self) -> Iterator[bytes]: + raise NotImplementedError( + "The '__iter__' method must be implemented." + ) # pragma: no cover + yield b"" # pragma: no cover + + def close(self) -> None: + """ + Subclasses can override this method to release any network resources + after a request/response cycle is complete. + """ + + +class AsyncByteStream: + async def __aiter__(self) -> AsyncIterator[bytes]: + raise NotImplementedError( + "The '__aiter__' method must be implemented." + ) # pragma: no cover + yield b"" # pragma: no cover + + async def aclose(self) -> None: + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_urlparse.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_urlparse.py new file mode 100644 index 0000000000000000000000000000000000000000..bf190fd560ee4fc8a11af371a15fc5f1dc284d34 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_urlparse.py @@ -0,0 +1,527 @@ +""" +An implementation of `urlparse` that provides URL validation and normalization +as described by RFC3986. + +We rely on this implementation rather than the one in Python's stdlib, because: + +* It provides more complete URL validation. +* It properly differentiates between an empty querystring and an absent querystring, + to distinguish URLs with a trailing '?'. +* It handles scheme, hostname, port, and path normalization. +* It supports IDNA hostnames, normalizing them to their encoded form. +* The API supports passing individual components, as well as the complete URL string. + +Previously we relied on the excellent `rfc3986` package to handle URL parsing and +validation, but this module provides a simpler alternative, with less indirection +required. +""" + +from __future__ import annotations + +import ipaddress +import re +import typing + +import idna + +from ._exceptions import InvalidURL + +MAX_URL_LENGTH = 65536 + +# https://datatracker.ietf.org/doc/html/rfc3986.html#section-2.3 +UNRESERVED_CHARACTERS = ( + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" +) +SUB_DELIMS = "!$&'()*+,;=" + +PERCENT_ENCODED_REGEX = re.compile("%[A-Fa-f0-9]{2}") + +# https://url.spec.whatwg.org/#percent-encoded-bytes + +# The fragment percent-encode set is the C0 control percent-encode set +# and U+0020 SPACE, U+0022 ("), U+003C (<), U+003E (>), and U+0060 (`). +FRAG_SAFE = "".join( + [chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x3C, 0x3E, 0x60)] +) + +# The query percent-encode set is the C0 control percent-encode set +# and U+0020 SPACE, U+0022 ("), U+0023 (#), U+003C (<), and U+003E (>). +QUERY_SAFE = "".join( + [chr(i) for i in range(0x20, 0x7F) if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E)] +) + +# The path percent-encode set is the query percent-encode set +# and U+003F (?), U+0060 (`), U+007B ({), and U+007D (}). +PATH_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + (0x3F, 0x60, 0x7B, 0x7D) + ] +) + +# The userinfo percent-encode set is the path percent-encode set +# and U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+0040 (@), +# U+005B ([) to U+005E (^), inclusive, and U+007C (|). +USERNAME_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i + not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + + (0x3F, 0x60, 0x7B, 0x7D) + + (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) + ] +) +PASSWORD_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i + not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + + (0x3F, 0x60, 0x7B, 0x7D) + + (0x2F, 0x3A, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) + ] +) +# Note... The terminology 'userinfo' percent-encode set in the WHATWG document +# is used for the username and password quoting. For the joint userinfo component +# we remove U+003A (:) from the safe set. +USERINFO_SAFE = "".join( + [ + chr(i) + for i in range(0x20, 0x7F) + if i + not in (0x20, 0x22, 0x23, 0x3C, 0x3E) + + (0x3F, 0x60, 0x7B, 0x7D) + + (0x2F, 0x3B, 0x3D, 0x40, 0x5B, 0x5C, 0x5D, 0x5E, 0x7C) + ] +) + + +# {scheme}: (optional) +# //{authority} (optional) +# {path} +# ?{query} (optional) +# #{fragment} (optional) +URL_REGEX = re.compile( + ( + r"(?:(?P{scheme}):)?" + r"(?://(?P{authority}))?" + r"(?P{path})" + r"(?:\?(?P{query}))?" + r"(?:#(?P{fragment}))?" + ).format( + scheme="([a-zA-Z][a-zA-Z0-9+.-]*)?", + authority="[^/?#]*", + path="[^?#]*", + query="[^#]*", + fragment=".*", + ) +) + +# {userinfo}@ (optional) +# {host} +# :{port} (optional) +AUTHORITY_REGEX = re.compile( + ( + r"(?:(?P{userinfo})@)?" r"(?P{host})" r":?(?P{port})?" + ).format( + userinfo=".*", # Any character sequence. + host="(\\[.*\\]|[^:@]*)", # Either any character sequence excluding ':' or '@', + # or an IPv6 address enclosed within square brackets. + port=".*", # Any character sequence. + ) +) + + +# If we call urlparse with an individual component, then we need to regex +# validate that component individually. +# Note that we're duplicating the same strings as above. Shock! Horror!! +COMPONENT_REGEX = { + "scheme": re.compile("([a-zA-Z][a-zA-Z0-9+.-]*)?"), + "authority": re.compile("[^/?#]*"), + "path": re.compile("[^?#]*"), + "query": re.compile("[^#]*"), + "fragment": re.compile(".*"), + "userinfo": re.compile("[^@]*"), + "host": re.compile("(\\[.*\\]|[^:]*)"), + "port": re.compile(".*"), +} + + +# We use these simple regexs as a first pass before handing off to +# the stdlib 'ipaddress' module for IP address validation. +IPv4_STYLE_HOSTNAME = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$") +IPv6_STYLE_HOSTNAME = re.compile(r"^\[.*\]$") + + +class ParseResult(typing.NamedTuple): + scheme: str + userinfo: str + host: str + port: int | None + path: str + query: str | None + fragment: str | None + + @property + def authority(self) -> str: + return "".join( + [ + f"{self.userinfo}@" if self.userinfo else "", + f"[{self.host}]" if ":" in self.host else self.host, + f":{self.port}" if self.port is not None else "", + ] + ) + + @property + def netloc(self) -> str: + return "".join( + [ + f"[{self.host}]" if ":" in self.host else self.host, + f":{self.port}" if self.port is not None else "", + ] + ) + + def copy_with(self, **kwargs: str | None) -> ParseResult: + if not kwargs: + return self + + defaults = { + "scheme": self.scheme, + "authority": self.authority, + "path": self.path, + "query": self.query, + "fragment": self.fragment, + } + defaults.update(kwargs) + return urlparse("", **defaults) + + def __str__(self) -> str: + authority = self.authority + return "".join( + [ + f"{self.scheme}:" if self.scheme else "", + f"//{authority}" if authority else "", + self.path, + f"?{self.query}" if self.query is not None else "", + f"#{self.fragment}" if self.fragment is not None else "", + ] + ) + + +def urlparse(url: str = "", **kwargs: str | None) -> ParseResult: + # Initial basic checks on allowable URLs. + # --------------------------------------- + + # Hard limit the maximum allowable URL length. + if len(url) > MAX_URL_LENGTH: + raise InvalidURL("URL too long") + + # If a URL includes any ASCII control characters including \t, \r, \n, + # then treat it as invalid. + if any(char.isascii() and not char.isprintable() for char in url): + char = next(char for char in url if char.isascii() and not char.isprintable()) + idx = url.find(char) + error = ( + f"Invalid non-printable ASCII character in URL, {char!r} at position {idx}." + ) + raise InvalidURL(error) + + # Some keyword arguments require special handling. + # ------------------------------------------------ + + # Coerce "port" to a string, if it is provided as an integer. + if "port" in kwargs: + port = kwargs["port"] + kwargs["port"] = str(port) if isinstance(port, int) else port + + # Replace "netloc" with "host and "port". + if "netloc" in kwargs: + netloc = kwargs.pop("netloc") or "" + kwargs["host"], _, kwargs["port"] = netloc.partition(":") + + # Replace "username" and/or "password" with "userinfo". + if "username" in kwargs or "password" in kwargs: + username = quote(kwargs.pop("username", "") or "", safe=USERNAME_SAFE) + password = quote(kwargs.pop("password", "") or "", safe=PASSWORD_SAFE) + kwargs["userinfo"] = f"{username}:{password}" if password else username + + # Replace "raw_path" with "path" and "query". + if "raw_path" in kwargs: + raw_path = kwargs.pop("raw_path") or "" + kwargs["path"], seperator, kwargs["query"] = raw_path.partition("?") + if not seperator: + kwargs["query"] = None + + # Ensure that IPv6 "host" addresses are always escaped with "[...]". + if "host" in kwargs: + host = kwargs.get("host") or "" + if ":" in host and not (host.startswith("[") and host.endswith("]")): + kwargs["host"] = f"[{host}]" + + # If any keyword arguments are provided, ensure they are valid. + # ------------------------------------------------------------- + + for key, value in kwargs.items(): + if value is not None: + if len(value) > MAX_URL_LENGTH: + raise InvalidURL(f"URL component '{key}' too long") + + # If a component includes any ASCII control characters including \t, \r, \n, + # then treat it as invalid. + if any(char.isascii() and not char.isprintable() for char in value): + char = next( + char for char in value if char.isascii() and not char.isprintable() + ) + idx = value.find(char) + error = ( + f"Invalid non-printable ASCII character in URL {key} component, " + f"{char!r} at position {idx}." + ) + raise InvalidURL(error) + + # Ensure that keyword arguments match as a valid regex. + if not COMPONENT_REGEX[key].fullmatch(value): + raise InvalidURL(f"Invalid URL component '{key}'") + + # The URL_REGEX will always match, but may have empty components. + url_match = URL_REGEX.match(url) + assert url_match is not None + url_dict = url_match.groupdict() + + # * 'scheme', 'authority', and 'path' may be empty strings. + # * 'query' may be 'None', indicating no trailing "?" portion. + # Any string including the empty string, indicates a trailing "?". + # * 'fragment' may be 'None', indicating no trailing "#" portion. + # Any string including the empty string, indicates a trailing "#". + scheme = kwargs.get("scheme", url_dict["scheme"]) or "" + authority = kwargs.get("authority", url_dict["authority"]) or "" + path = kwargs.get("path", url_dict["path"]) or "" + query = kwargs.get("query", url_dict["query"]) + frag = kwargs.get("fragment", url_dict["fragment"]) + + # The AUTHORITY_REGEX will always match, but may have empty components. + authority_match = AUTHORITY_REGEX.match(authority) + assert authority_match is not None + authority_dict = authority_match.groupdict() + + # * 'userinfo' and 'host' may be empty strings. + # * 'port' may be 'None'. + userinfo = kwargs.get("userinfo", authority_dict["userinfo"]) or "" + host = kwargs.get("host", authority_dict["host"]) or "" + port = kwargs.get("port", authority_dict["port"]) + + # Normalize and validate each component. + # We end up with a parsed representation of the URL, + # with components that are plain ASCII bytestrings. + parsed_scheme: str = scheme.lower() + parsed_userinfo: str = quote(userinfo, safe=USERINFO_SAFE) + parsed_host: str = encode_host(host) + parsed_port: int | None = normalize_port(port, scheme) + + has_scheme = parsed_scheme != "" + has_authority = ( + parsed_userinfo != "" or parsed_host != "" or parsed_port is not None + ) + validate_path(path, has_scheme=has_scheme, has_authority=has_authority) + if has_scheme or has_authority: + path = normalize_path(path) + + parsed_path: str = quote(path, safe=PATH_SAFE) + parsed_query: str | None = None if query is None else quote(query, safe=QUERY_SAFE) + parsed_frag: str | None = None if frag is None else quote(frag, safe=FRAG_SAFE) + + # The parsed ASCII bytestrings are our canonical form. + # All properties of the URL are derived from these. + return ParseResult( + parsed_scheme, + parsed_userinfo, + parsed_host, + parsed_port, + parsed_path, + parsed_query, + parsed_frag, + ) + + +def encode_host(host: str) -> str: + if not host: + return "" + + elif IPv4_STYLE_HOSTNAME.match(host): + # Validate IPv4 hostnames like #.#.#.# + # + # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 + # + # IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet + try: + ipaddress.IPv4Address(host) + except ipaddress.AddressValueError: + raise InvalidURL(f"Invalid IPv4 address: {host!r}") + return host + + elif IPv6_STYLE_HOSTNAME.match(host): + # Validate IPv6 hostnames like [...] + # + # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 + # + # "A host identified by an Internet Protocol literal address, version 6 + # [RFC3513] or later, is distinguished by enclosing the IP literal + # within square brackets ("[" and "]"). This is the only place where + # square bracket characters are allowed in the URI syntax." + try: + ipaddress.IPv6Address(host[1:-1]) + except ipaddress.AddressValueError: + raise InvalidURL(f"Invalid IPv6 address: {host!r}") + return host[1:-1] + + elif host.isascii(): + # Regular ASCII hostnames + # + # From https://datatracker.ietf.org/doc/html/rfc3986/#section-3.2.2 + # + # reg-name = *( unreserved / pct-encoded / sub-delims ) + WHATWG_SAFE = '"`{}%|\\' + return quote(host.lower(), safe=SUB_DELIMS + WHATWG_SAFE) + + # IDNA hostnames + try: + return idna.encode(host.lower()).decode("ascii") + except idna.IDNAError: + raise InvalidURL(f"Invalid IDNA hostname: {host!r}") + + +def normalize_port(port: str | int | None, scheme: str) -> int | None: + # From https://tools.ietf.org/html/rfc3986#section-3.2.3 + # + # "A scheme may define a default port. For example, the "http" scheme + # defines a default port of "80", corresponding to its reserved TCP + # port number. The type of port designated by the port number (e.g., + # TCP, UDP, SCTP) is defined by the URI scheme. URI producers and + # normalizers should omit the port component and its ":" delimiter if + # port is empty or if its value would be the same as that of the + # scheme's default." + if port is None or port == "": + return None + + try: + port_as_int = int(port) + except ValueError: + raise InvalidURL(f"Invalid port: {port!r}") + + # See https://url.spec.whatwg.org/#url-miscellaneous + default_port = {"ftp": 21, "http": 80, "https": 443, "ws": 80, "wss": 443}.get( + scheme + ) + if port_as_int == default_port: + return None + return port_as_int + + +def validate_path(path: str, has_scheme: bool, has_authority: bool) -> None: + """ + Path validation rules that depend on if the URL contains + a scheme or authority component. + + See https://datatracker.ietf.org/doc/html/rfc3986.html#section-3.3 + """ + if has_authority: + # If a URI contains an authority component, then the path component + # must either be empty or begin with a slash ("/") character." + if path and not path.startswith("/"): + raise InvalidURL("For absolute URLs, path must be empty or begin with '/'") + + if not has_scheme and not has_authority: + # If a URI does not contain an authority component, then the path cannot begin + # with two slash characters ("//"). + if path.startswith("//"): + raise InvalidURL("Relative URLs cannot have a path starting with '//'") + + # In addition, a URI reference (Section 4.1) may be a relative-path reference, + # in which case the first path segment cannot contain a colon (":") character. + if path.startswith(":"): + raise InvalidURL("Relative URLs cannot have a path starting with ':'") + + +def normalize_path(path: str) -> str: + """ + Drop "." and ".." segments from a URL path. + + For example: + + normalize_path("/path/./to/somewhere/..") == "/path/to" + """ + # Fast return when no '.' characters in the path. + if "." not in path: + return path + + components = path.split("/") + + # Fast return when no '.' or '..' components in the path. + if "." not in components and ".." not in components: + return path + + # https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + output: list[str] = [] + for component in components: + if component == ".": + pass + elif component == "..": + if output and output != [""]: + output.pop() + else: + output.append(component) + return "/".join(output) + + +def PERCENT(string: str) -> str: + return "".join([f"%{byte:02X}" for byte in string.encode("utf-8")]) + + +def percent_encoded(string: str, safe: str) -> str: + """ + Use percent-encoding to quote a string. + """ + NON_ESCAPED_CHARS = UNRESERVED_CHARACTERS + safe + + # Fast path for strings that don't need escaping. + if not string.rstrip(NON_ESCAPED_CHARS): + return string + + return "".join( + [char if char in NON_ESCAPED_CHARS else PERCENT(char) for char in string] + ) + + +def quote(string: str, safe: str) -> str: + """ + Use percent-encoding to quote a string, omitting existing '%xx' escape sequences. + + See: https://www.rfc-editor.org/rfc/rfc3986#section-2.1 + + * `string`: The string to be percent-escaped. + * `safe`: A string containing characters that may be treated as safe, and do not + need to be escaped. Unreserved characters are always treated as safe. + See: https://www.rfc-editor.org/rfc/rfc3986#section-2.3 + """ + parts = [] + current_position = 0 + for match in re.finditer(PERCENT_ENCODED_REGEX, string): + start_position, end_position = match.start(), match.end() + matched_text = match.group(0) + # Add any text up to the '%xx' escape sequence. + if start_position != current_position: + leading_text = string[current_position:start_position] + parts.append(percent_encoded(leading_text, safe=safe)) + + # Add the '%xx' escape sequence. + parts.append(matched_text) + current_position = end_position + + # Add any text after the final '%xx' escape sequence. + if current_position != len(string): + trailing_text = string[current_position:] + parts.append(percent_encoded(trailing_text, safe=safe)) + + return "".join(parts) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_urls.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..147a8fa333acaf31618d37ba2896e3a5bf5e4d02 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_urls.py @@ -0,0 +1,641 @@ +from __future__ import annotations + +import typing +from urllib.parse import parse_qs, unquote, urlencode + +import idna + +from ._types import QueryParamTypes +from ._urlparse import urlparse +from ._utils import primitive_value_to_str + +__all__ = ["URL", "QueryParams"] + + +class URL: + """ + url = httpx.URL("HTTPS://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink") + + assert url.scheme == "https" + assert url.username == "jo@email.com" + assert url.password == "a secret" + assert url.userinfo == b"jo%40email.com:a%20secret" + assert url.host == "müller.de" + assert url.raw_host == b"xn--mller-kva.de" + assert url.port == 1234 + assert url.netloc == b"xn--mller-kva.de:1234" + assert url.path == "/pa th" + assert url.query == b"?search=ab" + assert url.raw_path == b"/pa%20th?search=ab" + assert url.fragment == "anchorlink" + + The components of a URL are broken down like this: + + https://jo%40email.com:a%20secret@müller.de:1234/pa%20th?search=ab#anchorlink + [scheme] [ username ] [password] [ host ][port][ path ] [ query ] [fragment] + [ userinfo ] [ netloc ][ raw_path ] + + Note that: + + * `url.scheme` is normalized to always be lowercased. + + * `url.host` is normalized to always be lowercased. Internationalized domain + names are represented in unicode, without IDNA encoding applied. For instance: + + url = httpx.URL("http://中国.icom.museum") + assert url.host == "中国.icom.museum" + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.host == "中国.icom.museum" + + * `url.raw_host` is normalized to always be lowercased, and is IDNA encoded. + + url = httpx.URL("http://中国.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + * `url.port` is either None or an integer. URLs that include the default port for + "http", "https", "ws", "wss", and "ftp" schemes have their port + normalized to `None`. + + assert httpx.URL("http://example.com") == httpx.URL("http://example.com:80") + assert httpx.URL("http://example.com").port is None + assert httpx.URL("http://example.com:80").port is None + + * `url.userinfo` is raw bytes, without URL escaping. Usually you'll want to work + with `url.username` and `url.password` instead, which handle the URL escaping. + + * `url.raw_path` is raw bytes of both the path and query, without URL escaping. + This portion is used as the target when constructing HTTP requests. Usually you'll + want to work with `url.path` instead. + + * `url.query` is raw bytes, without URL escaping. A URL query string portion can + only be properly URL escaped when decoding the parameter names and values + themselves. + """ + + def __init__(self, url: URL | str = "", **kwargs: typing.Any) -> None: + if kwargs: + allowed = { + "scheme": str, + "username": str, + "password": str, + "userinfo": bytes, + "host": str, + "port": int, + "netloc": bytes, + "path": str, + "query": bytes, + "raw_path": bytes, + "fragment": str, + "params": object, + } + + # Perform type checking for all supported keyword arguments. + for key, value in kwargs.items(): + if key not in allowed: + message = f"{key!r} is an invalid keyword argument for URL()" + raise TypeError(message) + if value is not None and not isinstance(value, allowed[key]): + expected = allowed[key].__name__ + seen = type(value).__name__ + message = f"Argument {key!r} must be {expected} but got {seen}" + raise TypeError(message) + if isinstance(value, bytes): + kwargs[key] = value.decode("ascii") + + if "params" in kwargs: + # Replace any "params" keyword with the raw "query" instead. + # + # Ensure that empty params use `kwargs["query"] = None` rather + # than `kwargs["query"] = ""`, so that generated URLs do not + # include an empty trailing "?". + params = kwargs.pop("params") + kwargs["query"] = None if not params else str(QueryParams(params)) + + if isinstance(url, str): + self._uri_reference = urlparse(url, **kwargs) + elif isinstance(url, URL): + self._uri_reference = url._uri_reference.copy_with(**kwargs) + else: + raise TypeError( + "Invalid type for url. Expected str or httpx.URL," + f" got {type(url)}: {url!r}" + ) + + @property + def scheme(self) -> str: + """ + The URL scheme, such as "http", "https". + Always normalised to lowercase. + """ + return self._uri_reference.scheme + + @property + def raw_scheme(self) -> bytes: + """ + The raw bytes representation of the URL scheme, such as b"http", b"https". + Always normalised to lowercase. + """ + return self._uri_reference.scheme.encode("ascii") + + @property + def userinfo(self) -> bytes: + """ + The URL userinfo as a raw bytestring. + For example: b"jo%40email.com:a%20secret". + """ + return self._uri_reference.userinfo.encode("ascii") + + @property + def username(self) -> str: + """ + The URL username as a string, with URL decoding applied. + For example: "jo@email.com" + """ + userinfo = self._uri_reference.userinfo + return unquote(userinfo.partition(":")[0]) + + @property + def password(self) -> str: + """ + The URL password as a string, with URL decoding applied. + For example: "a secret" + """ + userinfo = self._uri_reference.userinfo + return unquote(userinfo.partition(":")[2]) + + @property + def host(self) -> str: + """ + The URL host as a string. + Always normalized to lowercase, with IDNA hosts decoded into unicode. + + Examples: + + url = httpx.URL("http://www.EXAMPLE.org") + assert url.host == "www.example.org" + + url = httpx.URL("http://中国.icom.museum") + assert url.host == "中国.icom.museum" + + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.host == "中国.icom.museum" + + url = httpx.URL("https://[::ffff:192.168.0.1]") + assert url.host == "::ffff:192.168.0.1" + """ + host: str = self._uri_reference.host + + if host.startswith("xn--"): + host = idna.decode(host) + + return host + + @property + def raw_host(self) -> bytes: + """ + The raw bytes representation of the URL host. + Always normalized to lowercase, and IDNA encoded. + + Examples: + + url = httpx.URL("http://www.EXAMPLE.org") + assert url.raw_host == b"www.example.org" + + url = httpx.URL("http://中国.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + url = httpx.URL("http://xn--fiqs8s.icom.museum") + assert url.raw_host == b"xn--fiqs8s.icom.museum" + + url = httpx.URL("https://[::ffff:192.168.0.1]") + assert url.raw_host == b"::ffff:192.168.0.1" + """ + return self._uri_reference.host.encode("ascii") + + @property + def port(self) -> int | None: + """ + The URL port as an integer. + + Note that the URL class performs port normalization as per the WHATWG spec. + Default ports for "http", "https", "ws", "wss", and "ftp" schemes are always + treated as `None`. + + For example: + + assert httpx.URL("http://www.example.com") == httpx.URL("http://www.example.com:80") + assert httpx.URL("http://www.example.com:80").port is None + """ + return self._uri_reference.port + + @property + def netloc(self) -> bytes: + """ + Either `` or `:` as bytes. + Always normalized to lowercase, and IDNA encoded. + + This property may be used for generating the value of a request + "Host" header. + """ + return self._uri_reference.netloc.encode("ascii") + + @property + def path(self) -> str: + """ + The URL path as a string. Excluding the query string, and URL decoded. + + For example: + + url = httpx.URL("https://example.com/pa%20th") + assert url.path == "/pa th" + """ + path = self._uri_reference.path or "/" + return unquote(path) + + @property + def query(self) -> bytes: + """ + The URL query string, as raw bytes, excluding the leading b"?". + + This is necessarily a bytewise interface, because we cannot + perform URL decoding of this representation until we've parsed + the keys and values into a QueryParams instance. + + For example: + + url = httpx.URL("https://example.com/?filter=some%20search%20terms") + assert url.query == b"filter=some%20search%20terms" + """ + query = self._uri_reference.query or "" + return query.encode("ascii") + + @property + def params(self) -> QueryParams: + """ + The URL query parameters, neatly parsed and packaged into an immutable + multidict representation. + """ + return QueryParams(self._uri_reference.query) + + @property + def raw_path(self) -> bytes: + """ + The complete URL path and query string as raw bytes. + Used as the target when constructing HTTP requests. + + For example: + + GET /users?search=some%20text HTTP/1.1 + Host: www.example.org + Connection: close + """ + path = self._uri_reference.path or "/" + if self._uri_reference.query is not None: + path += "?" + self._uri_reference.query + return path.encode("ascii") + + @property + def fragment(self) -> str: + """ + The URL fragments, as used in HTML anchors. + As a string, without the leading '#'. + """ + return unquote(self._uri_reference.fragment or "") + + @property + def is_absolute_url(self) -> bool: + """ + Return `True` for absolute URLs such as 'http://example.com/path', + and `False` for relative URLs such as '/path'. + """ + # We don't use `.is_absolute` from `rfc3986` because it treats + # URLs with a fragment portion as not absolute. + # What we actually care about is if the URL provides + # a scheme and hostname to which connections should be made. + return bool(self._uri_reference.scheme and self._uri_reference.host) + + @property + def is_relative_url(self) -> bool: + """ + Return `False` for absolute URLs such as 'http://example.com/path', + and `True` for relative URLs such as '/path'. + """ + return not self.is_absolute_url + + def copy_with(self, **kwargs: typing.Any) -> URL: + """ + Copy this URL, returning a new URL with some components altered. + Accepts the same set of parameters as the components that are made + available via properties on the `URL` class. + + For example: + + url = httpx.URL("https://www.example.com").copy_with( + username="jo@gmail.com", password="a secret" + ) + assert url == "https://jo%40email.com:a%20secret@www.example.com" + """ + return URL(self, **kwargs) + + def copy_set_param(self, key: str, value: typing.Any = None) -> URL: + return self.copy_with(params=self.params.set(key, value)) + + def copy_add_param(self, key: str, value: typing.Any = None) -> URL: + return self.copy_with(params=self.params.add(key, value)) + + def copy_remove_param(self, key: str) -> URL: + return self.copy_with(params=self.params.remove(key)) + + def copy_merge_params(self, params: QueryParamTypes) -> URL: + return self.copy_with(params=self.params.merge(params)) + + def join(self, url: URL | str) -> URL: + """ + Return an absolute URL, using this URL as the base. + + Eg. + + url = httpx.URL("https://www.example.com/test") + url = url.join("/new/path") + assert url == "https://www.example.com/new/path" + """ + from urllib.parse import urljoin + + return URL(urljoin(str(self), str(URL(url)))) + + def __hash__(self) -> int: + return hash(str(self)) + + def __eq__(self, other: typing.Any) -> bool: + return isinstance(other, (URL, str)) and str(self) == str(URL(other)) + + def __str__(self) -> str: + return str(self._uri_reference) + + def __repr__(self) -> str: + scheme, userinfo, host, port, path, query, fragment = self._uri_reference + + if ":" in userinfo: + # Mask any password component. + userinfo = f'{userinfo.split(":")[0]}:[secure]' + + authority = "".join( + [ + f"{userinfo}@" if userinfo else "", + f"[{host}]" if ":" in host else host, + f":{port}" if port is not None else "", + ] + ) + url = "".join( + [ + f"{self.scheme}:" if scheme else "", + f"//{authority}" if authority else "", + path, + f"?{query}" if query is not None else "", + f"#{fragment}" if fragment is not None else "", + ] + ) + + return f"{self.__class__.__name__}({url!r})" + + @property + def raw(self) -> tuple[bytes, bytes, int, bytes]: # pragma: nocover + import collections + import warnings + + warnings.warn("URL.raw is deprecated.") + RawURL = collections.namedtuple( + "RawURL", ["raw_scheme", "raw_host", "port", "raw_path"] + ) + return RawURL( + raw_scheme=self.raw_scheme, + raw_host=self.raw_host, + port=self.port, + raw_path=self.raw_path, + ) + + +class QueryParams(typing.Mapping[str, str]): + """ + URL query parameters, as a multi-dict. + """ + + def __init__(self, *args: QueryParamTypes | None, **kwargs: typing.Any) -> None: + assert len(args) < 2, "Too many arguments." + assert not (args and kwargs), "Cannot mix named and unnamed arguments." + + value = args[0] if args else kwargs + + if value is None or isinstance(value, (str, bytes)): + value = value.decode("ascii") if isinstance(value, bytes) else value + self._dict = parse_qs(value, keep_blank_values=True) + elif isinstance(value, QueryParams): + self._dict = {k: list(v) for k, v in value._dict.items()} + else: + dict_value: dict[typing.Any, list[typing.Any]] = {} + if isinstance(value, (list, tuple)): + # Convert list inputs like: + # [("a", "123"), ("a", "456"), ("b", "789")] + # To a dict representation, like: + # {"a": ["123", "456"], "b": ["789"]} + for item in value: + dict_value.setdefault(item[0], []).append(item[1]) + else: + # Convert dict inputs like: + # {"a": "123", "b": ["456", "789"]} + # To dict inputs where values are always lists, like: + # {"a": ["123"], "b": ["456", "789"]} + dict_value = { + k: list(v) if isinstance(v, (list, tuple)) else [v] + for k, v in value.items() + } + + # Ensure that keys and values are neatly coerced to strings. + # We coerce values `True` and `False` to JSON-like "true" and "false" + # representations, and coerce `None` values to the empty string. + self._dict = { + str(k): [primitive_value_to_str(item) for item in v] + for k, v in dict_value.items() + } + + def keys(self) -> typing.KeysView[str]: + """ + Return all the keys in the query params. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.keys()) == ["a", "b"] + """ + return self._dict.keys() + + def values(self) -> typing.ValuesView[str]: + """ + Return all the values in the query params. If a key occurs more than once + only the first item for that key is returned. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.values()) == ["123", "789"] + """ + return {k: v[0] for k, v in self._dict.items()}.values() + + def items(self) -> typing.ItemsView[str, str]: + """ + Return all items in the query params. If a key occurs more than once + only the first item for that key is returned. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.items()) == [("a", "123"), ("b", "789")] + """ + return {k: v[0] for k, v in self._dict.items()}.items() + + def multi_items(self) -> list[tuple[str, str]]: + """ + Return all items in the query params. Allow duplicate keys to occur. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert list(q.multi_items()) == [("a", "123"), ("a", "456"), ("b", "789")] + """ + multi_items: list[tuple[str, str]] = [] + for k, v in self._dict.items(): + multi_items.extend([(k, i) for i in v]) + return multi_items + + def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any: + """ + Get a value from the query param for a given key. If the key occurs + more than once, then only the first value is returned. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert q.get("a") == "123" + """ + if key in self._dict: + return self._dict[str(key)][0] + return default + + def get_list(self, key: str) -> list[str]: + """ + Get all values from the query param for a given key. + + Usage: + + q = httpx.QueryParams("a=123&a=456&b=789") + assert q.get_list("a") == ["123", "456"] + """ + return list(self._dict.get(str(key), [])) + + def set(self, key: str, value: typing.Any = None) -> QueryParams: + """ + Return a new QueryParams instance, setting the value of a key. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.set("a", "456") + assert q == httpx.QueryParams("a=456") + """ + q = QueryParams() + q._dict = dict(self._dict) + q._dict[str(key)] = [primitive_value_to_str(value)] + return q + + def add(self, key: str, value: typing.Any = None) -> QueryParams: + """ + Return a new QueryParams instance, setting or appending the value of a key. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.add("a", "456") + assert q == httpx.QueryParams("a=123&a=456") + """ + q = QueryParams() + q._dict = dict(self._dict) + q._dict[str(key)] = q.get_list(key) + [primitive_value_to_str(value)] + return q + + def remove(self, key: str) -> QueryParams: + """ + Return a new QueryParams instance, removing the value of a key. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.remove("a") + assert q == httpx.QueryParams("") + """ + q = QueryParams() + q._dict = dict(self._dict) + q._dict.pop(str(key), None) + return q + + def merge(self, params: QueryParamTypes | None = None) -> QueryParams: + """ + Return a new QueryParams instance, updated with. + + Usage: + + q = httpx.QueryParams("a=123") + q = q.merge({"b": "456"}) + assert q == httpx.QueryParams("a=123&b=456") + + q = httpx.QueryParams("a=123") + q = q.merge({"a": "456", "b": "789"}) + assert q == httpx.QueryParams("a=456&b=789") + """ + q = QueryParams(params) + q._dict = {**self._dict, **q._dict} + return q + + def __getitem__(self, key: typing.Any) -> str: + return self._dict[key][0] + + def __contains__(self, key: typing.Any) -> bool: + return key in self._dict + + def __iter__(self) -> typing.Iterator[typing.Any]: + return iter(self.keys()) + + def __len__(self) -> int: + return len(self._dict) + + def __bool__(self) -> bool: + return bool(self._dict) + + def __hash__(self) -> int: + return hash(str(self)) + + def __eq__(self, other: typing.Any) -> bool: + if not isinstance(other, self.__class__): + return False + return sorted(self.multi_items()) == sorted(other.multi_items()) + + def __str__(self) -> str: + return urlencode(self.multi_items()) + + def __repr__(self) -> str: + class_name = self.__class__.__name__ + query_string = str(self) + return f"{class_name}({query_string!r})" + + def update(self, params: QueryParamTypes | None = None) -> None: + raise RuntimeError( + "QueryParams are immutable since 0.18.0. " + "Use `q = q.merge(...)` to create an updated copy." + ) + + def __setitem__(self, key: str, value: str) -> None: + raise RuntimeError( + "QueryParams are immutable since 0.18.0. " + "Use `q = q.set(key, value)` to create an updated copy." + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe827da4d071b32ea6da44328629699d6fc88ce --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/_utils.py @@ -0,0 +1,242 @@ +from __future__ import annotations + +import ipaddress +import os +import re +import typing +from urllib.request import getproxies + +from ._types import PrimitiveData + +if typing.TYPE_CHECKING: # pragma: no cover + from ._urls import URL + + +def primitive_value_to_str(value: PrimitiveData) -> str: + """ + Coerce a primitive data type into a string value. + + Note that we prefer JSON-style 'true'/'false' for boolean values here. + """ + if value is True: + return "true" + elif value is False: + return "false" + elif value is None: + return "" + return str(value) + + +def get_environment_proxies() -> dict[str, str | None]: + """Gets proxy information from the environment""" + + # urllib.request.getproxies() falls back on System + # Registry and Config for proxies on Windows and macOS. + # We don't want to propagate non-HTTP proxies into + # our configuration such as 'TRAVIS_APT_PROXY'. + proxy_info = getproxies() + mounts: dict[str, str | None] = {} + + for scheme in ("http", "https", "all"): + if proxy_info.get(scheme): + hostname = proxy_info[scheme] + mounts[f"{scheme}://"] = ( + hostname if "://" in hostname else f"http://{hostname}" + ) + + no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")] + for hostname in no_proxy_hosts: + # See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details + # on how names in `NO_PROXY` are handled. + if hostname == "*": + # If NO_PROXY=* is used or if "*" occurs as any one of the comma + # separated hostnames, then we should just bypass any information + # from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore + # proxies. + return {} + elif hostname: + # NO_PROXY=.google.com is marked as "all://*.google.com, + # which disables "www.google.com" but not "google.com" + # NO_PROXY=google.com is marked as "all://*google.com, + # which disables "www.google.com" and "google.com". + # (But not "wwwgoogle.com") + # NO_PROXY can include domains, IPv6, IPv4 addresses and "localhost" + # NO_PROXY=example.com,::1,localhost,192.168.0.0/16 + if "://" in hostname: + mounts[hostname] = None + elif is_ipv4_hostname(hostname): + mounts[f"all://{hostname}"] = None + elif is_ipv6_hostname(hostname): + mounts[f"all://[{hostname}]"] = None + elif hostname.lower() == "localhost": + mounts[f"all://{hostname}"] = None + else: + mounts[f"all://*{hostname}"] = None + + return mounts + + +def to_bytes(value: str | bytes, encoding: str = "utf-8") -> bytes: + return value.encode(encoding) if isinstance(value, str) else value + + +def to_str(value: str | bytes, encoding: str = "utf-8") -> str: + return value if isinstance(value, str) else value.decode(encoding) + + +def to_bytes_or_str(value: str, match_type_of: typing.AnyStr) -> typing.AnyStr: + return value if isinstance(match_type_of, str) else value.encode() + + +def unquote(value: str) -> str: + return value[1:-1] if value[0] == value[-1] == '"' else value + + +def peek_filelike_length(stream: typing.Any) -> int | None: + """ + Given a file-like stream object, return its length in number of bytes + without reading it into memory. + """ + try: + # Is it an actual file? + fd = stream.fileno() + # Yup, seems to be an actual file. + length = os.fstat(fd).st_size + except (AttributeError, OSError): + # No... Maybe it's something that supports random access, like `io.BytesIO`? + try: + # Assuming so, go to end of stream to figure out its length, + # then put it back in place. + offset = stream.tell() + length = stream.seek(0, os.SEEK_END) + stream.seek(offset) + except (AttributeError, OSError): + # Not even that? Sorry, we're doomed... + return None + + return length + + +class URLPattern: + """ + A utility class currently used for making lookups against proxy keys... + + # Wildcard matching... + >>> pattern = URLPattern("all://") + >>> pattern.matches(httpx.URL("http://example.com")) + True + + # Witch scheme matching... + >>> pattern = URLPattern("https://") + >>> pattern.matches(httpx.URL("https://example.com")) + True + >>> pattern.matches(httpx.URL("http://example.com")) + False + + # With domain matching... + >>> pattern = URLPattern("https://example.com") + >>> pattern.matches(httpx.URL("https://example.com")) + True + >>> pattern.matches(httpx.URL("http://example.com")) + False + >>> pattern.matches(httpx.URL("https://other.com")) + False + + # Wildcard scheme, with domain matching... + >>> pattern = URLPattern("all://example.com") + >>> pattern.matches(httpx.URL("https://example.com")) + True + >>> pattern.matches(httpx.URL("http://example.com")) + True + >>> pattern.matches(httpx.URL("https://other.com")) + False + + # With port matching... + >>> pattern = URLPattern("https://example.com:1234") + >>> pattern.matches(httpx.URL("https://example.com:1234")) + True + >>> pattern.matches(httpx.URL("https://example.com")) + False + """ + + def __init__(self, pattern: str) -> None: + from ._urls import URL + + if pattern and ":" not in pattern: + raise ValueError( + f"Proxy keys should use proper URL forms rather " + f"than plain scheme strings. " + f'Instead of "{pattern}", use "{pattern}://"' + ) + + url = URL(pattern) + self.pattern = pattern + self.scheme = "" if url.scheme == "all" else url.scheme + self.host = "" if url.host == "*" else url.host + self.port = url.port + if not url.host or url.host == "*": + self.host_regex: typing.Pattern[str] | None = None + elif url.host.startswith("*."): + # *.example.com should match "www.example.com", but not "example.com" + domain = re.escape(url.host[2:]) + self.host_regex = re.compile(f"^.+\\.{domain}$") + elif url.host.startswith("*"): + # *example.com should match "www.example.com" and "example.com" + domain = re.escape(url.host[1:]) + self.host_regex = re.compile(f"^(.+\\.)?{domain}$") + else: + # example.com should match "example.com" but not "www.example.com" + domain = re.escape(url.host) + self.host_regex = re.compile(f"^{domain}$") + + def matches(self, other: URL) -> bool: + if self.scheme and self.scheme != other.scheme: + return False + if ( + self.host + and self.host_regex is not None + and not self.host_regex.match(other.host) + ): + return False + if self.port is not None and self.port != other.port: + return False + return True + + @property + def priority(self) -> tuple[int, int, int]: + """ + The priority allows URLPattern instances to be sortable, so that + we can match from most specific to least specific. + """ + # URLs with a port should take priority over URLs without a port. + port_priority = 0 if self.port is not None else 1 + # Longer hostnames should match first. + host_priority = -len(self.host) + # Longer schemes should match first. + scheme_priority = -len(self.scheme) + return (port_priority, host_priority, scheme_priority) + + def __hash__(self) -> int: + return hash(self.pattern) + + def __lt__(self, other: URLPattern) -> bool: + return self.priority < other.priority + + def __eq__(self, other: typing.Any) -> bool: + return isinstance(other, URLPattern) and self.pattern == other.pattern + + +def is_ipv4_hostname(hostname: str) -> bool: + try: + ipaddress.IPv4Address(hostname.split("/")[0]) + except Exception: + return False + return True + + +def is_ipv6_hostname(hostname: str) -> bool: + try: + ipaddress.IPv6Address(hostname.split("/")[0]) + except Exception: + return False + return True diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..41f3bf1fa4bb5b39c621342402bce2dae3499d3f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/METADATA @@ -0,0 +1,351 @@ +Metadata-Version: 2.4 +Name: httpx-sse +Version: 0.4.3 +Summary: Consume Server-Sent Event (SSE) messages with HTTPX. +Author-email: Florimond Manca +License: MIT +Project-URL: Homepage, https://github.com/florimondmanca/httpx-sse +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Dynamic: license-file + +# httpx-sse + +[![Build Status](https://dev.azure.com/florimondmanca/public/_apis/build/status/florimondmanca.httpx-sse?branchName=master)](https://dev.azure.com/florimondmanca/public/_build?definitionId=19) +[![Coverage](https://codecov.io/gh/florimondmanca/httpx-sse/branch/master/graph/badge.svg)](https://codecov.io/gh/florimondmanca/httpx-sse) +[![Package version](https://badge.fury.io/py/httpx-sse.svg)](https://pypi.org/project/httpx-sse) + +Consume [Server-Sent Event (SSE)](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events) messages with [HTTPX](https://www.python-httpx.org). + +**Table of contents** + +- [Installation](#installation) +- [Quickstart](#quickstart) +- [How-To](#how-to) +- [API Reference](#api-reference) + +## Installation + +**NOTE**: This is beta software. Please be sure to pin your dependencies. + +```bash +pip install httpx-sse=="0.4.*" +``` + +## Quickstart + +`httpx-sse` provides the [`connect_sse`](#connect_sse) and [`aconnect_sse`](#aconnect_sse) helpers for connecting to an SSE endpoint. The resulting [`EventSource`](#eventsource) object exposes the [`.iter_sse()`](#iter_sse) and [`.aiter_sse()`](#aiter_sse) methods to iterate over the server-sent events. + +Example usage: + +```python +import httpx +from httpx_sse import connect_sse + +with httpx.Client() as client: + with connect_sse(client, "GET", "http://localhost:8000/sse") as event_source: + for sse in event_source.iter_sse(): + print(sse.event, sse.data, sse.id, sse.retry) +``` + +You can try this against this example Starlette server ([credit](https://sysid.github.io/sse/)): + +```python +# Requirements: pip install uvicorn starlette sse-starlette +import asyncio +import uvicorn +from starlette.applications import Starlette +from starlette.routing import Route +from sse_starlette.sse import EventSourceResponse + +async def numbers(minimum, maximum): + for i in range(minimum, maximum + 1): + await asyncio.sleep(0.9) + yield {"data": i} + +async def sse(request): + generator = numbers(1, 5) + return EventSourceResponse(generator) + +routes = [ + Route("/sse", endpoint=sse) +] + +app = Starlette(routes=routes) + +if __name__ == "__main__": + uvicorn.run(app) +``` + +## How-To + +### Calling into Python web apps + +You can [call into Python web apps](https://www.python-httpx.org/async/#calling-into-python-web-apps) with HTTPX and `httpx-sse` to test SSE endpoints directly. + +Here's an example of calling into a Starlette ASGI app... + +```python +import asyncio + +import httpx +from httpx_sse import aconnect_sse +from sse_starlette.sse import EventSourceResponse +from starlette.applications import Starlette +from starlette.routing import Route + +async def auth_events(request): + async def events(): + yield { + "event": "login", + "data": '{"user_id": "4135"}', + } + + return EventSourceResponse(events()) + +app = Starlette(routes=[Route("/sse/auth/", endpoint=auth_events)]) + +async def main(): + async with httpx.AsyncClient(transport=httpx.ASGITransport(app)) as client: + async with aconnect_sse( + client, "GET", "http://localhost:8000/sse/auth/" + ) as event_source: + events = [sse async for sse in event_source.aiter_sse()] + (sse,) = events + assert sse.event == "login" + assert sse.json() == {"user_id": "4135"} + +asyncio.run(main()) +``` + +### Handling reconnections + +_(Advanced)_ + +`SSETransport` and `AsyncSSETransport` don't have reconnection built-in. This is because how to perform retries is generally dependent on your use case. As a result, if the connection breaks while attempting to read from the server, you will get an `httpx.ReadError` from `iter_sse()` (or `aiter_sse()`). + +However, `httpx-sse` does allow implementing reconnection by using the `Last-Event-ID` and reconnection time (in milliseconds), exposed as `sse.id` and `sse.retry` respectively. + +Here's how you might achieve this using [`stamina`](https://github.com/hynek/stamina)... + +```python +import time +from typing import Iterator + +import httpx +from httpx_sse import connect_sse, ServerSentEvent +from stamina import retry + +def iter_sse_retrying(client, method, url): + last_event_id = "" + reconnection_delay = 0.0 + + # `stamina` will apply jitter and exponential backoff on top of + # the `retry` reconnection delay sent by the server. + @retry(on=httpx.ReadError) + def _iter_sse(): + nonlocal last_event_id, reconnection_delay + + time.sleep(reconnection_delay) + + headers = {"Accept": "text/event-stream"} + + if last_event_id: + headers["Last-Event-ID"] = last_event_id + + with connect_sse(client, method, url, headers=headers) as event_source: + for sse in event_source.iter_sse(): + last_event_id = sse.id + + if sse.retry is not None: + reconnection_delay = sse.retry / 1000 + + yield sse + + return _iter_sse() +``` + +Usage: + +```python +with httpx.Client() as client: + for sse in iter_sse_retrying(client, "GET", "http://localhost:8000/sse"): + print(sse.event, sse.data) +``` + +## API Reference + +### `connect_sse` + +```python +def connect_sse( + client: httpx.Client, + method: str, + url: Union[str, httpx.URL], + **kwargs, +) -> ContextManager[EventSource] +``` + +Connect to an SSE endpoint and return an [`EventSource`](#eventsource) context manager. + +This sets `Cache-Control: no-store` on the request, as per the SSE spec, as well as `Accept: text/event-stream`. + +If the response `Content-Type` is not `text/event-stream`, this will raise an [`SSEError`](#sseerror). + +### `aconnect_sse` + +```python +async def aconnect_sse( + client: httpx.AsyncClient, + method: str, + url: Union[str, httpx.URL], + **kwargs, +) -> AsyncContextManager[EventSource] +``` + +An async equivalent to [`connect_sse`](#connect_sse). + +### `EventSource` + +```python +def __init__(response: httpx.Response) +``` + +Helper for working with an SSE response. + +#### `response` + +The underlying [`httpx.Response`](https://www.python-httpx.org/api/#response). + +You may use this to perform more operations and checks on the response, such as checking for HTTP status errors: + +```python +with connect_sse(...) as event_source: + event_source.response.raise_for_status() + + for sse in event_source.iter_sse(): + ... +``` + +#### `iter_sse` + +```python +def iter_sse() -> Iterator[ServerSentEvent] +``` + +Decode the response content and yield corresponding [`ServerSentEvent`](#serversentevent). + +Example usage: + +```python +for sse in event_source.iter_sse(): + ... +``` + +#### `aiter_sse` + +```python +async def iter_sse() -> AsyncIterator[ServerSentEvent] +``` + +An async equivalent to `iter_sse`. + +### `ServerSentEvent` + +Represents a server-sent event. + +* `event: str` - Defaults to `"message"`. +* `data: str` - Defaults to `""`. +* `id: str` - Defaults to `""`. +* `retry: str | None` - Defaults to `None`. + +Methods: + +* `json() -> Any` - Returns `sse.data` decoded as JSON. + +### `SSEError` + +An error that occurred while making a request to an SSE endpoint. + +Parents: + +* `httpx.TransportError` + +## License + +MIT + +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). + +## 0.4.3 - 2025-10-10 + +### Fixed + +* Fix performance issue introduced by the improved line parsing from release 0.4.2. (Pull #40) + +## 0.4.2 - 2025-10-07 + +### Fixed + +* Fix incorrect newline parsing that was not compliant with SSE spec. (Pull #37) + +## 0.4.1 - 2025-06-24 + +### Fixed + +* Always close the response async generator in `aiter_sse()`. (Pull #30) + +## 0.4.0 - 2023-12-22 + +### Removed + +* Dropped Python 3.7 support, as it has reached EOL. (Pull #21) + +### Added + +* Add official support for Python 3.12. (Pull #21) + +### Fixed + +* Allow `Content-Type` that contain but are not strictly `text/event-stream`. (Pull #22 by @dbuades) +* Improve error message when `Content-Type` is missing. (Pull #20 by @jamesbraza) + +## 0.3.1 - 2023-06-01 + +### Added + +* Add `__repr__()` for `ServerSentEvent` model, which may help with debugging and other tasks. (Pull #16) + +## 0.3.0 - 2023-04-27 + +### Changed + +* Raising an `SSEError` if the response content type is not `text/event-stream` is now performed as part of `iter_sse()` / `aiter_sse()`, instead of `connect_sse()` / `aconnect_sse()`. This allows inspecting the response before iterating on server-sent events, such as checking for error responses. (Pull #12) + +## 0.2.0 - 2023-03-27 + +### Changed + +* `connect_sse()` and `aconnect_sse()` now require a `method` argument: `connect_sse(client, "GET", "https://example.org")`. This provides support for SSE requests with HTTP verbs other than `GET`. (Pull #7) + +## 0.1.0 - 2023-02-05 + +_Initial release_ + +### Added + +* Add `connect_sse`, `aconnect_sse()`, `ServerSentEvent` and `SSEError`. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..26e4e392a2c31d180adb9a71ab460785edad3377 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/RECORD @@ -0,0 +1,17 @@ +httpx_sse-0.4.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +httpx_sse-0.4.3.dist-info/METADATA,sha256=1MbYBO5axG6bO2WVwnq4riunz7X2kseLFv9GPkvRqB4,9671 +httpx_sse-0.4.3.dist-info/RECORD,, +httpx_sse-0.4.3.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +httpx_sse-0.4.3.dist-info/licenses/LICENSE,sha256=vuxn5O6Dp68m8kK-2Zh6qGPW0t-3dhBqojYMQYfzGQE,1072 +httpx_sse-0.4.3.dist-info/top_level.txt,sha256=hbK3kwBH9d-rEZQvJ6yBawdDylIKfJ8fh0CM4EVNs04,10 +httpx_sse/__init__.py,sha256=G-F8jpJLo4eJwKvKt6ejTQYPhBHgmksZTNuaQySRAjc,282 +httpx_sse/__pycache__/__init__.cpython-311.pyc,, +httpx_sse/__pycache__/_api.cpython-311.pyc,, +httpx_sse/__pycache__/_decoders.cpython-311.pyc,, +httpx_sse/__pycache__/_exceptions.cpython-311.pyc,, +httpx_sse/__pycache__/_models.cpython-311.pyc,, +httpx_sse/_api.py,sha256=D7pfkajmdHlms75OV8HpdOrOEr5NbWQlDwMfSFcJ8FU,2919 +httpx_sse/_decoders.py,sha256=na1XyVBiCLbRE8tg0o713U5Gz-m9fBxYPfSMmu_xns8,4005 +httpx_sse/_exceptions.py,sha256=sFZBUT1xIM1DvYQ6ckpzrhBG9d8VffFSZFMIEhv1N58,62 +httpx_sse/_models.py,sha256=4WwGeBEGMR2nbROTZ7PyVlu7chmWg7tbkJyXyd5DTx0,1221 +httpx_sse/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a5e926f56e3d2574317cd01713fe078afad84fc2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse-0.4.3.dist-info/top_level.txt @@ -0,0 +1 @@ +httpx_sse diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b83cf09a2d8e8d26e91bc3f74e92b1c7d7eaa7ca --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/__init__.py @@ -0,0 +1,14 @@ +from ._api import EventSource, aconnect_sse, connect_sse +from ._exceptions import SSEError +from ._models import ServerSentEvent + +__version__ = "0.4.3" + +__all__ = [ + "__version__", + "EventSource", + "connect_sse", + "aconnect_sse", + "ServerSentEvent", + "SSEError", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/_api.py new file mode 100644 index 0000000000000000000000000000000000000000..017ed5eb3c0c09e64f74aa0fb985cdb6b1d3bd6f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/_api.py @@ -0,0 +1,93 @@ +from collections.abc import AsyncGenerator +from contextlib import asynccontextmanager, contextmanager +from typing import Any, AsyncIterator, Iterator, cast + +import httpx + +from ._decoders import SSEDecoder, SSELineDecoder +from ._exceptions import SSEError +from ._models import ServerSentEvent + + +class EventSource: + def __init__(self, response: httpx.Response) -> None: + self._response = response + + def _check_content_type(self) -> None: + content_type = self._response.headers.get("content-type", "").partition(";")[0] + if "text/event-stream" not in content_type: + raise SSEError( + "Expected response header Content-Type to contain 'text/event-stream', " + f"got {content_type!r}" + ) + + @property + def response(self) -> httpx.Response: + return self._response + + def iter_sse(self) -> Iterator[ServerSentEvent]: + self._check_content_type() + decoder = SSEDecoder() + for line in _iter_sse_lines(self._response): + line = line.rstrip("\n") + sse = decoder.decode(line) + if sse is not None: + yield sse + + async def aiter_sse(self) -> AsyncGenerator[ServerSentEvent, None]: + self._check_content_type() + decoder = SSEDecoder() + lines = cast(AsyncGenerator[str, None], _aiter_sse_lines(self._response)) + try: + async for line in lines: + line = line.rstrip("\n") + sse = decoder.decode(line) + if sse is not None: + yield sse + finally: + await lines.aclose() + + +@contextmanager +def connect_sse( + client: httpx.Client, method: str, url: str, **kwargs: Any +) -> Iterator[EventSource]: + headers = kwargs.pop("headers", {}) + headers["Accept"] = "text/event-stream" + headers["Cache-Control"] = "no-store" + + with client.stream(method, url, headers=headers, **kwargs) as response: + yield EventSource(response) + + +@asynccontextmanager +async def aconnect_sse( + client: httpx.AsyncClient, + method: str, + url: str, + **kwargs: Any, +) -> AsyncIterator[EventSource]: + headers = kwargs.pop("headers", {}) + headers["Accept"] = "text/event-stream" + headers["Cache-Control"] = "no-store" + + async with client.stream(method, url, headers=headers, **kwargs) as response: + yield EventSource(response) + + +async def _aiter_sse_lines(response: httpx.Response) -> AsyncIterator[str]: + decoder = SSELineDecoder() + async for text in response.aiter_text(): + for line in decoder.decode(text): + yield line + for line in decoder.flush(): + yield line + + +def _iter_sse_lines(response: httpx.Response) -> Iterator[str]: + decoder = SSELineDecoder() + for text in response.iter_text(): + for line in decoder.decode(text): + yield line + for line in decoder.flush(): + yield line diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/_decoders.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/_decoders.py new file mode 100644 index 0000000000000000000000000000000000000000..287e3844b0670f0eb967c39146848601181b3cf5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/_decoders.py @@ -0,0 +1,139 @@ +from typing import List, Optional + +from ._models import ServerSentEvent + + +def _splitlines_sse(text: str) -> List[str]: + """Split text on \r\n, \r, or \n only.""" + if not text: + return [] + + if "\r" not in text: + lines = text.split("\n") + else: + normalized = text.replace("\r\n", "\n").replace("\r", "\n") + lines = normalized.split("\n") + + if text[-1] in "\r\n": + lines.pop() + + return lines + + +class SSELineDecoder: + """ + Handles incrementally reading lines from text. + + Mostly a copy of httpx._decoders.LineDecoder, but as per SSE spec, only \r\n, \r, + and \n are treated as newlines, which differs from the behavior of splitlines() + used by httpx._decoders.LineDecoder. + """ + + def __init__(self) -> None: + self.buffer: list[str] = [] + self.trailing_cr: bool = False + + def decode(self, text: str) -> list[str]: + # We always push a trailing `\r` into the next decode iteration. + if self.trailing_cr: + text = "\r" + text + self.trailing_cr = False + if text.endswith("\r"): + self.trailing_cr = True + text = text[:-1] + + if not text: + # NOTE: the edge case input of empty text doesn't occur in practice, + # because other httpx internals filter out this value + return [] # pragma: no cover + + trailing_newline = text[-1] in "\n\r" + lines = _splitlines_sse(text) + + if len(lines) == 1 and not trailing_newline: + # No new lines, buffer the input and continue. + self.buffer.append(lines[0]) + return [] + + if self.buffer: + # Include any existing buffer in the first portion of the + # splitlines result. + lines = ["".join(self.buffer) + lines[0]] + lines[1:] + self.buffer = [] + + if not trailing_newline: + # If the last segment of splitlines is not newline terminated, + # then drop it from our output and start a new buffer. + self.buffer = [lines.pop()] + + return lines + + def flush(self) -> list[str]: + if not self.buffer and not self.trailing_cr: + return [] + + lines = ["".join(self.buffer)] + self.buffer = [] + self.trailing_cr = False + return lines + + +class SSEDecoder: + def __init__(self) -> None: + self._event = "" + self._data: List[str] = [] + self._last_event_id = "" + self._retry: Optional[int] = None + + def decode(self, line: str) -> Optional[ServerSentEvent]: + # See: https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation # noqa: E501 + + if not line: + if ( + not self._event + and not self._data + and not self._last_event_id + and self._retry is None + ): + return None + + sse = ServerSentEvent( + event=self._event, + data="\n".join(self._data), + id=self._last_event_id, + retry=self._retry, + ) + + # NOTE: as per the SSE spec, do not reset last_event_id. + self._event = "" + self._data = [] + self._retry = None + + return sse + + if line.startswith(":"): + return None + + fieldname, _, value = line.partition(":") + + if value.startswith(" "): + value = value[1:] + + if fieldname == "event": + self._event = value + elif fieldname == "data": + self._data.append(value) + elif fieldname == "id": + if "\0" in value: + pass + else: + self._last_event_id = value + elif fieldname == "retry": + try: + self._retry = int(value) + except (TypeError, ValueError): + pass + else: + pass # Field is ignored. + + return None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/_exceptions.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..cd2c4d287ce86c4e922d56c66423615085892e14 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/_exceptions.py @@ -0,0 +1,5 @@ +import httpx + + +class SSEError(httpx.TransportError): + pass diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/_models.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/_models.py new file mode 100644 index 0000000000000000000000000000000000000000..d4dc1190f7b02a8c97ab85e4f896787ca39dd9ec --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/_models.py @@ -0,0 +1,54 @@ +import json +from typing import Any, Optional + + +class ServerSentEvent: + def __init__( + self, + event: Optional[str] = None, + data: Optional[str] = None, + id: Optional[str] = None, + retry: Optional[int] = None, + ) -> None: + if not event: + event = "message" + + if data is None: + data = "" + + if id is None: + id = "" + + self._event = event + self._data = data + self._id = id + self._retry = retry + + @property + def event(self) -> str: + return self._event + + @property + def data(self) -> str: + return self._data + + @property + def id(self) -> str: + return self._id + + @property + def retry(self) -> Optional[int]: + return self._retry + + def json(self) -> Any: + return json.loads(self.data) + + def __repr__(self) -> str: + pieces = [f"event={self.event!r}"] + if self.data != "": + pieces.append(f"data={self.data!r}") + if self.id != "": + pieces.append(f"id={self.id!r}") + if self.retry is not None: + pieces.append(f"retry={self.retry!r}") + return f"ServerSentEvent({', '.join(pieces)})" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/httpx_sse/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..40868c8c1b8a480dbb5856e892cc64b454315232 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/METADATA @@ -0,0 +1,324 @@ +Metadata-Version: 2.4 +Name: huggingface_hub +Version: 1.14.0 +Summary: Client library to download and publish models, datasets and other repos on the huggingface.co hub +Home-page: https://github.com/huggingface/huggingface_hub +Author: Hugging Face, Inc. +Author-email: julien@huggingface.co +License: Apache-2.0 +Keywords: model-hub machine-learning models natural-language-processing deep-learning pytorch pretrained-models +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Requires-Python: >=3.10.0 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: filelock>=3.10.0 +Requires-Dist: fsspec>=2023.5.0 +Requires-Dist: hf-xet<2.0.0,>=1.4.3; platform_machine == "x86_64" or platform_machine == "amd64" or platform_machine == "AMD64" or platform_machine == "arm64" or platform_machine == "aarch64" +Requires-Dist: httpx<1,>=0.23.0 +Requires-Dist: packaging>=20.9 +Requires-Dist: pyyaml>=5.1 +Requires-Dist: tqdm>=4.42.1 +Requires-Dist: typer>=0.20.0 +Requires-Dist: typing-extensions>=4.1.0 +Provides-Extra: oauth +Requires-Dist: authlib>=1.3.2; extra == "oauth" +Requires-Dist: fastapi; extra == "oauth" +Requires-Dist: httpx; extra == "oauth" +Requires-Dist: itsdangerous; extra == "oauth" +Provides-Extra: torch +Requires-Dist: torch; extra == "torch" +Requires-Dist: safetensors[torch]; extra == "torch" +Provides-Extra: fastai +Requires-Dist: toml; extra == "fastai" +Requires-Dist: fastai>=2.4; extra == "fastai" +Requires-Dist: fastcore>=1.3.27; extra == "fastai" +Provides-Extra: hf-xet +Requires-Dist: hf-xet<2.0.0,>=1.4.3; extra == "hf-xet" +Provides-Extra: mcp +Requires-Dist: mcp>=1.8.0; extra == "mcp" +Provides-Extra: testing +Requires-Dist: authlib>=1.3.2; extra == "testing" +Requires-Dist: fastapi; extra == "testing" +Requires-Dist: httpx; extra == "testing" +Requires-Dist: itsdangerous; extra == "testing" +Requires-Dist: jedi; extra == "testing" +Requires-Dist: Jinja2; extra == "testing" +Requires-Dist: pytest>=8.4.2; extra == "testing" +Requires-Dist: pytest-cov; extra == "testing" +Requires-Dist: pytest-env; extra == "testing" +Requires-Dist: pytest-xdist; extra == "testing" +Requires-Dist: pytest-vcr; extra == "testing" +Requires-Dist: pytest-asyncio; extra == "testing" +Requires-Dist: pytest-rerunfailures<16.0; extra == "testing" +Requires-Dist: pytest-mock; extra == "testing" +Requires-Dist: urllib3<2.0; extra == "testing" +Requires-Dist: soundfile; extra == "testing" +Requires-Dist: Pillow; extra == "testing" +Requires-Dist: numpy; extra == "testing" +Requires-Dist: duckdb; extra == "testing" +Requires-Dist: fastapi; extra == "testing" +Provides-Extra: gradio +Requires-Dist: gradio>=5.0.0; extra == "gradio" +Requires-Dist: requests; extra == "gradio" +Provides-Extra: typing +Requires-Dist: typing-extensions>=4.8.0; extra == "typing" +Requires-Dist: types-PyYAML; extra == "typing" +Requires-Dist: types-simplejson; extra == "typing" +Requires-Dist: types-toml; extra == "typing" +Requires-Dist: types-tqdm; extra == "typing" +Requires-Dist: types-urllib3; extra == "typing" +Provides-Extra: quality +Requires-Dist: ruff>=0.9.0; extra == "quality" +Requires-Dist: mypy==1.15.0; extra == "quality" +Requires-Dist: libcst>=1.4.0; extra == "quality" +Requires-Dist: ty; extra == "quality" +Provides-Extra: all +Requires-Dist: authlib>=1.3.2; extra == "all" +Requires-Dist: fastapi; extra == "all" +Requires-Dist: httpx; extra == "all" +Requires-Dist: itsdangerous; extra == "all" +Requires-Dist: jedi; extra == "all" +Requires-Dist: Jinja2; extra == "all" +Requires-Dist: pytest>=8.4.2; extra == "all" +Requires-Dist: pytest-cov; extra == "all" +Requires-Dist: pytest-env; extra == "all" +Requires-Dist: pytest-xdist; extra == "all" +Requires-Dist: pytest-vcr; extra == "all" +Requires-Dist: pytest-asyncio; extra == "all" +Requires-Dist: pytest-rerunfailures<16.0; extra == "all" +Requires-Dist: pytest-mock; extra == "all" +Requires-Dist: urllib3<2.0; extra == "all" +Requires-Dist: soundfile; extra == "all" +Requires-Dist: Pillow; extra == "all" +Requires-Dist: numpy; extra == "all" +Requires-Dist: duckdb; extra == "all" +Requires-Dist: fastapi; extra == "all" +Requires-Dist: ruff>=0.9.0; extra == "all" +Requires-Dist: mypy==1.15.0; extra == "all" +Requires-Dist: libcst>=1.4.0; extra == "all" +Requires-Dist: ty; extra == "all" +Requires-Dist: typing-extensions>=4.8.0; extra == "all" +Requires-Dist: types-PyYAML; extra == "all" +Requires-Dist: types-simplejson; extra == "all" +Requires-Dist: types-toml; extra == "all" +Requires-Dist: types-tqdm; extra == "all" +Requires-Dist: types-urllib3; extra == "all" +Provides-Extra: dev +Requires-Dist: authlib>=1.3.2; extra == "dev" +Requires-Dist: fastapi; extra == "dev" +Requires-Dist: httpx; extra == "dev" +Requires-Dist: itsdangerous; extra == "dev" +Requires-Dist: jedi; extra == "dev" +Requires-Dist: Jinja2; extra == "dev" +Requires-Dist: pytest>=8.4.2; extra == "dev" +Requires-Dist: pytest-cov; extra == "dev" +Requires-Dist: pytest-env; extra == "dev" +Requires-Dist: pytest-xdist; extra == "dev" +Requires-Dist: pytest-vcr; extra == "dev" +Requires-Dist: pytest-asyncio; extra == "dev" +Requires-Dist: pytest-rerunfailures<16.0; extra == "dev" +Requires-Dist: pytest-mock; extra == "dev" +Requires-Dist: urllib3<2.0; extra == "dev" +Requires-Dist: soundfile; extra == "dev" +Requires-Dist: Pillow; extra == "dev" +Requires-Dist: numpy; extra == "dev" +Requires-Dist: duckdb; extra == "dev" +Requires-Dist: fastapi; extra == "dev" +Requires-Dist: ruff>=0.9.0; extra == "dev" +Requires-Dist: mypy==1.15.0; extra == "dev" +Requires-Dist: libcst>=1.4.0; extra == "dev" +Requires-Dist: ty; extra == "dev" +Requires-Dist: typing-extensions>=4.8.0; extra == "dev" +Requires-Dist: types-PyYAML; extra == "dev" +Requires-Dist: types-simplejson; extra == "dev" +Requires-Dist: types-toml; extra == "dev" +Requires-Dist: types-tqdm; extra == "dev" +Requires-Dist: types-urllib3; extra == "dev" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + +

+ + + + huggingface_hub library logo + +
+
+

+ +

+ The official Python client for the Huggingface Hub. +

+ +

+ Documentation + GitHub release + PyPi version + PyPI - Downloads + Code coverage +

+ +

+

+ English | + Deutsch | + Français | + हिंदी | + 한국어 | + 中文 (简体) +

+

+ +--- + +**Documentation**: https://hf.co/docs/huggingface_hub + +**Source Code**: https://github.com/huggingface/huggingface_hub + +--- + +## Welcome to the huggingface_hub library + +The `huggingface_hub` library allows you to interact with the [Hugging Face Hub](https://huggingface.co/), a platform democratizing open-source Machine Learning for creators and collaborators. Discover pre-trained models and datasets for your projects or play with the thousands of machine learning apps hosted on the Hub. You can also create and share your own models, datasets and demos with the community. The `huggingface_hub` library provides a simple way to do all these things with Python. + +## Key features + +- [Download files](https://huggingface.co/docs/huggingface_hub/en/guides/download) from the Hub. +- [Upload files](https://huggingface.co/docs/huggingface_hub/en/guides/upload) to the Hub. +- [Manage your repositories](https://huggingface.co/docs/huggingface_hub/en/guides/repository). +- [Run Inference](https://huggingface.co/docs/huggingface_hub/en/guides/inference) on deployed models. +- [Search](https://huggingface.co/docs/huggingface_hub/en/guides/search) for models, datasets and Spaces. +- [Share Model Cards](https://huggingface.co/docs/huggingface_hub/en/guides/model-cards) to document your models. +- [Engage with the community](https://huggingface.co/docs/huggingface_hub/en/guides/community) through PRs and comments. + +## Installation + +Install the `huggingface_hub` package with [pip](https://pypi.org/project/huggingface-hub/): + +```bash +pip install huggingface_hub +``` + +If you prefer, you can also install it with [conda](https://huggingface.co/docs/huggingface_hub/en/installation#install-with-conda). + +In order to keep the package minimal by default, `huggingface_hub` comes with optional dependencies useful for some use cases. For example, if you want to use the MCP module, run: + +```bash +pip install "huggingface_hub[mcp]" +``` + +To learn more installation and optional dependencies, check out the [installation guide](https://huggingface.co/docs/huggingface_hub/en/installation). + +## Quick start + +### Download files + +Download a single file + +```py +from huggingface_hub import hf_hub_download + +hf_hub_download(repo_id="tiiuae/falcon-7b-instruct", filename="config.json") +``` + +Or an entire repository + +```py +from huggingface_hub import snapshot_download + +snapshot_download("stabilityai/stable-diffusion-2-1") +``` + +Files will be downloaded in a local cache folder. More details in [this guide](https://huggingface.co/docs/huggingface_hub/en/guides/manage-cache). + +### Login + +The Hugging Face Hub uses tokens to authenticate applications (see [docs](https://huggingface.co/docs/hub/security-tokens)). To log in your machine, run the following CLI: + +```bash +hf auth login +# or using an environment variable +hf auth login --token $HUGGINGFACE_TOKEN +``` + +### Create a repository + +```py +from huggingface_hub import create_repo + +create_repo(repo_id="super-cool-model") +``` + +### Upload files + +Upload a single file + +```py +from huggingface_hub import upload_file + +upload_file( + path_or_fileobj="/home/lysandre/dummy-test/README.md", + path_in_repo="README.md", + repo_id="lysandre/test-model", +) +``` + +Or an entire folder + +```py +from huggingface_hub import upload_folder + +upload_folder( + folder_path="/path/to/local/space", + repo_id="username/my-cool-space", + repo_type="space", +) +``` + +For details in the [upload guide](https://huggingface.co/docs/huggingface_hub/en/guides/upload). + +## Integrating to the Hub. + +We're partnering with cool open source ML libraries to provide free model hosting and versioning. You can find the existing integrations [here](https://huggingface.co/docs/hub/libraries). + +The advantages are: + +- Free model or dataset hosting for libraries and their users. +- Built-in file versioning, even with very large files, thanks to a git-based approach. +- In-browser widgets to play with the uploaded models. +- Anyone can upload a new model for your library, they just need to add the corresponding tag for the model to be discoverable. +- Fast downloads! We use Cloudfront (a CDN) to geo-replicate downloads so they're blazing fast from anywhere on the globe. +- Usage stats and more features to come. + +If you would like to integrate your library, feel free to open an issue to begin the discussion. We wrote a [step-by-step guide](https://huggingface.co/docs/hub/adding-a-library) with ❤️ showing how to do this integration. + +## Contributions (feature requests, bugs, etc.) are super welcome 💙💚💛💜🧡❤️ + +Everyone is welcome to contribute, and we value everybody's contribution. Code is not the only way to help the community. +Answering questions, helping others, reaching out and improving the documentations are immensely valuable to the community. +We wrote a [contribution guide](https://github.com/huggingface/huggingface_hub/blob/main/CONTRIBUTING.md) to summarize +how to get started to contribute to this repository. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..1fe3b233e98214d09ea9da8c195bb39a3a704dea --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/RECORD @@ -0,0 +1,363 @@ +../../Scripts/hf.exe,sha256=g4VKBD4bJ674Trwqo6kRfLAbUswGB5AZg557MlfrIV4,108370 +../../Scripts/huggingface-cli.exe,sha256=_i9Hqf08wPo7aK9vQuyx9xWTixVXehZRJurd7O61nIs,108382 +../../Scripts/tiny-agents.exe,sha256=VYzxhjbEzVQRdBm0PFhqjgxEbGfL3dX6O2xpgO6Tl3k,108380 +huggingface_hub-1.14.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +huggingface_hub-1.14.0.dist-info/METADATA,sha256=NGKGEcwoHsM57iwi1I0nz9hp3WP7M8nTgnQx3W_m0Ik,14025 +huggingface_hub-1.14.0.dist-info/RECORD,, +huggingface_hub-1.14.0.dist-info/WHEEL,sha256=SmOxYU7pzNKBqASvQJ7DjX3XGUF92lrGhMb3R6_iiqI,91 +huggingface_hub-1.14.0.dist-info/entry_points.txt,sha256=zP7F_bBSdircPQFysHQZ9F3Lcn5_dCSOEZxVlGCsG0w,212 +huggingface_hub-1.14.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357 +huggingface_hub-1.14.0.dist-info/top_level.txt,sha256=8KzlQJAY4miUvjAssOAJodqKOw3harNzuiwGQ9qLSSk,16 +huggingface_hub/__init__.py,sha256=oI1-0abcGlCY_WJVgCHNQxgObpR0dnVMCpYbyN_ZRPI,58431 +huggingface_hub/__pycache__/__init__.cpython-311.pyc,, +huggingface_hub/__pycache__/_buckets.cpython-311.pyc,, +huggingface_hub/__pycache__/_commit_api.cpython-311.pyc,, +huggingface_hub/__pycache__/_commit_scheduler.cpython-311.pyc,, +huggingface_hub/__pycache__/_dataset_viewer.cpython-311.pyc,, +huggingface_hub/__pycache__/_eval_results.cpython-311.pyc,, +huggingface_hub/__pycache__/_inference_endpoints.cpython-311.pyc,, +huggingface_hub/__pycache__/_jobs_api.cpython-311.pyc,, +huggingface_hub/__pycache__/_local_folder.cpython-311.pyc,, +huggingface_hub/__pycache__/_login.cpython-311.pyc,, +huggingface_hub/__pycache__/_oauth.cpython-311.pyc,, +huggingface_hub/__pycache__/_snapshot_download.cpython-311.pyc,, +huggingface_hub/__pycache__/_space_api.cpython-311.pyc,, +huggingface_hub/__pycache__/_tensorboard_logger.cpython-311.pyc,, +huggingface_hub/__pycache__/_upload_large_folder.cpython-311.pyc,, +huggingface_hub/__pycache__/_webhooks_payload.cpython-311.pyc,, +huggingface_hub/__pycache__/_webhooks_server.cpython-311.pyc,, +huggingface_hub/__pycache__/community.cpython-311.pyc,, +huggingface_hub/__pycache__/constants.cpython-311.pyc,, +huggingface_hub/__pycache__/dataclasses.cpython-311.pyc,, +huggingface_hub/__pycache__/errors.cpython-311.pyc,, +huggingface_hub/__pycache__/fastai_utils.cpython-311.pyc,, +huggingface_hub/__pycache__/file_download.cpython-311.pyc,, +huggingface_hub/__pycache__/hf_api.cpython-311.pyc,, +huggingface_hub/__pycache__/hf_file_system.cpython-311.pyc,, +huggingface_hub/__pycache__/hub_mixin.cpython-311.pyc,, +huggingface_hub/__pycache__/lfs.cpython-311.pyc,, +huggingface_hub/__pycache__/repocard.cpython-311.pyc,, +huggingface_hub/__pycache__/repocard_data.cpython-311.pyc,, +huggingface_hub/_buckets.py,sha256=gqybQRY6R02kwyhMCH6VILQLo3Nd6m5XqhOQnfJMHU8,44899 +huggingface_hub/_commit_api.py,sha256=cEdBcUeL6e2mb2KSTXV9A5bQPuQ48rF1nhJQ4DqC2-c,40992 +huggingface_hub/_commit_scheduler.py,sha256=VG3zjb7xb66NrFMq_pB9dWIsoqSPoF6CntovV7vUiWg,14684 +huggingface_hub/_dataset_viewer.py,sha256=LE9k4s0WJ0JNdriJ8L6qV_-xfbUVC1VEh7CBd0jOjLI,5675 +huggingface_hub/_eval_results.py,sha256=Og7p7bCl2HQG6ZWlSDyir-CRTXjNWPu3S3q65cTGffs,8126 +huggingface_hub/_hot_reload/__init__.py,sha256=nQEuyVZLAS_463Dff1JH5MorTpkYsBVFCyPhYWY3UyI,606 +huggingface_hub/_hot_reload/__pycache__/__init__.cpython-311.pyc,, +huggingface_hub/_hot_reload/__pycache__/client.cpython-311.pyc,, +huggingface_hub/_hot_reload/__pycache__/sse_client.cpython-311.pyc,, +huggingface_hub/_hot_reload/__pycache__/types.cpython-311.pyc,, +huggingface_hub/_hot_reload/client.py,sha256=Ax7qT4CUi5wrg3mDzqkAG8ZzDsCwdcIIS1FIXK0SqD8,4269 +huggingface_hub/_hot_reload/sse_client.py,sha256=49kmsB2P9sxgbZ16ed6F4aLDs3rsHrNpbp6iKlvF90c,4948 +huggingface_hub/_hot_reload/types.py,sha256=d3AOJCLUxT41Fhz4jUrFevm9bfpooe_3PQhpBdgNYSs,2725 +huggingface_hub/_inference_endpoints.py,sha256=rwetck_MnbV-MrTLVN7cazIrxUNYi5x2nBkw1devnxY,17643 +huggingface_hub/_jobs_api.py,sha256=XSmWO4MfXalDTfJ9wyrtV6wPW9I_2PiXGEuuMXylAhQ,14479 +huggingface_hub/_local_folder.py,sha256=Fc_hikyMaZRHtXIDZj38hL7MNkq5nZZVxQF-dd-EkMo,18279 +huggingface_hub/_login.py,sha256=Y4n1dlXYBr_6hrTv6X_Sx5iR2SR9_2NgFZ5t8grWmgk,19447 +huggingface_hub/_oauth.py,sha256=S8evEd8JLJHz-JiSjGH4WiIi_A7oDox_xH7E9rN1Jic,18628 +huggingface_hub/_snapshot_download.py,sha256=KqiEBSM8CvVXFAZHUS1lINN94WK05q9-exNWrzYO6kE,20614 +huggingface_hub/_space_api.py,sha256=Sz_v5i8uPl8EUBAzrN47bphQL7ElRd_6B603b5krxDM,12177 +huggingface_hub/_tensorboard_logger.py,sha256=GA-LhoG4Z-0Zq7w5B9vTIDJbWUkAhiG2d8a-ktlwGDY,8377 +huggingface_hub/_upload_large_folder.py,sha256=BWA1zyOK9W_3YUerX9YWQa3wAYtHRe_ypgsO79JEkqo,31235 +huggingface_hub/_webhooks_payload.py,sha256=B9zqljcm20DGeVxJKba570i6RP-cR9CEupMGBuNDHHA,3544 +huggingface_hub/_webhooks_server.py,sha256=A172KmELV-pGjA819D4UgOHcuvHxCFdwOLPlu2kqHa4,15668 +huggingface_hub/cli/__init__.py,sha256=A4zmzuHD2OHjQ5zmdfcnsj0JeCzHVPtpzh-wCjInugA,606 +huggingface_hub/cli/__pycache__/__init__.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/_cli_utils.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/_errors.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/_file_listing.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/_output.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/_skills.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/auth.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/buckets.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/cache.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/collections.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/datasets.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/deprecated_cli.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/discussions.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/download.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/extensions.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/hf.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/inference_endpoints.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/jobs.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/lfs.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/models.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/papers.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/repo_files.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/repos.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/skills.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/spaces.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/system.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/upload.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/upload_large_folder.cpython-311.pyc,, +huggingface_hub/cli/__pycache__/webhooks.cpython-311.pyc,, +huggingface_hub/cli/_cli_utils.py,sha256=74tG3KKfBImta8qooCIfdCGwd3jJmqJGsNbyDy_ZHrc,45989 +huggingface_hub/cli/_errors.py,sha256=iVc59bPwNUy7vmE_02vCsqJLbCDli_W7fneHQ-0qVfQ,4494 +huggingface_hub/cli/_file_listing.py,sha256=20SGu3-PRJiGZu3wPEMzf8lKgf1eMTLxuF-q59KJeAE,7950 +huggingface_hub/cli/_output.py,sha256=QmoT4Jngi7XM2zNmumwbZwKmNHzsIvXaZLIVEgooyN4,10635 +huggingface_hub/cli/_skills.py,sha256=MtX4fH3ZhvR4YZ8jw9lzUzBSS7MtOY3T4SfGGYuFx3E,9811 +huggingface_hub/cli/auth.py,sha256=N-u8T1pld-ZrY7X9PKtyFO0d8qcj8c0C9PVoCyTkCSo,5311 +huggingface_hub/cli/buckets.py,sha256=kBhuaAFT6av9WNElmmzuPNeZV4mjfCtR6vrCaMjSL-Y,26668 +huggingface_hub/cli/cache.py,sha256=FHl9lWIA2byWKdjn3eoa8IPoHhFDqmXJDHliAPJiZu4,26198 +huggingface_hub/cli/collections.py,sha256=ttCZBumqb6p3GAqdW36Ux02h2h2ey7m9qCZPZJVelec,10775 +huggingface_hub/cli/datasets.py,sha256=XK_wgrArGuF3AcRIpMJkqv3VwtGppyIiFBE1EwH3ne4,10816 +huggingface_hub/cli/deprecated_cli.py,sha256=vAK_CR4NE9uzNJ0I59SyBnIln5nlypG4CPoohMoPMVg,1090 +huggingface_hub/cli/discussions.py,sha256=mLUZrTW8h40TLt4pIa4qmBkJusVt970z15fcnwo3uSY,12654 +huggingface_hub/cli/download.py,sha256=rXKUBcWayWltonlGQ-vmwFkR-ht036BBE6kHsdf184o,7953 +huggingface_hub/cli/extensions.py,sha256=yQwyQdm-k9OVsezvG99COxl27-YsjoXuB3dR70-Lnqc,22030 +huggingface_hub/cli/hf.py,sha256=71mAgK3VnjV4nRZkVPcSEthnUM-fZgCVvftFAb95kBE,4562 +huggingface_hub/cli/inference_endpoints.py,sha256=0T2FMOo3kIrlJeTjtxgnE1-9BKlelzm0m2g_0jB62UA,14040 +huggingface_hub/cli/jobs.py,sha256=VeshuYeSYos2r4AoIhlenqwvSpJ1PKVXY7A5nW9OyQo,38530 +huggingface_hub/cli/lfs.py,sha256=v2yBjwBNOg0WAr6WtT5wWlTxut8OUVmcQ0ryG99OtCA,5876 +huggingface_hub/cli/models.py,sha256=xdiy8l9ECuY0TSUOmfBdryJAy-hjV7tgwg3T7oAUWms,7747 +huggingface_hub/cli/papers.py,sha256=3MR7hZbvH3BxldCbdbbsNh5o7q85wXSHDQhBn9AK_eY,5747 +huggingface_hub/cli/repo_files.py,sha256=0VdacUlJH_fxCMrVutBt-rtOTjYk_2AhlbW5xlAeKck,2440 +huggingface_hub/cli/repos.py,sha256=77WRElbQ2n4U7fkmAaZg-ryxO4tV5EtvrP0jfYpy-vY,16195 +huggingface_hub/cli/skills.py,sha256=lxJEX3rwoypAzBiKOGMCY5_DlUXJzKtnISmOteoEki0,17909 +huggingface_hub/cli/spaces.py,sha256=GBTcYS7mpNuGUwEIQ0jnNMBBzT-3tgay9YEHLpSHrNY,38098 +huggingface_hub/cli/system.py,sha256=YJmwZcy-ffDKq2MVVXJt1W0_u2Yyua5koPe1Cvma4D4,1723 +huggingface_hub/cli/upload.py,sha256=DXhdx0-Lapiu-HLJg8iP5Mr9xN50sQP2pSNajGH2Lok,10949 +huggingface_hub/cli/upload_large_folder.py,sha256=WDhKyGeH5FqAkesfzCla-nRVQHl6spOVc9VD-iHtcd8,4575 +huggingface_hub/cli/webhooks.py,sha256=uO2t1Kgc4DXy_Ut2nWK3uDlvFrKmqvLUSjb68kbafA0,9268 +huggingface_hub/community.py,sha256=N5OE5Rbc2BMwpNXCFOPQAwn0otqQunsXdEnSE_0J2Xo,12325 +huggingface_hub/constants.py,sha256=zu42eXu8shEy_JGffr7TM83XKWugv_Qca3AK_fn8eNU,11697 +huggingface_hub/dataclasses.py,sha256=LoEOPRQTXgr9V7OPWvieADLuflW47l6THGaduntlqx4,26047 +huggingface_hub/errors.py,sha256=OVdrv_WpfyOHinFP7_RhZncwafVE0CoFNj0tTsHEC8A,14739 +huggingface_hub/fastai_utils.py,sha256=jwKeVXH_VP0zxnOKVNQCVCkF-stH70l-bExbbrYkBKQ,16583 +huggingface_hub/file_download.py,sha256=9_lRpeb7s440EDss4VRlOd2hmwdgQ5oBvtpCpj4W0h8,81520 +huggingface_hub/hf_api.py,sha256=LxRs7YOX4Onz28Kv7qJAwdrRUjMXb3W5Odcezxd8_dc,616527 +huggingface_hub/hf_file_system.py,sha256=hFpVPJgLyfmkOayXEkiYb7yR_hqRS_JYU9o76J2tE6E,61802 +huggingface_hub/hub_mixin.py,sha256=ljKAtm3qQsY-ARtxY-PCFx0koFXLI37JytMrzpqfnQo,36912 +huggingface_hub/inference/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +huggingface_hub/inference/__pycache__/__init__.cpython-311.pyc,, +huggingface_hub/inference/__pycache__/_client.cpython-311.pyc,, +huggingface_hub/inference/__pycache__/_common.cpython-311.pyc,, +huggingface_hub/inference/_client.py,sha256=yu99zMNIkXBEpq7WFdRZ8sy1ZICIXI-DwCDxjr17_as,157777 +huggingface_hub/inference/_common.py,sha256=X-fBP8s6xuNTAuQsGVIethE8dNQaa-mK7Ds54qVVDz8,14999 +huggingface_hub/inference/_generated/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +huggingface_hub/inference/_generated/__pycache__/__init__.cpython-311.pyc,, +huggingface_hub/inference/_generated/__pycache__/_async_client.cpython-311.pyc,, +huggingface_hub/inference/_generated/_async_client.py,sha256=xST7gThlcdS50Ky6KiTo5RukiS5FaFECPi33uaHNnQ4,160988 +huggingface_hub/inference/_generated/types/__init__.py,sha256=e625ENOmTUM4uUL1eAlsZOK7CovNoGBDH-TxSNQhaC4,6869 +huggingface_hub/inference/_generated/types/__pycache__/__init__.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/audio_classification.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/audio_to_audio.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/automatic_speech_recognition.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/base.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/chat_completion.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/depth_estimation.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/document_question_answering.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/feature_extraction.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/fill_mask.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/image_classification.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/image_segmentation.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/image_text_to_image.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/image_text_to_video.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/image_to_image.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/image_to_text.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/image_to_video.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/object_detection.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/question_answering.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/sentence_similarity.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/summarization.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/table_question_answering.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/text2text_generation.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/text_classification.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/text_generation.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/text_to_audio.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/text_to_image.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/text_to_speech.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/text_to_video.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/token_classification.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/translation.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/video_classification.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/visual_question_answering.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/zero_shot_classification.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/zero_shot_image_classification.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/__pycache__/zero_shot_object_detection.cpython-311.pyc,, +huggingface_hub/inference/_generated/types/audio_classification.py,sha256=DGWEvrRPX7xpXlbYY4LMojGcULdEZFTshhNR81rTNcQ,1567 +huggingface_hub/inference/_generated/types/audio_to_audio.py,sha256=2Ep4WkePL7oJwcp5nRJqApwviumGHbft9HhXE9XLHj4,891 +huggingface_hub/inference/_generated/types/automatic_speech_recognition.py,sha256=X0uCj9qwAcOmlKtV3vWH5cAgLGY0PuYIy2eSH7GE1qs,5439 +huggingface_hub/inference/_generated/types/base.py,sha256=EPWp1qudjeEimEAyQ-ptdxpAACoRM8tW342-Ds7pP3I,6938 +huggingface_hub/inference/_generated/types/chat_completion.py,sha256=3yc06ZI0NCZzsaeoxSMWyIHqGc8Vn_6aExncuXa1llE,11100 +huggingface_hub/inference/_generated/types/depth_estimation.py,sha256=5Kn4xNGJg235Cofr1lzO59eRGCuLTZun8z5t6a2do8Q,910 +huggingface_hub/inference/_generated/types/document_question_answering.py,sha256=aUZcrDGexjw8Fnm2rACm_3my77V15NnQHZxj-sa7bjo,3146 +huggingface_hub/inference/_generated/types/feature_extraction.py,sha256=DiO47PqwhdNta_KPDBsXfCPIL6BWNhyCLymxORlqUA0,1509 +huggingface_hub/inference/_generated/types/fill_mask.py,sha256=NhEskgoiMst7U_0cV_S-wryga4_2T5LgpbyQ23vHMp0,1680 +huggingface_hub/inference/_generated/types/image_classification.py,sha256=xWr4OY65EcIIhd7MI610a7xlaAVHQeydi8Gc7tlaPTU,1579 +huggingface_hub/inference/_generated/types/image_segmentation.py,sha256=lZKzbn_gkSi1sYGLb9ryeRr0aDAVrfYh0H5Iiv5JNsY,1935 +huggingface_hub/inference/_generated/types/image_text_to_image.py,sha256=pRQgYKXJbIpEjRBxuIE6NRDtk_km9DSTQ2s2qxkYJRM,2585 +huggingface_hub/inference/_generated/types/image_text_to_video.py,sha256=MVhP8D4eYjpT3hWYkkpuiME-hWY09o7C4rIn_wmnAmY,2450 +huggingface_hub/inference/_generated/types/image_to_image.py,sha256=P9TeMFSnZI_pa6DyinzDPWL0PNm_INJwsqFUEzpwIcU,2262 +huggingface_hub/inference/_generated/types/image_to_text.py,sha256=DCDS0Nqi-4AuATitvZm4EgrzYQuQEQ5lzBcaHuCmHnY,4740 +huggingface_hub/inference/_generated/types/image_to_video.py,sha256=iMCjiFTUza9AW_MyJ1videhYgvMY9QSzQ59kNdTE9QY,2206 +huggingface_hub/inference/_generated/types/object_detection.py,sha256=zNILlyZJh59rNNfqXM5x9uprDCPfEU-bvBtabeKSMzI,1965 +huggingface_hub/inference/_generated/types/question_answering.py,sha256=lIRf8DjRiAsjzWUBEsGt354SB4bvejLokf-8luHw6_o,2845 +huggingface_hub/inference/_generated/types/sentence_similarity.py,sha256=eNGiO4dR-Lft9yOLE0E97jfVyOT_ExDWZW5GeJGdatU,1027 +huggingface_hub/inference/_generated/types/summarization.py,sha256=5Dpt6LRteT-hO9esa3Ty_-xSL5U-zTtVZzy3iKwZRng,1472 +huggingface_hub/inference/_generated/types/table_question_answering.py,sha256=bwn616XJ-eLa5JKzn3m9rZZ3z63INGEUwRSOCWlEh-4,2269 +huggingface_hub/inference/_generated/types/text2text_generation.py,sha256=fotSlPWtIlp_LG26AQvNRXxU-jCUfda5PWsxCkbFeKM,1591 +huggingface_hub/inference/_generated/types/text_classification.py,sha256=uamBzz4YzWQ9mb6yuriykX8r47ZHf0K3eJpOLzB2qJw,1439 +huggingface_hub/inference/_generated/types/text_generation.py,sha256=FRUljypvCSQ2RaiylhlHeLJfHNy8qZvuty6SCB_zcaA,5813 +huggingface_hub/inference/_generated/types/text_to_audio.py,sha256=CiaTUSBdFtOs3gGTosqyQrjCwrN8mVJLRxDDWUtwZpQ,4677 +huggingface_hub/inference/_generated/types/text_to_image.py,sha256=Ju25WIDHE-1n8jlZ_udG4rpAaPYpmghR7-cDgVfuf48,1869 +huggingface_hub/inference/_generated/types/text_to_speech.py,sha256=WqDzWkhZsDcjapkoFrkyjF903SKs7aHhjypsYrn8oBw,4693 +huggingface_hub/inference/_generated/types/text_to_video.py,sha256=KjcDbtChwrIxIdTH6vcesUaMcjL2xjPf2nWEnHazj4Y,1756 +huggingface_hub/inference/_generated/types/token_classification.py,sha256=8KRBlqgFDszaUnPMvdRkZNQaZBtDfBhKZ6SggQldQMM,1894 +huggingface_hub/inference/_generated/types/translation.py,sha256=-j2PC1-qfoxvGMaKesqf5jXelqj0BDlEpfvZ7dsIEJM,1742 +huggingface_hub/inference/_generated/types/video_classification.py,sha256=vfaCqp8MuRMMtGvYCX0x4-AcwEd71kPHgSYJTNIOxLQ,1668 +huggingface_hub/inference/_generated/types/visual_question_answering.py,sha256=sWIB-SuEpW21oU6O5qQF3tt5PavUFsFOa8Xg4upTtek,1654 +huggingface_hub/inference/_generated/types/zero_shot_classification.py,sha256=gx-7WHad7xsNa89iSKSteKHjaHrKbIyzN_nSdJN3HCY,1697 +huggingface_hub/inference/_generated/types/zero_shot_image_classification.py,sha256=JZTQvcbSGrOQlWcPuJvAMT8YziDpBRn1O2RQSw507uY,1449 +huggingface_hub/inference/_generated/types/zero_shot_object_detection.py,sha256=sjdpVUN5zW9aYBymLVUs6i5HVk2qkUBO9ysEjHmsXVM,1605 +huggingface_hub/inference/_mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +huggingface_hub/inference/_mcp/__pycache__/__init__.cpython-311.pyc,, +huggingface_hub/inference/_mcp/__pycache__/_cli_hacks.cpython-311.pyc,, +huggingface_hub/inference/_mcp/__pycache__/agent.cpython-311.pyc,, +huggingface_hub/inference/_mcp/__pycache__/cli.cpython-311.pyc,, +huggingface_hub/inference/_mcp/__pycache__/constants.cpython-311.pyc,, +huggingface_hub/inference/_mcp/__pycache__/mcp_client.cpython-311.pyc,, +huggingface_hub/inference/_mcp/__pycache__/types.cpython-311.pyc,, +huggingface_hub/inference/_mcp/__pycache__/utils.cpython-311.pyc,, +huggingface_hub/inference/_mcp/_cli_hacks.py,sha256=KX9HZJPa1p8ngY3mtYGGlVUXfg4vYbbBRs-8HLToP04,3284 +huggingface_hub/inference/_mcp/agent.py,sha256=ufIzMGHore5n252hV5GZPM0ouDXIl6tv5Jl_5gHXnbg,4250 +huggingface_hub/inference/_mcp/cli.py,sha256=YsabbtVJzQ4vNN5km86BYcLV0SgkgE3hM2pIt6BpyAA,9801 +huggingface_hub/inference/_mcp/constants.py,sha256=lLRgR6gRuqJ4u7jqngVUgVYeOzactgJpkTxx66t1piE,2463 +huggingface_hub/inference/_mcp/mcp_client.py,sha256=dGp8PhN6aVw4bDnuSySFSiguHUiz-nzhgv89CVdO7pI,17243 +huggingface_hub/inference/_mcp/types.py,sha256=yHNfPsM9MhD06oeKdkbmrBsW-3WhUeqA26fyfRfx_bk,929 +huggingface_hub/inference/_mcp/utils.py,sha256=gxSB_rBjQ6VrkApKFsxk6-UzhijxkDVNuZrsjW5pL8k,4318 +huggingface_hub/inference/_providers/__init__.py,sha256=sOsixpAIWprZYEuTmrNGHxMiZ75P7fj94rrIl99hVpI,10688 +huggingface_hub/inference/_providers/__pycache__/__init__.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/_common.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/black_forest_labs.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/cerebras.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/clarifai.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/cohere.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/deepinfra.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/fal_ai.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/featherless_ai.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/fireworks_ai.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/groq.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/hf_inference.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/hyperbolic.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/nebius.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/novita.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/nscale.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/nvidia.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/openai.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/ovhcloud.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/publicai.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/replicate.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/sambanova.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/scaleway.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/together.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/wavespeed.cpython-311.pyc,, +huggingface_hub/inference/_providers/__pycache__/zai_org.cpython-311.pyc,, +huggingface_hub/inference/_providers/_common.py,sha256=9Ykgz6nT5ok-p7PpvnxkuNURR-yr85uP9B1wHwbSJ58,13815 +huggingface_hub/inference/_providers/black_forest_labs.py,sha256=HO3DaD97Hqy6b823b6VUPqiEqhHLKGeMVtJ4CMjGRPA,2817 +huggingface_hub/inference/_providers/cerebras.py,sha256=QOJ-1U-os7uE7p6eUnn_P_APq-yQhx28be7c3Tq2EuA,210 +huggingface_hub/inference/_providers/clarifai.py,sha256=1cEXQwhGk4DRKiPCQUa5y-L6okTo4781EImQC8yJVOw,380 +huggingface_hub/inference/_providers/cohere.py,sha256=P9kbIuvQ2rXI1yNmgbw5VKFFTE0huLq2k-BCyDkDico,1226 +huggingface_hub/inference/_providers/deepinfra.py,sha256=EaeeEMJCiKKuAdOjZwq0lWGonzBISr4ucErb6KpVCgE,1564 +huggingface_hub/inference/_providers/fal_ai.py,sha256=Y2vo5Dl3e8EoehplwNshu8LbDT1e7V4ZyhAMqs0wXws,11705 +huggingface_hub/inference/_providers/featherless_ai.py,sha256=C8OHdFpoFyA--pawLTekUmUSRq4sw_r0D-cSPekD4kE,1347 +huggingface_hub/inference/_providers/fireworks_ai.py,sha256=go6XPum8u0-g768HJ_r0S4Gb445gZJxnuY_acktz-9c,1188 +huggingface_hub/inference/_providers/groq.py,sha256=JTk2JV4ZOlaohho7zLAFQtk92kGVsPmLJ1hmzcwsqvQ,315 +huggingface_hub/inference/_providers/hf_inference.py,sha256=d2vdCKSi5CtyQqYndHHvH7SY131-7YHUK3yE7653eIc,9467 +huggingface_hub/inference/_providers/hyperbolic.py,sha256=Zk2rw2k-R0JxrfpcaHhAUuB5D6s40XK0tuvuKwglsUE,1950 +huggingface_hub/inference/_providers/nebius.py,sha256=OTPXQIYxQSwZc8FzhGAHUaa6Mkp3h6LphSVoa_1gY7I,3513 +huggingface_hub/inference/_providers/novita.py,sha256=ATEoSdPAPLMfx3JpBc0sOyLh4upJYP6xHBuo4YEDYvg,2470 +huggingface_hub/inference/_providers/nscale.py,sha256=T1L2JLI9LqYT9_YEdW76YEtxfDNtdGkoFhH-p2LmSxg,1767 +huggingface_hub/inference/_providers/nvidia.py,sha256=ocMuhycyIo8qiJf-E50oHGYuPvMcJC0BexSXBOYaOFg,251 +huggingface_hub/inference/_providers/openai.py,sha256=wwjaaQ55xLmDsDnHpZk52xbuLoGZfWzJkFsE8AdFVaI,1054 +huggingface_hub/inference/_providers/ovhcloud.py,sha256=tdmymlkbddMJKV7NRZ-tH2wymbLPFDTqUSXpWJUXyDQ,314 +huggingface_hub/inference/_providers/publicai.py,sha256=1I2W6rORloB5QHSvky4njZO2XKLTwA-kPdNoauoT5rg,210 +huggingface_hub/inference/_providers/replicate.py,sha256=hte0ZB2RtGFwpAuLrFp2Gbgsn3EOlccCnJkWTDTW__A,6027 +huggingface_hub/inference/_providers/sambanova.py,sha256=2dkhLf5nKGZ8hOqF-oWYHIN-Wckcwq0cMVf8UYgmDy4,1999 +huggingface_hub/inference/_providers/scaleway.py,sha256=MfIc7ZND1sPr__rOmNHZVg0VpECQo0bVyksgIm_32xQ,1174 +huggingface_hub/inference/_providers/together.py,sha256=OviPGPE6JvJwxf94DKpmsyWlryLU-W9OrHBcr36JT1w,3384 +huggingface_hub/inference/_providers/wavespeed.py,sha256=MGM7Y7r2nQiH_EH0t5UE1o1fT-o3sS7RaQlicS9WHsg,5028 +huggingface_hub/inference/_providers/zai_org.py,sha256=gLJZOEmCPmUZvdM7VDn2nxm4ac3veHdoMgQNR63UeWE,4739 +huggingface_hub/lfs.py,sha256=sVkRZMD8w-3vxaqSDSrsBCog6-lLyWP98u_xR1dIwMo,14123 +huggingface_hub/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +huggingface_hub/repocard.py,sha256=p2b9GiEzqrMJZW3O41nwiC6AseQhFNbqCbSIpoP_8VE,34829 +huggingface_hub/repocard_data.py,sha256=lI-DEIbmjtlOMvkntqwXA9ED4icTeCvNbAOYc2P2ZMk,33879 +huggingface_hub/serialization/__init__.py,sha256=jCiw_vVQYW52gwVfWiqgocf2Q19kGTQlRGVpf-4SLP8,963 +huggingface_hub/serialization/__pycache__/__init__.cpython-311.pyc,, +huggingface_hub/serialization/__pycache__/_base.cpython-311.pyc,, +huggingface_hub/serialization/__pycache__/_dduf.cpython-311.pyc,, +huggingface_hub/serialization/__pycache__/_torch.cpython-311.pyc,, +huggingface_hub/serialization/_base.py,sha256=-bhRW21ZIqza5gE_kWkL8ax-EE6L6xabKkkK35wOX0Y,8176 +huggingface_hub/serialization/_dduf.py,sha256=FmGRg5wkXI5sNCgZgCNJFmqb_nVrrQYOHf4Lqq0d64I,15385 +huggingface_hub/serialization/_torch.py,sha256=BtaCP-G3oYRP6Pj9MhI-ygBsk3JbBPnVDW9huSOgtkk,46897 +huggingface_hub/templates/datasetcard_template.md,sha256=W-EMqR6wndbrnZorkVv56URWPG49l7MATGeI015kTvs,5503 +huggingface_hub/templates/modelcard_template.md,sha256=4AqArS3cqdtbit5Bo-DhjcnDFR-pza5hErLLTPM4Yuc,6870 +huggingface_hub/utils/__init__.py,sha256=RW7Cq8t_YPvVk6DeFaV9cPEKXB5g31JbPQCFjYIoaDc,4050 +huggingface_hub/utils/__pycache__/__init__.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_auth.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_cache_assets.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_cache_manager.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_chunk_utils.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_datetime.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_deprecation.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_detect_agent.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_dotenv.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_experimental.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_fixes.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_git_credential.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_headers.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_hf_uris.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_http.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_lfs.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_pagination.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_parsing.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_paths.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_runtime.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_safetensors.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_subprocess.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_telemetry.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_terminal.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_typing.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_validators.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_verification.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_xet.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/_xet_progress_reporting.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/endpoint_helpers.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/insecure_hashlib.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/logging.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/sha.cpython-311.pyc,, +huggingface_hub/utils/__pycache__/tqdm.cpython-311.pyc,, +huggingface_hub/utils/_auth.py,sha256=DeSmNYy8UiAgrETNsHE5VZtzc-3-IKRqtFjxMxXBRdE,8227 +huggingface_hub/utils/_cache_assets.py,sha256=nnzHRtQAR50dQeIK6qKddsmjjTW9v9HZ7b9bq7PJqss,5691 +huggingface_hub/utils/_cache_manager.py,sha256=K3MfxR2we_uU2j5xLD1bMru6zihzDDlyZZm6mGUOxtM,33023 +huggingface_hub/utils/_chunk_utils.py,sha256=pTjy8Z-KLU4W_6D3OUh3E8lCodWDCd6aJwjNDU0C5U8,2121 +huggingface_hub/utils/_datetime.py,sha256=tbNyI0Dkh27oScPUtLIT_8apqIIkXZYbigjOn9S3aMw,2755 +huggingface_hub/utils/_deprecation.py,sha256=n4kNHbGipquSObJ-gxodcfd6lqoe_8s-VIsTuo3Oruk,4865 +huggingface_hub/utils/_detect_agent.py,sha256=tSfJZsIzrPZWYHV77UJY07KLiNkaoxAXaOmF9MXWkdI,3029 +huggingface_hub/utils/_dotenv.py,sha256=QfL6aWFp5NffhJEYFd6FtKHqly5EBpY8Cb-o9t8Ul04,1980 +huggingface_hub/utils/_experimental.py,sha256=q9vUvc1JybVFRQ0GRREG-BLouZEJC_40MxcwbAlOud0,2464 +huggingface_hub/utils/_fixes.py,sha256=jTK1VLmc0ZC9ROSXjKoL5F6kOZFByzirRWIdXxhBfWU,4124 +huggingface_hub/utils/_git_credential.py,sha256=1BhjvIScCOAToDORLOKrR3Szs-m0E5AYHPmC0SD7Nrs,4548 +huggingface_hub/utils/_headers.py,sha256=fHd8JflV1sX02mdQnwc7k1zll3ZXceu-HmmGz0UOEFo,8090 +huggingface_hub/utils/_hf_uris.py,sha256=i_4QCMtffC7XKn8X7N38OLiUyW8pdWhQmOlIECBUVP0,16464 +huggingface_hub/utils/_http.py,sha256=SCTMeZjKM9agYGfVfRjtT_eXKMNK9u1-RCSzBif_ojs,42652 +huggingface_hub/utils/_lfs.py,sha256=xMU-ROgNAUpDkzbH6yRZsE-eVYUYTNMGrgVb_QdTv-k,3942 +huggingface_hub/utils/_pagination.py,sha256=buIKERSyWOJqVSY9nv8hImDmNErD-PPOnXosXm2O87Y,1832 +huggingface_hub/utils/_parsing.py,sha256=Z07oEU-19L_0Mav7_LRZLz0z0NuS4bLDaAY1RPdeqf0,2982 +huggingface_hub/utils/_paths.py,sha256=ZceF9JnRzNrvrMSvPbgriuRQ3_LpLa3EE8W21bvBxaU,5265 +huggingface_hub/utils/_runtime.py,sha256=GVJ_Dt6y_48TZWl0ui9yPdW8M7rqGblRGyUqKaXxkCo,13493 +huggingface_hub/utils/_safetensors.py,sha256=qFE7OA-vjU8X0zBBtOeNRzLu147KF-PdFoaxkYfWB4M,4426 +huggingface_hub/utils/_subprocess.py,sha256=tFVBBNot_HLVqQ79y873TGb12C4PUTMwub-GhzDTemE,4542 +huggingface_hub/utils/_telemetry.py,sha256=Tpa3YmOLhK_MEnL2i2fRLQy8aqAEZWbj6MKC18Hs8BA,4824 +huggingface_hub/utils/_terminal.py,sha256=7jdWt1xvmx7nOlYG416833EjJyukvDzksTVfRFloAtg,3532 +huggingface_hub/utils/_typing.py,sha256=1LeE785YedppXSR9a1fQDu5rhTxX5v9kBYBaHrP65rA,3542 +huggingface_hub/utils/_validators.py,sha256=tuC1U4yxB-4XKIajZMnKZUSKvZ6qPpydY8LItfa0g40,8419 +huggingface_hub/utils/_verification.py,sha256=ZSilnolSkYmHB3vmBlWuuVr53xz59P5uGnxC3H-Hjc0,5434 +huggingface_hub/utils/_xet.py,sha256=v2VI_iVGIp4-mGT44L9nY9R4fdBeVepjUBzsVIeQS1g,9834 +huggingface_hub/utils/_xet_progress_reporting.py,sha256=IlrrHAgHYKsep4o9fhsCtdMFhKxp5rKoHs785x5q21k,6826 +huggingface_hub/utils/endpoint_helpers.py,sha256=9VtIAlxQ5H_4y30sjCAgbu7XCqAtNLC7aRYxaNn0hLI,2366 +huggingface_hub/utils/insecure_hashlib.py,sha256=z3dVUFvdBZ8kQI_8Vzvvlr3ims-EBiY-SYPdnzIKOkw,1008 +huggingface_hub/utils/logging.py,sha256=WaXk5gRa8Ml_LUIH34QCr8suYj8i_8Wot4IDnYJyWyM,4870 +huggingface_hub/utils/sha.py,sha256=h8wxheZpcv671RhtiIFcFmQTDSrogN3kwQx3ZaNEUHg,2121 +huggingface_hub/utils/tqdm.py,sha256=KbHhkB5g76JgGOGCcjAQOaR-oc-wzd4Sr3wqd41ny7k,13350 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..8acb95590701b87bf84eec079cf4e3989f63b098 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (79.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/entry_points.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..62018f2f5622f61920179a20b80488f21dbb1686 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/entry_points.txt @@ -0,0 +1,7 @@ +[console_scripts] +hf = huggingface_hub.cli.hf:main +huggingface-cli = huggingface_hub.cli.deprecated_cli:main +tiny-agents = huggingface_hub.inference._mcp.cli:app + +[fsspec.specs] +hf = huggingface_hub.HfFileSystem diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..6b964ccca3c1b6766042b3fe3b2707ba25372924 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub-1.14.0.dist-info/top_level.txt @@ -0,0 +1 @@ +huggingface_hub diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..443487f6dad78e9fe7044842de7d8003ebbdd7f7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/__init__.py @@ -0,0 +1,1741 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# *********** +# `huggingface_hub` init has 2 modes: +# - Normal usage: +# If imported to use it, all modules and functions are lazy-loaded. This means +# they exist at top level in module but are imported only the first time they are +# used. This way, `from huggingface_hub import something` will import `something` +# quickly without the hassle of importing all the features from `huggingface_hub`. +# - Static check: +# If statically analyzed, all modules and functions are loaded normally. This way +# static typing check works properly as well as autocomplete in text editors and +# IDEs. +# +# The static model imports are done inside the `if TYPE_CHECKING:` statement at +# the bottom of this file. Since module/functions imports are duplicated, it is +# mandatory to make sure to add them twice when adding one. This is checked in the +# `make quality` command. +# +# To update the static imports, please run the following command and commit the changes. +# ``` +# # Use script +# python utils/check_static_imports.py --update-file +# +# # Or run style on codebase +# make style +# ``` +# +# *********** +# Lazy loader vendored from https://github.com/scientific-python/lazy_loader +import importlib +import os +import sys +from typing import TYPE_CHECKING + + +__version__ = "1.14.0" + +# Alphabetical order of definitions is ensured in tests +# WARNING: any comment added in this dictionary definition will be lost when +# re-generating the file ! +_SUBMOD_ATTRS = { + "_buckets": [ + "BucketFile", + "BucketFileMetadata", + "BucketFolder", + "BucketInfo", + "BucketUrl", + "SyncOperation", + "SyncPlan", + ], + "_commit_scheduler": [ + "CommitScheduler", + ], + "_eval_results": [ + "EvalResultEntry", + "eval_result_entries_to_yaml", + "parse_eval_result_entries", + ], + "_inference_endpoints": [ + "InferenceEndpoint", + "InferenceEndpointError", + "InferenceEndpointStatus", + "InferenceEndpointTimeoutError", + "InferenceEndpointType", + ], + "_jobs_api": [ + "JobAccelerator", + "JobHardware", + "JobInfo", + "JobOwner", + "JobStage", + "JobStatus", + ], + "_login": [ + "auth_list", + "auth_switch", + "interpreter_login", + "login", + "logout", + "notebook_login", + ], + "_oauth": [ + "OAuthInfo", + "OAuthOrgInfo", + "OAuthUserInfo", + "attach_huggingface_oauth", + "parse_huggingface_oauth", + ], + "_snapshot_download": [ + "snapshot_download", + ], + "_space_api": [ + "SpaceHardware", + "SpaceRuntime", + "SpaceSecret", + "SpaceStage", + "SpaceStorage", + "SpaceVariable", + "Volume", + ], + "_tensorboard_logger": [ + "HFSummaryWriter", + ], + "_webhooks_payload": [ + "WebhookPayload", + "WebhookPayloadComment", + "WebhookPayloadDiscussion", + "WebhookPayloadDiscussionChanges", + "WebhookPayloadEvent", + "WebhookPayloadMovedTo", + "WebhookPayloadRepo", + "WebhookPayloadUrl", + "WebhookPayloadWebhook", + ], + "_webhooks_server": [ + "WebhooksServer", + "webhook_endpoint", + ], + "cli._cli_utils": [ + "check_cli_update", + "typer_factory", + ], + "community": [ + "Discussion", + "DiscussionComment", + "DiscussionCommit", + "DiscussionEvent", + "DiscussionStatusChange", + "DiscussionTitleChange", + "DiscussionWithDetails", + ], + "constants": [ + "CONFIG_NAME", + "FLAX_WEIGHTS_NAME", + "HUGGINGFACE_CO_URL_HOME", + "HUGGINGFACE_CO_URL_TEMPLATE", + "PYTORCH_WEIGHTS_NAME", + "REPO_TYPE_DATASET", + "REPO_TYPE_MODEL", + "REPO_TYPE_SPACE", + "TF2_WEIGHTS_NAME", + "TF_WEIGHTS_NAME", + "is_offline_mode", + ], + "fastai_utils": [ + "_save_pretrained_fastai", + "from_pretrained_fastai", + "push_to_hub_fastai", + ], + "file_download": [ + "DryRunFileInfo", + "HfFileMetadata", + "_CACHED_NO_EXIST", + "get_hf_file_metadata", + "hf_hub_download", + "hf_hub_url", + "try_to_load_from_cache", + ], + "hf_api": [ + "Collection", + "CollectionItem", + "CommitInfo", + "CommitOperation", + "CommitOperationAdd", + "CommitOperationCopy", + "CommitOperationDelete", + "DatasetInfo", + "DatasetLeaderboardEntry", + "GitCommitInfo", + "GitRefInfo", + "GitRefs", + "HfApi", + "KernelInfo", + "ModelInfo", + "Organization", + "RepoFile", + "RepoFolder", + "RepoUrl", + "SpaceInfo", + "SpaceSearchResult", + "User", + "UserLikes", + "WebhookInfo", + "WebhookWatchedItem", + "accept_access_request", + "add_collection_item", + "add_space_secret", + "add_space_variable", + "auth_check", + "batch_bucket_files", + "bucket_info", + "cancel_access_request", + "cancel_job", + "change_discussion_status", + "comment_discussion", + "copy_files", + "create_branch", + "create_bucket", + "create_collection", + "create_commit", + "create_discussion", + "create_inference_endpoint", + "create_inference_endpoint_from_catalog", + "create_pull_request", + "create_repo", + "create_scheduled_job", + "create_scheduled_uv_job", + "create_tag", + "create_webhook", + "dataset_info", + "delete_branch", + "delete_bucket", + "delete_collection", + "delete_collection_item", + "delete_file", + "delete_folder", + "delete_inference_endpoint", + "delete_repo", + "delete_scheduled_job", + "delete_space_secret", + "delete_space_storage", + "delete_space_variable", + "delete_space_volumes", + "delete_tag", + "delete_webhook", + "disable_space_dev_mode", + "disable_webhook", + "download_bucket_files", + "duplicate_repo", + "duplicate_space", + "edit_discussion_comment", + "enable_space_dev_mode", + "enable_webhook", + "fetch_job_logs", + "fetch_job_metrics", + "fetch_space_logs", + "file_exists", + "get_bucket_file_metadata", + "get_bucket_paths_info", + "get_collection", + "get_dataset_leaderboard", + "get_dataset_tags", + "get_discussion_details", + "get_full_repo_name", + "get_inference_endpoint", + "get_local_safetensors_metadata", + "get_model_tags", + "get_organization_overview", + "get_paths_info", + "get_repo_discussions", + "get_safetensors_metadata", + "get_space_runtime", + "get_space_secrets", + "get_space_variables", + "get_user_overview", + "get_webhook", + "grant_access", + "inspect_job", + "inspect_scheduled_job", + "kernel_info", + "list_accepted_access_requests", + "list_bucket_tree", + "list_buckets", + "list_collections", + "list_daily_papers", + "list_dataset_parquet_files", + "list_datasets", + "list_inference_catalog", + "list_inference_endpoints", + "list_jobs", + "list_jobs_hardware", + "list_lfs_files", + "list_liked_repos", + "list_models", + "list_organization_followers", + "list_organization_members", + "list_papers", + "list_pending_access_requests", + "list_rejected_access_requests", + "list_repo_commits", + "list_repo_files", + "list_repo_likers", + "list_repo_refs", + "list_repo_tree", + "list_spaces", + "list_spaces_hardware", + "list_user_followers", + "list_user_following", + "list_webhooks", + "merge_pull_request", + "model_info", + "move_bucket", + "move_repo", + "paper_info", + "parse_local_safetensors_file_metadata", + "parse_safetensors_file_metadata", + "pause_inference_endpoint", + "pause_space", + "permanently_delete_lfs_files", + "preupload_lfs_files", + "read_paper", + "reject_access_request", + "rename_discussion", + "repo_exists", + "repo_info", + "repo_type_and_id_from_hf_id", + "request_space_hardware", + "request_space_storage", + "restart_space", + "resume_inference_endpoint", + "resume_scheduled_job", + "revision_exists", + "run_as_future", + "run_job", + "run_uv_job", + "scale_to_zero_inference_endpoint", + "search_spaces", + "set_space_sleep_time", + "set_space_volumes", + "space_info", + "super_squash_history", + "suspend_scheduled_job", + "sync_bucket", + "unlike", + "update_collection_item", + "update_collection_metadata", + "update_inference_endpoint", + "update_repo_settings", + "update_webhook", + "upload_file", + "upload_folder", + "upload_large_folder", + "verify_repo_checksums", + "whoami", + ], + "hf_file_system": [ + "HfFileSystem", + "HfFileSystemFile", + "HfFileSystemResolvedPath", + "HfFileSystemStreamFile", + "hffs", + ], + "hub_mixin": [ + "ModelHubMixin", + "PyTorchModelHubMixin", + ], + "inference._client": [ + "InferenceClient", + "InferenceTimeoutError", + ], + "inference._generated._async_client": [ + "AsyncInferenceClient", + ], + "inference._generated.types": [ + "AudioClassificationInput", + "AudioClassificationOutputElement", + "AudioClassificationOutputTransform", + "AudioClassificationParameters", + "AudioToAudioInput", + "AudioToAudioOutputElement", + "AutomaticSpeechRecognitionEarlyStoppingEnum", + "AutomaticSpeechRecognitionGenerationParameters", + "AutomaticSpeechRecognitionInput", + "AutomaticSpeechRecognitionOutput", + "AutomaticSpeechRecognitionOutputChunk", + "AutomaticSpeechRecognitionParameters", + "ChatCompletionInput", + "ChatCompletionInputFunctionDefinition", + "ChatCompletionInputFunctionName", + "ChatCompletionInputGrammarType", + "ChatCompletionInputJSONSchema", + "ChatCompletionInputMessage", + "ChatCompletionInputMessageChunk", + "ChatCompletionInputMessageChunkType", + "ChatCompletionInputResponseFormatJSONObject", + "ChatCompletionInputResponseFormatJSONSchema", + "ChatCompletionInputResponseFormatText", + "ChatCompletionInputStreamOptions", + "ChatCompletionInputTool", + "ChatCompletionInputToolCall", + "ChatCompletionInputToolChoiceClass", + "ChatCompletionInputToolChoiceEnum", + "ChatCompletionInputURL", + "ChatCompletionOutput", + "ChatCompletionOutputComplete", + "ChatCompletionOutputFunctionDefinition", + "ChatCompletionOutputLogprob", + "ChatCompletionOutputLogprobs", + "ChatCompletionOutputMessage", + "ChatCompletionOutputToolCall", + "ChatCompletionOutputTopLogprob", + "ChatCompletionOutputUsage", + "ChatCompletionStreamOutput", + "ChatCompletionStreamOutputChoice", + "ChatCompletionStreamOutputDelta", + "ChatCompletionStreamOutputDeltaToolCall", + "ChatCompletionStreamOutputFunction", + "ChatCompletionStreamOutputLogprob", + "ChatCompletionStreamOutputLogprobs", + "ChatCompletionStreamOutputTopLogprob", + "ChatCompletionStreamOutputUsage", + "DepthEstimationInput", + "DepthEstimationOutput", + "DocumentQuestionAnsweringInput", + "DocumentQuestionAnsweringInputData", + "DocumentQuestionAnsweringOutputElement", + "DocumentQuestionAnsweringParameters", + "FeatureExtractionInput", + "FeatureExtractionInputTruncationDirection", + "FillMaskInput", + "FillMaskOutputElement", + "FillMaskParameters", + "ImageClassificationInput", + "ImageClassificationOutputElement", + "ImageClassificationOutputTransform", + "ImageClassificationParameters", + "ImageSegmentationInput", + "ImageSegmentationOutputElement", + "ImageSegmentationParameters", + "ImageSegmentationSubtask", + "ImageTextToImageInput", + "ImageTextToImageOutput", + "ImageTextToImageParameters", + "ImageTextToImageTargetSize", + "ImageTextToVideoInput", + "ImageTextToVideoOutput", + "ImageTextToVideoParameters", + "ImageTextToVideoTargetSize", + "ImageToImageInput", + "ImageToImageOutput", + "ImageToImageParameters", + "ImageToImageTargetSize", + "ImageToTextEarlyStoppingEnum", + "ImageToTextGenerationParameters", + "ImageToTextInput", + "ImageToTextOutput", + "ImageToTextParameters", + "ImageToVideoInput", + "ImageToVideoOutput", + "ImageToVideoParameters", + "ImageToVideoTargetSize", + "ObjectDetectionBoundingBox", + "ObjectDetectionInput", + "ObjectDetectionOutputElement", + "ObjectDetectionParameters", + "Padding", + "QuestionAnsweringInput", + "QuestionAnsweringInputData", + "QuestionAnsweringOutputElement", + "QuestionAnsweringParameters", + "SentenceSimilarityInput", + "SentenceSimilarityInputData", + "SummarizationInput", + "SummarizationOutput", + "SummarizationParameters", + "SummarizationTruncationStrategy", + "TableQuestionAnsweringInput", + "TableQuestionAnsweringInputData", + "TableQuestionAnsweringOutputElement", + "TableQuestionAnsweringParameters", + "Text2TextGenerationInput", + "Text2TextGenerationOutput", + "Text2TextGenerationParameters", + "Text2TextGenerationTruncationStrategy", + "TextClassificationInput", + "TextClassificationOutputElement", + "TextClassificationOutputTransform", + "TextClassificationParameters", + "TextGenerationInput", + "TextGenerationInputGenerateParameters", + "TextGenerationInputGrammarType", + "TextGenerationOutput", + "TextGenerationOutputBestOfSequence", + "TextGenerationOutputDetails", + "TextGenerationOutputFinishReason", + "TextGenerationOutputPrefillToken", + "TextGenerationOutputToken", + "TextGenerationStreamOutput", + "TextGenerationStreamOutputStreamDetails", + "TextGenerationStreamOutputToken", + "TextToAudioEarlyStoppingEnum", + "TextToAudioGenerationParameters", + "TextToAudioInput", + "TextToAudioOutput", + "TextToAudioParameters", + "TextToImageInput", + "TextToImageOutput", + "TextToImageParameters", + "TextToSpeechEarlyStoppingEnum", + "TextToSpeechGenerationParameters", + "TextToSpeechInput", + "TextToSpeechOutput", + "TextToSpeechParameters", + "TextToVideoInput", + "TextToVideoOutput", + "TextToVideoParameters", + "TokenClassificationAggregationStrategy", + "TokenClassificationInput", + "TokenClassificationOutputElement", + "TokenClassificationParameters", + "TranslationInput", + "TranslationOutput", + "TranslationParameters", + "TranslationTruncationStrategy", + "TypeEnum", + "VideoClassificationInput", + "VideoClassificationOutputElement", + "VideoClassificationOutputTransform", + "VideoClassificationParameters", + "VisualQuestionAnsweringInput", + "VisualQuestionAnsweringInputData", + "VisualQuestionAnsweringOutputElement", + "VisualQuestionAnsweringParameters", + "ZeroShotClassificationInput", + "ZeroShotClassificationOutputElement", + "ZeroShotClassificationParameters", + "ZeroShotImageClassificationInput", + "ZeroShotImageClassificationOutputElement", + "ZeroShotImageClassificationParameters", + "ZeroShotObjectDetectionBoundingBox", + "ZeroShotObjectDetectionInput", + "ZeroShotObjectDetectionOutputElement", + "ZeroShotObjectDetectionParameters", + ], + "inference._mcp.agent": [ + "Agent", + ], + "inference._mcp.mcp_client": [ + "MCPClient", + ], + "repocard": [ + "DatasetCard", + "ModelCard", + "RepoCard", + "SpaceCard", + "metadata_eval_result", + "metadata_load", + "metadata_save", + "metadata_update", + ], + "repocard_data": [ + "CardData", + "DatasetCardData", + "EvalResult", + "ModelCardData", + "SpaceCardData", + ], + "serialization": [ + "StateDictSplit", + "get_torch_storage_id", + "get_torch_storage_size", + "load_state_dict_from_file", + "load_torch_model", + "save_torch_model", + "save_torch_state_dict", + "split_state_dict_into_shards_factory", + "split_torch_state_dict_into_shards", + ], + "serialization._dduf": [ + "DDUFEntry", + "export_entries_as_dduf", + "export_folder_as_dduf", + "read_dduf_file", + ], + "utils": [ + "ASYNC_CLIENT_FACTORY_T", + "CLIENT_FACTORY_T", + "CacheNotFound", + "CachedFileInfo", + "CachedRepoInfo", + "CachedRevisionInfo", + "CorruptedCacheException", + "DeleteCacheStrategy", + "HFCacheInfo", + "HfUri", + "cached_assets_path", + "close_session", + "dump_environment_info", + "get_async_session", + "get_session", + "get_token", + "hf_raise_for_status", + "logging", + "parse_hf_uri", + "scan_cache_dir", + "set_async_client_factory", + "set_client_factory", + ], +} + +# WARNING: __all__ is generated automatically, Any manual edit will be lost when re-generating this file ! +# +# To update the static imports, please run the following command and commit the changes. +# ``` +# # Use script +# python utils/check_all_variable.py --update +# +# # Or run style on codebase +# make style +# ``` + +__all__ = [ + "ASYNC_CLIENT_FACTORY_T", + "Agent", + "AsyncInferenceClient", + "AudioClassificationInput", + "AudioClassificationOutputElement", + "AudioClassificationOutputTransform", + "AudioClassificationParameters", + "AudioToAudioInput", + "AudioToAudioOutputElement", + "AutomaticSpeechRecognitionEarlyStoppingEnum", + "AutomaticSpeechRecognitionGenerationParameters", + "AutomaticSpeechRecognitionInput", + "AutomaticSpeechRecognitionOutput", + "AutomaticSpeechRecognitionOutputChunk", + "AutomaticSpeechRecognitionParameters", + "BucketFile", + "BucketFileMetadata", + "BucketFolder", + "BucketInfo", + "BucketUrl", + "CLIENT_FACTORY_T", + "CONFIG_NAME", + "CacheNotFound", + "CachedFileInfo", + "CachedRepoInfo", + "CachedRevisionInfo", + "CardData", + "ChatCompletionInput", + "ChatCompletionInputFunctionDefinition", + "ChatCompletionInputFunctionName", + "ChatCompletionInputGrammarType", + "ChatCompletionInputJSONSchema", + "ChatCompletionInputMessage", + "ChatCompletionInputMessageChunk", + "ChatCompletionInputMessageChunkType", + "ChatCompletionInputResponseFormatJSONObject", + "ChatCompletionInputResponseFormatJSONSchema", + "ChatCompletionInputResponseFormatText", + "ChatCompletionInputStreamOptions", + "ChatCompletionInputTool", + "ChatCompletionInputToolCall", + "ChatCompletionInputToolChoiceClass", + "ChatCompletionInputToolChoiceEnum", + "ChatCompletionInputURL", + "ChatCompletionOutput", + "ChatCompletionOutputComplete", + "ChatCompletionOutputFunctionDefinition", + "ChatCompletionOutputLogprob", + "ChatCompletionOutputLogprobs", + "ChatCompletionOutputMessage", + "ChatCompletionOutputToolCall", + "ChatCompletionOutputTopLogprob", + "ChatCompletionOutputUsage", + "ChatCompletionStreamOutput", + "ChatCompletionStreamOutputChoice", + "ChatCompletionStreamOutputDelta", + "ChatCompletionStreamOutputDeltaToolCall", + "ChatCompletionStreamOutputFunction", + "ChatCompletionStreamOutputLogprob", + "ChatCompletionStreamOutputLogprobs", + "ChatCompletionStreamOutputTopLogprob", + "ChatCompletionStreamOutputUsage", + "Collection", + "CollectionItem", + "CommitInfo", + "CommitOperation", + "CommitOperationAdd", + "CommitOperationCopy", + "CommitOperationDelete", + "CommitScheduler", + "CorruptedCacheException", + "DDUFEntry", + "DatasetCard", + "DatasetCardData", + "DatasetInfo", + "DatasetLeaderboardEntry", + "DeleteCacheStrategy", + "DepthEstimationInput", + "DepthEstimationOutput", + "Discussion", + "DiscussionComment", + "DiscussionCommit", + "DiscussionEvent", + "DiscussionStatusChange", + "DiscussionTitleChange", + "DiscussionWithDetails", + "DocumentQuestionAnsweringInput", + "DocumentQuestionAnsweringInputData", + "DocumentQuestionAnsweringOutputElement", + "DocumentQuestionAnsweringParameters", + "DryRunFileInfo", + "EvalResult", + "EvalResultEntry", + "FLAX_WEIGHTS_NAME", + "FeatureExtractionInput", + "FeatureExtractionInputTruncationDirection", + "FillMaskInput", + "FillMaskOutputElement", + "FillMaskParameters", + "GitCommitInfo", + "GitRefInfo", + "GitRefs", + "HFCacheInfo", + "HFSummaryWriter", + "HUGGINGFACE_CO_URL_HOME", + "HUGGINGFACE_CO_URL_TEMPLATE", + "HfApi", + "HfFileMetadata", + "HfFileSystem", + "HfFileSystemFile", + "HfFileSystemResolvedPath", + "HfFileSystemStreamFile", + "HfUri", + "ImageClassificationInput", + "ImageClassificationOutputElement", + "ImageClassificationOutputTransform", + "ImageClassificationParameters", + "ImageSegmentationInput", + "ImageSegmentationOutputElement", + "ImageSegmentationParameters", + "ImageSegmentationSubtask", + "ImageTextToImageInput", + "ImageTextToImageOutput", + "ImageTextToImageParameters", + "ImageTextToImageTargetSize", + "ImageTextToVideoInput", + "ImageTextToVideoOutput", + "ImageTextToVideoParameters", + "ImageTextToVideoTargetSize", + "ImageToImageInput", + "ImageToImageOutput", + "ImageToImageParameters", + "ImageToImageTargetSize", + "ImageToTextEarlyStoppingEnum", + "ImageToTextGenerationParameters", + "ImageToTextInput", + "ImageToTextOutput", + "ImageToTextParameters", + "ImageToVideoInput", + "ImageToVideoOutput", + "ImageToVideoParameters", + "ImageToVideoTargetSize", + "InferenceClient", + "InferenceEndpoint", + "InferenceEndpointError", + "InferenceEndpointStatus", + "InferenceEndpointTimeoutError", + "InferenceEndpointType", + "InferenceTimeoutError", + "JobAccelerator", + "JobHardware", + "JobInfo", + "JobOwner", + "JobStage", + "JobStatus", + "KernelInfo", + "MCPClient", + "ModelCard", + "ModelCardData", + "ModelHubMixin", + "ModelInfo", + "OAuthInfo", + "OAuthOrgInfo", + "OAuthUserInfo", + "ObjectDetectionBoundingBox", + "ObjectDetectionInput", + "ObjectDetectionOutputElement", + "ObjectDetectionParameters", + "Organization", + "PYTORCH_WEIGHTS_NAME", + "Padding", + "PyTorchModelHubMixin", + "QuestionAnsweringInput", + "QuestionAnsweringInputData", + "QuestionAnsweringOutputElement", + "QuestionAnsweringParameters", + "REPO_TYPE_DATASET", + "REPO_TYPE_MODEL", + "REPO_TYPE_SPACE", + "RepoCard", + "RepoFile", + "RepoFolder", + "RepoUrl", + "SentenceSimilarityInput", + "SentenceSimilarityInputData", + "SpaceCard", + "SpaceCardData", + "SpaceHardware", + "SpaceInfo", + "SpaceRuntime", + "SpaceSearchResult", + "SpaceSecret", + "SpaceStage", + "SpaceStorage", + "SpaceVariable", + "StateDictSplit", + "SummarizationInput", + "SummarizationOutput", + "SummarizationParameters", + "SummarizationTruncationStrategy", + "SyncOperation", + "SyncPlan", + "TF2_WEIGHTS_NAME", + "TF_WEIGHTS_NAME", + "TableQuestionAnsweringInput", + "TableQuestionAnsweringInputData", + "TableQuestionAnsweringOutputElement", + "TableQuestionAnsweringParameters", + "Text2TextGenerationInput", + "Text2TextGenerationOutput", + "Text2TextGenerationParameters", + "Text2TextGenerationTruncationStrategy", + "TextClassificationInput", + "TextClassificationOutputElement", + "TextClassificationOutputTransform", + "TextClassificationParameters", + "TextGenerationInput", + "TextGenerationInputGenerateParameters", + "TextGenerationInputGrammarType", + "TextGenerationOutput", + "TextGenerationOutputBestOfSequence", + "TextGenerationOutputDetails", + "TextGenerationOutputFinishReason", + "TextGenerationOutputPrefillToken", + "TextGenerationOutputToken", + "TextGenerationStreamOutput", + "TextGenerationStreamOutputStreamDetails", + "TextGenerationStreamOutputToken", + "TextToAudioEarlyStoppingEnum", + "TextToAudioGenerationParameters", + "TextToAudioInput", + "TextToAudioOutput", + "TextToAudioParameters", + "TextToImageInput", + "TextToImageOutput", + "TextToImageParameters", + "TextToSpeechEarlyStoppingEnum", + "TextToSpeechGenerationParameters", + "TextToSpeechInput", + "TextToSpeechOutput", + "TextToSpeechParameters", + "TextToVideoInput", + "TextToVideoOutput", + "TextToVideoParameters", + "TokenClassificationAggregationStrategy", + "TokenClassificationInput", + "TokenClassificationOutputElement", + "TokenClassificationParameters", + "TranslationInput", + "TranslationOutput", + "TranslationParameters", + "TranslationTruncationStrategy", + "TypeEnum", + "User", + "UserLikes", + "VideoClassificationInput", + "VideoClassificationOutputElement", + "VideoClassificationOutputTransform", + "VideoClassificationParameters", + "VisualQuestionAnsweringInput", + "VisualQuestionAnsweringInputData", + "VisualQuestionAnsweringOutputElement", + "VisualQuestionAnsweringParameters", + "Volume", + "WebhookInfo", + "WebhookPayload", + "WebhookPayloadComment", + "WebhookPayloadDiscussion", + "WebhookPayloadDiscussionChanges", + "WebhookPayloadEvent", + "WebhookPayloadMovedTo", + "WebhookPayloadRepo", + "WebhookPayloadUrl", + "WebhookPayloadWebhook", + "WebhookWatchedItem", + "WebhooksServer", + "ZeroShotClassificationInput", + "ZeroShotClassificationOutputElement", + "ZeroShotClassificationParameters", + "ZeroShotImageClassificationInput", + "ZeroShotImageClassificationOutputElement", + "ZeroShotImageClassificationParameters", + "ZeroShotObjectDetectionBoundingBox", + "ZeroShotObjectDetectionInput", + "ZeroShotObjectDetectionOutputElement", + "ZeroShotObjectDetectionParameters", + "_CACHED_NO_EXIST", + "_save_pretrained_fastai", + "accept_access_request", + "add_collection_item", + "add_space_secret", + "add_space_variable", + "attach_huggingface_oauth", + "auth_check", + "auth_list", + "auth_switch", + "batch_bucket_files", + "bucket_info", + "cached_assets_path", + "cancel_access_request", + "cancel_job", + "change_discussion_status", + "check_cli_update", + "close_session", + "comment_discussion", + "copy_files", + "create_branch", + "create_bucket", + "create_collection", + "create_commit", + "create_discussion", + "create_inference_endpoint", + "create_inference_endpoint_from_catalog", + "create_pull_request", + "create_repo", + "create_scheduled_job", + "create_scheduled_uv_job", + "create_tag", + "create_webhook", + "dataset_info", + "delete_branch", + "delete_bucket", + "delete_collection", + "delete_collection_item", + "delete_file", + "delete_folder", + "delete_inference_endpoint", + "delete_repo", + "delete_scheduled_job", + "delete_space_secret", + "delete_space_storage", + "delete_space_variable", + "delete_space_volumes", + "delete_tag", + "delete_webhook", + "disable_space_dev_mode", + "disable_webhook", + "download_bucket_files", + "dump_environment_info", + "duplicate_repo", + "duplicate_space", + "edit_discussion_comment", + "enable_space_dev_mode", + "enable_webhook", + "eval_result_entries_to_yaml", + "export_entries_as_dduf", + "export_folder_as_dduf", + "fetch_job_logs", + "fetch_job_metrics", + "fetch_space_logs", + "file_exists", + "from_pretrained_fastai", + "get_async_session", + "get_bucket_file_metadata", + "get_bucket_paths_info", + "get_collection", + "get_dataset_leaderboard", + "get_dataset_tags", + "get_discussion_details", + "get_full_repo_name", + "get_hf_file_metadata", + "get_inference_endpoint", + "get_local_safetensors_metadata", + "get_model_tags", + "get_organization_overview", + "get_paths_info", + "get_repo_discussions", + "get_safetensors_metadata", + "get_session", + "get_space_runtime", + "get_space_secrets", + "get_space_variables", + "get_token", + "get_torch_storage_id", + "get_torch_storage_size", + "get_user_overview", + "get_webhook", + "grant_access", + "hf_hub_download", + "hf_hub_url", + "hf_raise_for_status", + "hffs", + "inspect_job", + "inspect_scheduled_job", + "interpreter_login", + "is_offline_mode", + "kernel_info", + "list_accepted_access_requests", + "list_bucket_tree", + "list_buckets", + "list_collections", + "list_daily_papers", + "list_dataset_parquet_files", + "list_datasets", + "list_inference_catalog", + "list_inference_endpoints", + "list_jobs", + "list_jobs_hardware", + "list_lfs_files", + "list_liked_repos", + "list_models", + "list_organization_followers", + "list_organization_members", + "list_papers", + "list_pending_access_requests", + "list_rejected_access_requests", + "list_repo_commits", + "list_repo_files", + "list_repo_likers", + "list_repo_refs", + "list_repo_tree", + "list_spaces", + "list_spaces_hardware", + "list_user_followers", + "list_user_following", + "list_webhooks", + "load_state_dict_from_file", + "load_torch_model", + "logging", + "login", + "logout", + "merge_pull_request", + "metadata_eval_result", + "metadata_load", + "metadata_save", + "metadata_update", + "model_info", + "move_bucket", + "move_repo", + "notebook_login", + "paper_info", + "parse_eval_result_entries", + "parse_hf_uri", + "parse_huggingface_oauth", + "parse_local_safetensors_file_metadata", + "parse_safetensors_file_metadata", + "pause_inference_endpoint", + "pause_space", + "permanently_delete_lfs_files", + "preupload_lfs_files", + "push_to_hub_fastai", + "read_dduf_file", + "read_paper", + "reject_access_request", + "rename_discussion", + "repo_exists", + "repo_info", + "repo_type_and_id_from_hf_id", + "request_space_hardware", + "request_space_storage", + "restart_space", + "resume_inference_endpoint", + "resume_scheduled_job", + "revision_exists", + "run_as_future", + "run_job", + "run_uv_job", + "save_torch_model", + "save_torch_state_dict", + "scale_to_zero_inference_endpoint", + "scan_cache_dir", + "search_spaces", + "set_async_client_factory", + "set_client_factory", + "set_space_sleep_time", + "set_space_volumes", + "snapshot_download", + "space_info", + "split_state_dict_into_shards_factory", + "split_torch_state_dict_into_shards", + "super_squash_history", + "suspend_scheduled_job", + "sync_bucket", + "try_to_load_from_cache", + "typer_factory", + "unlike", + "update_collection_item", + "update_collection_metadata", + "update_inference_endpoint", + "update_repo_settings", + "update_webhook", + "upload_file", + "upload_folder", + "upload_large_folder", + "verify_repo_checksums", + "webhook_endpoint", + "whoami", +] + + +def _attach(package_name, submodules=None, submod_attrs=None): + """Attach lazily loaded submodules, functions, or other attributes. + + Typically, modules import submodules and attributes as follows: + + ```py + import mysubmodule + import anothersubmodule + + from .foo import someattr + ``` + + The idea is to replace a package's `__getattr__`, `__dir__`, such that all imports + work exactly the way they would with normal imports, except that the import occurs + upon first use. + + The typical way to call this function, replacing the above imports, is: + + ```python + __getattr__, __dir__ = lazy.attach( + __name__, + ['mysubmodule', 'anothersubmodule'], + {'foo': ['someattr']} + ) + ``` + This functionality requires Python 3.7 or higher. + + Args: + package_name (`str`): + Typically use `__name__`. + submodules (`set`): + List of submodules to attach. + submod_attrs (`dict`): + Dictionary of submodule -> list of attributes / functions. + These attributes are imported as they are used. + + Returns: + __getattr__, __dir__, __all__ + + """ + if submod_attrs is None: + submod_attrs = {} + + if submodules is None: + submodules = set() + else: + submodules = set(submodules) + + attr_to_modules = {attr: mod for mod, attrs in submod_attrs.items() for attr in attrs} + + def __getattr__(name): + if name in submodules: + try: + return importlib.import_module(f"{package_name}.{name}") + except Exception as e: + print(f"Error importing {package_name}.{name}: {e}") + raise + elif name in attr_to_modules: + submod_path = f"{package_name}.{attr_to_modules[name]}" + try: + submod = importlib.import_module(submod_path) + except Exception as e: + print(f"Error importing {submod_path}: {e}") + raise + attr = getattr(submod, name) + + # If the attribute lives in a file (module) with the same + # name as the attribute, ensure that the attribute and *not* + # the module is accessible on the package. + if name == attr_to_modules[name]: + pkg = sys.modules[package_name] + pkg.__dict__[name] = attr + + return attr + else: + raise AttributeError(f"No {package_name} attribute {name}") + + def __dir__(): + return __all__ + + return __getattr__, __dir__ + + +__getattr__, __dir__ = _attach(__name__, submodules=[], submod_attrs=_SUBMOD_ATTRS) + +if os.environ.get("EAGER_IMPORT", ""): + for attr in __all__: + __getattr__(attr) + +# WARNING: any content below this statement is generated automatically. Any manual edit +# will be lost when re-generating this file ! +# +# To update the static imports, please run the following command and commit the changes. +# ``` +# # Use script +# python utils/check_static_imports.py --update +# +# # Or run style on codebase +# make style +# ``` +if TYPE_CHECKING: # pragma: no cover + from ._buckets import ( + BucketFile, # noqa: F401 + BucketFileMetadata, # noqa: F401 + BucketFolder, # noqa: F401 + BucketInfo, # noqa: F401 + BucketUrl, # noqa: F401 + SyncOperation, # noqa: F401 + SyncPlan, # noqa: F401 + ) + from ._commit_scheduler import CommitScheduler # noqa: F401 + from ._eval_results import ( + EvalResultEntry, # noqa: F401 + eval_result_entries_to_yaml, # noqa: F401 + parse_eval_result_entries, # noqa: F401 + ) + from ._inference_endpoints import ( + InferenceEndpoint, # noqa: F401 + InferenceEndpointError, # noqa: F401 + InferenceEndpointStatus, # noqa: F401 + InferenceEndpointTimeoutError, # noqa: F401 + InferenceEndpointType, # noqa: F401 + ) + from ._jobs_api import ( + JobAccelerator, # noqa: F401 + JobHardware, # noqa: F401 + JobInfo, # noqa: F401 + JobOwner, # noqa: F401 + JobStage, # noqa: F401 + JobStatus, # noqa: F401 + ) + from ._login import ( + auth_list, # noqa: F401 + auth_switch, # noqa: F401 + interpreter_login, # noqa: F401 + login, # noqa: F401 + logout, # noqa: F401 + notebook_login, # noqa: F401 + ) + from ._oauth import ( + OAuthInfo, # noqa: F401 + OAuthOrgInfo, # noqa: F401 + OAuthUserInfo, # noqa: F401 + attach_huggingface_oauth, # noqa: F401 + parse_huggingface_oauth, # noqa: F401 + ) + from ._snapshot_download import snapshot_download # noqa: F401 + from ._space_api import ( + SpaceHardware, # noqa: F401 + SpaceRuntime, # noqa: F401 + SpaceSecret, # noqa: F401 + SpaceStage, # noqa: F401 + SpaceStorage, # noqa: F401 + SpaceVariable, # noqa: F401 + Volume, # noqa: F401 + ) + from ._tensorboard_logger import HFSummaryWriter # noqa: F401 + from ._webhooks_payload import ( + WebhookPayload, # noqa: F401 + WebhookPayloadComment, # noqa: F401 + WebhookPayloadDiscussion, # noqa: F401 + WebhookPayloadDiscussionChanges, # noqa: F401 + WebhookPayloadEvent, # noqa: F401 + WebhookPayloadMovedTo, # noqa: F401 + WebhookPayloadRepo, # noqa: F401 + WebhookPayloadUrl, # noqa: F401 + WebhookPayloadWebhook, # noqa: F401 + ) + from ._webhooks_server import ( + WebhooksServer, # noqa: F401 + webhook_endpoint, # noqa: F401 + ) + from .cli._cli_utils import ( + check_cli_update, # noqa: F401 + typer_factory, # noqa: F401 + ) + from .community import ( + Discussion, # noqa: F401 + DiscussionComment, # noqa: F401 + DiscussionCommit, # noqa: F401 + DiscussionEvent, # noqa: F401 + DiscussionStatusChange, # noqa: F401 + DiscussionTitleChange, # noqa: F401 + DiscussionWithDetails, # noqa: F401 + ) + from .constants import ( + CONFIG_NAME, # noqa: F401 + FLAX_WEIGHTS_NAME, # noqa: F401 + HUGGINGFACE_CO_URL_HOME, # noqa: F401 + HUGGINGFACE_CO_URL_TEMPLATE, # noqa: F401 + PYTORCH_WEIGHTS_NAME, # noqa: F401 + REPO_TYPE_DATASET, # noqa: F401 + REPO_TYPE_MODEL, # noqa: F401 + REPO_TYPE_SPACE, # noqa: F401 + TF2_WEIGHTS_NAME, # noqa: F401 + TF_WEIGHTS_NAME, # noqa: F401 + is_offline_mode, # noqa: F401 + ) + from .fastai_utils import ( + _save_pretrained_fastai, # noqa: F401 + from_pretrained_fastai, # noqa: F401 + push_to_hub_fastai, # noqa: F401 + ) + from .file_download import ( + _CACHED_NO_EXIST, # noqa: F401 + DryRunFileInfo, # noqa: F401 + HfFileMetadata, # noqa: F401 + get_hf_file_metadata, # noqa: F401 + hf_hub_download, # noqa: F401 + hf_hub_url, # noqa: F401 + try_to_load_from_cache, # noqa: F401 + ) + from .hf_api import ( + Collection, # noqa: F401 + CollectionItem, # noqa: F401 + CommitInfo, # noqa: F401 + CommitOperation, # noqa: F401 + CommitOperationAdd, # noqa: F401 + CommitOperationCopy, # noqa: F401 + CommitOperationDelete, # noqa: F401 + DatasetInfo, # noqa: F401 + DatasetLeaderboardEntry, # noqa: F401 + GitCommitInfo, # noqa: F401 + GitRefInfo, # noqa: F401 + GitRefs, # noqa: F401 + HfApi, # noqa: F401 + KernelInfo, # noqa: F401 + ModelInfo, # noqa: F401 + Organization, # noqa: F401 + RepoFile, # noqa: F401 + RepoFolder, # noqa: F401 + RepoUrl, # noqa: F401 + SpaceInfo, # noqa: F401 + SpaceSearchResult, # noqa: F401 + User, # noqa: F401 + UserLikes, # noqa: F401 + WebhookInfo, # noqa: F401 + WebhookWatchedItem, # noqa: F401 + accept_access_request, # noqa: F401 + add_collection_item, # noqa: F401 + add_space_secret, # noqa: F401 + add_space_variable, # noqa: F401 + auth_check, # noqa: F401 + batch_bucket_files, # noqa: F401 + bucket_info, # noqa: F401 + cancel_access_request, # noqa: F401 + cancel_job, # noqa: F401 + change_discussion_status, # noqa: F401 + comment_discussion, # noqa: F401 + copy_files, # noqa: F401 + create_branch, # noqa: F401 + create_bucket, # noqa: F401 + create_collection, # noqa: F401 + create_commit, # noqa: F401 + create_discussion, # noqa: F401 + create_inference_endpoint, # noqa: F401 + create_inference_endpoint_from_catalog, # noqa: F401 + create_pull_request, # noqa: F401 + create_repo, # noqa: F401 + create_scheduled_job, # noqa: F401 + create_scheduled_uv_job, # noqa: F401 + create_tag, # noqa: F401 + create_webhook, # noqa: F401 + dataset_info, # noqa: F401 + delete_branch, # noqa: F401 + delete_bucket, # noqa: F401 + delete_collection, # noqa: F401 + delete_collection_item, # noqa: F401 + delete_file, # noqa: F401 + delete_folder, # noqa: F401 + delete_inference_endpoint, # noqa: F401 + delete_repo, # noqa: F401 + delete_scheduled_job, # noqa: F401 + delete_space_secret, # noqa: F401 + delete_space_storage, # noqa: F401 + delete_space_variable, # noqa: F401 + delete_space_volumes, # noqa: F401 + delete_tag, # noqa: F401 + delete_webhook, # noqa: F401 + disable_space_dev_mode, # noqa: F401 + disable_webhook, # noqa: F401 + download_bucket_files, # noqa: F401 + duplicate_repo, # noqa: F401 + duplicate_space, # noqa: F401 + edit_discussion_comment, # noqa: F401 + enable_space_dev_mode, # noqa: F401 + enable_webhook, # noqa: F401 + fetch_job_logs, # noqa: F401 + fetch_job_metrics, # noqa: F401 + fetch_space_logs, # noqa: F401 + file_exists, # noqa: F401 + get_bucket_file_metadata, # noqa: F401 + get_bucket_paths_info, # noqa: F401 + get_collection, # noqa: F401 + get_dataset_leaderboard, # noqa: F401 + get_dataset_tags, # noqa: F401 + get_discussion_details, # noqa: F401 + get_full_repo_name, # noqa: F401 + get_inference_endpoint, # noqa: F401 + get_local_safetensors_metadata, # noqa: F401 + get_model_tags, # noqa: F401 + get_organization_overview, # noqa: F401 + get_paths_info, # noqa: F401 + get_repo_discussions, # noqa: F401 + get_safetensors_metadata, # noqa: F401 + get_space_runtime, # noqa: F401 + get_space_secrets, # noqa: F401 + get_space_variables, # noqa: F401 + get_user_overview, # noqa: F401 + get_webhook, # noqa: F401 + grant_access, # noqa: F401 + inspect_job, # noqa: F401 + inspect_scheduled_job, # noqa: F401 + kernel_info, # noqa: F401 + list_accepted_access_requests, # noqa: F401 + list_bucket_tree, # noqa: F401 + list_buckets, # noqa: F401 + list_collections, # noqa: F401 + list_daily_papers, # noqa: F401 + list_dataset_parquet_files, # noqa: F401 + list_datasets, # noqa: F401 + list_inference_catalog, # noqa: F401 + list_inference_endpoints, # noqa: F401 + list_jobs, # noqa: F401 + list_jobs_hardware, # noqa: F401 + list_lfs_files, # noqa: F401 + list_liked_repos, # noqa: F401 + list_models, # noqa: F401 + list_organization_followers, # noqa: F401 + list_organization_members, # noqa: F401 + list_papers, # noqa: F401 + list_pending_access_requests, # noqa: F401 + list_rejected_access_requests, # noqa: F401 + list_repo_commits, # noqa: F401 + list_repo_files, # noqa: F401 + list_repo_likers, # noqa: F401 + list_repo_refs, # noqa: F401 + list_repo_tree, # noqa: F401 + list_spaces, # noqa: F401 + list_spaces_hardware, # noqa: F401 + list_user_followers, # noqa: F401 + list_user_following, # noqa: F401 + list_webhooks, # noqa: F401 + merge_pull_request, # noqa: F401 + model_info, # noqa: F401 + move_bucket, # noqa: F401 + move_repo, # noqa: F401 + paper_info, # noqa: F401 + parse_local_safetensors_file_metadata, # noqa: F401 + parse_safetensors_file_metadata, # noqa: F401 + pause_inference_endpoint, # noqa: F401 + pause_space, # noqa: F401 + permanently_delete_lfs_files, # noqa: F401 + preupload_lfs_files, # noqa: F401 + read_paper, # noqa: F401 + reject_access_request, # noqa: F401 + rename_discussion, # noqa: F401 + repo_exists, # noqa: F401 + repo_info, # noqa: F401 + repo_type_and_id_from_hf_id, # noqa: F401 + request_space_hardware, # noqa: F401 + request_space_storage, # noqa: F401 + restart_space, # noqa: F401 + resume_inference_endpoint, # noqa: F401 + resume_scheduled_job, # noqa: F401 + revision_exists, # noqa: F401 + run_as_future, # noqa: F401 + run_job, # noqa: F401 + run_uv_job, # noqa: F401 + scale_to_zero_inference_endpoint, # noqa: F401 + search_spaces, # noqa: F401 + set_space_sleep_time, # noqa: F401 + set_space_volumes, # noqa: F401 + space_info, # noqa: F401 + super_squash_history, # noqa: F401 + suspend_scheduled_job, # noqa: F401 + sync_bucket, # noqa: F401 + unlike, # noqa: F401 + update_collection_item, # noqa: F401 + update_collection_metadata, # noqa: F401 + update_inference_endpoint, # noqa: F401 + update_repo_settings, # noqa: F401 + update_webhook, # noqa: F401 + upload_file, # noqa: F401 + upload_folder, # noqa: F401 + upload_large_folder, # noqa: F401 + verify_repo_checksums, # noqa: F401 + whoami, # noqa: F401 + ) + from .hf_file_system import ( + HfFileSystem, # noqa: F401 + HfFileSystemFile, # noqa: F401 + HfFileSystemResolvedPath, # noqa: F401 + HfFileSystemStreamFile, # noqa: F401 + hffs, # noqa: F401 + ) + from .hub_mixin import ( + ModelHubMixin, # noqa: F401 + PyTorchModelHubMixin, # noqa: F401 + ) + from .inference._client import ( + InferenceClient, # noqa: F401 + InferenceTimeoutError, # noqa: F401 + ) + from .inference._generated._async_client import AsyncInferenceClient # noqa: F401 + from .inference._generated.types import ( + AudioClassificationInput, # noqa: F401 + AudioClassificationOutputElement, # noqa: F401 + AudioClassificationOutputTransform, # noqa: F401 + AudioClassificationParameters, # noqa: F401 + AudioToAudioInput, # noqa: F401 + AudioToAudioOutputElement, # noqa: F401 + AutomaticSpeechRecognitionEarlyStoppingEnum, # noqa: F401 + AutomaticSpeechRecognitionGenerationParameters, # noqa: F401 + AutomaticSpeechRecognitionInput, # noqa: F401 + AutomaticSpeechRecognitionOutput, # noqa: F401 + AutomaticSpeechRecognitionOutputChunk, # noqa: F401 + AutomaticSpeechRecognitionParameters, # noqa: F401 + ChatCompletionInput, # noqa: F401 + ChatCompletionInputFunctionDefinition, # noqa: F401 + ChatCompletionInputFunctionName, # noqa: F401 + ChatCompletionInputGrammarType, # noqa: F401 + ChatCompletionInputJSONSchema, # noqa: F401 + ChatCompletionInputMessage, # noqa: F401 + ChatCompletionInputMessageChunk, # noqa: F401 + ChatCompletionInputMessageChunkType, # noqa: F401 + ChatCompletionInputResponseFormatJSONObject, # noqa: F401 + ChatCompletionInputResponseFormatJSONSchema, # noqa: F401 + ChatCompletionInputResponseFormatText, # noqa: F401 + ChatCompletionInputStreamOptions, # noqa: F401 + ChatCompletionInputTool, # noqa: F401 + ChatCompletionInputToolCall, # noqa: F401 + ChatCompletionInputToolChoiceClass, # noqa: F401 + ChatCompletionInputToolChoiceEnum, # noqa: F401 + ChatCompletionInputURL, # noqa: F401 + ChatCompletionOutput, # noqa: F401 + ChatCompletionOutputComplete, # noqa: F401 + ChatCompletionOutputFunctionDefinition, # noqa: F401 + ChatCompletionOutputLogprob, # noqa: F401 + ChatCompletionOutputLogprobs, # noqa: F401 + ChatCompletionOutputMessage, # noqa: F401 + ChatCompletionOutputToolCall, # noqa: F401 + ChatCompletionOutputTopLogprob, # noqa: F401 + ChatCompletionOutputUsage, # noqa: F401 + ChatCompletionStreamOutput, # noqa: F401 + ChatCompletionStreamOutputChoice, # noqa: F401 + ChatCompletionStreamOutputDelta, # noqa: F401 + ChatCompletionStreamOutputDeltaToolCall, # noqa: F401 + ChatCompletionStreamOutputFunction, # noqa: F401 + ChatCompletionStreamOutputLogprob, # noqa: F401 + ChatCompletionStreamOutputLogprobs, # noqa: F401 + ChatCompletionStreamOutputTopLogprob, # noqa: F401 + ChatCompletionStreamOutputUsage, # noqa: F401 + DepthEstimationInput, # noqa: F401 + DepthEstimationOutput, # noqa: F401 + DocumentQuestionAnsweringInput, # noqa: F401 + DocumentQuestionAnsweringInputData, # noqa: F401 + DocumentQuestionAnsweringOutputElement, # noqa: F401 + DocumentQuestionAnsweringParameters, # noqa: F401 + FeatureExtractionInput, # noqa: F401 + FeatureExtractionInputTruncationDirection, # noqa: F401 + FillMaskInput, # noqa: F401 + FillMaskOutputElement, # noqa: F401 + FillMaskParameters, # noqa: F401 + ImageClassificationInput, # noqa: F401 + ImageClassificationOutputElement, # noqa: F401 + ImageClassificationOutputTransform, # noqa: F401 + ImageClassificationParameters, # noqa: F401 + ImageSegmentationInput, # noqa: F401 + ImageSegmentationOutputElement, # noqa: F401 + ImageSegmentationParameters, # noqa: F401 + ImageSegmentationSubtask, # noqa: F401 + ImageTextToImageInput, # noqa: F401 + ImageTextToImageOutput, # noqa: F401 + ImageTextToImageParameters, # noqa: F401 + ImageTextToImageTargetSize, # noqa: F401 + ImageTextToVideoInput, # noqa: F401 + ImageTextToVideoOutput, # noqa: F401 + ImageTextToVideoParameters, # noqa: F401 + ImageTextToVideoTargetSize, # noqa: F401 + ImageToImageInput, # noqa: F401 + ImageToImageOutput, # noqa: F401 + ImageToImageParameters, # noqa: F401 + ImageToImageTargetSize, # noqa: F401 + ImageToTextEarlyStoppingEnum, # noqa: F401 + ImageToTextGenerationParameters, # noqa: F401 + ImageToTextInput, # noqa: F401 + ImageToTextOutput, # noqa: F401 + ImageToTextParameters, # noqa: F401 + ImageToVideoInput, # noqa: F401 + ImageToVideoOutput, # noqa: F401 + ImageToVideoParameters, # noqa: F401 + ImageToVideoTargetSize, # noqa: F401 + ObjectDetectionBoundingBox, # noqa: F401 + ObjectDetectionInput, # noqa: F401 + ObjectDetectionOutputElement, # noqa: F401 + ObjectDetectionParameters, # noqa: F401 + Padding, # noqa: F401 + QuestionAnsweringInput, # noqa: F401 + QuestionAnsweringInputData, # noqa: F401 + QuestionAnsweringOutputElement, # noqa: F401 + QuestionAnsweringParameters, # noqa: F401 + SentenceSimilarityInput, # noqa: F401 + SentenceSimilarityInputData, # noqa: F401 + SummarizationInput, # noqa: F401 + SummarizationOutput, # noqa: F401 + SummarizationParameters, # noqa: F401 + SummarizationTruncationStrategy, # noqa: F401 + TableQuestionAnsweringInput, # noqa: F401 + TableQuestionAnsweringInputData, # noqa: F401 + TableQuestionAnsweringOutputElement, # noqa: F401 + TableQuestionAnsweringParameters, # noqa: F401 + Text2TextGenerationInput, # noqa: F401 + Text2TextGenerationOutput, # noqa: F401 + Text2TextGenerationParameters, # noqa: F401 + Text2TextGenerationTruncationStrategy, # noqa: F401 + TextClassificationInput, # noqa: F401 + TextClassificationOutputElement, # noqa: F401 + TextClassificationOutputTransform, # noqa: F401 + TextClassificationParameters, # noqa: F401 + TextGenerationInput, # noqa: F401 + TextGenerationInputGenerateParameters, # noqa: F401 + TextGenerationInputGrammarType, # noqa: F401 + TextGenerationOutput, # noqa: F401 + TextGenerationOutputBestOfSequence, # noqa: F401 + TextGenerationOutputDetails, # noqa: F401 + TextGenerationOutputFinishReason, # noqa: F401 + TextGenerationOutputPrefillToken, # noqa: F401 + TextGenerationOutputToken, # noqa: F401 + TextGenerationStreamOutput, # noqa: F401 + TextGenerationStreamOutputStreamDetails, # noqa: F401 + TextGenerationStreamOutputToken, # noqa: F401 + TextToAudioEarlyStoppingEnum, # noqa: F401 + TextToAudioGenerationParameters, # noqa: F401 + TextToAudioInput, # noqa: F401 + TextToAudioOutput, # noqa: F401 + TextToAudioParameters, # noqa: F401 + TextToImageInput, # noqa: F401 + TextToImageOutput, # noqa: F401 + TextToImageParameters, # noqa: F401 + TextToSpeechEarlyStoppingEnum, # noqa: F401 + TextToSpeechGenerationParameters, # noqa: F401 + TextToSpeechInput, # noqa: F401 + TextToSpeechOutput, # noqa: F401 + TextToSpeechParameters, # noqa: F401 + TextToVideoInput, # noqa: F401 + TextToVideoOutput, # noqa: F401 + TextToVideoParameters, # noqa: F401 + TokenClassificationAggregationStrategy, # noqa: F401 + TokenClassificationInput, # noqa: F401 + TokenClassificationOutputElement, # noqa: F401 + TokenClassificationParameters, # noqa: F401 + TranslationInput, # noqa: F401 + TranslationOutput, # noqa: F401 + TranslationParameters, # noqa: F401 + TranslationTruncationStrategy, # noqa: F401 + TypeEnum, # noqa: F401 + VideoClassificationInput, # noqa: F401 + VideoClassificationOutputElement, # noqa: F401 + VideoClassificationOutputTransform, # noqa: F401 + VideoClassificationParameters, # noqa: F401 + VisualQuestionAnsweringInput, # noqa: F401 + VisualQuestionAnsweringInputData, # noqa: F401 + VisualQuestionAnsweringOutputElement, # noqa: F401 + VisualQuestionAnsweringParameters, # noqa: F401 + ZeroShotClassificationInput, # noqa: F401 + ZeroShotClassificationOutputElement, # noqa: F401 + ZeroShotClassificationParameters, # noqa: F401 + ZeroShotImageClassificationInput, # noqa: F401 + ZeroShotImageClassificationOutputElement, # noqa: F401 + ZeroShotImageClassificationParameters, # noqa: F401 + ZeroShotObjectDetectionBoundingBox, # noqa: F401 + ZeroShotObjectDetectionInput, # noqa: F401 + ZeroShotObjectDetectionOutputElement, # noqa: F401 + ZeroShotObjectDetectionParameters, # noqa: F401 + ) + from .inference._mcp.agent import Agent # noqa: F401 + from .inference._mcp.mcp_client import MCPClient # noqa: F401 + from .repocard import ( + DatasetCard, # noqa: F401 + ModelCard, # noqa: F401 + RepoCard, # noqa: F401 + SpaceCard, # noqa: F401 + metadata_eval_result, # noqa: F401 + metadata_load, # noqa: F401 + metadata_save, # noqa: F401 + metadata_update, # noqa: F401 + ) + from .repocard_data import ( + CardData, # noqa: F401 + DatasetCardData, # noqa: F401 + EvalResult, # noqa: F401 + ModelCardData, # noqa: F401 + SpaceCardData, # noqa: F401 + ) + from .serialization import ( + StateDictSplit, # noqa: F401 + get_torch_storage_id, # noqa: F401 + get_torch_storage_size, # noqa: F401 + load_state_dict_from_file, # noqa: F401 + load_torch_model, # noqa: F401 + save_torch_model, # noqa: F401 + save_torch_state_dict, # noqa: F401 + split_state_dict_into_shards_factory, # noqa: F401 + split_torch_state_dict_into_shards, # noqa: F401 + ) + from .serialization._dduf import ( + DDUFEntry, # noqa: F401 + export_entries_as_dduf, # noqa: F401 + export_folder_as_dduf, # noqa: F401 + read_dduf_file, # noqa: F401 + ) + from .utils import ( + ASYNC_CLIENT_FACTORY_T, # noqa: F401 + CLIENT_FACTORY_T, # noqa: F401 + CachedFileInfo, # noqa: F401 + CachedRepoInfo, # noqa: F401 + CachedRevisionInfo, # noqa: F401 + CacheNotFound, # noqa: F401 + CorruptedCacheException, # noqa: F401 + DeleteCacheStrategy, # noqa: F401 + HFCacheInfo, # noqa: F401 + HfUri, # noqa: F401 + cached_assets_path, # noqa: F401 + close_session, # noqa: F401 + dump_environment_info, # noqa: F401 + get_async_session, # noqa: F401 + get_session, # noqa: F401 + get_token, # noqa: F401 + hf_raise_for_status, # noqa: F401 + logging, # noqa: F401 + parse_hf_uri, # noqa: F401 + scan_cache_dir, # noqa: F401 + set_async_client_factory, # noqa: F401 + set_client_factory, # noqa: F401 + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_buckets.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_buckets.py new file mode 100644 index 0000000000000000000000000000000000000000..179b885032ddd32113b360a7c9d99a3ff7670866 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_buckets.py @@ -0,0 +1,1225 @@ +# Copyright 2026-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Shared logic for bucket operations. + +This module contains the core buckets logic used by both the CLI and the Python API. +""" + +import fnmatch +import json +import mimetypes +import os +import stat +import sys +import time +from collections.abc import Iterator +from dataclasses import dataclass, field +from datetime import datetime, timezone +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal + +from . import constants, logging +from .errors import BucketNotFoundError +from .utils import XetFileData, disable_progress_bars, enable_progress_bars, parse_datetime +from .utils._terminal import StatusLine + + +if TYPE_CHECKING: + from .hf_api import HfApi + + +logger = logging.get_logger(__name__) + + +BUCKET_PREFIX = "hf://buckets/" +_SYNC_TIME_WINDOW_MS = 1000 # 1s safety-window for file modification time comparisons + + +# ============================================================================= +# Bucket data structures +# ============================================================================= + + +def _split_bucket_id_and_prefix(path: str) -> tuple[str, str]: + """Split 'namespace/name(/optional/prefix)' into ('namespace/name', 'prefix'). + + Returns (bucket_id, prefix) where prefix may be empty string. + Raises ValueError if path doesn't contain at least namespace/name. + """ + parts = path.split("/", 2) + if len(parts) < 2 or not parts[0] or not parts[1]: + raise ValueError(f"Invalid bucket path: '{path}'. Expected format: namespace/bucket_name") + bucket_id = f"{parts[0]}/{parts[1]}" + prefix = parts[2] if len(parts) > 2 else "" + return bucket_id, prefix + + +@dataclass +class BucketInfo: + """ + Contains information about a bucket on the Hub. This object is returned by [`bucket_info`] and [`list_buckets`]. + + Attributes: + id (`str`): + ID of the bucket. + private (`bool`): + Is the bucket private. + created_at (`datetime`): + Date of creation of the bucket on the Hub. + size (`int`): + Size of the bucket in bytes. + total_files (`int`): + Total number of files in the bucket. + """ + + id: str + private: bool + created_at: datetime + size: int + total_files: int + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.private = kwargs.pop("private") + self.created_at = parse_datetime(kwargs.pop("createdAt")) + self.size = kwargs.pop("size") + self.total_files = kwargs.pop("totalFiles") + self.__dict__.update(**kwargs) + + +@dataclass +class _BucketAddFile: + source: str | Path | bytes + destination: str + + xet_hash: str | None = field(default=None) + size: int | None = field(default=None) + mtime: int = field(init=False) + content_type: str | None = field(init=False) + + def __post_init__(self) -> None: + self.content_type = None + if isinstance(self.source, (str, Path)): # guess content type from source path + self.content_type = mimetypes.guess_type(self.source)[0] + if self.content_type is None: # or default to destination path content type + self.content_type = mimetypes.guess_type(self.destination)[0] + + self.mtime = int( + os.path.getmtime(self.source) * 1000 if not isinstance(self.source, bytes) else time.time() * 1000 + ) + + +@dataclass +class _BucketCopyFile: + destination: str + xet_hash: str + source_repo_type: str # "model", "dataset", "space", "bucket" + source_repo_id: str + size: int | None = field(default=None) + mtime: int = field(init=False) + content_type: str | None = field(init=False) + + def __post_init__(self) -> None: + self.content_type = mimetypes.guess_type(self.destination)[0] + self.mtime = int(time.time() * 1000) + + +@dataclass +class _BucketDeleteFile: + path: str + + +@dataclass(frozen=True) +class BucketFileMetadata: + """Data structure containing information about a file in a bucket. + + Returned by [`get_bucket_file_metadata`]. + + Args: + size (`int`): + Size of the file in bytes. + xet_file_data (`XetFileData`): + Xet information for the file (hash and refresh route). + """ + + size: int + xet_file_data: XetFileData + + +@dataclass +class BucketUrl: + """Describes a bucket URL on the Hub. + + `BucketUrl` is returned by [`create_bucket`]. At initialization, the URL is parsed to populate properties: + - endpoint (`str`) + - namespace (`str`) + - bucket_id (`str`) + - url (`str`) + - handle (`str`) + + Args: + url (`str`): + String value of the bucket url. + endpoint (`str`, *optional*): + Endpoint of the Hub. Defaults to . + """ + + url: str + endpoint: str = "" + namespace: str = field(init=False) + bucket_id: str = field(init=False) + handle: str = field(init=False) + + def __post_init__(self) -> None: + self.endpoint = self.endpoint or constants.ENDPOINT + + # Parse URL: expected format is `{endpoint}/buckets/{namespace}/{bucket_name}` + url_path = self.url.replace(self.endpoint, "").strip("/") + # Remove leading "buckets/" prefix + if url_path.startswith("buckets/"): + url_path = url_path[len("buckets/") :] + bucket_id, prefix = _split_bucket_id_and_prefix(url_path) + if prefix: + raise ValueError(f"Unable to parse bucket URL: {self.url}") + self.namespace = bucket_id.split("/")[0] + self.bucket_id = bucket_id + + self.handle = f"hf://buckets/{self.bucket_id}" + + +@dataclass +class BucketFile: + """ + Contains information about a file in a bucket on the Hub. This object is returned by [`list_bucket_tree`]. + + Similar to [`RepoFile`] but for files in buckets. + """ + + type: Literal["file"] + path: str + size: int + xet_hash: str + mtime: datetime | None + uploaded_at: datetime | None + + def __init__(self, **kwargs): + self.type = kwargs.pop("type") + self.path = kwargs.pop("path") + self.size = kwargs.pop("size") + self.xet_hash = kwargs.pop("xetHash") + mtime = kwargs.pop("mtime", None) + self.mtime = parse_datetime(mtime) if mtime else None + uploaded_at = kwargs.pop("uploadedAt", None) + self.uploaded_at = parse_datetime(uploaded_at) if uploaded_at else None + + +@dataclass +class BucketFolder: + """ + Contains information about a directory in a bucket on the Hub. This object is returned by [`list_bucket_tree`]. + + Similar to [`RepoFolder`] but for directories in buckets. + """ + + type: Literal["directory"] + path: str + uploaded_at: datetime | None + + def __init__(self, **kwargs): + self.type = kwargs.pop("type") + self.path = kwargs.pop("path") + uploaded_at = kwargs.pop("uploadedAt", None) or kwargs.pop("uploaded_at", None) + self.uploaded_at = ( + (uploaded_at if isinstance(uploaded_at, datetime) else parse_datetime(uploaded_at)) + if uploaded_at + else None + ) + + +# ============================================================================= +# Bucket path parsing +# ============================================================================= + + +def _parse_bucket_path(path: str) -> tuple[str, str]: + """Parse a bucket path like hf://buckets/namespace/bucket_name/prefix into (bucket_id, prefix). + + Returns: + tuple: (bucket_id, prefix) where bucket_id is "namespace/bucket_name" and prefix may be empty string. + """ + if not path.startswith(BUCKET_PREFIX): + raise ValueError(f"Invalid bucket path: {path}. Must start with {BUCKET_PREFIX}") + return _split_bucket_id_and_prefix(path.removeprefix(BUCKET_PREFIX)) + + +def _is_bucket_path(path: str) -> bool: + """Check if a path is a bucket path.""" + return path.startswith(BUCKET_PREFIX) + + +# ============================================================================= +# Sync data structures +# ============================================================================= + + +@dataclass +class SyncOperation: + """Represents a sync operation to be performed.""" + + action: Literal["upload", "download", "delete", "skip"] + path: str + size: int | None = None + reason: str = "" + local_mtime: str | None = None + remote_mtime: str | None = None + bucket_file: BucketFile | None = None # BucketFile when available (not serialized to plan file) + + +@dataclass +class SyncPlan: + """Represents a complete sync plan.""" + + source: str + dest: str + timestamp: str + operations: list[SyncOperation] = field(default_factory=list) + + def summary(self) -> dict[str, int | str]: + uploads = sum(1 for op in self.operations if op.action == "upload") + downloads = sum(1 for op in self.operations if op.action == "download") + deletes = sum(1 for op in self.operations if op.action == "delete") + skips = sum(1 for op in self.operations if op.action == "skip") + total_size = sum(op.size or 0 for op in self.operations if op.action in ("upload", "download")) + return { + "uploads": uploads, + "downloads": downloads, + "deletes": deletes, + "skips": skips, + "total_size": total_size, + } + + +# ============================================================================= +# Filter matching +# ============================================================================= + + +class FilterMatcher: + """Matches file paths against include/exclude patterns.""" + + def __init__( + self, + include_patterns: list[str] | None = None, + exclude_patterns: list[str] | None = None, + filter_rules: list[tuple[str, str]] | None = None, + ): + """Initialize the filter matcher. + + Args: + include_patterns: Patterns to include (from --include) + exclude_patterns: Patterns to exclude (from --exclude) + filter_rules: Rules from filter file as list of ("+"/"-", pattern) tuples + """ + self.include_patterns = include_patterns or [] + self.exclude_patterns = exclude_patterns or [] + self.filter_rules = filter_rules or [] + + def matches(self, path: str) -> bool: + """Check if a path should be included based on the filter rules. + + Filtering rules: + - Filters are evaluated in order, first matching rule decides + - If no rules match, include by default (unless include patterns are specified) + """ + # First check filter rules from file (in order) + for sign, pattern in self.filter_rules: + if fnmatch.fnmatch(path, pattern): + return sign == "+" + + # Then check CLI patterns + for pattern in self.exclude_patterns: + if fnmatch.fnmatch(path, pattern): + return False + + for pattern in self.include_patterns: + if fnmatch.fnmatch(path, pattern): + return True + + # If include patterns were specified but none matched, exclude + if self.include_patterns: + return False + + # Default: include + return True + + +def _parse_filter_file(filter_file: str) -> list[tuple[str, str]]: + """Parse a filter file and return a list of (sign, pattern) tuples. + + Filter file format: + - Lines starting with "+" are include patterns + - Lines starting with "-" are exclude patterns + - Empty lines and lines starting with "#" are ignored + """ + rules = [] + with open(filter_file) as f: + for line in f: + line = line.strip() + if not line or line.startswith("#"): + continue + if line.startswith("+"): + rules.append(("+", line[1:].strip())) + elif line.startswith("-"): + rules.append(("-", line[1:].strip())) + else: + # Default to include if no prefix + rules.append(("+", line)) + return rules + + +# ============================================================================= +# File listing +# ============================================================================= + + +def _stat_local(path: str) -> tuple[int, float] | None: + """Stat a local file and return (size, mtime_ms). + + Returns None if the path is missing or is a directory. Uses a single + ``os.stat`` call so callers don't pay for multiple syscalls per file. + """ + try: + st = os.stat(path) + except OSError: + return None + if stat.S_ISDIR(st.st_mode): + return None + return st.st_size, st.st_mtime * 1000 + + +def _list_local_files(local_path: str) -> Iterator[tuple[str, int, float]]: + """List all files in a local directory. + + Yields: + tuple: (relative_path, size, mtime_ms) for each file + """ + local_path = os.path.abspath(local_path) + if not os.path.isdir(local_path): + raise ValueError(f"Local path must be a directory: {local_path}") + + for root, _, files in os.walk(local_path): + for filename in files: + full_path = os.path.join(root, filename) + stat_info = _stat_local(full_path) + if stat_info is None: + continue + rel_path = os.path.relpath(full_path, local_path) + # Normalize to forward slashes for consistency + rel_path = rel_path.replace(os.sep, "/") + yield rel_path, stat_info[0], stat_info[1] + + +def _list_remote_files(api: "HfApi", bucket_id: str, prefix: str) -> Iterator[tuple[str, int, float, Any]]: + """List all files in a bucket with a given prefix. + + Yields: + tuple: (relative_path, size, mtime_ms, bucket_file) for each file. + bucket_file is the BucketFile object from list_bucket_tree. + """ + for item in api.list_bucket_tree(bucket_id, prefix=prefix or None, recursive=True): + if isinstance(item, BucketFolder): + continue + path = item.path + # Remove prefix from path to get relative path + # Only strip prefix if it's followed by "/" (directory boundary) or is exact match + if prefix: + if path.startswith(prefix + "/"): + rel_path = path[len(prefix) + 1 :] + elif path == prefix: + # Exact match: the file IS the prefix (e.g., single file download) + rel_path = path.rsplit("/", 1)[-1] if "/" in path else path + else: + # Path doesn't match prefix pattern (e.g., "submarine.txt" for prefix "sub") + # Skip this file - it was returned by the API but doesn't belong to this prefix + continue + else: + rel_path = path + mtime_ms = item.mtime.timestamp() * 1000 if item.mtime else 0 + yield rel_path, item.size, mtime_ms, item + + +# ============================================================================= +# Sync plan computation +# ============================================================================= + + +def _mtime_to_iso(mtime_ms: float) -> str: + """Convert mtime in milliseconds to ISO format string.""" + return datetime.fromtimestamp(mtime_ms / 1000, tz=timezone.utc).isoformat() + + +def _compare_files_for_sync( + *, + path: str, + action: Literal["upload", "download"], + source_size: int, + source_mtime: float, + dest_size: int, + dest_mtime: float, + source_newer_label: str, + dest_newer_label: str, + ignore_sizes: bool, + ignore_times: bool, + ignore_existing: bool, + bucket_file: Any | None = None, +) -> SyncOperation: + """Compare source and dest files and return the appropriate sync operation. + + This is a unified helper for both upload and download directions. + + Args: + path: Relative file path + action: "upload" or "download" + source_size: Size of the source file (bytes) + source_mtime: Mtime of the source file (milliseconds) + dest_size: Size of the destination file (bytes) + dest_mtime: Mtime of the destination file (milliseconds) + source_newer_label: Label when source is newer (e.g., "local newer" or "remote newer") + dest_newer_label: Label when dest is newer (e.g., "remote newer" or "local newer") + ignore_sizes: Only compare mtime + ignore_times: Only compare size + ignore_existing: Skip files that exist on receiver + bucket_file: BucketFile object (for downloads only) + + Returns: + SyncOperation describing the action to take + """ + local_mtime_iso = _mtime_to_iso(source_mtime if action == "upload" else dest_mtime) + remote_mtime_iso = _mtime_to_iso(dest_mtime if action == "upload" else source_mtime) + + base_kwargs: dict[str, Any] = { + "path": path, + "size": source_size, + "local_mtime": local_mtime_iso, + "remote_mtime": remote_mtime_iso, + } + + if ignore_existing: + return SyncOperation(action="skip", reason="exists on receiver (--ignore-existing)", **base_kwargs) + + size_differs = source_size != dest_size + source_newer = (source_mtime - dest_mtime) > _SYNC_TIME_WINDOW_MS + + if ignore_sizes: + if source_newer: + return SyncOperation(action=action, reason=source_newer_label, bucket_file=bucket_file, **base_kwargs) + else: + dest_newer = (dest_mtime - source_mtime) > _SYNC_TIME_WINDOW_MS + skip_reason = dest_newer_label if dest_newer else "same mtime" + return SyncOperation(action="skip", reason=skip_reason, **base_kwargs) + elif ignore_times: + if size_differs: + return SyncOperation(action=action, reason="size differs", bucket_file=bucket_file, **base_kwargs) + else: + return SyncOperation(action="skip", reason="same size", **base_kwargs) + else: + if size_differs or source_newer: + reason = "size differs" if size_differs else source_newer_label + return SyncOperation(action=action, reason=reason, bucket_file=bucket_file, **base_kwargs) + else: + return SyncOperation(action="skip", reason="identical", **base_kwargs) + + +def _compute_sync_plan( + source: str, + dest: str, + api: "HfApi", + delete: bool = False, + ignore_times: bool = False, + ignore_sizes: bool = False, + existing: bool = False, + ignore_existing: bool = False, + filter_matcher: FilterMatcher | None = None, + status: Any | None = None, +) -> SyncPlan: + """Compute the sync plan by comparing source and destination. + + Returns: + SyncPlan with all operations to be performed + """ + filter_matcher = filter_matcher or FilterMatcher() + is_upload = not _is_bucket_path(source) and _is_bucket_path(dest) + is_download = _is_bucket_path(source) and not _is_bucket_path(dest) + + if not is_upload and not is_download: + raise ValueError("One of source or dest must be a bucket path (hf://buckets/...) and the other must be local.") + + plan = SyncPlan( + source=source, + dest=dest, + timestamp=datetime.now(timezone.utc).isoformat(), + ) + + remote_total: int | None = None + if is_upload: + # Local -> Remote + local_path = os.path.abspath(source) + bucket_id, prefix = _parse_bucket_path(dest) + + if not os.path.isdir(local_path): + raise ValueError(f"Source must be a directory: {local_path}") + + # Get local and remote file lists + local_files = {} + for rel_path, size, mtime_ms in _list_local_files(local_path): + if filter_matcher.matches(rel_path): + local_files[rel_path] = (size, mtime_ms) + if status: + status.update(f"Scanning local directory ({len(local_files)} files)") + if status: + status.done(f"Scanning local directory ({len(local_files)} files)") + + remote_files = {} + if status: + try: + remote_total = api.bucket_info(bucket_id).total_files + except Exception: + pass + try: + for rel_path, size, mtime_ms, _ in _list_remote_files(api, bucket_id, prefix): + if filter_matcher.matches(rel_path): + remote_files[rel_path] = (size, mtime_ms) + if status: + total_str = f"/{remote_total}" if remote_total is not None else "" + status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)") + except BucketNotFoundError: + # Bucket doesn't exist yet - this is expected for new uploads + logger.debug(f"Bucket '{bucket_id}' not found, treating as empty.") + if status: + status.done(f"Scanning remote bucket ({len(remote_files)} files)") + + # Compare files + all_paths = set(local_files.keys()) | set(remote_files.keys()) + if status: + status.done(f"Comparing files ({len(all_paths)} paths)") + for path in sorted(all_paths): + local_info = local_files.get(path) + remote_info = remote_files.get(path) + + if local_info and not remote_info: + # New file + if existing: + # --existing: skip new files + plan.operations.append( + SyncOperation( + action="skip", + path=path, + size=local_info[0], + reason="new file (--existing)", + local_mtime=_mtime_to_iso(local_info[1]), + ) + ) + else: + plan.operations.append( + SyncOperation( + action="upload", + path=path, + size=local_info[0], + reason="new file", + local_mtime=_mtime_to_iso(local_info[1]), + ) + ) + elif local_info and remote_info: + # File exists in both - use helper to determine action + local_size, local_mtime = local_info + remote_size, remote_mtime = remote_info + plan.operations.append( + _compare_files_for_sync( + path=path, + action="upload", + source_size=local_size, + source_mtime=local_mtime, + dest_size=remote_size, + dest_mtime=remote_mtime, + source_newer_label="local newer", + dest_newer_label="remote newer", + ignore_sizes=ignore_sizes, + ignore_times=ignore_times, + ignore_existing=ignore_existing, + ) + ) + elif not local_info and remote_info and delete: + # File only in remote and --delete mode + plan.operations.append( + SyncOperation( + action="delete", + path=path, + size=remote_info[0], + reason="not in source (--delete)", + remote_mtime=_mtime_to_iso(remote_info[1]), + ) + ) + + else: + # Remote -> Local (download) + bucket_id, prefix = _parse_bucket_path(source) + local_path = os.path.abspath(dest) + + # Get remote and local file lists + remote_files = {} + bucket_file_map: dict[str, Any] = {} + if status: + try: + remote_total = api.bucket_info(bucket_id).total_files + except Exception: + pass + for rel_path, size, mtime_ms, bucket_file in _list_remote_files(api, bucket_id, prefix): + if filter_matcher.matches(rel_path): + remote_files[rel_path] = (size, mtime_ms) + bucket_file_map[rel_path] = bucket_file + if status: + total_str = f"/{remote_total}" if remote_total is not None else "" + status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)") + if status: + status.done(f"Scanning remote bucket ({len(remote_files)} files)") + + local_files = {} + if os.path.isdir(local_path): + if delete: + # Full walk needed to discover local-only files for deletion. + for rel_path, size, mtime_ms in _list_local_files(local_path): + if filter_matcher.matches(rel_path): + local_files[rel_path] = (size, mtime_ms) + if status: + status.update(f"Scanning local directory ({len(local_files)} files)") + else: + # Without --delete, the plan only depends on paths that exist + # remotely. Stat just those instead of walking the whole tree, + # which can take minutes when dest sits in a large directory + # like ~/.cache/huggingface/. + for rel_path in remote_files: + local_file = os.path.join(local_path, rel_path) + stat_info = _stat_local(local_file) + if stat_info is None: + continue + local_files[rel_path] = stat_info + if status: + status.update(f"Scanning local directory ({len(local_files)} files)") + if status: + status.done(f"Scanning local directory ({len(local_files)} files)") + + # Compare files + all_paths = set(remote_files.keys()) | set(local_files.keys()) + if status: + status.done(f"Comparing files ({len(all_paths)} paths)") + for path in sorted(all_paths): + remote_info = remote_files.get(path) + local_info = local_files.get(path) + + if remote_info and not local_info: + # New file + if existing: + # --existing: skip new files + plan.operations.append( + SyncOperation( + action="skip", + path=path, + size=remote_info[0], + reason="new file (--existing)", + remote_mtime=_mtime_to_iso(remote_info[1]), + ) + ) + else: + plan.operations.append( + SyncOperation( + action="download", + path=path, + size=remote_info[0], + reason="new file", + remote_mtime=_mtime_to_iso(remote_info[1]), + bucket_file=bucket_file_map.get(path), + ) + ) + elif remote_info and local_info: + # File exists in both - use helper to determine action + remote_size, remote_mtime = remote_info + local_size, local_mtime = local_info + plan.operations.append( + _compare_files_for_sync( + path=path, + action="download", + source_size=remote_size, + source_mtime=remote_mtime, + dest_size=local_size, + dest_mtime=local_mtime, + source_newer_label="remote newer", + dest_newer_label="local newer", + ignore_sizes=ignore_sizes, + ignore_times=ignore_times, + ignore_existing=ignore_existing, + bucket_file=bucket_file_map.get(path), + ) + ) + elif not remote_info and local_info and delete: + # File only in local and --delete mode + plan.operations.append( + SyncOperation( + action="delete", + path=path, + size=local_info[0], + reason="not in source (--delete)", + local_mtime=_mtime_to_iso(local_info[1]), + ) + ) + + return plan + + +# ============================================================================= +# Plan serialization +# ============================================================================= + + +def _write_plan(plan: SyncPlan, f) -> None: + """Write a sync plan as JSONL to a file-like object.""" + # Write header + header = { + "type": "header", + "source": plan.source, + "dest": plan.dest, + "timestamp": plan.timestamp, + "summary": plan.summary(), + } + f.write(json.dumps(header) + "\n") + + # Write operations + for op in plan.operations: + op_dict: dict[str, Any] = { + "type": "operation", + "action": op.action, + "path": op.path, + "reason": op.reason, + } + if op.size is not None: + op_dict["size"] = op.size + if op.local_mtime is not None: + op_dict["local_mtime"] = op.local_mtime + if op.remote_mtime is not None: + op_dict["remote_mtime"] = op.remote_mtime + f.write(json.dumps(op_dict) + "\n") + + +def _save_plan(plan: SyncPlan, plan_file: str) -> None: + """Save a sync plan to a JSONL file.""" + with open(plan_file, "w") as f: + _write_plan(plan, f) + + +def _load_plan(plan_file: str) -> SyncPlan: + """Load a sync plan from a JSONL file.""" + with open(plan_file) as f: + lines = f.readlines() + + if not lines: + raise ValueError(f"Empty plan file: {plan_file}") + + # Parse header + header = json.loads(lines[0]) + if header.get("type") != "header": + raise ValueError("Invalid plan file: expected header as first line") + + plan = SyncPlan( + source=header["source"], + dest=header["dest"], + timestamp=header["timestamp"], + ) + + # Parse operations + for line in lines[1:]: + op_dict = json.loads(line) + if op_dict.get("type") != "operation": + continue + plan.operations.append( + SyncOperation( + action=op_dict["action"], + path=op_dict["path"], + size=op_dict.get("size"), + reason=op_dict.get("reason", ""), + local_mtime=op_dict.get("local_mtime"), + remote_mtime=op_dict.get("remote_mtime"), + ) + ) + + return plan + + +# ============================================================================= +# Plan execution +# ============================================================================= + + +def _execute_plan(plan: SyncPlan, api: "HfApi", verbose: bool = False, status: Any | None = None) -> None: + """Execute a sync plan.""" + is_upload = not _is_bucket_path(plan.source) and _is_bucket_path(plan.dest) + is_download = _is_bucket_path(plan.source) and not _is_bucket_path(plan.dest) + + if is_upload: + local_path = os.path.abspath(plan.source) + bucket_id, prefix = _parse_bucket_path(plan.dest) + prefix = prefix.rstrip("/") # Avoid double slashes in remote paths + + # Collect operations + add_files: list[tuple[str | Path | bytes, str]] = [] + delete_paths: list[str] = [] + + for op in plan.operations: + match op.action: + case "upload": + local_file = os.path.join(local_path, op.path) + remote_path = f"{prefix}/{op.path}" if prefix else op.path + if verbose: + print(f" Uploading: {op.path} ({op.reason})") + add_files.append((local_file, remote_path)) + case "delete": + remote_path = f"{prefix}/{op.path}" if prefix else op.path + if verbose: + print(f" Deleting: {op.path} ({op.reason})") + delete_paths.append(remote_path) + case "skip" if verbose: + print(f" Skipping: {op.path} ({op.reason})") + + # Execute batch operations + if add_files or delete_paths: + if status: + parts = [] + if add_files: + parts.append(f"uploading {len(add_files)} files") + if delete_paths: + parts.append(f"deleting {len(delete_paths)} files") + status.done(", ".join(parts).capitalize()) + api.batch_bucket_files( + bucket_id, + add=add_files or None, + delete=delete_paths or None, + ) + + elif is_download: + bucket_id, prefix = _parse_bucket_path(plan.source) + prefix = prefix.rstrip("/") # Avoid double slashes in remote paths + local_path = os.path.abspath(plan.dest) + + # Ensure local directory exists + os.makedirs(local_path, exist_ok=True) + + # Collect download operations + download_files: list[tuple[str | BucketFile, str | Path]] = [] + delete_files: list[str] = [] + + for op in plan.operations: + if op.action == "download": + local_file = os.path.join(local_path, op.path) + # Ensure parent directory exists + os.makedirs(os.path.dirname(local_file), exist_ok=True) + if verbose: + print(f" Downloading: {op.path} ({op.reason})") + # Use BucketFile when available (avoids extra metadata fetch per file) + if op.bucket_file is not None: + download_files.append((op.bucket_file, local_file)) + else: + remote_path = f"{prefix}/{op.path}" if prefix else op.path + download_files.append((remote_path, local_file)) + elif op.action == "delete": + local_file = os.path.join(local_path, op.path) + if verbose: + print(f" Deleting: {op.path} ({op.reason})") + delete_files.append(local_file) + elif op.action == "skip" and verbose: + print(f" Skipping: {op.path} ({op.reason})") + + # Execute downloads + if len(download_files) > 0: + if status: + status.done(f"Downloading {len(download_files)} files") + api.download_bucket_files(bucket_id, download_files) + + # Execute deletes + if status and delete_files: + status.done(f"Deleting {len(delete_files)} local files") + for file_path in delete_files: + if os.path.exists(file_path): + os.remove(file_path) + # Remove empty parent directories + parent = os.path.dirname(file_path) + while parent != local_path: + try: + os.rmdir(parent) + parent = os.path.dirname(parent) + except OSError: + break + + +def _print_plan_summary(plan: SyncPlan) -> None: + """Print a summary of the sync plan.""" + summary = plan.summary() + print(f"Sync plan: {plan.source} -> {plan.dest}") + print(f" Uploads: {summary['uploads']}") + print(f" Downloads: {summary['downloads']}") + print(f" Deletes: {summary['deletes']}") + print(f" Skips: {summary['skips']}") + + +# ============================================================================= +# Public sync function (Python API) +# ============================================================================= + + +def sync_bucket_internal( + source: str | None = None, + dest: str | None = None, + *, + api: "HfApi", + delete: bool = False, + ignore_times: bool = False, + ignore_sizes: bool = False, + existing: bool = False, + ignore_existing: bool = False, + include: list[str] | None = None, + exclude: list[str] | None = None, + filter_from: str | None = None, + plan: str | None = None, + apply: str | None = None, + dry_run: bool = False, + verbose: bool = False, + quiet: bool = False, + token: bool | str | None = None, +) -> SyncPlan: + """Sync files between a local directory and a bucket. + + This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path + (``hf://buckets/...``) and the other must be a local directory path. + + Args: + source (`str`, *optional*): + Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``. + Required unless using ``apply``. + dest (`str`, *optional*): + Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``. + Required unless using ``apply``. + api ([`HfApi`]): + The HfApi instance to use for API calls. + delete (`bool`, *optional*, defaults to `False`): + Delete destination files not present in source. + ignore_times (`bool`, *optional*, defaults to `False`): + Skip files only based on size, ignoring modification times. + ignore_sizes (`bool`, *optional*, defaults to `False`): + Skip files only based on modification times, ignoring sizes. + existing (`bool`, *optional*, defaults to `False`): + Skip creating new files on receiver (only update existing files). + ignore_existing (`bool`, *optional*, defaults to `False`): + Skip updating files that exist on receiver (only create new files). + include (`list[str]`, *optional*): + Include files matching patterns (fnmatch-style). + exclude (`list[str]`, *optional*): + Exclude files matching patterns (fnmatch-style). + filter_from (`str`, *optional*): + Path to a filter file with include/exclude rules. + plan (`str`, *optional*): + Save sync plan to this JSONL file instead of executing. + apply (`str`, *optional*): + Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed. + dry_run (`bool`, *optional*, defaults to `False`): + Print sync plan to stdout as JSONL without executing. + verbose (`bool`, *optional*, defaults to `False`): + Show detailed per-file operations. + quiet (`bool`, *optional*, defaults to `False`): + Suppress all output and progress bars. + token (Union[bool, str, None], optional): + A valid user access token. If not provided, the locally saved token will be used. + + Returns: + [`SyncPlan`]: The computed (or loaded) sync plan. + + Raises: + `ValueError`: If arguments are invalid (e.g., both paths are remote, conflicting options). + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + + # Upload local directory to bucket + >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket") + + # Download bucket to local directory + >>> api.sync_bucket("hf://buckets/username/my-bucket", "./data") + + # Sync with delete and filtering + >>> api.sync_bucket( + ... "./data", + ... "hf://buckets/username/my-bucket", + ... delete=True, + ... include=["*.safetensors"], + ... ) + + # Dry run: preview what would be synced + >>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True) + >>> plan.summary() + {'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096} + + # Save plan for review, then apply + >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl") + >>> api.sync_bucket(apply="sync-plan.jsonl") + ``` + """ + # Build API with token if needed + if token is not None: + from .hf_api import HfApi + + api = HfApi(token=token) + # --- Apply mode --- + if apply: + if source or dest: + raise ValueError("Cannot specify source/dest when using apply.") + if plan is not None: + raise ValueError("Cannot specify both plan and apply.") + if delete: + raise ValueError("Cannot specify delete when using apply.") + if ignore_times: + raise ValueError("Cannot specify ignore_times when using apply.") + if ignore_sizes: + raise ValueError("Cannot specify ignore_sizes when using apply.") + if include: + raise ValueError("Cannot specify include when using apply.") + if exclude: + raise ValueError("Cannot specify exclude when using apply.") + if filter_from: + raise ValueError("Cannot specify filter_from when using apply.") + if existing: + raise ValueError("Cannot specify existing when using apply.") + if ignore_existing: + raise ValueError("Cannot specify ignore_existing when using apply.") + if dry_run: + raise ValueError("Cannot specify dry_run when using apply.") + + sync_plan = _load_plan(apply) + status = StatusLine(enabled=not quiet) + if not quiet: + _print_plan_summary(sync_plan) + print("Executing plan...") + + if quiet: + disable_progress_bars() + try: + _execute_plan(sync_plan, api, verbose=verbose, status=status) + finally: + if quiet: + enable_progress_bars() + + if not quiet: + print("Sync completed.") + + return sync_plan + + # --- Normal mode --- + if not source or not dest: + raise ValueError("Both source and dest are required (unless using apply).") + + source_is_bucket = _is_bucket_path(source) + dest_is_bucket = _is_bucket_path(dest) + + if source_is_bucket and dest_is_bucket: + raise ValueError("Remote to remote sync is not supported. One path must be local.") + + if not source_is_bucket and not dest_is_bucket: + raise ValueError("One of source or dest must be a bucket path (hf://buckets/...).") + + if ignore_times and ignore_sizes: + raise ValueError("Cannot specify both ignore_times and ignore_sizes.") + + if existing and ignore_existing: + raise ValueError("Cannot specify both existing and ignore_existing.") + + if dry_run and plan: + raise ValueError("Cannot specify both dry_run and plan.") + + # Validate local path + if source_is_bucket: + if os.path.exists(dest) and not os.path.isdir(dest): + raise ValueError(f"Destination must be a directory: {dest}") + else: + if not os.path.isdir(source): + raise ValueError(f"Source must be an existing directory: {source}") + + # Build filter matcher + filter_rules = None + if filter_from: + filter_rules = _parse_filter_file(filter_from) + + filter_matcher = FilterMatcher( + include_patterns=include, + exclude_patterns=exclude, + filter_rules=filter_rules, + ) + + # Compute sync plan + status = StatusLine(enabled=not quiet and not dry_run) + sync_plan = _compute_sync_plan( + source=source, + dest=dest, + api=api, + delete=delete, + ignore_times=ignore_times, + ignore_sizes=ignore_sizes, + existing=existing, + ignore_existing=ignore_existing, + filter_matcher=filter_matcher, + status=status, + ) + + if dry_run: + _write_plan(sync_plan, sys.stdout) + return sync_plan + + if plan: + _save_plan(sync_plan, plan) + if not quiet: + _print_plan_summary(sync_plan) + print(f"Plan saved to: {plan}") + return sync_plan + + # Execute plan + if not quiet: + _print_plan_summary(sync_plan) + + summary = sync_plan.summary() + if summary["uploads"] == 0 and summary["downloads"] == 0 and summary["deletes"] == 0: + if not quiet: + print("Nothing to sync.") + return sync_plan + + if not quiet: + print("Syncing...") + + if quiet: + disable_progress_bars() + try: + _execute_plan(sync_plan, api, verbose=verbose, status=status) + finally: + if quiet: + enable_progress_bars() + + if not quiet: + print("Sync completed.") + + return sync_plan diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_commit_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_commit_api.py new file mode 100644 index 0000000000000000000000000000000000000000..883d22549b268c524c0e59b75a103f0ea87abf73 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_commit_api.py @@ -0,0 +1,976 @@ +""" +Type definitions and utilities for the `create_commit` API +""" + +import base64 +import io +import os +import warnings +from collections import defaultdict +from collections.abc import Iterable, Iterator +from contextlib import contextmanager +from dataclasses import dataclass, field +from itertools import groupby +from pathlib import Path, PurePosixPath +from typing import TYPE_CHECKING, Any, BinaryIO, Literal, Union + +from tqdm.contrib.concurrent import thread_map + +from . import constants +from .errors import EntryNotFoundError, HfHubHTTPError, XetAuthorizationError, XetRefreshTokenError +from .file_download import hf_hub_url +from .lfs import UploadInfo, lfs_upload, post_lfs_batch_info +from .utils import ( + FORBIDDEN_FOLDERS, + XetTokenType, + are_progress_bars_disabled, + chunk_iterable, + fetch_xet_connection_info_from_repo_info, + get_session, + hf_raise_for_status, + http_backoff, + logging, + sha, + tqdm_stream_file, + validate_hf_hub_args, +) +from .utils import tqdm as hf_tqdm +from .utils._runtime import is_xet_available + + +if TYPE_CHECKING: + from .hf_api import RepoFile + + +logger = logging.get_logger(__name__) + + +UploadMode = Literal["lfs", "regular"] + +# Max is 1,000 per request on the Hub for HfApi.get_paths_info +# Otherwise we get: +# HfHubHTTPError: 413 Client Error: Payload Too Large for url: https://huggingface.co/api/datasets/xxx (Request ID: xxx)\n\ntoo many parameters +# See https://github.com/huggingface/huggingface_hub/issues/1503 +FETCH_LFS_BATCH_SIZE = 500 + +UPLOAD_BATCH_MAX_NUM_FILES = 256 + + +@dataclass +class CommitOperationDelete: + """ + Data structure holding necessary info to delete a file or a folder from a repository + on the Hub. + + Args: + path_in_repo (`str`): + Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"` + for a file or `"checkpoints/1fec34a/"` for a folder. + is_folder (`bool` or `Literal["auto"]`, *optional*) + Whether the Delete Operation applies to a folder or not. If "auto", the path + type (file or folder) is guessed automatically by looking if path ends with + a "/" (folder) or not (file). To explicitly set the path type, you can set + `is_folder=True` or `is_folder=False`. + """ + + path_in_repo: str + is_folder: bool | Literal["auto"] = "auto" + + def __post_init__(self): + self.path_in_repo = _validate_path_in_repo(self.path_in_repo) + + if self.is_folder == "auto": + self.is_folder = self.path_in_repo.endswith("/") + if not isinstance(self.is_folder, bool): + raise ValueError( + f"Wrong value for `is_folder`. Must be one of [`True`, `False`, `'auto'`]. Got '{self.is_folder}'." + ) + + +@dataclass +class CommitOperationCopy: + """ + Data structure holding necessary info to copy a file in a repository on the Hub. + + Limitations: + - Only LFS files can be copied. To copy a regular file, you need to download it locally and re-upload it + - Cross-repository copies are not supported. + + Note: you can combine a [`CommitOperationCopy`] and a [`CommitOperationDelete`] to rename an LFS file on the Hub. + + Args: + src_path_in_repo (`str`): + Relative filepath in the repo of the file to be copied, e.g. `"checkpoints/1fec34a/weights.bin"`. + path_in_repo (`str`): + Relative filepath in the repo where to copy the file, e.g. `"checkpoints/1fec34a/weights_copy.bin"`. + src_revision (`str`, *optional*): + The git revision of the file to be copied. Can be any valid git revision. + Default to the target commit revision. + """ + + src_path_in_repo: str + path_in_repo: str + src_revision: str | None = None + # set to the OID of the file to be copied if it has already been uploaded + # useful to determine if a commit will be empty or not. + _src_oid: str | None = None + # set to the OID of the file to copy to if it has already been uploaded + # useful to determine if a commit will be empty or not. + _dest_oid: str | None = None + + def __post_init__(self): + self.src_path_in_repo = _validate_path_in_repo(self.src_path_in_repo) + self.path_in_repo = _validate_path_in_repo(self.path_in_repo) + + +@dataclass +class CommitOperationAdd: + """ + Data structure holding necessary info to upload a file to a repository on the Hub. + + Args: + path_in_repo (`str`): + Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"` + path_or_fileobj (`str`, `Path`, `bytes`, or `BinaryIO`): + Either: + - a path to a local file (as `str` or `pathlib.Path`) to upload + - a buffer of bytes (`bytes`) holding the content of the file to upload + - a "file object" (subclass of `io.BufferedIOBase`), typically obtained + with `open(path, "rb")`. It must support `seek()` and `tell()` methods. + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `path_or_fileobj` is not one of `str`, `Path`, `bytes` or `io.BufferedIOBase`. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `path_or_fileobj` is a `str` or `Path` but not a path to an existing file. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `path_or_fileobj` is a `io.BufferedIOBase` but it doesn't support both + `seek()` and `tell()`. + """ + + path_in_repo: str + path_or_fileobj: str | Path | bytes | BinaryIO + upload_info: UploadInfo = field(init=False, repr=False) + + # Internal attributes + + # set to "lfs" or "regular" once known + _upload_mode: UploadMode | None = field(init=False, repr=False, default=None) + + # set to True if .gitignore rules prevent the file from being uploaded as LFS + # (server-side check) + _should_ignore: bool | None = field(init=False, repr=False, default=None) + + # set to the remote OID of the file if it has already been uploaded + # useful to determine if a commit will be empty or not + _remote_oid: str | None = field(init=False, repr=False, default=None) + + # set to True once the file has been uploaded as LFS + _is_uploaded: bool = field(init=False, repr=False, default=False) + + # set to True once the file has been committed + _is_committed: bool = field(init=False, repr=False, default=False) + + def __post_init__(self) -> None: + """Validates `path_or_fileobj` and compute `upload_info`.""" + self.path_in_repo = _validate_path_in_repo(self.path_in_repo) + + # Validate `path_or_fileobj` value + if isinstance(self.path_or_fileobj, Path): + self.path_or_fileobj = str(self.path_or_fileobj) + if isinstance(self.path_or_fileobj, str): + path_or_fileobj = os.path.normpath(os.path.expanduser(self.path_or_fileobj)) + if not os.path.isfile(path_or_fileobj): + raise ValueError(f"Provided path: '{path_or_fileobj}' is not a file on the local file system") + elif not isinstance(self.path_or_fileobj, (io.BufferedIOBase, bytes)): + # ^^ Inspired from: https://stackoverflow.com/questions/44584829/how-to-determine-if-file-is-opened-in-binary-or-text-mode + raise ValueError( + "path_or_fileobj must be either an instance of str, bytes or" + " io.BufferedIOBase. If you passed a file-like object, make sure it is" + " in binary mode." + ) + if isinstance(self.path_or_fileobj, io.BufferedIOBase): + try: + self.path_or_fileobj.tell() + self.path_or_fileobj.seek(0, os.SEEK_CUR) + except (OSError, AttributeError) as exc: + raise ValueError( + "path_or_fileobj is a file-like object but does not implement seek() and tell()" + ) from exc + + # Compute "upload_info" attribute + if isinstance(self.path_or_fileobj, str): + self.upload_info = UploadInfo.from_path(self.path_or_fileobj) + elif isinstance(self.path_or_fileobj, bytes): + self.upload_info = UploadInfo.from_bytes(self.path_or_fileobj) + else: + self.upload_info = UploadInfo.from_fileobj(self.path_or_fileobj) + + @contextmanager + def as_file(self, with_tqdm: bool = False) -> Iterator[BinaryIO]: + """ + A context manager that yields a file-like object allowing to read the underlying + data behind `path_or_fileobj`. + + Args: + with_tqdm (`bool`, *optional*, defaults to `False`): + If True, iterating over the file object will display a progress bar. Only + works if the file-like object is a path to a file. Pure bytes and buffers + are not supported. + + Example: + + ```python + >>> operation = CommitOperationAdd( + ... path_in_repo="remote/dir/weights.h5", + ... path_or_fileobj="./local/weights.h5", + ... ) + CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5') + + >>> with operation.as_file() as file: + ... content = file.read() + + >>> with operation.as_file(with_tqdm=True) as file: + ... while True: + ... data = file.read(1024) + ... if not data: + ... break + config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s] + + >>> with operation.as_file(with_tqdm=True) as file: + ... httpx.put(..., data=file) + config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s] + ``` + """ + if isinstance(self.path_or_fileobj, str) or isinstance(self.path_or_fileobj, Path): + if with_tqdm: + with tqdm_stream_file(self.path_or_fileobj) as file: + yield file + else: + with open(self.path_or_fileobj, "rb") as file: + yield file + elif isinstance(self.path_or_fileobj, bytes): + yield io.BytesIO(self.path_or_fileobj) + elif isinstance(self.path_or_fileobj, io.BufferedIOBase): + prev_pos = self.path_or_fileobj.tell() + yield self.path_or_fileobj + self.path_or_fileobj.seek(prev_pos, io.SEEK_SET) + + def b64content(self) -> bytes: + """ + The base64-encoded content of `path_or_fileobj` + + Returns: `bytes` + """ + with self.as_file() as file: + return base64.b64encode(file.read()) + + @property + def _local_oid(self) -> str | None: + """Return the OID of the local file. + + This OID is then compared to `self._remote_oid` to check if the file has changed compared to the remote one. + If the file did not change, we won't upload it again to prevent empty commits. + + For LFS files, the OID corresponds to the SHA256 of the file content (used a LFS ref). + For regular files, the OID corresponds to the SHA1 of the file content. + Note: this is slightly different to git OID computation since the oid of an LFS file is usually the git-SHA1 of the + pointer file content (not the actual file content). However, using the SHA256 is enough to detect changes + and more convenient client-side. + """ + if self._upload_mode is None: + return None + elif self._upload_mode == "lfs": + return self.upload_info.sha256.hex() + else: + # Regular file => compute sha1 + # => no need to read by chunk since the file is guaranteed to be <=5MB. + with self.as_file() as file: + return sha.git_hash(file.read()) + + +def _validate_path_in_repo(path_in_repo: str) -> str: + # Validate `path_in_repo` value to prevent a server-side issue + if path_in_repo.startswith("/"): + path_in_repo = path_in_repo[1:] + if path_in_repo == "." or path_in_repo == ".." or path_in_repo.startswith("../"): + raise ValueError(f"Invalid `path_in_repo` in CommitOperation: '{path_in_repo}'") + if path_in_repo.startswith("./"): + path_in_repo = path_in_repo[2:] + for forbidden in FORBIDDEN_FOLDERS: + if any(part == forbidden for part in path_in_repo.split("/")): + raise ValueError( + f"Invalid `path_in_repo` in CommitOperation: cannot update files under a '{forbidden}/' folder (path:" + f" '{path_in_repo}')." + ) + return path_in_repo + + +CommitOperation = Union[CommitOperationAdd, CommitOperationCopy, CommitOperationDelete] + + +def _warn_on_overwriting_operations(operations: list[CommitOperation]) -> None: + """ + Warn user when a list of operations is expected to overwrite itself in a single + commit. + + Rules: + - If a filepath is updated by multiple `CommitOperationAdd` operations, a warning + message is triggered. + - If a filepath is updated at least once by a `CommitOperationAdd` and then deleted + by a `CommitOperationDelete`, a warning is triggered. + - If a `CommitOperationDelete` deletes a filepath that is then updated by a + `CommitOperationAdd`, no warning is triggered. This is usually useless (no need to + delete before upload) but can happen if a user deletes an entire folder and then + add new files to it. + """ + nb_additions_per_path: dict[str, int] = defaultdict(int) + for operation in operations: + path_in_repo = operation.path_in_repo + if isinstance(operation, CommitOperationAdd): + if nb_additions_per_path[path_in_repo] > 0: + warnings.warn( + "About to update multiple times the same file in the same commit:" + f" '{path_in_repo}'. This can cause undesired inconsistencies in" + " your repo." + ) + nb_additions_per_path[path_in_repo] += 1 + for parent in PurePosixPath(path_in_repo).parents: + # Also keep track of number of updated files per folder + # => warns if deleting a folder overwrite some contained files + nb_additions_per_path[str(parent)] += 1 + if isinstance(operation, CommitOperationDelete): + if nb_additions_per_path[str(PurePosixPath(path_in_repo))] > 0: + if operation.is_folder: + warnings.warn( + "About to delete a folder containing files that have just been" + f" updated within the same commit: '{path_in_repo}'. This can" + " cause undesired inconsistencies in your repo." + ) + else: + warnings.warn( + "About to delete a file that have just been updated within the" + f" same commit: '{path_in_repo}'. This can cause undesired" + " inconsistencies in your repo." + ) + + +@validate_hf_hub_args +def _upload_files( + *, + additions: list[CommitOperationAdd], + repo_type: str, + repo_id: str, + headers: dict[str, str], + endpoint: str | None = None, + num_threads: int = 5, + revision: str | None = None, + create_pr: bool | None = None, +): + """ + Negotiates per-file transfer (LFS vs Xet) and uploads in batches. + """ + xet_additions: list[CommitOperationAdd] = [] + lfs_actions: list[dict[str, Any]] = [] + lfs_oid2addop: dict[str, CommitOperationAdd] = {} + + for chunk in chunk_iterable(additions, chunk_size=UPLOAD_BATCH_MAX_NUM_FILES): + chunk_list = [op for op in chunk] + + transfers: list[str] = ["basic", "multipart"] + has_buffered_io_data = any(isinstance(op.path_or_fileobj, io.BufferedIOBase) for op in chunk_list) + if is_xet_available(): + if not has_buffered_io_data: + transfers.append("xet") + else: + logger.warning( + "Uploading files as a binary IO buffer is not supported by Xet Storage. " + "Falling back to HTTP upload." + ) + + actions_chunk, errors_chunk, chosen_transfer = post_lfs_batch_info( + upload_infos=[op.upload_info for op in chunk_list], + repo_id=repo_id, + repo_type=repo_type, + revision=revision, + endpoint=endpoint, + headers=headers, + token=None, # already passed in 'headers' + transfers=transfers, + ) + if errors_chunk: + message = "\n".join( + [ + f"Encountered error for file with OID {err.get('oid')}: `{err.get('error', {}).get('message')}" + for err in errors_chunk + ] + ) + raise ValueError(f"LFS batch API returned errors:\n{message}") + + # If server returns a transfer we didn't offer (e.g "xet" while uploading from BytesIO), + # fall back to LFS for this chunk. + if chosen_transfer == "xet" and ("xet" in transfers): + xet_additions.extend(chunk_list) + else: + lfs_actions.extend(actions_chunk) + for op in chunk_list: + lfs_oid2addop[op.upload_info.sha256.hex()] = op + + if len(lfs_actions) > 0: + _upload_lfs_files( + actions=lfs_actions, + oid2addop=lfs_oid2addop, + headers=headers, + endpoint=endpoint, + num_threads=num_threads, + ) + + if len(xet_additions) > 0: + _upload_xet_files( + additions=xet_additions, + repo_type=repo_type, + repo_id=repo_id, + headers=headers, + endpoint=endpoint, + revision=revision, + create_pr=create_pr, + ) + + +@validate_hf_hub_args +def _upload_lfs_files( + *, + actions: list[dict[str, Any]], + oid2addop: dict[str, CommitOperationAdd], + headers: dict[str, str], + endpoint: str | None = None, + num_threads: int = 5, +): + """ + Uploads the content of `additions` to the Hub using the large file storage protocol. + + Relevant external documentation: + - LFS Batch API: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md + + Args: + actions (`list[dict[str, Any]]`): + LFS batch actions returned by the server. + oid2addop (`dict[str, CommitOperationAdd]`): + A dictionary mapping the OID of the file to the corresponding `CommitOperationAdd` object. + headers (`dict[str, str]`): + Headers to use for the request, including authorization headers and user agent. + endpoint (`str`, *optional*): + The endpoint to use for the request. Defaults to `constants.ENDPOINT`. + num_threads (`int`, *optional*): + The number of concurrent threads to use when uploading. Defaults to 5. + + Raises: + [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + If an upload failed for any reason + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + headers (`dict[str, str]`): + Headers to use for the request, including authorization headers and user agent. + num_threads (`int`, *optional*): + The number of concurrent threads to use when uploading. Defaults to 5. + revision (`str`, *optional*): + The git revision to upload to. + + Raises: + [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + If an upload failed for any reason + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If the server returns malformed responses + [`HfHubHTTPError`] + If the LFS batch endpoint returned an HTTP error. + """ + # Filter out files already present upstream + filtered_actions = [] + for action in actions: + if action.get("actions") is None: + logger.debug( + f"Content of file {oid2addop[action['oid']].path_in_repo} is already present upstream - skipping upload." + ) + else: + filtered_actions.append(action) + + # Upload according to server-provided actions + def _wrapped_lfs_upload(batch_action) -> None: + try: + operation = oid2addop[batch_action["oid"]] + lfs_upload(operation=operation, lfs_batch_action=batch_action, headers=headers, endpoint=endpoint) + except Exception as exc: + raise RuntimeError(f"Error while uploading '{operation.path_in_repo}' to the Hub.") from exc + + if len(filtered_actions) == 1: + logger.debug("Uploading 1 LFS file to the Hub") + _wrapped_lfs_upload(filtered_actions[0]) + else: + logger.debug( + f"Uploading {len(filtered_actions)} LFS files to the Hub using up to {num_threads} threads concurrently" + ) + thread_map( + _wrapped_lfs_upload, + filtered_actions, + desc=f"Upload {len(filtered_actions)} LFS files", + max_workers=num_threads, + tqdm_class=hf_tqdm, + ) + + +@validate_hf_hub_args +def _upload_xet_files( + *, + additions: list[CommitOperationAdd], + repo_type: str, + repo_id: str, + headers: dict[str, str], + endpoint: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, +): + """ + Uploads the content of `additions` to the Hub using the xet storage protocol. + This chunks the files and deduplicates the chunks before uploading them to xetcas storage. + + Args: + additions (`` of `CommitOperationAdd`): + The files to be uploaded. + repo_type (`str`): + Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + headers (`dict[str, str]`): + Headers to use for the request, including authorization headers and user agent. + endpoint: (`str`, *optional*): + The endpoint to use for the xetcas service. Defaults to `constants.ENDPOINT`. + revision (`str`, *optional*): + The git revision to upload to. + create_pr (`bool`, *optional*): + Whether or not to create a Pull Request with that commit. + + Raises: + [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + If an upload failed for any reason. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If the server returns malformed responses or if the user is unauthorized to upload to xet storage. + [`HfHubHTTPError`] + If the LFS batch endpoint returned an HTTP error. + + **How it works:** + The file download system uses Xet storage, which is a content-addressable storage system that breaks files into chunks + for efficient storage and transfer. + + `hf_xet.upload_files` manages uploading files by: + - Taking a list of file paths to upload + - Breaking files into smaller chunks for efficient storage + - Avoiding duplicate storage by recognizing identical chunks across files + - Connecting to a storage server (CAS server) that manages these chunks + + The upload process works like this: + 1. Create a local folder at ~/.cache/huggingface/xet/chunk-cache to store file chunks for reuse. + 2. Process files in parallel (up to 8 files at once): + 2.1. Read the file content. + 2.2. Split the file content into smaller chunks based on content patterns: each chunk gets a unique ID based on what's in it. + 2.3. For each chunk: + - Check if it already exists in storage. + - Skip uploading chunks that already exist. + 2.4. Group chunks into larger blocks for efficient transfer. + 2.5. Upload these blocks to the storage server. + 2.6. Create and upload information about how the file is structured. + 3. Return reference files that contain information about the uploaded files, which can be used later to download them. + """ + if len(additions) == 0: + return + + # at this point, we know that hf_xet is installed + from hf_xet import upload_bytes, upload_files + + from .utils._xet_progress_reporting import XetProgressReporter + + try: + xet_connection_info = fetch_xet_connection_info_from_repo_info( + token_type=XetTokenType.WRITE, + repo_id=repo_id, + repo_type=repo_type, + revision=revision, + headers=headers, + endpoint=endpoint, + params={"create_pr": "1"} if create_pr else None, + ) + except HfHubHTTPError as e: + if e.response.status_code == 401: + raise XetAuthorizationError( + f"You are unauthorized to upload to xet storage for {repo_type}/{repo_id}. " + f"Please check that you have configured your access token with write access to the repo." + ) from e + raise + + xet_endpoint = xet_connection_info.endpoint + access_token_info = (xet_connection_info.access_token, xet_connection_info.expiration_unix_epoch) + + def token_refresher() -> tuple[str, int]: + new_xet_connection = fetch_xet_connection_info_from_repo_info( + token_type=XetTokenType.WRITE, + repo_id=repo_id, + repo_type=repo_type, + revision=revision, + headers=headers, + endpoint=endpoint, + params={"create_pr": "1"} if create_pr else None, + ) + if new_xet_connection is None: + raise XetRefreshTokenError("Failed to refresh xet token") + return new_xet_connection.access_token, new_xet_connection.expiration_unix_epoch + + if not are_progress_bars_disabled(): + progress = XetProgressReporter() + progress_callback = progress.update_progress + else: + progress, progress_callback = None, None + + try: + all_bytes_ops = [op for op in additions if isinstance(op.path_or_fileobj, bytes)] + all_paths_ops = [op for op in additions if isinstance(op.path_or_fileobj, (str, Path))] + + xet_headers = headers.copy() + xet_headers.pop("authorization", None) + + if len(all_paths_ops) > 0: + all_paths = [str(op.path_or_fileobj) for op in all_paths_ops] + all_sha256s = [op.upload_info.sha256.hex() for op in all_paths_ops] + upload_files( + all_paths, + xet_endpoint, + access_token_info, + token_refresher, + progress_callback, + repo_type, + request_headers=xet_headers, + sha256s=all_sha256s, + ) + + if len(all_bytes_ops) > 0: + all_bytes = [op.path_or_fileobj for op in all_bytes_ops] + all_sha256s = [op.upload_info.sha256.hex() for op in all_bytes_ops] + upload_bytes( + all_bytes, + xet_endpoint, + access_token_info, + token_refresher, + progress_callback, + repo_type, + request_headers=xet_headers, + sha256s=all_sha256s, + ) + + finally: + if progress is not None: + progress.close(False) + + return + + +def _validate_preupload_info(preupload_info: dict): + files = preupload_info.get("files") + if not isinstance(files, list): + raise ValueError("preupload_info is improperly formatted") + for file_info in files: + if not ( + isinstance(file_info, dict) + and isinstance(file_info.get("path"), str) + and isinstance(file_info.get("uploadMode"), str) + and (file_info["uploadMode"] in ("lfs", "regular")) + ): + raise ValueError("preupload_info is improperly formatted:") + return preupload_info + + +@validate_hf_hub_args +def _fetch_upload_modes( + additions: Iterable[CommitOperationAdd], + repo_type: str, + repo_id: str, + headers: dict[str, str], + revision: str, + endpoint: str | None = None, + create_pr: bool = False, + gitignore_content: str | None = None, +) -> None: + """ + Requests the Hub "preupload" endpoint to determine whether each input file should be uploaded as a regular git blob, + as a git LFS blob, or as a XET file. Input `additions` are mutated in-place with the upload mode. + + Args: + additions (`Iterable` of :class:`CommitOperationAdd`): + Iterable of :class:`CommitOperationAdd` describing the files to + upload to the Hub. + repo_type (`str`): + Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + headers (`dict[str, str]`): + Headers to use for the request, including authorization headers and user agent. + revision (`str`): + The git revision to upload the files to. Can be any valid git revision. + gitignore_content (`str`, *optional*): + The content of the `.gitignore` file to know which files should be ignored. The order of priority + is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present + in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub + (if any). + Raises: + [`~utils.HfHubHTTPError`] + If the Hub API returned an error. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If the Hub API response is improperly formatted. + """ + endpoint = endpoint if endpoint is not None else constants.ENDPOINT + + # Fetch upload mode (LFS or regular) chunk by chunk. + upload_modes: dict[str, UploadMode] = {} + should_ignore_info: dict[str, bool] = {} + oid_info: dict[str, str | None] = {} + + for chunk in chunk_iterable(additions, 256): + payload: dict = { + "files": [ + { + "path": op.path_in_repo, + "sample": base64.b64encode(op.upload_info.sample).decode("ascii"), + "size": op.upload_info.size, + } + for op in chunk + ] + } + if gitignore_content is not None: + payload["gitIgnore"] = gitignore_content + + resp = http_backoff( + "POST", + f"{endpoint}/api/{repo_type}s/{repo_id}/preupload/{revision}", + json=payload, + headers=headers, + params={"create_pr": "1"} if create_pr else None, + ) + hf_raise_for_status(resp) + preupload_info = _validate_preupload_info(resp.json()) + upload_modes.update(**{file["path"]: file["uploadMode"] for file in preupload_info["files"]}) + should_ignore_info.update(**{file["path"]: file["shouldIgnore"] for file in preupload_info["files"]}) + oid_info.update(**{file["path"]: file.get("oid") for file in preupload_info["files"]}) + + # Set upload mode for each addition operation + for addition in additions: + addition._upload_mode = upload_modes[addition.path_in_repo] + addition._should_ignore = should_ignore_info[addition.path_in_repo] + addition._remote_oid = oid_info[addition.path_in_repo] + + # Empty files cannot be uploaded as LFS (S3 would fail with a 501 Not Implemented) + # => empty files are uploaded as "regular" to still allow users to commit them. + for addition in additions: + if addition.upload_info.size == 0: + addition._upload_mode = "regular" + + +@validate_hf_hub_args +def _fetch_files_to_copy( + copies: Iterable[CommitOperationCopy], + repo_type: str, + repo_id: str, + headers: dict[str, str], + revision: str, + endpoint: str | None = None, +) -> dict[tuple[str, str | None], Union["RepoFile", bytes]]: + """ + Fetch information about the files to copy. + + For LFS files, we only need their metadata (file size and sha256) while for regular files + we need to download the raw content from the Hub. + + Args: + copies (`Iterable` of :class:`CommitOperationCopy`): + Iterable of :class:`CommitOperationCopy` describing the files to + copy on the Hub. + repo_type (`str`): + Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + headers (`dict[str, str]`): + Headers to use for the request, including authorization headers and user agent. + revision (`str`): + The git revision to upload the files to. Can be any valid git revision. + + Returns: `dict[tuple[str, Optional[str]], Union[RepoFile, bytes]]]` + Key is the file path and revision of the file to copy. + Value is the raw content as bytes (for regular files) or the file information as a RepoFile (for LFS files). + + Raises: + [`~utils.HfHubHTTPError`] + If the Hub API returned an error. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If the Hub API response is improperly formatted. + """ + from .hf_api import HfApi, RepoFolder + + hf_api = HfApi(endpoint=endpoint, headers=headers) + files_to_copy: dict[tuple[str, str | None], Union["RepoFile", bytes]] = {} + # Store (path, revision) -> oid mapping + oid_info: dict[tuple[str, str | None], str | None] = {} + # 1. Fetch OIDs for destination paths in batches. + dest_paths = [op.path_in_repo for op in copies] + for offset in range(0, len(dest_paths), FETCH_LFS_BATCH_SIZE): + dest_repo_files = hf_api.get_paths_info( + repo_id=repo_id, + paths=dest_paths[offset : offset + FETCH_LFS_BATCH_SIZE], + revision=revision, + repo_type=repo_type, + ) + for file in dest_repo_files: + if not isinstance(file, RepoFolder): + oid_info[(file.path, revision)] = file.blob_id + + # 2. Group by source revision and fetch source file info in batches. + for src_revision, operations in groupby(copies, key=lambda op: op.src_revision): + operations = list(operations) # type: ignore + src_paths = [op.src_path_in_repo for op in operations] + for offset in range(0, len(src_paths), FETCH_LFS_BATCH_SIZE): + src_repo_files = hf_api.get_paths_info( + repo_id=repo_id, + paths=src_paths[offset : offset + FETCH_LFS_BATCH_SIZE], + revision=src_revision or revision, + repo_type=repo_type, + ) + + for src_repo_file in src_repo_files: + if isinstance(src_repo_file, RepoFolder): + raise NotImplementedError("Copying a folder is not implemented.") + oid_info[(src_repo_file.path, src_revision)] = src_repo_file.blob_id + # If it's an LFS file, store the RepoFile object. Otherwise, download raw bytes. + if src_repo_file.lfs: + files_to_copy[(src_repo_file.path, src_revision)] = src_repo_file + else: + # TODO: (optimization) download regular files to copy concurrently + url = hf_hub_url( + endpoint=endpoint, + repo_type=repo_type, + repo_id=repo_id, + revision=src_revision or revision, + filename=src_repo_file.path, + ) + response = get_session().get(url, headers=headers) + hf_raise_for_status(response) + files_to_copy[(src_repo_file.path, src_revision)] = response.content + # 3. Ensure all operations found a corresponding file in the Hub + # and track src/dest OIDs for each operation. + for operation in operations: + if (operation.src_path_in_repo, src_revision) not in files_to_copy: + raise EntryNotFoundError( + f"Cannot copy {operation.src_path_in_repo} at revision " + f"{src_revision or revision}: file is missing on repo." + ) + operation._src_oid = oid_info.get((operation.src_path_in_repo, operation.src_revision)) + operation._dest_oid = oid_info.get((operation.path_in_repo, revision)) + return files_to_copy + + +def _prepare_commit_payload( + operations: Iterable[CommitOperation], + files_to_copy: dict[tuple[str, str | None], Union["RepoFile", bytes]], + commit_message: str, + commit_description: str | None = None, + parent_commit: str | None = None, +) -> Iterable[dict[str, Any]]: + """ + Builds the payload to POST to the `/commit` API of the Hub. + + Payload is returned as an iterator so that it can be streamed as a ndjson in the + POST request. + + For more information, see: + - https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073 + - http://ndjson.org/ + """ + commit_description = commit_description if commit_description is not None else "" + + # 1. Send a header item with the commit metadata + header_value = {"summary": commit_message, "description": commit_description} + if parent_commit is not None: + header_value["parentCommit"] = parent_commit + yield {"key": "header", "value": header_value} + + nb_ignored_files = 0 + + # 2. Send operations, one per line + for operation in operations: + # Skip ignored files + if isinstance(operation, CommitOperationAdd) and operation._should_ignore: + logger.debug(f"Skipping file '{operation.path_in_repo}' in commit (ignored by gitignore file).") + nb_ignored_files += 1 + continue + + # 2.a. Case adding a regular file + if isinstance(operation, CommitOperationAdd) and operation._upload_mode == "regular": + yield { + "key": "file", + "value": { + "content": operation.b64content().decode(), + "path": operation.path_in_repo, + "encoding": "base64", + }, + } + # 2.b. Case adding an LFS file + elif isinstance(operation, CommitOperationAdd) and operation._upload_mode == "lfs": + yield { + "key": "lfsFile", + "value": { + "path": operation.path_in_repo, + "algo": "sha256", + "oid": operation.upload_info.sha256.hex(), + "size": operation.upload_info.size, + }, + } + # 2.c. Case deleting a file or folder + elif isinstance(operation, CommitOperationDelete): + yield { + "key": "deletedFolder" if operation.is_folder else "deletedFile", + "value": {"path": operation.path_in_repo}, + } + # 2.d. Case copying a file or folder + elif isinstance(operation, CommitOperationCopy): + file_to_copy = files_to_copy[(operation.src_path_in_repo, operation.src_revision)] + if isinstance(file_to_copy, bytes): + yield { + "key": "file", + "value": { + "content": base64.b64encode(file_to_copy).decode(), + "path": operation.path_in_repo, + "encoding": "base64", + }, + } + elif file_to_copy.lfs: + yield { + "key": "lfsFile", + "value": { + "path": operation.path_in_repo, + "algo": "sha256", + "oid": file_to_copy.lfs.sha256, + }, + } + else: + raise ValueError( + "Malformed files_to_copy (should be raw file content as bytes or RepoFile objects with LFS info." + ) + # 2.e. Never expected to happen + else: + raise ValueError( + f"Unknown operation to commit. Operation: {operation}. Upload mode:" + f" {getattr(operation, '_upload_mode', None)}" + ) + + if nb_ignored_files > 0: + logger.info(f"Skipped {nb_ignored_files} file(s) in commit (ignored by gitignore file).") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_commit_scheduler.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_commit_scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa4b8bf19400f318251838da0245f1aad2f1dbc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_commit_scheduler.py @@ -0,0 +1,353 @@ +import atexit +import logging +import os +import time +from concurrent.futures import Future +from dataclasses import dataclass +from io import SEEK_END, SEEK_SET, BytesIO +from pathlib import Path +from threading import Lock, Thread +from typing import Optional + +from .hf_api import DEFAULT_IGNORE_PATTERNS, CommitInfo, CommitOperationAdd, HfApi +from .utils import filter_repo_objects + + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class _FileToUpload: + """Temporary dataclass to store info about files to upload. Not meant to be used directly.""" + + local_path: Path + path_in_repo: str + size_limit: int + last_modified: float + + +class CommitScheduler: + """ + Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes). + + The recommended way to use the scheduler is to use it as a context manager. This ensures that the scheduler is + properly stopped and the last commit is triggered when the script ends. The scheduler can also be stopped manually + with the `stop` method. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads) + to learn more about how to use it. + + Args: + repo_id (`str`): + The id of the repo to commit to. + folder_path (`str` or `Path`): + Path to the local folder to upload regularly. + every (`int` or `float`, *optional*): + The number of minutes between each commit. Defaults to 5 minutes. + path_in_repo (`str`, *optional*): + Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder + of the repository. + repo_type (`str`, *optional*): + The type of the repo to commit to. Defaults to `model`. + revision (`str`, *optional*): + The revision of the repo to commit to. Defaults to `main`. + private (`bool`, *optional*): + Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. + token (`str`, *optional*): + The token to use to commit to the repo. Defaults to the token saved on the machine. + allow_patterns (`list[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are uploaded. + ignore_patterns (`list[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not uploaded. + squash_history (`bool`, *optional*): + Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is + useful to avoid degraded performances on the repo when it grows too large. + hf_api (`HfApi`, *optional*): + The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...). + + Example: + ```py + >>> from pathlib import Path + >>> from huggingface_hub import CommitScheduler + + # Scheduler uploads every 10 minutes + >>> csv_path = Path("watched_folder/data.csv") + >>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10) + + >>> with csv_path.open("a") as f: + ... f.write("first line") + + # Some time later (...) + >>> with csv_path.open("a") as f: + ... f.write("second line") + ``` + + Example using a context manager: + ```py + >>> from pathlib import Path + >>> from huggingface_hub import CommitScheduler + + >>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler: + ... csv_path = Path("watched_folder/data.csv") + ... with csv_path.open("a") as f: + ... f.write("first line") + ... (...) + ... with csv_path.open("a") as f: + ... f.write("second line") + + # Scheduler is now stopped and last commit have been triggered + ``` + """ + + def __init__( + self, + *, + repo_id: str, + folder_path: str | Path, + every: int | float = 5, + path_in_repo: str | None = None, + repo_type: str | None = None, + revision: str | None = None, + private: bool | None = None, + token: str | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + squash_history: bool = False, + hf_api: Optional["HfApi"] = None, + ) -> None: + self.api = hf_api or HfApi(token=token) + + # Folder + self.folder_path = Path(folder_path).expanduser().resolve() + self.path_in_repo = path_in_repo or "" + self.allow_patterns = allow_patterns + + if ignore_patterns is None: + ignore_patterns = [] + elif isinstance(ignore_patterns, str): + ignore_patterns = [ignore_patterns] + self.ignore_patterns = ignore_patterns + DEFAULT_IGNORE_PATTERNS + + if self.folder_path.is_file(): + raise ValueError(f"'folder_path' must be a directory, not a file: '{self.folder_path}'.") + self.folder_path.mkdir(parents=True, exist_ok=True) + + # Repository + repo_url = self.api.create_repo(repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True) + self.repo_id = repo_url.repo_id + self.repo_type = repo_type + self.revision = revision + self.token = token + + # Keep track of already uploaded files + self.last_uploaded: dict[Path, float] = {} # key is local path, value is timestamp + + # Scheduler + if not every > 0: + raise ValueError(f"'every' must be a positive integer, not '{every}'.") + self.lock = Lock() + self.every = every + self.squash_history = squash_history + + logger.info(f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes.") + self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True) + self._scheduler_thread.start() + atexit.register(self._push_to_hub) + + self.__stopped = False + + def stop(self) -> None: + """Stop the scheduler. + + A stopped scheduler cannot be restarted. Mostly for tests purposes. + """ + self.__stopped = True + + def __enter__(self) -> "CommitScheduler": + return self + + def __exit__(self, exc_type, exc_value, traceback) -> None: + # Upload last changes before exiting + self.trigger().result() + self.stop() + return + + def _run_scheduler(self) -> None: + """Dumb thread waiting between each scheduled push to Hub.""" + while True: + self.last_future = self.trigger() + time.sleep(self.every * 60) + if self.__stopped: + break + + def trigger(self) -> Future: + """Trigger a `push_to_hub` and return a future. + + This method is automatically called every `every` minutes. You can also call it manually to trigger a commit + immediately, without waiting for the next scheduled commit. + """ + return self.api.run_as_future(self._push_to_hub) + + def _push_to_hub(self) -> CommitInfo | None: + if self.__stopped: # If stopped, already scheduled commits are ignored + return None + + logger.info("(Background) scheduled commit triggered.") + try: + value = self.push_to_hub() + if self.squash_history: + logger.info("(Background) squashing repo history.") + self.api.super_squash_history(repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision) + return value + except Exception as e: + logger.error(f"Error while pushing to Hub: {e}") # Depending on the setup, error might be silenced + raise + + def push_to_hub(self) -> CommitInfo | None: + """ + Push folder to the Hub and return the commit info. + + > [!WARNING] + > This method is not meant to be called directly. It is run in the background by the scheduler, respecting a + > queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency + > issues. + + The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and + uploads only changed files. If no changes are found, the method returns without committing anything. If you want + to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful + for example to compress data together in a single file before committing. For more details and examples, check + out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads). + """ + # Check files to upload (with lock) + with self.lock: + logger.debug("Listing files to upload for scheduled commit.") + + # List files from folder (taken from `_prepare_upload_folder_additions`) + relpath_to_abspath = { + path.relative_to(self.folder_path).as_posix(): path + for path in sorted(self.folder_path.glob("**/*")) # sorted to be deterministic + if path.is_file() + } + prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else "" + + # Filter with pattern + filter out unchanged files + retrieve current file size + files_to_upload: list[_FileToUpload] = [] + for relpath in filter_repo_objects( + relpath_to_abspath.keys(), allow_patterns=self.allow_patterns, ignore_patterns=self.ignore_patterns + ): + local_path = relpath_to_abspath[relpath] + stat = local_path.stat() + if self.last_uploaded.get(local_path) is None or self.last_uploaded[local_path] != stat.st_mtime: + files_to_upload.append( + _FileToUpload( + local_path=local_path, + path_in_repo=prefix + relpath, + size_limit=stat.st_size, + last_modified=stat.st_mtime, + ) + ) + + # Return if nothing to upload + if len(files_to_upload) == 0: + logger.debug("Dropping schedule commit: no changed file to upload.") + return None + + # Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size) + logger.debug("Removing unchanged files since previous scheduled commit.") + add_operations = [ + CommitOperationAdd( + # Cap the file to its current size, even if the user append data to it while a scheduled commit is happening + path_or_fileobj=PartialFileIO(file_to_upload.local_path, size_limit=file_to_upload.size_limit), + path_in_repo=file_to_upload.path_in_repo, + ) + for file_to_upload in files_to_upload + ] + + # Upload files (append mode expected - no need for lock) + logger.debug("Uploading files for scheduled commit.") + commit_info = self.api.create_commit( + repo_id=self.repo_id, + repo_type=self.repo_type, + operations=add_operations, + commit_message="Scheduled Commit", + revision=self.revision, + ) + + # Successful commit: keep track of the latest "last_modified" for each file + for file in files_to_upload: + self.last_uploaded[file.local_path] = file.last_modified + return commit_info + + +class PartialFileIO(BytesIO): + """A file-like object that reads only the first part of a file. + + Useful to upload a file to the Hub when the user might still be appending data to it. Only the first part of the + file is uploaded (i.e. the part that was available when the filesystem was first scanned). + + In practice, only used internally by the CommitScheduler to regularly push a folder to the Hub with minimal + disturbance for the user. The object is passed to `CommitOperationAdd`. + + Only supports `read`, `tell` and `seek` methods. + + Args: + file_path (`str` or `Path`): + Path to the file to read. + size_limit (`int`): + The maximum number of bytes to read from the file. If the file is larger than this, only the first part + will be read (and uploaded). + """ + + def __init__(self, file_path: str | Path, size_limit: int) -> None: + self._file_path = Path(file_path) + self._file = self._file_path.open("rb") + self._size_limit = min(size_limit, os.fstat(self._file.fileno()).st_size) + + def __del__(self) -> None: + self._file.close() + return super().__del__() + + def __repr__(self) -> str: + return f"" + + def __len__(self) -> int: + return self._size_limit + + def __getattribute__(self, name: str): + if name.startswith("_") or name in ("read", "tell", "seek", "fileno"): # only 4 public methods supported + return super().__getattribute__(name) + raise NotImplementedError(f"PartialFileIO does not support '{name}'.") + + def fileno(self): + raise AttributeError("PartialFileIO does not have a fileno.") + + def tell(self) -> int: + """Return the current file position.""" + return self._file.tell() + + def seek(self, __offset: int, __whence: int = SEEK_SET) -> int: + """Change the stream position to the given offset. + + Behavior is the same as a regular file, except that the position is capped to the size limit. + """ + if __whence == SEEK_END: + # SEEK_END => set from the truncated end + __offset = len(self) + __offset + __whence = SEEK_SET + + pos = self._file.seek(__offset, __whence) + if pos > self._size_limit: + return self._file.seek(self._size_limit) + return pos + + def read(self, __size: int | None = -1) -> bytes: + """Read at most `__size` bytes from the file. + + Behavior is the same as a regular file, except that it is capped to the size limit. + """ + current = self._file.tell() + if __size is None or __size < 0: + # Read until file limit + truncated_size = self._size_limit - current + else: + # Read until file limit or __size + truncated_size = min(__size, self._size_limit - current) + return self._file.read(truncated_size) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_dataset_viewer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_dataset_viewer.py new file mode 100644 index 0000000000000000000000000000000000000000..ada15a7f0c3fd2d8d67d4fe9d803598b32896bb2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_dataset_viewer.py @@ -0,0 +1,172 @@ +# Copyright 2026 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import json +import os +import shutil +import subprocess +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Union + +from . import constants +from .utils import get_token + + +if TYPE_CHECKING: + import duckdb + + +@dataclass(frozen=True) +class DatasetParquetEntry: + """Represents a single parquet file available for a dataset on the Hub.""" + + config: str + split: str + url: str + size: int + + +def execute_raw_sql_query(sql_query: str, *, token: str | bool | None = None) -> list[dict[str, Any]]: + normalized_query = sql_query.strip().rstrip(";").strip() + _raise_on_forbidden_query(normalized_query) + + connection = None + try: + connection = _get_duckdb_connection(token=token) + relation = connection.sql(normalized_query) + if relation is None: + raise ValueError("SQL query must return rows.") + + if isinstance(relation, _DuckDBCliRelation): + # DuckDB binary => run CLI => parse JSON + return relation.execute() + else: + # DuckDB Python API => fetch columns + rows => convert to dicts + columns = tuple(column[0] for column in relation.description) + rows = tuple(tuple(row) for row in relation.fetchall()) + return [dict(zip(columns, row)) for row in rows] + finally: + if connection is not None: + connection.close() + + +def _raise_on_forbidden_query(query: str) -> None: + if len(query) == 0: + raise ValueError("SQL query cannot be empty.") + + # DuckDB CLI meta-commands are dot-prefixed words (e.g. `.shell`, `.output`). + # Let's forbid them for now but allow SQL expressions like `.5` that can legitimately start a line. + for line in query.splitlines(): + stripped = line.lstrip() + if stripped.startswith(".") and stripped[1:2].isalpha(): + raise ValueError("DuckDB CLI meta-commands are not allowed in SQL queries.") + + +def _get_duckdb_connection( + token: str | bool | None, +) -> Union["duckdb.DuckDBPyConnection", "_DuckDBCliConnection"]: + try: + # If DuckDB is installed as a Python package, use it! + import duckdb + except ImportError as error: + # Otherwise, use the DuckDB CLI binary. + duckdb_binary = shutil.which("duckdb") + if duckdb_binary is None: + raise ImportError( + "DuckDB is required for `hf datasets sql`. Install the Python package with `pip install duckdb` or " + "install the DuckDB CLI binary (for example `brew install duckdb`)." + ) from error + return _DuckDBCliConnection(binary_path=duckdb_binary, token=token) + + # Create a new connection (Python API). + connection = duckdb.connect() + try: + for statement in _build_duckdb_secret_statements(token): + connection.execute(statement) + return connection + except Exception: + connection.close() + raise + + +@dataclass +class _DuckDBCliConnection: + """DuckDB connection. + + Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary. + """ + + binary_path: str + token: str | bool | None + + def __post_init__(self) -> None: + self._setup_statements = _build_duckdb_secret_statements(self.token) + + def sql(self, query: str) -> "_DuckDBCliRelation": + return _DuckDBCliRelation(binary_path=self.binary_path, setup_statements=self._setup_statements, query=query) + + def close(self) -> None: + pass + + +@dataclass +class _DuckDBCliRelation: + """DuckDB relation. + + Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary. + """ + + binary_path: str + setup_statements: list[str] + query: str + + def execute(self) -> list[dict[str, Any]]: + # Build the DuckDB CLI input. + setup = [] + if self.setup_statements: + setup = [ + f".output {os.devnull}", + *(f"{stmt};" for stmt in self.setup_statements), + ".output", + ] + full_query = "\n".join(setup + [self.query + ";"]) + + # Run DuckDB binary + result = subprocess.run( + [self.binary_path, "-json"], + input=full_query, + capture_output=True, + text=True, + check=False, + ) + if result.returncode != 0: + error_message = result.stderr.strip() or result.stdout.strip() or "DuckDB CLI command failed." + raise RuntimeError(error_message) + + # Parse JSON output and return + return json.loads(result.stdout.strip()) + + +def _build_duckdb_secret_statements(token: str | bool | None) -> list[str]: + if token is None or token is True: + token = get_token() + + if not token: + return [] + + escaped_token = token.replace("'", "''") + escaped_endpoint = constants.ENDPOINT.replace("'", "''") + return [ + f"CREATE OR REPLACE SECRET hf_hub_token (TYPE HTTP, BEARER_TOKEN '{escaped_token}', SCOPE '{escaped_endpoint}')", + f"CREATE OR REPLACE SECRET hf_token (TYPE HUGGINGFACE, TOKEN '{escaped_token}')", + ] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_eval_results.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_eval_results.py new file mode 100644 index 0000000000000000000000000000000000000000..77aee2b595e979a0d4e83a71f7bea81a6f2e4d33 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_eval_results.py @@ -0,0 +1,211 @@ +"""Evaluation results utilities for the `.eval_results/*.yaml` format. + +See https://huggingface.co/docs/hub/eval-results for more details. +Specifications are available at https://github.com/huggingface/hub-docs/blob/main/eval_results.yaml. +""" + +from dataclasses import dataclass +from typing import Any + + +@dataclass +class EvalResultEntry: + """ + Evaluation result entry for the `.eval_results/*.yaml` format. + + Represents evaluation scores stored in model repos that automatically appear on + the model page and the benchmark dataset's leaderboard. + + For the legacy `model-index` format in `README.md`, use [`EvalResult`] instead. + + See https://huggingface.co/docs/hub/eval-results for more details. + + Args: + dataset_id (`str`): + Benchmark dataset ID from the Hub. Example: "cais/hle", "Idavidrein/gpqa". + task_id (`str`): + Task identifier within the benchmark. Example: "gpqa_diamond". + value (`Any`): + The metric value. Example: 20.90. + dataset_revision (`str`, *optional*): + Git SHA of the benchmark dataset. + verify_token (`str`, *optional*): + A signature that can be used to prove that evaluation is provably auditable and reproducible. + date (`str`, *optional*): + When the evaluation was run (ISO-8601 datetime). Defaults to git commit time. + source_url (`str`, *optional*): + Link to the evaluation source (e.g., https://huggingface.co/spaces/SaylorTwift/smollm3-mmlu-pro). Required if `source_name`, `source_user`, or `source_org` is provided. + source_name (`str`, *optional*): + Display name for the source. Example: "Eval Logs". + source_user (`str`, *optional*): + HF user name for attribution. Example: "celinah". + source_org (`str`, *optional*): + HF org name for attribution. Example: "cais". + notes (`str`, *optional*): + Details about the evaluation setup. Example: "tools", "no-tools", "chain-of-thought". + + Example: + ```python + >>> from huggingface_hub import EvalResultEntry + >>> # Minimal example with required fields only + >>> result = EvalResultEntry( + ... dataset_id="Idavidrein/gpqa", + ... task_id="gpqa_diamond", + ... value=0.412, + ... ) + >>> # Full example with all fields + >>> result = EvalResultEntry( + ... dataset_id="cais/hle", + ... task_id="default", + ... value=20.90, + ... dataset_revision="5503434ddd753f426f4b38109466949a1217c2bb", + ... verify_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", + ... date="2025-01-15T10:30:00Z", + ... source_url="https://huggingface.co/datasets/cais/hle", + ... source_name="CAIS HLE", + ... source_org="cais", + ... notes="no-tools", + ... ) + + ``` + """ + + dataset_id: str + task_id: str + value: Any + dataset_revision: str | None = None + verify_token: str | None = None + date: str | None = None + source_url: str | None = None + source_name: str | None = None + source_user: str | None = None + source_org: str | None = None + notes: str | None = None + + def __post_init__(self) -> None: + if ( + self.source_name is not None or self.source_user is not None or self.source_org is not None + ) and self.source_url is None: + raise ValueError( + "If `source_name`, `source_user`, or `source_org` is provided, `source_url` must also be provided." + ) + + +def eval_result_entries_to_yaml(entries: list[EvalResultEntry]) -> list[dict[str, Any]]: + """Convert a list of [`EvalResultEntry`] objects to a YAML-serializable list of dicts. + + This produces the format expected in `.eval_results/*.yaml` files. + + Args: + entries (`list[EvalResultEntry]`): + List of evaluation result entries to serialize. + + Returns: + `list[dict[str, Any]]`: A list of dictionaries ready to be dumped to YAML. + + Example: + ```python + >>> from huggingface_hub import EvalResultEntry, eval_result_entries_to_yaml + >>> entries = [ + ... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90), + ... EvalResultEntry(dataset_id="Idavidrein/gpqa", task_id="gpqa_diamond", value=0.412), + ... ] + >>> yaml_data = eval_result_entries_to_yaml(entries) + >>> yaml_data[0] + {'dataset': {'id': 'cais/hle', 'task_id': 'default'}, 'value': 20.9} + + ``` + + To upload eval results to the Hub: + ```python + >>> import yaml + >>> from huggingface_hub import upload_file, EvalResultEntry, eval_result_entries_to_yaml + >>> entries = [ + ... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90), + ... ] + >>> yaml_content = yaml.dump(eval_result_entries_to_yaml(entries)) + >>> upload_file( + ... path_or_fileobj=yaml_content.encode(), + ... path_in_repo=".eval_results/hle.yaml", + ... repo_id="your-username/your-model", + ... ) + + ``` + """ + result = [] + for entry in entries: + # build the dataset object + dataset: dict[str, Any] = {"id": entry.dataset_id, "task_id": entry.task_id} + if entry.dataset_revision is not None: + dataset["revision"] = entry.dataset_revision + + data: dict[str, Any] = {"dataset": dataset, "value": entry.value} + if entry.verify_token is not None: + data["verifyToken"] = entry.verify_token + if entry.date is not None: + data["date"] = entry.date + # build the source object + if entry.source_url is not None: + source: dict[str, Any] = {"url": entry.source_url} + if entry.source_name is not None: + source["name"] = entry.source_name + if entry.source_user is not None: + source["user"] = entry.source_user + if entry.source_org is not None: + source["org"] = entry.source_org + data["source"] = source + if entry.notes is not None: + data["notes"] = entry.notes + + result.append(data) + return result + + +def parse_eval_result_entries(data: list[dict[str, Any]]) -> list[EvalResultEntry]: + """Parse a list of dicts into [`EvalResultEntry`] objects. + + This parses the `.eval_results/*.yaml` format. For the legacy `model-index` format, + use [`model_index_to_eval_results`] instead. + + Args: + data (`list[dict[str, Any]]`): + A list of dictionaries (e.g., parsed from YAML or API response). + + Returns: + `list[EvalResultEntry]`: A list of evaluation result entry objects. + + Example: + ```python + >>> from huggingface_hub import parse_eval_result_entries + >>> data = [ + ... {"dataset": {"id": "cais/hle", "task_id": "default"}, "value": 20.90}, + ... {"dataset": {"id": "Idavidrein/gpqa", "task_id": "gpqa_diamond"}, "value": 0.412}, + ... ] + >>> entries = parse_eval_result_entries(data) + >>> entries[0].dataset_id + 'cais/hle' + >>> entries[0].value + 20.9 + + ``` + """ + entries = [] + for item in data: + entry_data = item.get("data", item) + dataset = entry_data.get("dataset", {}) + source = entry_data.get("source", {}) + entry = EvalResultEntry( + dataset_id=dataset["id"], + value=entry_data["value"], + task_id=dataset["task_id"], + dataset_revision=dataset.get("revision"), + verify_token=entry_data.get("verifyToken"), + date=entry_data.get("date"), + source_url=source.get("url") if source else None, + source_name=source.get("name") if source else None, + source_user=source.get("user") if source else None, + source_org=source.get("org") if source else None, + notes=entry_data.get("notes"), + ) + entries.append(entry) + return entries diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_inference_endpoints.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_inference_endpoints.py new file mode 100644 index 0000000000000000000000000000000000000000..5b8381a8e59459a768685d627ff3301bc9b9940e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_inference_endpoints.py @@ -0,0 +1,418 @@ +import time +from dataclasses import dataclass, field +from datetime import datetime +from enum import Enum +from typing import TYPE_CHECKING, Optional + +from huggingface_hub.errors import InferenceEndpointError, InferenceEndpointTimeoutError + +from .utils import get_session, logging, parse_datetime + + +if TYPE_CHECKING: + from .hf_api import HfApi + from .inference._client import InferenceClient + from .inference._generated._async_client import AsyncInferenceClient + +logger = logging.get_logger(__name__) + + +class InferenceEndpointStatus(str, Enum): + PENDING = "pending" + INITIALIZING = "initializing" + UPDATING = "updating" + UPDATE_FAILED = "updateFailed" + RUNNING = "running" + PAUSED = "paused" + FAILED = "failed" + SCALED_TO_ZERO = "scaledToZero" + + +class InferenceEndpointType(str, Enum): + PUBlIC = "public" + PROTECTED = "protected" + PRIVATE = "private" + + +class InferenceEndpointScalingMetric(str, Enum): + PENDING_REQUESTS = "pendingRequests" + HARDWARE_USAGE = "hardwareUsage" + + +@dataclass +class InferenceEndpoint: + """ + Contains information about a deployed Inference Endpoint. + + Args: + name (`str`): + The unique name of the Inference Endpoint. + namespace (`str`): + The namespace where the Inference Endpoint is located. + repository (`str`): + The name of the model repository deployed on this Inference Endpoint. + status ([`InferenceEndpointStatus`]): + The current status of the Inference Endpoint. + url (`str`, *optional*): + The URL of the Inference Endpoint, if available. Only a deployed Inference Endpoint will have a URL. + framework (`str`): + The machine learning framework used for the model. + revision (`str`): + The specific model revision deployed on the Inference Endpoint. + task (`str`): + The task associated with the deployed model. + created_at (`datetime.datetime`): + The timestamp when the Inference Endpoint was created. + updated_at (`datetime.datetime`): + The timestamp of the last update of the Inference Endpoint. + type ([`InferenceEndpointType`]): + The type of the Inference Endpoint (public, protected, private). + raw (`dict`): + The raw dictionary data returned from the API. + token (`str` or `bool`, *optional*): + Authentication token for the Inference Endpoint, if set when requesting the API. Will default to the + locally saved token if not provided. Pass `token=False` if you don't want to send your token to the server. + + Example: + ```python + >>> from huggingface_hub import get_inference_endpoint + >>> endpoint = get_inference_endpoint("my-text-to-image") + >>> endpoint + InferenceEndpoint(name='my-text-to-image', ...) + + # Get status + >>> endpoint.status + 'running' + >>> endpoint.url + 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud' + + # Run inference + >>> endpoint.client.text_to_image(...) + + # Pause endpoint to save $$$ + >>> endpoint.pause() + + # ... + # Resume and wait for deployment + >>> endpoint.resume() + >>> endpoint.wait() + >>> endpoint.client.text_to_image(...) + ``` + """ + + # Field in __repr__ + name: str = field(init=False) + namespace: str + repository: str = field(init=False) + status: InferenceEndpointStatus = field(init=False) + health_route: str = field(init=False) + url: str | None = field(init=False) + + # Other fields + framework: str = field(repr=False, init=False) + revision: str = field(repr=False, init=False) + task: str = field(repr=False, init=False) + created_at: datetime = field(repr=False, init=False) + updated_at: datetime = field(repr=False, init=False) + type: InferenceEndpointType = field(repr=False, init=False) + + # Raw dict from the API + raw: dict = field(repr=False) + + # Internal fields + _token: str | bool | None = field(repr=False, compare=False) + _api: "HfApi" = field(repr=False, compare=False) + + @classmethod + def from_raw( + cls, raw: dict, namespace: str, token: str | bool | None = None, api: Optional["HfApi"] = None + ) -> "InferenceEndpoint": + """Initialize object from raw dictionary.""" + if api is None: + from .hf_api import HfApi + + api = HfApi() + if token is None: + token = api.token + + # All other fields are populated in __post_init__ + return cls(raw=raw, namespace=namespace, _token=token, _api=api) + + def __post_init__(self) -> None: + """Populate fields from raw dictionary.""" + self._populate_from_raw() + + @property + def client(self) -> "InferenceClient": + """Returns a client to make predictions on this Inference Endpoint. + + Returns: + [`InferenceClient`]: an inference client pointing to the deployed endpoint. + + Raises: + [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed. + """ + if self.url is None: + raise InferenceEndpointError( + "Cannot create a client for this Inference Endpoint as it is not yet deployed. " + "Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again." + ) + from .inference._client import InferenceClient + + return InferenceClient( + model=self.url, + token=self._token, # type: ignore # boolean token shouldn't be possible. In practice it's ok. + ) + + @property + def async_client(self) -> "AsyncInferenceClient": + """Returns a client to make predictions on this Inference Endpoint. + + Returns: + [`AsyncInferenceClient`]: an asyncio-compatible inference client pointing to the deployed endpoint. + + Raises: + [`InferenceEndpointError`]: If the Inference Endpoint is not yet deployed. + """ + if self.url is None: + raise InferenceEndpointError( + "Cannot create a client for this Inference Endpoint as it is not yet deployed. " + "Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again." + ) + from .inference._generated._async_client import AsyncInferenceClient + + return AsyncInferenceClient( + model=self.url, + token=self._token, # type: ignore # boolean token shouldn't be possible. In practice it's ok. + ) + + def wait(self, timeout: int | None = None, refresh_every: int = 5) -> "InferenceEndpoint": + """Wait for the Inference Endpoint to be deployed. + + Information from the server will be fetched every 1s. If the Inference Endpoint is not deployed after `timeout` + seconds, a [`InferenceEndpointTimeoutError`] will be raised. The [`InferenceEndpoint`] will be mutated in place with the latest + data. + + Args: + timeout (`int`, *optional*): + The maximum time to wait for the Inference Endpoint to be deployed, in seconds. If `None`, will wait + indefinitely. + refresh_every (`int`, *optional*): + The time to wait between each fetch of the Inference Endpoint status, in seconds. Defaults to 5s. + + Returns: + [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. + + Raises: + [`InferenceEndpointError`] + If the Inference Endpoint ended up in a failed state. + [`InferenceEndpointTimeoutError`] + If the Inference Endpoint is not deployed after `timeout` seconds. + """ + if timeout is not None and timeout < 0: + raise ValueError("`timeout` cannot be negative.") + if refresh_every <= 0: + raise ValueError("`refresh_every` must be positive.") + + start = time.time() + while True: + if self.status == InferenceEndpointStatus.FAILED: + raise InferenceEndpointError( + f"Inference Endpoint {self.name} failed to deploy. Please check the logs for more information." + ) + if self.status == InferenceEndpointStatus.UPDATE_FAILED: + raise InferenceEndpointError( + f"Inference Endpoint {self.name} failed to update. Please check the logs for more information." + ) + if self.status == InferenceEndpointStatus.RUNNING and self.url is not None: + # Verify the endpoint is actually reachable + _health_url = f"{self.url.rstrip('/')}/{self.health_route.lstrip('/')}" + response = get_session().get(_health_url, headers=self._api._build_hf_headers(token=self._token)) + if response.status_code == 200: + logger.info("Inference Endpoint is ready to be used.") + return self + + if timeout is not None: + if time.time() - start > timeout: + raise InferenceEndpointTimeoutError("Timeout while waiting for Inference Endpoint to be deployed.") + logger.info(f"Inference Endpoint is not deployed yet ({self.status}). Waiting {refresh_every}s...") + time.sleep(refresh_every) + self.fetch() + + def fetch(self) -> "InferenceEndpoint": + """Fetch latest information about the Inference Endpoint. + + Returns: + [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. + """ + obj = self._api.get_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type] + self.raw = obj.raw + self._populate_from_raw() + return self + + def update( + self, + *, + # Compute update + accelerator: str | None = None, + instance_size: str | None = None, + instance_type: str | None = None, + min_replica: int | None = None, + max_replica: int | None = None, + scale_to_zero_timeout: int | None = None, + # Model update + repository: str | None = None, + framework: str | None = None, + revision: str | None = None, + task: str | None = None, + custom_image: dict | None = None, + secrets: dict[str, str] | None = None, + ) -> "InferenceEndpoint": + """Update the Inference Endpoint. + + This method allows the update of either the compute configuration, the deployed model, or both. All arguments are + optional but at least one must be provided. + + This is an alias for [`HfApi.update_inference_endpoint`]. The current object is mutated in place with the + latest data from the server. + + Args: + accelerator (`str`, *optional*): + The hardware accelerator to be used for inference (e.g. `"cpu"`). + instance_size (`str`, *optional*): + The size or type of the instance to be used for hosting the model (e.g. `"x4"`). + instance_type (`str`, *optional*): + The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`). + min_replica (`int`, *optional*): + The minimum number of replicas (instances) to keep running for the Inference Endpoint. + max_replica (`int`, *optional*): + The maximum number of replicas (instances) to scale to for the Inference Endpoint. + scale_to_zero_timeout (`int`, *optional*): + The duration in minutes before an inactive endpoint is scaled to zero. + + repository (`str`, *optional*): + The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`). + framework (`str`, *optional*): + The machine learning framework used for the model (e.g. `"custom"`). + revision (`str`, *optional*): + The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`). + task (`str`, *optional*): + The task on which to deploy the model (e.g. `"text-classification"`). + custom_image (`dict`, *optional*): + A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an + Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples). + secrets (`dict[str, str]`, *optional*): + Secret values to inject in the container environment. + Returns: + [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. + """ + # Make API call + obj = self._api.update_inference_endpoint( + name=self.name, + namespace=self.namespace, + accelerator=accelerator, + instance_size=instance_size, + instance_type=instance_type, + min_replica=min_replica, + max_replica=max_replica, + scale_to_zero_timeout=scale_to_zero_timeout, + repository=repository, + framework=framework, + revision=revision, + task=task, + custom_image=custom_image, + secrets=secrets, + token=self._token, # type: ignore [arg-type] + ) + + # Mutate current object + self.raw = obj.raw + self._populate_from_raw() + return self + + def pause(self) -> "InferenceEndpoint": + """Pause the Inference Endpoint. + + A paused Inference Endpoint will not be charged. It can be resumed at any time using [`InferenceEndpoint.resume`]. + This is different from scaling the Inference Endpoint to zero with [`InferenceEndpoint.scale_to_zero`], which + would be automatically restarted when a request is made to it. + + This is an alias for [`HfApi.pause_inference_endpoint`]. The current object is mutated in place with the + latest data from the server. + + Returns: + [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. + """ + obj = self._api.pause_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type] + self.raw = obj.raw + self._populate_from_raw() + return self + + def resume(self, running_ok: bool = True) -> "InferenceEndpoint": + """Resume the Inference Endpoint. + + This is an alias for [`HfApi.resume_inference_endpoint`]. The current object is mutated in place with the + latest data from the server. + + Args: + running_ok (`bool`, *optional*): + If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to + `True`. + + Returns: + [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. + """ + obj = self._api.resume_inference_endpoint( + name=self.name, namespace=self.namespace, running_ok=running_ok, token=self._token + ) # type: ignore [arg-type] + self.raw = obj.raw + self._populate_from_raw() + return self + + def scale_to_zero(self) -> "InferenceEndpoint": + """Scale Inference Endpoint to zero. + + An Inference Endpoint scaled to zero will not be charged. It will be resumed on the next request to it, with a + cold start delay. This is different from pausing the Inference Endpoint with [`InferenceEndpoint.pause`], which + would require a manual resume with [`InferenceEndpoint.resume`]. + + This is an alias for [`HfApi.scale_to_zero_inference_endpoint`]. The current object is mutated in place with the + latest data from the server. + + Returns: + [`InferenceEndpoint`]: the same Inference Endpoint, mutated in place with the latest data. + """ + obj = self._api.scale_to_zero_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type] + self.raw = obj.raw + self._populate_from_raw() + return self + + def delete(self) -> None: + """Delete the Inference Endpoint. + + This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable + to pause it with [`InferenceEndpoint.pause`] or scale it to zero with [`InferenceEndpoint.scale_to_zero`]. + + This is an alias for [`HfApi.delete_inference_endpoint`]. + """ + self._api.delete_inference_endpoint(name=self.name, namespace=self.namespace, token=self._token) # type: ignore [arg-type] + + def _populate_from_raw(self) -> None: + """Populate fields from raw dictionary. + + Called in __post_init__ + each time the Inference Endpoint is updated. + """ + # Repr fields + self.name = self.raw["name"] + self.repository = self.raw["model"]["repository"] + self.status = self.raw["status"]["state"] + self.url = self.raw["status"].get("url") + self.health_route = self.raw["healthRoute"] + + # Other fields + self.framework = self.raw["model"]["framework"] + self.revision = self.raw["model"]["revision"] + self.task = self.raw["model"]["task"] + self.created_at = parse_datetime(self.raw["status"]["createdAt"]) + self.updated_at = parse_datetime(self.raw["status"]["updatedAt"]) + self.type = self.raw["type"] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_jobs_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_jobs_api.py new file mode 100644 index 0000000000000000000000000000000000000000..108871ce429f67c76782c89a13a845fed88027af --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_jobs_api.py @@ -0,0 +1,410 @@ +# Copyright 2025-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from datetime import datetime +from enum import Enum +from typing import Any + +from huggingface_hub import constants +from huggingface_hub._space_api import SpaceHardware, Volume +from huggingface_hub.utils._datetime import parse_datetime + + +class JobStage(str, Enum): + """ + Enumeration of possible stage of a Job on the Hub. + + Value can be compared to a string: + ```py + assert JobStage.COMPLETED == "COMPLETED" + ``` + Possible values are: `COMPLETED`, `CANCELED`, `ERROR`, `DELETED`, `RUNNING`. + Taken from https://github.com/huggingface/moon-landing/blob/main/server/job_types/JobInfo.ts#L61 (private url). + """ + + # Copied from moon-landing > server > lib > Job.ts + COMPLETED = "COMPLETED" + CANCELED = "CANCELED" + ERROR = "ERROR" + DELETED = "DELETED" + RUNNING = "RUNNING" + + +@dataclass +class JobStatus: + stage: JobStage + message: str | None + + +@dataclass +class JobOwner: + id: str + name: str + type: str + + +@dataclass +class JobInfo: + """ + Contains information about a Job. + + Args: + id (`str`): + Job ID. + created_at (`datetime` or `None`): + When the Job was created. + docker_image (`str` or `None`): + The Docker image from Docker Hub used for the Job. + Can be None if space_id is present instead. + space_id (`str` or `None`): + The Docker image from Hugging Face Spaces used for the Job. + Can be None if docker_image is present instead. + command (`list[str]` or `None`): + Command of the Job, e.g. `["python", "-c", "print('hello world')"]` + arguments (`list[str]` or `None`): + Arguments passed to the command + environment (`dict[str]` or `None`): + Environment variables of the Job as a dictionary. + secrets (`dict[str]` or `None`): + Secret environment variables of the Job (encrypted). + flavor (`str` or `None`): + Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values. + E.g. `"cpu-basic"`. + labels (`dict[str, str]` or `None`): + Labels to attach to the job (key-value pairs). + volumes (`list[Volume]` or `None`): + Volumes mounted in the job container (buckets, models, datasets, spaces). + status: (`JobStatus` or `None`): + Status of the Job, e.g. `JobStatus(stage="RUNNING", message=None)` + See [`JobStage`] for possible stage values. + owner: (`JobOwner` or `None`): + Owner of the Job, e.g. `JobOwner(id="5e9ecfc04957053f60648a3e", name="lhoestq", type="user")` + + Example: + + ```python + >>> from huggingface_hub import run_job + >>> job = run_job( + ... image="python:3.12", + ... command=["python", "-c", "print('Hello from the cloud!')"] + ... ) + >>> job + JobInfo(id='687fb701029421ae5549d998', created_at=datetime.datetime(2025, 7, 22, 16, 6, 25, 79000, tzinfo=datetime.timezone.utc), docker_image='python:3.12', space_id=None, command=['python', '-c', "print('Hello from the cloud!')"], arguments=[], environment={}, secrets={}, flavor='cpu-basic', labels=None, status=JobStatus(stage='RUNNING', message=None), owner=JobOwner(id='5e9ecfc04957053f60648a3e', name='lhoestq', type='user'), endpoint='https://huggingface.co', url='https://huggingface.co/jobs/lhoestq/687fb701029421ae5549d998') + >>> job.id + '687fb701029421ae5549d998' + >>> job.url + 'https://huggingface.co/jobs/lhoestq/687fb701029421ae5549d998' + >>> job.status.stage + 'RUNNING' + ``` + """ + + id: str + created_at: datetime | None + docker_image: str | None + space_id: str | None + command: list[str] | None + arguments: list[str] | None + environment: dict[str, Any] | None + secrets: dict[str, Any] | None + flavor: SpaceHardware | None + labels: dict[str, str] | None + volumes: list[Volume] | None + status: JobStatus + owner: JobOwner + + # Inferred fields + endpoint: str + url: str + + def __init__(self, **kwargs) -> None: + self.id = kwargs["id"] + created_at = kwargs.get("createdAt") or kwargs.get("created_at") + self.created_at = parse_datetime(created_at) if created_at else None + self.docker_image = kwargs.get("dockerImage") or kwargs.get("docker_image") + self.space_id = kwargs.get("spaceId") or kwargs.get("space_id") + owner = kwargs.get("owner", {}) + self.owner = JobOwner(id=owner["id"], name=owner["name"], type=owner["type"]) + self.command = kwargs.get("command") + self.arguments = kwargs.get("arguments") + self.environment = kwargs.get("environment") + self.secrets = kwargs.get("secrets") + self.flavor = kwargs.get("flavor") + self.labels = kwargs.get("labels") + volumes = kwargs.get("volumes") + self.volumes = [Volume(**v) for v in volumes] if volumes else None + status = kwargs.get("status", {}) + self.status = JobStatus(stage=status["stage"], message=status.get("message")) + + # Inferred fields + self.endpoint = kwargs.get("endpoint", constants.ENDPOINT) + self.url = f"{self.endpoint}/jobs/{self.owner.name}/{self.id}" + + +@dataclass +class JobSpec: + docker_image: str | None + space_id: str | None + command: list[str] | None + arguments: list[str] | None + environment: dict[str, Any] | None + secrets: dict[str, Any] | None + flavor: SpaceHardware | None + timeout: int | None + tags: list[str] | None + arch: str | None + labels: dict[str, str] | None + volumes: list[Volume] | None + + def __init__(self, **kwargs) -> None: + self.docker_image = kwargs.get("dockerImage") or kwargs.get("docker_image") + self.space_id = kwargs.get("spaceId") or kwargs.get("space_id") + self.command = kwargs.get("command") + self.arguments = kwargs.get("arguments") + self.environment = kwargs.get("environment") + self.secrets = kwargs.get("secrets") + self.flavor = kwargs.get("flavor") + self.timeout = kwargs.get("timeout") + self.tags = kwargs.get("tags") + self.arch = kwargs.get("arch") + self.labels = kwargs.get("labels") + volumes = kwargs.get("volumes") + self.volumes = [Volume(**v) for v in volumes] if volumes else None + + +@dataclass +class LastJobInfo: + id: str + at: datetime + + def __init__(self, **kwargs) -> None: + self.id = kwargs["id"] + self.at = parse_datetime(kwargs["at"]) + + +@dataclass +class ScheduledJobStatus: + last_job: LastJobInfo | None + next_job_run_at: datetime | None + + def __init__(self, **kwargs) -> None: + last_job = kwargs.get("lastJob") or kwargs.get("last_job") + self.last_job = LastJobInfo(**last_job) if last_job else None + next_job_run_at = kwargs.get("nextJobRunAt") or kwargs.get("next_job_run_at") + self.next_job_run_at = parse_datetime(str(next_job_run_at)) if next_job_run_at else None + + +@dataclass +class ScheduledJobInfo: + """ + Contains information about a Job. + + Args: + id (`str`): + Scheduled Job ID. + created_at (`datetime` or `None`): + When the scheduled Job was created. + tags (`list[str]` or `None`): + The tags of the scheduled Job. + schedule (`str` or `None`): + One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a + CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday). + suspend (`bool` or `None`): + Whether the scheduled job is suspended (paused). + concurrency (`bool` or `None`): + Whether multiple instances of this Job can run concurrently. + status (`ScheduledJobStatus` or `None`): + Status of the scheduled Job. + owner: (`JobOwner` or `None`): + Owner of the scheduled Job, e.g. `JobOwner(id="5e9ecfc04957053f60648a3e", name="lhoestq", type="user")` + job_spec: (`JobSpec` or `None`): + Specifications of the Job. + + Example: + + ```python + >>> from huggingface_hub import run_job + >>> scheduled_job = create_scheduled_job( + ... image="python:3.12", + ... command=["python", "-c", "print('Hello from the cloud!')"], + ... schedule="@hourly", + ... ) + >>> scheduled_job.id + '687fb701029421ae5549d999' + >>> scheduled_job.status.next_job_run_at + datetime.datetime(2025, 7, 22, 17, 6, 25, 79000, tzinfo=datetime.timezone.utc) + ``` + """ + + id: str + created_at: datetime | None + job_spec: JobSpec + schedule: str | None + suspend: bool | None + concurrency: bool | None + status: ScheduledJobStatus + owner: JobOwner + + def __init__(self, **kwargs) -> None: + self.id = kwargs["id"] + created_at = kwargs.get("createdAt") or kwargs.get("created_at") + self.created_at = parse_datetime(created_at) if created_at else None + self.job_spec = JobSpec(**(kwargs.get("job_spec") or kwargs.get("jobSpec", {}))) + self.schedule = kwargs.get("schedule") + self.suspend = kwargs.get("suspend") + self.concurrency = kwargs.get("concurrency") + status = kwargs.get("status", {}) + self.status = ScheduledJobStatus( + last_job=status.get("last_job") or status.get("lastJob"), + next_job_run_at=status.get("next_job_run_at") or status.get("nextJobRunAt"), + ) + owner = kwargs.get("owner", {}) + self.owner = JobOwner(id=owner["id"], name=owner["name"], type=owner["type"]) + + +@dataclass +class JobAccelerator: + """ + Contains information about a Job accelerator (GPU). + + Args: + type (`str`): + Type of accelerator, e.g. `"gpu"`. + model (`str`): + Model of accelerator, e.g. `"T4"`, `"A10G"`, `"A100"`, `"L4"`, `"L40S"`. + quantity (`str`): + Number of accelerators, e.g. `"1"`, `"2"`, `"4"`, `"8"`. + vram (`str`): + Total VRAM, e.g. `"16 GB"`, `"24 GB"`. + manufacturer (`str`): + Manufacturer of the accelerator, e.g. `"Nvidia"`. + """ + + type: str + model: str + quantity: str + vram: str + manufacturer: str + + def __init__(self, **kwargs) -> None: + self.type = kwargs["type"] + self.model = kwargs["model"] + self.quantity = kwargs["quantity"] + self.vram = kwargs["vram"] + self.manufacturer = kwargs["manufacturer"] + + +@dataclass +class JobHardware: + """ + Contains information about available Job hardware. + + Args: + name (`str`): + Machine identifier, e.g. `"cpu-basic"`, `"a10g-large"`. + pretty_name (`str`): + Human-readable name, e.g. `"CPU Basic"`, `"Nvidia A10G - large"`. + cpu (`str`): + CPU specification, e.g. `"2 vCPU"`, `"12 vCPU"`. + ram (`str`): + RAM specification, e.g. `"16 GB"`, `"46 GB"`. + accelerator (`JobAccelerator` or `None`): + GPU/accelerator details if available. + unit_cost_micro_usd (`int`): + Cost in micro-dollars per unit, e.g. `167` (= $0.000167). + unit_cost_usd (`float`): + Cost in USD per unit, e.g. `0.000167`. + unit_label (`str`): + Cost unit period, e.g. `"minute"`. + + Example: + + ```python + >>> from huggingface_hub import list_jobs_hardware + >>> hardware_list = list_jobs_hardware() + >>> hardware_list[0] + JobHardware(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute') + >>> hardware_list[0].name + 'cpu-basic' + ``` + """ + + name: str + pretty_name: str + cpu: str + ram: str + accelerator: JobAccelerator | None + unit_cost_micro_usd: int + unit_cost_usd: float + unit_label: str + + def __init__(self, **kwargs) -> None: + self.name = kwargs["name"] + self.pretty_name = kwargs["prettyName"] + self.cpu = kwargs["cpu"] + self.ram = kwargs["ram"] + accelerator = kwargs.get("accelerator") + self.accelerator = JobAccelerator(**accelerator) if accelerator else None + self.unit_cost_micro_usd = kwargs["unitCostMicroUSD"] + self.unit_cost_usd = kwargs["unitCostUSD"] + self.unit_label = kwargs["unitLabel"] + + +def _create_job_spec( + *, + image: str, + command: list[str], + env: dict[str, Any] | None, + secrets: dict[str, Any] | None, + flavor: SpaceHardware | None, + timeout: int | float | str | None, + labels: dict[str, str] | None = None, + volumes: list[Volume] | None = None, +) -> dict[str, Any]: + # prepare job spec to send to HF Jobs API + job_spec: dict[str, Any] = { + "command": command, + "arguments": [], + "environment": env or {}, + "flavor": flavor or SpaceHardware.CPU_BASIC, + } + # secrets are optional + if secrets: + job_spec["secrets"] = secrets + # timeout is optional + if timeout: + time_units_factors = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24} + if isinstance(timeout, str) and timeout[-1] in time_units_factors: + job_spec["timeoutSeconds"] = int(float(timeout[:-1]) * time_units_factors[timeout[-1]]) + else: + job_spec["timeoutSeconds"] = int(timeout) + # labels are optional + if labels: + job_spec["labels"] = labels + # volumes are optional + if volumes: + job_spec["volumes"] = [vol.to_dict() for vol in volumes] + # input is either from docker hub or from HF spaces + for prefix in ( + "https://huggingface.co/spaces/", + "https://hf.co/spaces/", + "huggingface.co/spaces/", + "hf.co/spaces/", + ): + if image.startswith(prefix): + job_spec["spaceId"] = image[len(prefix) :] + break + else: + job_spec["dockerImage"] = image + return job_spec diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_local_folder.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_local_folder.py new file mode 100644 index 0000000000000000000000000000000000000000..2e60361293d0bd45b8a877e55291882144279e42 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_local_folder.py @@ -0,0 +1,473 @@ +# Copyright 2024-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains utilities to handle the `../.cache/huggingface` folder in local directories. + +First discussed in https://github.com/huggingface/huggingface_hub/issues/1738 to store +download metadata when downloading files from the hub to a local directory (without +using the cache). + +./.cache/huggingface folder structure: +[4.0K] data +├── [4.0K] .cache +│ └── [4.0K] huggingface +│ └── [4.0K] download +│ ├── [ 16] file.parquet.metadata +│ ├── [ 16] file.txt.metadata +│ └── [4.0K] folder +│ └── [ 16] file.parquet.metadata +│ +├── [6.5G] file.parquet +├── [1.5K] file.txt +└── [4.0K] folder + └── [ 16] file.parquet + + +Download metadata file structure: +``` +# file.txt.metadata +11c5a3d5811f50298f278a704980280950aedb10 +a16a55fda99d2f2e7b69cce5cf93ff4ad3049930 +1712656091.123 + +# file.parquet.metadata +11c5a3d5811f50298f278a704980280950aedb10 +7c5d3f4b8b76583b422fcb9189ad6c89d5d97a094541ce8932dce3ecabde1421 +1712656091.123 +} +``` +""" + +import base64 +import hashlib +import logging +import os +import time +from dataclasses import dataclass +from pathlib import Path + +from .utils import WeakFileLock + + +logger = logging.getLogger(__name__) + +CACHEDIR_TAG_CONTENT = ( + "Signature: 8a477f597d28d172789f06886806bc55\n" + "# This file is a cache directory tag created by huggingface_hub.\n" + "# For information about cache directory tags, see:\n" + "#\thttps://bford.info/cachedir/\n" +) + + +@dataclass +class LocalDownloadFilePaths: + """ + Paths to the files related to a download process in a local dir. + + Returned by [`get_local_download_paths`]. + + Attributes: + file_path (`Path`): + Path where the file will be saved. + lock_path (`Path`): + Path to the lock file used to ensure atomicity when reading/writing metadata. + metadata_path (`Path`): + Path to the metadata file. + """ + + file_path: Path + lock_path: Path + metadata_path: Path + + def incomplete_path(self, etag: str) -> Path: + """Return the path where a file will be temporarily downloaded before being moved to `file_path`.""" + path = self.metadata_path.parent / f"{_short_hash(self.metadata_path.name)}.{etag}.incomplete" + resolved_path = str(path.resolve()) + # Some Windows versions do not allow for paths longer than 255 characters. + # In this case, we must specify it as an extended path by using the "\\?\" prefix. + if os.name == "nt" and len(resolved_path) > 255 and not resolved_path.startswith("\\\\?\\"): + path = Path("\\\\?\\" + resolved_path) + return path + + +@dataclass(frozen=True) +class LocalUploadFilePaths: + """ + Paths to the files related to an upload process in a local dir. + + Returned by [`get_local_upload_paths`]. + + Attributes: + path_in_repo (`str`): + Path of the file in the repo. + file_path (`Path`): + Path where the file will be saved. + lock_path (`Path`): + Path to the lock file used to ensure atomicity when reading/writing metadata. + metadata_path (`Path`): + Path to the metadata file. + """ + + path_in_repo: str + file_path: Path + lock_path: Path + metadata_path: Path + + +@dataclass +class LocalDownloadFileMetadata: + """ + Metadata about a file in the local directory related to a download process. + + Attributes: + filename (`str`): + Path of the file in the repo. + commit_hash (`str`): + Commit hash of the file in the repo. + etag (`str`): + ETag of the file in the repo. Used to check if the file has changed. + For LFS files, this is the sha256 of the file. For regular files, it corresponds to the git hash. + timestamp (`int`): + Unix timestamp of when the metadata was saved i.e. when the metadata was accurate. + """ + + filename: str + commit_hash: str + etag: str + timestamp: float + + +@dataclass +class LocalUploadFileMetadata: + """ + Metadata about a file in the local directory related to an upload process. + """ + + size: int + + # Default values correspond to "we don't know yet" + timestamp: float | None = None + should_ignore: bool | None = None + sha256: str | None = None + upload_mode: str | None = None + remote_oid: str | None = None + is_uploaded: bool = False + is_committed: bool = False + + def save(self, paths: LocalUploadFilePaths) -> None: + """Save the metadata to disk.""" + with WeakFileLock(paths.lock_path): + with paths.metadata_path.open("w") as f: + new_timestamp = time.time() + f.write(str(new_timestamp) + "\n") + + f.write(str(self.size)) # never None + f.write("\n") + + if self.should_ignore is not None: + f.write(str(int(self.should_ignore))) + f.write("\n") + + if self.sha256 is not None: + f.write(self.sha256) + f.write("\n") + + if self.upload_mode is not None: + f.write(self.upload_mode) + f.write("\n") + + if self.remote_oid is not None: + f.write(self.remote_oid) + f.write("\n") + + f.write(str(int(self.is_uploaded)) + "\n") + f.write(str(int(self.is_committed)) + "\n") + + self.timestamp = new_timestamp + + +def get_local_download_paths(local_dir: Path, filename: str) -> LocalDownloadFilePaths: + """Compute paths to the files related to a download process. + + Folders containing the paths are all guaranteed to exist. + + Args: + local_dir (`Path`): + Path to the local directory in which files are downloaded. + filename (`str`): + Path of the file in the repo. + + Return: + [`LocalDownloadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path, incomplete_path). + """ + # filename is the path in the Hub repository (separated by '/') + # make sure to have a cross-platform transcription + sanitized_filename = os.path.join(*filename.split("/")) + if os.name == "nt": + if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename: + raise ValueError( + f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository" + " owner to rename this file." + ) + file_path = local_dir / sanitized_filename + metadata_path = _huggingface_dir(local_dir) / "download" / f"{sanitized_filename}.metadata" + lock_path = metadata_path.with_suffix(".lock") + + # Some Windows versions do not allow for paths longer than 255 characters. + # In this case, we must specify it as an extended path by using the "\\?\" prefix + if os.name == "nt": + if not str(local_dir).startswith("\\\\?\\") and len(os.path.abspath(lock_path)) > 255: + file_path = Path("\\\\?\\" + os.path.abspath(file_path)) + lock_path = Path("\\\\?\\" + os.path.abspath(lock_path)) + metadata_path = Path("\\\\?\\" + os.path.abspath(metadata_path)) + + file_path.parent.mkdir(parents=True, exist_ok=True) + metadata_path.parent.mkdir(parents=True, exist_ok=True) + return LocalDownloadFilePaths(file_path=file_path, lock_path=lock_path, metadata_path=metadata_path) + + +def get_local_upload_paths(local_dir: Path, filename: str) -> LocalUploadFilePaths: + """Compute paths to the files related to an upload process. + + Folders containing the paths are all guaranteed to exist. + + Args: + local_dir (`Path`): + Path to the local directory that is uploaded. + filename (`str`): + Path of the file in the repo. + + Return: + [`LocalUploadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path). + """ + # filename is the path in the Hub repository (separated by '/') + # make sure to have a cross-platform transcription + sanitized_filename = os.path.join(*filename.split("/")) + if os.name == "nt": + if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename: + raise ValueError( + f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository" + " owner to rename this file." + ) + file_path = local_dir / sanitized_filename + metadata_path = _huggingface_dir(local_dir) / "upload" / f"{sanitized_filename}.metadata" + lock_path = metadata_path.with_suffix(".lock") + + # Some Windows versions do not allow for paths longer than 255 characters. + # In this case, we must specify it as an extended path by using the "\\?\" prefix + if os.name == "nt": + if not str(local_dir).startswith("\\\\?\\") and len(os.path.abspath(lock_path)) > 255: + file_path = Path("\\\\?\\" + os.path.abspath(file_path)) + lock_path = Path("\\\\?\\" + os.path.abspath(lock_path)) + metadata_path = Path("\\\\?\\" + os.path.abspath(metadata_path)) + + file_path.parent.mkdir(parents=True, exist_ok=True) + metadata_path.parent.mkdir(parents=True, exist_ok=True) + return LocalUploadFilePaths( + path_in_repo=filename, file_path=file_path, lock_path=lock_path, metadata_path=metadata_path + ) + + +def read_download_metadata(local_dir: Path, filename: str) -> LocalDownloadFileMetadata | None: + """Read metadata about a file in the local directory related to a download process. + + Args: + local_dir (`Path`): + Path to the local directory in which files are downloaded. + filename (`str`): + Path of the file in the repo. + + Return: + `[LocalDownloadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise. + """ + paths = get_local_download_paths(local_dir, filename) + with WeakFileLock(paths.lock_path): + if paths.metadata_path.exists(): + try: + with paths.metadata_path.open() as f: + commit_hash = f.readline().strip() + etag = f.readline().strip() + timestamp = float(f.readline().strip()) + metadata = LocalDownloadFileMetadata( + filename=filename, + commit_hash=commit_hash, + etag=etag, + timestamp=timestamp, + ) + except Exception as e: + # remove the metadata file if it is corrupted / not the right format + logger.warning( + f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue." + ) + try: + paths.metadata_path.unlink() + except Exception as e: + logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}") + return None + + try: + # check if the file exists and hasn't been modified since the metadata was saved + stat = paths.file_path.stat() + if ( + stat.st_mtime - 1 <= metadata.timestamp + ): # allow 1s difference as stat.st_mtime might not be precise + return metadata + logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.") + except FileNotFoundError: + # file does not exist => metadata is outdated + return None + return None + + +def read_upload_metadata(local_dir: Path, filename: str) -> LocalUploadFileMetadata: + """Read metadata about a file in the local directory related to an upload process. + + TODO: factorize logic with `read_download_metadata`. + + Args: + local_dir (`Path`): + Path to the local directory in which files are downloaded. + filename (`str`): + Path of the file in the repo. + + Return: + `[LocalUploadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise. + """ + paths = get_local_upload_paths(local_dir, filename) + with WeakFileLock(paths.lock_path): + if paths.metadata_path.exists(): + try: + with paths.metadata_path.open() as f: + timestamp = float(f.readline().strip()) + + size = int(f.readline().strip()) # never None + + _should_ignore = f.readline().strip() + should_ignore = None if _should_ignore == "" else bool(int(_should_ignore)) + + _sha256 = f.readline().strip() + sha256 = None if _sha256 == "" else _sha256 + + _upload_mode = f.readline().strip() + upload_mode = None if _upload_mode == "" else _upload_mode + if upload_mode not in (None, "regular", "lfs"): + raise ValueError(f"Invalid upload mode in metadata {paths.path_in_repo}: {upload_mode}") + + _remote_oid = f.readline().strip() + remote_oid = None if _remote_oid == "" else _remote_oid + + is_uploaded = bool(int(f.readline().strip())) + is_committed = bool(int(f.readline().strip())) + + metadata = LocalUploadFileMetadata( + timestamp=timestamp, + size=size, + should_ignore=should_ignore, + sha256=sha256, + upload_mode=upload_mode, + remote_oid=remote_oid, + is_uploaded=is_uploaded, + is_committed=is_committed, + ) + except Exception as e: + # remove the metadata file if it is corrupted / not the right format + logger.warning( + f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue." + ) + try: + paths.metadata_path.unlink() + except Exception as e: + logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}") + + # corrupted metadata => we don't know anything expect its size + return LocalUploadFileMetadata(size=paths.file_path.stat().st_size) + + # TODO: can we do better? + if ( + metadata.timestamp is not None + and metadata.is_uploaded # file was uploaded + and not metadata.is_committed # but not committed + and time.time() - metadata.timestamp > 20 * 3600 # and it's been more than 20 hours + ): # => we consider it as garbage-collected by S3 + metadata.is_uploaded = False + + # check if the file exists and hasn't been modified since the metadata was saved + try: + if metadata.timestamp is not None and paths.file_path.stat().st_mtime <= metadata.timestamp: + return metadata + logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.") + except FileNotFoundError: + # file does not exist => metadata is outdated + pass + + # empty metadata => we don't know anything expect its size + return LocalUploadFileMetadata(size=paths.file_path.stat().st_size) + + +def write_download_metadata(local_dir: Path, filename: str, commit_hash: str, etag: str) -> None: + """Write metadata about a file in the local directory related to a download process. + + Args: + local_dir (`Path`): + Path to the local directory in which files are downloaded. + """ + paths = get_local_download_paths(local_dir, filename) + with WeakFileLock(paths.lock_path): + with paths.metadata_path.open("w") as f: + f.write(f"{commit_hash}\n{etag}\n{time.time()}\n") + + +def _huggingface_dir(local_dir: Path) -> Path: + """Return the path to the `.cache/huggingface` directory in a local directory.""" + # Wrap in lru_cache to avoid overwriting the .gitignore file if called multiple times + path = local_dir / ".cache" / "huggingface" + path.mkdir(exist_ok=True, parents=True) + + # Create a CACHEDIR.TAG so backup tools can skip this directory. + _create_cachedir_tag(path) + + # Create a .gitignore file in the .cache/huggingface directory if it doesn't exist + # Should be thread-safe enough like this. + gitignore = path / ".gitignore" + gitignore_lock = path / ".gitignore.lock" + if not gitignore.exists(): + try: + with WeakFileLock(gitignore_lock, timeout=0.1): + gitignore.write_text("*") + except IndexError: + pass + except OSError: # TimeoutError, FileNotFoundError, PermissionError, etc. + pass + try: + gitignore_lock.unlink() + except OSError: + pass + return path + + +def _create_cachedir_tag(cache_dir: Path) -> None: + """Create a CACHEDIR.TAG file in ``cache_dir`` if one does not already exist. + + The tag follows the `Cache Directory Tagging Standard `_ + so that backup tools can recognize and skip cache directories. + """ + tag_path = cache_dir / "CACHEDIR.TAG" + if not tag_path.exists(): + try: + tag_path.write_text(CACHEDIR_TAG_CONTENT) + except OSError: + pass + + +def _short_hash(filename: str) -> str: + return base64.urlsafe_b64encode(hashlib.sha1(filename.encode()).digest()).decode() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_login.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_login.py new file mode 100644 index 0000000000000000000000000000000000000000..1e358d355c1e9ed92944c553e9c1edd56d2f8a96 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_login.py @@ -0,0 +1,494 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains methods to log in to the Hub.""" + +import os +import subprocess +from getpass import getpass +from pathlib import Path + +import typer + +from . import constants +from .utils import ( + ANSI, + capture_output, + get_token, + is_google_colab, + is_notebook, + list_credential_helpers, + logging, + run_subprocess, + set_git_credential, + unset_git_credential, +) +from .utils._auth import ( + _get_token_by_name, + _get_token_from_environment, + _get_token_from_file, + _get_token_from_google_colab, + _save_stored_tokens, + _save_token, + get_stored_tokens, +) + + +logger = logging.get_logger(__name__) + +_HF_LOGO_ASCII = """ + _| _| _| _| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _|_|_|_| _|_| _|_|_| _|_|_|_| + _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _| + _|_|_|_| _| _| _| _|_| _| _|_| _| _| _| _| _| _|_| _|_|_| _|_|_|_| _| _|_|_| + _| _| _| _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _| + _| _| _|_| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _| _| _| _|_|_| _|_|_|_| +""" + + +def login( + token: str | None = None, + *, + add_to_git_credential: bool = False, + skip_if_logged_in: bool = True, +) -> None: + """Login the machine to access the Hub. + + The `token` is persisted in cache and set as a git credential. Once done, the machine + is logged in and the access token will be available across all `huggingface_hub` + components. If `token` is not provided, it will be prompted to the user either with + a widget (in a notebook) or via the terminal. + + To log in from outside of a script, one can also use `hf auth login` which is + a cli command that wraps [`login`]. + + > [!TIP] + > [`login`] is a drop-in replacement method for [`notebook_login`] as it wraps and + > extends its capabilities. + + > [!TIP] + > When the token is not passed, [`login`] will automatically detect if the script runs + > in a notebook or not. However, this detection might not be accurate due to the + > variety of notebooks that exists nowadays. If that is the case, you can always force + > the UI by using [`notebook_login`] or [`interpreter_login`]. + + Args: + token (`str`, *optional*): + User access token to generate from https://huggingface.co/settings/token. + add_to_git_credential (`bool`, defaults to `False`): + If `True`, token will be set as git credential. If no git credential helper + is configured, a warning will be displayed to the user. If `token` is `None`, + the value of `add_to_git_credential` is ignored and will be prompted again + to the end user. + skip_if_logged_in (`bool`, defaults to `True`): + If `True`, do not prompt for token if user is already logged in. + Set to `False` to force re-login. In CLI, use `--force` instead. + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If an organization token is passed. Only personal account tokens are valid + to log in. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If token is invalid. + [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError) + If running in a notebook but `ipywidgets` is not installed. + """ + if token is not None: + if not add_to_git_credential: + logger.info( + "The token has not been saved to the git credentials helper. Pass " + "`add_to_git_credential=True` in this function directly or " + "`--add-to-git-credential` if using via `hf`CLI if " + "you want to set the git credential as well." + ) + _login(token, add_to_git_credential=add_to_git_credential) + elif is_notebook(): + notebook_login(skip_if_logged_in=skip_if_logged_in) + else: + interpreter_login(skip_if_logged_in=skip_if_logged_in) + + +def logout(token_name: str | None = None) -> None: + """Logout the machine from the Hub. + + Token is deleted from the machine and removed from git credential. + + Args: + token_name (`str`, *optional*): + Name of the access token to logout from. If `None`, will log out from all saved access tokens. + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError): + If the access token name is not found. + """ + if get_token() is None and not get_stored_tokens(): # No active token and no saved access tokens + logger.warning("Not logged in!") + return + if not token_name: + # Delete all saved access tokens and token + for file_path in (constants.HF_TOKEN_PATH, constants.HF_STORED_TOKENS_PATH): + try: + Path(file_path).unlink() + except FileNotFoundError: + pass + logger.info("Successfully logged out from all access tokens.") + else: + _logout_from_token(token_name) + logger.info(f"Successfully logged out from access token: {token_name}.") + + unset_git_credential() + + # Check if still logged in + if _get_token_from_google_colab() is not None: + raise OSError( + "You are automatically logged in using a Google Colab secret.\n" + "To log out, you must unset the `HF_TOKEN` secret in your Colab settings." + ) + if _get_token_from_environment() is not None: + raise OSError( + "Token has been deleted from your machine but you are still logged in.\n" + "To log out, you must clear out both `HF_TOKEN` and `HUGGING_FACE_HUB_TOKEN` environment variables." + ) + + +def auth_switch(token_name: str, add_to_git_credential: bool = False) -> None: + """Switch to a different access token. + + Args: + token_name (`str`): + Name of the access token to switch to. + add_to_git_credential (`bool`, defaults to `False`): + If `True`, token will be set as git credential. If no git credential helper + is configured, a warning will be displayed to the user. If `token` is `None`, + the value of `add_to_git_credential` is ignored and will be prompted again + to the end user. + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError): + If the access token name is not found. + """ + token = _get_token_by_name(token_name) + if not token: + raise ValueError(f"Access token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}") + # Write token to HF_TOKEN_PATH + _set_active_token(token_name, add_to_git_credential) + logger.info(f"The current active token is: {token_name}") + token_from_environment = _get_token_from_environment() + if token_from_environment is not None and token_from_environment != token: + logger.warning( + "The environment variable `HF_TOKEN` is set and will override the access token you've just switched to." + ) + + +def auth_list() -> None: + """List all stored access tokens.""" + tokens = get_stored_tokens() + + if not tokens: + if _get_token_from_environment(): + logger.info("No stored access tokens found.") + logger.warning("Note: Environment variable `HF_TOKEN` is set and is the current active token.") + else: + logger.info("No access tokens found.") + return + # Find current token + current_token = get_token() + current_token_name = None + for token_name in tokens: + if tokens.get(token_name) == current_token: + current_token_name = token_name + # Print header + max_offset = max(len("token"), max(len(token) for token in tokens)) + 2 + print(f" {{:<{max_offset}}}| {{:<15}}".format("name", "token")) + print("-" * (max_offset + 2) + "|" + "-" * 15) + + # Print saved access tokens + for token_name in tokens: + token = tokens.get(token_name, "") + masked_token = f"{token[:3]}****{token[-4:]}" if token != "" else token + is_current = "*" if token == current_token else " " + + print(f"{is_current} {{:<{max_offset}}}| {{:<15}}".format(token_name, masked_token)) + + if _get_token_from_environment(): + logger.warning( + "\nNote: Environment variable `HF_TOKEN` is set and is the current active token independently from the stored tokens listed above." + ) + elif current_token_name is None: + logger.warning( + "\nNote: No active token is set and no environment variable `HF_TOKEN` is found. Use `hf auth login` to log in." + ) + + +### +# Interpreter-based login (text) +### + + +def interpreter_login(*, skip_if_logged_in: bool = True) -> None: + """ + Displays a prompt to log in to the HF website and store the token. + + This is equivalent to [`login`] without passing a token when not run in a notebook. + [`interpreter_login`] is useful if you want to force the use of the terminal prompt + instead of a notebook widget. + + For more details, see [`login`]. + + Args: + skip_if_logged_in (`bool`, defaults to `True`): + If `True`, do not prompt for token if user is already logged in. + Set to `False` to force re-login. In CLI, use `--force` instead. + """ + if skip_if_logged_in and get_token() is not None: + logger.info("User is already logged in. Use `hf auth login --force` to force re-login.") + return + + print(_HF_LOGO_ASCII) + if get_token() is not None: + logger.info( + " A token is already saved on your machine. Run `hf auth whoami`" + " to get more information or `hf auth logout` if you want" + " to log out." + ) + logger.info(" Setting a new token will erase the existing one.") + + logger.info( + " To log in, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens ." + ) + if os.name == "nt": + logger.info("Token can be pasted using 'Right-Click'.") + token = getpass("Enter your token (input will not be visible): ") + add_to_git_credential = typer.confirm("Add token as git credential?") + + _login(token=token, add_to_git_credential=add_to_git_credential) + + +### +# Notebook-based login (widget) +### + +NOTEBOOK_LOGIN_PASSWORD_HTML = """

Immediately click login after typing your password or +it might be stored in plain text in this notebook file.
""" + + +NOTEBOOK_LOGIN_TOKEN_HTML_START = """

Copy a token from your Hugging Face +tokens page and paste it below.
Immediately click login after copying +your token or it might be stored in plain text in this notebook file.
""" + + +NOTEBOOK_LOGIN_TOKEN_HTML_END = """ +Pro Tip: If you don't already have one, you can create a dedicated +'notebooks' token with 'write' access, that you can then easily reuse for all +notebooks. """ + + +def notebook_login(*, skip_if_logged_in: bool = True) -> None: + """ + Displays a widget to log in to the HF website and store the token. + + This is equivalent to [`login`] without passing a token when run in a notebook. + [`notebook_login`] is useful if you want to force the use of the notebook widget + instead of a prompt in the terminal. + + For more details, see [`login`]. + + Args: + skip_if_logged_in (`bool`, defaults to `True`): + If `True`, do not prompt for token if user is already logged in. + Set to `False` to force re-login. In CLI, use `--force` instead. + """ + try: + import ipywidgets.widgets as widgets # type: ignore + from IPython.display import display # type: ignore + except ImportError: + raise ImportError( + "The `notebook_login` function can only be used in a notebook (Jupyter or" + " Colab) and you need the `ipywidgets` module: `pip install ipywidgets`." + ) + if skip_if_logged_in and get_token() is not None: + logger.info("User is already logged in. Use `hf auth login --force` to force re-login.") + return + + box_layout = widgets.Layout(display="flex", flex_flow="column", align_items="center", width="50%") + + token_widget = widgets.Password(description="Token:") + git_checkbox_widget = widgets.Checkbox(value=True, description="Add token as git credential?") + token_finish_button = widgets.Button(description="Login") + + login_token_widget = widgets.VBox( + [ + widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_START), + token_widget, + git_checkbox_widget, + token_finish_button, + widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_END), + ], + layout=box_layout, + ) + display(login_token_widget) + + # On click events + def login_token_event(t): + """Event handler for the login button.""" + token = token_widget.value + add_to_git_credential = git_checkbox_widget.value + # Erase token and clear value to make sure it's not saved in the notebook. + token_widget.value = "" + # Hide inputs + login_token_widget.children = [widgets.Label("Connecting...")] + try: + with capture_output() as captured: + _login(token, add_to_git_credential=add_to_git_credential) + message = captured.getvalue() + except Exception as error: + message = str(error) + # Print result (success message or error) + login_token_widget.children = [widgets.Label(line) for line in message.split("\n") if line.strip()] + + token_finish_button.on_click(login_token_event) + + +### +# Login private helpers +### + + +def _login( + token: str, + add_to_git_credential: bool, +) -> None: + from .hf_api import whoami # avoid circular import + + if token.startswith("api_org"): + raise ValueError("You must use your personal account token, not an organization token.") + + token_info = whoami(token) + permission = token_info["auth"]["accessToken"]["role"] + logger.info(f"Token is valid (permission: {permission}).") + + token_name = token_info["auth"]["accessToken"]["displayName"] + # Store token locally + _save_token(token=token, token_name=token_name) + # Set active token + _set_active_token(token_name=token_name, add_to_git_credential=add_to_git_credential) + logger.info("Login successful.") + if _get_token_from_environment(): + logger.warning( + "Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured." + ) + else: + logger.info(f"The current active token is: `{token_name}`") + + +def _logout_from_token(token_name: str) -> None: + """Logout from a specific access token. + + Args: + token_name (`str`): + The name of the access token to logout from. + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError): + If the access token name is not found. + """ + stored_tokens = get_stored_tokens() + # If there is no access tokens saved or the access token name is not found, do nothing + if not stored_tokens or token_name not in stored_tokens: + return + + token = stored_tokens.pop(token_name) + _save_stored_tokens(stored_tokens) + + if token == _get_token_from_file(): + logger.warning(f"Active token '{token_name}' has been deleted.") + Path(constants.HF_TOKEN_PATH).unlink(missing_ok=True) + + +def _set_active_token( + token_name: str, + add_to_git_credential: bool, +) -> None: + """Set the active access token. + + Args: + token_name (`str`): + The name of the token to set as active. + """ + token = _get_token_by_name(token_name) + if not token: + raise ValueError(f"Token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}") + if add_to_git_credential: + if _is_git_credential_helper_configured(): + set_git_credential(token) + logger.info( + "Your token has been saved in your configured git credential helpers" + + f" ({','.join(list_credential_helpers())})." + ) + else: + logger.warning("Token has not been saved to git credential helper.") + # Write token to HF_TOKEN_PATH + path = Path(constants.HF_TOKEN_PATH) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(token) + logger.info(f"Your token has been saved to {constants.HF_TOKEN_PATH}") + + +def _is_git_credential_helper_configured() -> bool: + """Check if a git credential helper is configured. + + Warns user if not the case (except for Google Colab where "store" is set by default + by `huggingface_hub`). + """ + helpers = list_credential_helpers() + if len(helpers) > 0: + return True # Do not warn: at least 1 helper is set + + # Only in Google Colab to avoid the warning message + # See https://github.com/huggingface/huggingface_hub/issues/1043#issuecomment-1247010710 + if is_google_colab(): + _set_store_as_git_credential_helper_globally() + return True # Do not warn: "store" is used by default in Google Colab + + # Otherwise, warn user + print( + ANSI.red( + "Cannot authenticate through git-credential as no helper is defined on your" + " machine.\nYou might have to re-authenticate when pushing to the Hugging" + " Face Hub.\nRun the following command in your terminal in case you want to" + " set the 'store' credential helper as default.\n\ngit config --global" + " credential.helper store\n\nRead" + " https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for more" + " details." + ) + ) + return False + + +def _set_store_as_git_credential_helper_globally() -> None: + """Set globally the credential.helper to `store`. + + To be used only in Google Colab as we assume the user doesn't care about the git + credential config. It is the only particular case where we don't want to display the + warning message in [`notebook_login()`]. + + Related: + - https://github.com/huggingface/huggingface_hub/issues/1043 + - https://github.com/huggingface/huggingface_hub/issues/1051 + - https://git-scm.com/docs/git-credential-store + """ + try: + run_subprocess("git config --global credential.helper store") + except subprocess.CalledProcessError as exc: + raise OSError(exc.stderr) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_oauth.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_oauth.py new file mode 100644 index 0000000000000000000000000000000000000000..cac82ada87262370031740ea6d7c9234aec44de0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_oauth.py @@ -0,0 +1,460 @@ +import datetime +import hashlib +import logging +import os +import time +import urllib.parse +import warnings +from dataclasses import dataclass +from typing import TYPE_CHECKING, Literal + +from . import constants +from .hf_api import whoami +from .utils import experimental, get_token + + +logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + import fastapi + + +@dataclass +class OAuthOrgInfo: + """ + Information about an organization linked to a user logged in with OAuth. + + Attributes: + sub (`str`): + Unique identifier for the org. OpenID Connect field. + name (`str`): + The org's full name. OpenID Connect field. + preferred_username (`str`): + The org's username. OpenID Connect field. + picture (`str`): + The org's profile picture URL. OpenID Connect field. + plan (`str`, *optional*): + The org's plan (e.g., "enterprise", "team"). Hugging Face field. + can_pay (`Optional[bool]`, *optional*): + Whether the org has a payment method set up. Hugging Face field. + role_in_org (`Optional[str]`, *optional*): + The user's role in the org. Hugging Face field. + security_restrictions (`Optional[list[Literal["ip", "token-policy", "mfa", "sso"]]]`, *optional*): + Array of security restrictions that the user hasn't completed for this org. Possible values: "ip", "token-policy", "mfa", "sso". Hugging Face field. + """ + + sub: str + name: str + preferred_username: str + picture: str + plan: str | None = None + can_pay: bool | None = None + role_in_org: str | None = None + security_restrictions: list[Literal["ip", "token-policy", "mfa", "sso"]] | None = None + + +@dataclass +class OAuthUserInfo: + """ + Information about a user logged in with OAuth. + + Attributes: + sub (`str`): + Unique identifier for the user, even in case of rename. OpenID Connect field. + name (`str`): + The user's full name. OpenID Connect field. + preferred_username (`str`): + The user's username. OpenID Connect field. + email_verified (`Optional[bool]`, *optional*): + Indicates if the user's email is verified. OpenID Connect field. + email (`Optional[str]`, *optional*): + The user's email address. OpenID Connect field. + picture (`str`): + The user's profile picture URL. OpenID Connect field. + profile (`str`): + The user's profile URL. OpenID Connect field. + website (`Optional[str]`, *optional*): + The user's website URL. OpenID Connect field. + is_pro (`bool`): + Whether the user is a pro user. Hugging Face field. + can_pay (`Optional[bool]`, *optional*): + Whether the user has a payment method set up. Hugging Face field. + orgs (`Optional[list[OrgInfo]]`, *optional*): + List of organizations the user is part of. Hugging Face field. + """ + + sub: str + name: str + preferred_username: str + email_verified: bool | None + email: str | None + picture: str + profile: str + website: str | None + is_pro: bool + can_pay: bool | None + orgs: list[OAuthOrgInfo] | None + + +@dataclass +class OAuthInfo: + """ + Information about the OAuth login. + + Attributes: + access_token (`str`): + The access token. + access_token_expires_at (`datetime.datetime`): + The expiration date of the access token. + user_info ([`OAuthUserInfo`]): + The user information. + state (`str`, *optional*): + State passed to the OAuth provider in the original request to the OAuth provider. + scope (`str`): + Granted scope. + """ + + access_token: str + access_token_expires_at: datetime.datetime + user_info: OAuthUserInfo + state: str | None + scope: str + + +@experimental +def attach_huggingface_oauth(app: "fastapi.FastAPI", route_prefix: str = "/"): + """ + Add OAuth endpoints to a FastAPI app to enable OAuth login with Hugging Face. + + How to use: + - Call this method on your FastAPI app to add the OAuth endpoints. + - Inside your route handlers, call `parse_huggingface_oauth(request)` to retrieve the OAuth info. + - If user is logged in, an [`OAuthInfo`] object is returned with the user's info. If not, `None` is returned. + - In your app, make sure to add links to `/oauth/huggingface/login` and `/oauth/huggingface/logout` for the user to log in and out. + + Example: + ```py + from huggingface_hub import attach_huggingface_oauth, parse_huggingface_oauth + + # Create a FastAPI app + app = FastAPI() + + # Add OAuth endpoints to the FastAPI app + attach_huggingface_oauth(app) + + # Add a route that greets the user if they are logged in + @app.get("/") + def greet_json(request: Request): + # Retrieve the OAuth info from the request + oauth_info = parse_huggingface_oauth(request) # e.g. OAuthInfo dataclass + if oauth_info is None: + return {"msg": "Not logged in!"} + return {"msg": f"Hello, {oauth_info.user_info.preferred_username}!"} + ``` + """ + # TODO: handle generic case (handling OAuth in a non-Space environment with custom dev values) (low priority) + + # Add SessionMiddleware to the FastAPI app to store the OAuth info in the session. + # Session Middleware requires a secret key to sign the cookies. Let's use a hash + # of the OAuth secret key to make it unique to the Space + updated in case OAuth + # config gets updated. When ran locally, we use an empty string as a secret key. + try: + from starlette.middleware.sessions import SessionMiddleware + except ImportError as e: + raise ImportError( + "Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add " + "`huggingface_hub[oauth]` to your requirements.txt file in order to install the required dependencies." + ) from e + session_secret = (constants.OAUTH_CLIENT_SECRET or "") + "-v1" + app.add_middleware( + SessionMiddleware, # type: ignore + secret_key=hashlib.sha256(session_secret.encode()).hexdigest(), + same_site="none", + https_only=True, + ) # type: ignore + + # Add OAuth endpoints to the FastAPI app: + # - {route_prefix}/oauth/huggingface/login + # - {route_prefix}/oauth/huggingface/callback + # - {route_prefix}/oauth/huggingface/logout + # If the app is running in a Space, OAuth is enabled normally. + # Otherwise, we mock the endpoints to make the user log in with a fake user profile - without any calls to hf.co. + route_prefix = route_prefix.strip("/") + if os.getenv("SPACE_ID") is not None: + logger.info("OAuth is enabled in the Space. Adding OAuth routes.") + _add_oauth_routes(app, route_prefix=route_prefix) + else: + logger.info("App is not running in a Space. Adding mocked OAuth routes.") + _add_mocked_oauth_routes(app, route_prefix=route_prefix) + + +def parse_huggingface_oauth(request: "fastapi.Request") -> OAuthInfo | None: + """ + Returns the information from a logged-in user as a [`OAuthInfo`] object. + + For flexibility and future-proofing, this method is very lax in its parsing and does not raise errors. + Missing fields are set to `None` without a warning. + + Return `None`, if the user is not logged in (no info in session cookie). + + See [`attach_huggingface_oauth`] for an example on how to use this method. + """ + if "oauth_info" not in request.session: + logger.debug("No OAuth info in session.") + return None + + logger.debug("Parsing OAuth info from session.") + oauth_data = request.session["oauth_info"] + user_data = oauth_data.get("userinfo", {}) + orgs_data = user_data.get("orgs", []) + + orgs = ( + [ + OAuthOrgInfo( + sub=org.get("sub"), + name=org.get("name"), + preferred_username=org.get("preferred_username"), + picture=org.get("picture"), + plan=org.get("plan"), + can_pay=org.get("canPay"), + role_in_org=org.get("roleInOrg"), + security_restrictions=org.get("securityRestrictions"), + ) + for org in orgs_data + ] + if orgs_data + else None + ) + + user_info = OAuthUserInfo( + sub=user_data.get("sub"), + name=user_data.get("name"), + preferred_username=user_data.get("preferred_username"), + email_verified=user_data.get("email_verified"), + email=user_data.get("email"), + picture=user_data.get("picture"), + profile=user_data.get("profile"), + website=user_data.get("website"), + is_pro=user_data.get("isPro"), + can_pay=user_data.get("canPay"), + orgs=orgs, + ) + + return OAuthInfo( + access_token=oauth_data.get("access_token"), + access_token_expires_at=datetime.datetime.fromtimestamp(oauth_data.get("expires_at")), + user_info=user_info, + state=oauth_data.get("state"), + scope=oauth_data.get("scope"), + ) + + +def _add_oauth_routes(app: "fastapi.FastAPI", route_prefix: str) -> None: + """Add OAuth routes to the FastAPI app (login, callback handler and logout).""" + try: + import fastapi + from authlib.integrations.base_client.errors import MismatchingStateError + from authlib.integrations.starlette_client import OAuth + from fastapi.responses import RedirectResponse + except ImportError as e: + raise ImportError( + "Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add " + "`huggingface_hub[oauth]` to your requirements.txt file." + ) from e + + # Check environment variables + msg = ( + "OAuth is required but '{}' environment variable is not set. Make sure you've enabled OAuth in your Space by" + " setting `hf_oauth: true` in the Space metadata." + ) + if constants.OAUTH_CLIENT_ID is None: + raise ValueError(msg.format("OAUTH_CLIENT_ID")) + if constants.OAUTH_CLIENT_SECRET is None: + raise ValueError(msg.format("OAUTH_CLIENT_SECRET")) + if constants.OAUTH_SCOPES is None: + raise ValueError(msg.format("OAUTH_SCOPES")) + if constants.OPENID_PROVIDER_URL is None: + raise ValueError(msg.format("OPENID_PROVIDER_URL")) + + # Register OAuth server + oauth = OAuth() + oauth.register( + name="huggingface", + client_id=constants.OAUTH_CLIENT_ID, + client_secret=constants.OAUTH_CLIENT_SECRET, + client_kwargs={"scope": constants.OAUTH_SCOPES}, + server_metadata_url=constants.OPENID_PROVIDER_URL + "/.well-known/openid-configuration", + ) + + login_uri, callback_uri, logout_uri = _get_oauth_uris(route_prefix) + + # Register OAuth endpoints + @app.get(login_uri) + async def oauth_login(request: fastapi.Request) -> RedirectResponse: + """Endpoint that redirects to HF OAuth page.""" + redirect_uri = _generate_redirect_uri(request) + return await oauth.huggingface.authorize_redirect(request, redirect_uri) # type: ignore + + @app.get(callback_uri) + async def oauth_redirect_callback(request: fastapi.Request) -> RedirectResponse: + """Endpoint that handles the OAuth callback.""" + try: + oauth_info = await oauth.huggingface.authorize_access_token(request) # type: ignore + except MismatchingStateError: + # Parse query params + nb_redirects = int(request.query_params.get("_nb_redirects", 0)) + target_url = request.query_params.get("_target_url") + + # Build redirect URI with the same query params as before and bump nb_redirects count + query_params: dict[str, int | str] = {"_nb_redirects": nb_redirects + 1} + if target_url: + query_params["_target_url"] = target_url + + redirect_uri = f"{login_uri}?{urllib.parse.urlencode(query_params)}" + + # If the user is redirected more than 3 times, it is very likely that the cookie is not working properly. + # (e.g. browser is blocking third-party cookies in iframe). In this case, redirect the user in the + # non-iframe view. + if nb_redirects > constants.OAUTH_MAX_REDIRECTS: + host = os.environ.get("SPACE_HOST") + if host is None: # cannot happen in a Space + raise RuntimeError( + "App is not running in a Space (SPACE_HOST environment variable is not set). Cannot redirect to non-iframe view." + ) from None + host_url = "https://" + host.rstrip("/") + return RedirectResponse(host_url + redirect_uri) + + # Redirect the user to the login page again + return RedirectResponse(redirect_uri) + + # OAuth login worked => store the user info in the session and redirect + logger.debug("Successfully logged in with OAuth. Storing user info in session.") + request.session["oauth_info"] = oauth_info + return RedirectResponse(_get_redirect_target(request)) + + @app.get(logout_uri) + async def oauth_logout(request: fastapi.Request) -> RedirectResponse: + """Endpoint that logs out the user (e.g. delete info from cookie session).""" + logger.debug("Logged out with OAuth. Removing user info from session.") + request.session.pop("oauth_info", None) + return RedirectResponse(_get_redirect_target(request)) + + +def _add_mocked_oauth_routes(app: "fastapi.FastAPI", route_prefix: str = "/") -> None: + """Add fake oauth routes if app is run locally and OAuth is enabled. + + Using OAuth will have the same behavior as in a Space but instead of authenticating with HF, a mocked user profile + is added to the session. + """ + try: + import fastapi + from fastapi.responses import RedirectResponse + from starlette.datastructures import URL + except ImportError as e: + raise ImportError( + "Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add " + "`huggingface_hub[oauth]` to your requirements.txt file." + ) from e + + warnings.warn( + "OAuth is not supported outside of a Space environment. To help you debug your app locally, the oauth endpoints" + " are mocked to return your profile and token. To make it work, your machine must be logged in to Huggingface." + ) + mocked_oauth_info = _get_mocked_oauth_info() + + login_uri, callback_uri, logout_uri = _get_oauth_uris(route_prefix) + + # Define OAuth routes + @app.get(login_uri) + async def oauth_login(request: fastapi.Request) -> RedirectResponse: + """Fake endpoint that redirects to HF OAuth page.""" + # Define target (where to redirect after login) + redirect_uri = _generate_redirect_uri(request) + return RedirectResponse(callback_uri + "?" + urllib.parse.urlencode({"_target_url": redirect_uri})) + + @app.get(callback_uri) + async def oauth_redirect_callback(request: fastapi.Request) -> RedirectResponse: + """Endpoint that handles the OAuth callback.""" + request.session["oauth_info"] = mocked_oauth_info + return RedirectResponse(_get_redirect_target(request)) + + @app.get(logout_uri) + async def oauth_logout(request: fastapi.Request) -> RedirectResponse: + """Endpoint that logs out the user (e.g. delete cookie session).""" + request.session.pop("oauth_info", None) + logout_url = URL("/").include_query_params(**request.query_params) + return RedirectResponse(url=logout_url, status_code=302) # see https://github.com/gradio-app/gradio/pull/9659 + + +def _generate_redirect_uri(request: "fastapi.Request") -> str: + if "_target_url" in request.query_params: + # if `_target_url` already in query params => respect it + target = request.query_params["_target_url"] + else: + # otherwise => keep query params + target = "/?" + urllib.parse.urlencode(request.query_params) + + redirect_uri = request.url_for("oauth_redirect_callback").include_query_params(_target_url=target) + redirect_uri_as_str = str(redirect_uri) + if redirect_uri.netloc.endswith(".hf.space"): + # In Space, FastAPI redirect as http but we want https + redirect_uri_as_str = redirect_uri_as_str.replace("http://", "https://") + return redirect_uri_as_str + + +def _get_redirect_target(request: "fastapi.Request", default_target: str = "/") -> str: + return request.query_params.get("_target_url", default_target) + + +def _get_mocked_oauth_info() -> dict: + token = get_token() + if token is None: + raise ValueError( + "Your machine must be logged in to HF to debug an OAuth app locally. Please" + " run `hf auth login` or set `HF_TOKEN` as environment variable " + "with one of your access token. You can generate a new token in your " + "settings page (https://huggingface.co/settings/tokens)." + ) + + user = whoami() + if user["type"] != "user": + raise ValueError( + "Your machine is not logged in with a personal account. Please use a " + "personal access token. You can generate a new token in your settings page" + " (https://huggingface.co/settings/tokens)." + ) + + return { + "access_token": token, + "token_type": "bearer", + "expires_in": 8 * 60 * 60, # 8 hours + "id_token": "FOOBAR", + "scope": "openid profile", + "refresh_token": "hf_oauth__refresh_token", + "expires_at": int(time.time()) + 8 * 60 * 60, # 8 hours + "userinfo": { + "sub": "0123456789", + "name": user["fullname"], + "preferred_username": user["name"], + "profile": f"https://huggingface.co/{user['name']}", + "picture": user["avatarUrl"], + "website": "", + "aud": "00000000-0000-0000-0000-000000000000", + "auth_time": 1691672844, + "nonce": "aaaaaaaaaaaaaaaaaaa", + "iat": 1691672844, + "exp": 1691676444, + "iss": "https://huggingface.co", + }, + } + + +def _get_oauth_uris(route_prefix: str = "/") -> tuple[str, str, str]: + route_prefix = route_prefix.strip("/") + if route_prefix: + route_prefix = f"/{route_prefix}" + return ( + f"{route_prefix}/oauth/huggingface/login", + f"{route_prefix}/oauth/huggingface/callback", + f"{route_prefix}/oauth/huggingface/logout", + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_snapshot_download.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_snapshot_download.py new file mode 100644 index 0000000000000000000000000000000000000000..bd03124729be17694db9a6d5be610584b584d881 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_snapshot_download.py @@ -0,0 +1,471 @@ +import os +from collections.abc import Iterable +from pathlib import Path +from typing import Literal, overload + +import httpx +from tqdm.auto import tqdm as base_tqdm +from tqdm.contrib.concurrent import thread_map + +from . import constants +from .errors import ( + DryRunError, + GatedRepoError, + HfHubHTTPError, + LocalEntryNotFoundError, + RepositoryNotFoundError, + RevisionNotFoundError, +) +from .file_download import REGEX_COMMIT_HASH, DryRunFileInfo, hf_hub_download, repo_folder_name +from .hf_api import DatasetInfo, HfApi, KernelInfo, ModelInfo, RepoFile, SpaceInfo +from .utils import OfflineModeIsEnabled, filter_repo_objects, logging, validate_hf_hub_args +from .utils.tqdm import _create_progress_bar +from .utils.tqdm import tqdm as hf_tqdm + + +logger = logging.get_logger(__name__) + +LARGE_REPO_THRESHOLD = 1000 # After this limit, we don't consider `repo_info.siblings` to be reliable enough + + +@overload +def snapshot_download( + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + library_name: str | None = None, + library_version: str | None = None, + user_agent: dict | str | None = None, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + force_download: bool = False, + token: bool | str | None = None, + local_files_only: bool = False, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + max_workers: int = 8, + tqdm_class: type[base_tqdm] | None = None, + headers: dict[str, str] | None = None, + endpoint: str | None = None, + dry_run: Literal[False] = False, +) -> str: ... + + +@overload +def snapshot_download( + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + library_name: str | None = None, + library_version: str | None = None, + user_agent: dict | str | None = None, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + force_download: bool = False, + token: bool | str | None = None, + local_files_only: bool = False, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + max_workers: int = 8, + tqdm_class: type[base_tqdm] | None = None, + headers: dict[str, str] | None = None, + endpoint: str | None = None, + dry_run: Literal[True] = True, +) -> list[DryRunFileInfo]: ... + + +@overload +def snapshot_download( + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + library_name: str | None = None, + library_version: str | None = None, + user_agent: dict | str | None = None, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + force_download: bool = False, + token: bool | str | None = None, + local_files_only: bool = False, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + max_workers: int = 8, + tqdm_class: type[base_tqdm] | None = None, + headers: dict[str, str] | None = None, + endpoint: str | None = None, + dry_run: bool = False, +) -> str | list[DryRunFileInfo]: ... + + +@validate_hf_hub_args +def snapshot_download( + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + library_name: str | None = None, + library_version: str | None = None, + user_agent: dict | str | None = None, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + force_download: bool = False, + token: bool | str | None = None, + local_files_only: bool = False, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + max_workers: int = 8, + tqdm_class: type[base_tqdm] | None = None, + headers: dict[str, str] | None = None, + endpoint: str | None = None, + dry_run: bool = False, +) -> str | list[DryRunFileInfo]: + """Download repo files. + + Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from + a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order + to keep their actual filename relative to that folder. You can also filter which files to download using + `allow_patterns` and `ignore_patterns`. + + If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this + option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir` + to store some metadata related to the downloaded files. While this mechanism is not as robust as the main + cache-system, it's optimized for regularly pulling the latest version of a repository. + + An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly + configured. It is also not possible to filter which files to download when cloning a repository using git. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"`, `"space"` or `"kernel"` if downloading from a dataset, space or kernel repo, + `None` or `"model"` if downloading from a model. Default is `None`. + revision (`str`, *optional*): + An optional Git revision id which can be a branch name, a tag, or a + commit hash. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_dir (`str` or `Path`, *optional*): + If provided, the downloaded files will be placed under this directory. + library_name (`str`, *optional*): + The name of the library to which the object corresponds. + library_version (`str`, *optional*): + The version of the library. + user_agent (`str`, `dict`, *optional*): + The user-agent info in the form of a dictionary or a string. + etag_timeout (`float`, *optional*, defaults to `10`): + When fetching ETag, how many seconds to wait for the server to send + data before giving up which is passed to `httpx.request`. + force_download (`bool`, *optional*, defaults to `False`): + Whether the file should be downloaded even if it already exists in the local cache. + token (`str`, `bool`, *optional*): + A token to be used for the download. + - If `True`, the token is read from the HuggingFace config + folder. + - If a string, it's used as the authentication token. + headers (`dict`, *optional*): + Additional headers to include in the request. Those headers take precedence over the others. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the + local cached file if it exists. + allow_patterns (`list[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are downloaded. + ignore_patterns (`list[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not downloaded. + max_workers (`int`, *optional*): + Number of concurrent threads to download files (1 thread = 1 file download). + Defaults to 8. + tqdm_class (`tqdm`, *optional*): + If provided, overwrites the default behavior for the progress bar. Passed + argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior. + Note that the `tqdm_class` is not passed to each individual download. + Defaults to the custom HF progress bar that can be disabled by setting + `HF_HUB_DISABLE_PROGRESS_BARS` environment variable. + dry_run (`bool`, *optional*, defaults to `False`): + If `True`, perform a dry run without actually downloading the files. Returns a list of + [`DryRunFileInfo`] objects containing information about what would be downloaded. + + Returns: + `str` or list of [`DryRunFileInfo`]: + - If `dry_run=False`: Local snapshot path. + - If `dry_run=True`: A list of [`DryRunFileInfo`] objects containing download information. + + Raises: + [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + If `token=True` and the token cannot be found. + [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if + ETag cannot be determined. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid. + """ + if cache_dir is None: + cache_dir = constants.HF_HUB_CACHE + if revision is None: + revision = constants.DEFAULT_REVISION + if isinstance(cache_dir, Path): + cache_dir = str(cache_dir) + + if repo_type is None: + repo_type = "model" + if repo_type not in constants.REPO_TYPES_WITH_KERNEL: + raise ValueError( + f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES_WITH_KERNEL)}" + ) + + storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type)) + + api = HfApi( + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + endpoint=endpoint, + headers=headers, + token=token, + ) + + repo_info: ModelInfo | DatasetInfo | SpaceInfo | KernelInfo | None = None + api_call_error: Exception | None = None + if not local_files_only: + # try/except logic to handle different errors => taken from `hf_hub_download` + try: + # if we have internet connection we want to list files to download + repo_info = api.repo_info(repo_id=repo_id, repo_type=repo_type, revision=revision) + except httpx.ProxyError: + # Actually raise on proxy error + raise + except (httpx.ConnectError, httpx.TimeoutException, OfflineModeIsEnabled) as error: + # Internet connection is down + # => will try to use local files only + api_call_error = error + pass + except RevisionNotFoundError: + # The repo was found but the revision doesn't exist on the Hub (never existed or got deleted) + raise + except HfHubHTTPError as error: + # Multiple reasons for an http error: + # - Repository is private and invalid/missing token sent + # - Repository is gated and invalid/missing token sent + # - Hub is down (error 500 or 504) + # => let's switch to 'local_files_only=True' to check if the files are already cached. + # (if it's not the case, the error will be re-raised) + api_call_error = error + pass + + # At this stage, if `repo_info` is None it means either: + # - internet connection is down + # - internet connection is deactivated (local_files_only=True or HF_HUB_OFFLINE=True) + # - repo is private/gated and invalid/missing token sent + # - Hub is down + # => let's look if we can find the appropriate folder in the cache: + # - if the specified revision is a commit hash, look inside "snapshots". + # - f the specified revision is a branch or tag, look inside "refs". + # => if local_dir is not None, we will return the path to the local folder if it exists. + if repo_info is None: + if dry_run: + raise DryRunError( + "Dry run cannot be performed as the repository cannot be accessed. Please check your internet connection or authentication token." + ) from api_call_error + + # Try to get which commit hash corresponds to the specified revision + commit_hash = None + if REGEX_COMMIT_HASH.match(revision): + commit_hash = revision + else: + ref_path = os.path.join(storage_folder, "refs", revision) + if os.path.exists(ref_path): + # retrieve commit_hash from refs file + with open(ref_path) as f: + commit_hash = f.read() + + # Try to locate snapshot folder for this commit hash + if commit_hash is not None and local_dir is None: + snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash) + if os.path.exists(snapshot_folder): + # Snapshot folder exists => let's return it + # (but we can't check if all the files are actually there) + return snapshot_folder + + # If local_dir is not None, return it if it exists and is not empty + if local_dir is not None: + local_dir = Path(local_dir) + if local_dir.is_dir() and any(local_dir.iterdir()): + logger.warning( + f"Returning existing local_dir `{local_dir}` as remote repo cannot be accessed in `snapshot_download` ({api_call_error})." + ) + return str(local_dir.resolve()) + # If we couldn't find the appropriate folder on disk, raise an error. + if local_files_only: + raise LocalEntryNotFoundError( + "Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and " + "outgoing traffic has been disabled. To enable repo look-ups and downloads online, pass " + "'local_files_only=False' as input." + ) + elif isinstance(api_call_error, OfflineModeIsEnabled): + raise LocalEntryNotFoundError( + "Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and " + "outgoing traffic has been disabled. To enable repo look-ups and downloads online, set " + "'HF_HUB_OFFLINE=0' as environment variable." + ) from api_call_error + elif isinstance(api_call_error, (RepositoryNotFoundError, GatedRepoError)) or ( + isinstance(api_call_error, HfHubHTTPError) and api_call_error.response.status_code == 401 + ): + # Repo not found, gated, or specific authentication error => let's raise the actual error + raise api_call_error + else: + # Otherwise: most likely a connection issue or Hub downtime => let's warn the user + raise LocalEntryNotFoundError( + f"Got: {api_call_error.__class__.__name__}: {api_call_error}" + "\nAn error happened while trying to locate the files on the Hub and we cannot find the appropriate" + " snapshot folder for the specified revision on the local disk. Please check your internet connection" + " and try again." + ) from api_call_error + + # At this stage, internet connection is up and running + # => let's download the files! + assert repo_info.sha is not None, "Repo info returned from server must have a revision sha." + + # Corner case: on very large repos, the siblings list in `repo_info` might not contain all files. + # In that case, we need to use the `list_repo_tree` method to prevent caching issues. + # Note: kernel repos don't expose siblings in their info response, so we always fall back to `list_repo_tree`. + siblings = getattr(repo_info, "siblings", None) + repo_files: Iterable[str] = [f.rfilename for f in siblings] if siblings is not None else [] + unreliable_nb_files = siblings is None or len(siblings) == 0 or len(siblings) > LARGE_REPO_THRESHOLD + if unreliable_nb_files: + logger.info( + "Number of files in the repo is unreliable. Using `list_repo_tree` to ensure all files are listed." + ) + repo_files = ( + f.rfilename + for f in api.list_repo_tree(repo_id=repo_id, recursive=True, revision=revision, repo_type=repo_type) + if isinstance(f, RepoFile) + ) + + filtered_repo_files: Iterable[str] = filter_repo_objects( + items=repo_files, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + ) + + if not unreliable_nb_files: + filtered_repo_files = list(filtered_repo_files) + tqdm_desc = f"Fetching {len(filtered_repo_files)} files" + else: + tqdm_desc = "Fetching ... files" + if dry_run: + tqdm_desc = "[dry-run] " + tqdm_desc + + commit_hash = repo_info.sha + snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash) + # if passed revision is not identical to commit_hash + # then revision has to be a branch name or tag name. + # In that case store a ref. + if revision != commit_hash: + ref_path = os.path.join(storage_folder, "refs", revision) + try: + os.makedirs(os.path.dirname(ref_path), exist_ok=True) + with open(ref_path, "w") as f: + f.write(commit_hash) + except OSError as e: + logger.warning(f"Ignored error while writing commit hash to {ref_path}: {e}.") + + results: list[str | DryRunFileInfo] = [] + + # User can use its own tqdm class or the default one from `huggingface_hub.utils` + tqdm_class = tqdm_class or hf_tqdm + + # Create a progress bar for the bytes downloaded + # This progress bar is shared across threads/files and gets updated each time we fetch + # metadata for a file. + bytes_progress = _create_progress_bar( + cls=tqdm_class, + log_level=logger.getEffectiveLevel(), + name="huggingface_hub.snapshot_download", + desc="Downloading (incomplete total...)", + total=0, + initial=0, + unit="B", + unit_scale=True, + ) + + class _AggregatedTqdm: + """Fake tqdm object to aggregate progress into the parent `bytes_progress` bar. + + In practice the `_AggregatedTqdm` object won't be displayed, it's just used to update + the `bytes_progress` bar from each thread/file download. + """ + + def __init__(self, *args, **kwargs): + # Adjust the total of the parent progress bar + total = kwargs.pop("total", None) + if total is not None: + bytes_progress.total += total + bytes_progress.refresh() + + # Adjust initial of the parent progress bar + initial = kwargs.pop("initial", 0) + if initial: + bytes_progress.update(initial) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + pass + + def update(self, n: int | float | None = 1) -> None: + bytes_progress.update(n) + + # we pass the commit_hash to hf_hub_download + # so no network call happens if we already + # have the file locally. + def _inner_hf_hub_download(repo_file: str) -> None: + results.append( + hf_hub_download( # type: ignore + repo_id, + filename=repo_file, + repo_type=repo_type, + revision=commit_hash, + endpoint=endpoint, + cache_dir=cache_dir, + local_dir=local_dir, + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + etag_timeout=etag_timeout, + force_download=force_download, + token=token, + headers=headers, + tqdm_class=_AggregatedTqdm, # type: ignore + dry_run=dry_run, + ) + ) + + thread_map( + _inner_hf_hub_download, + filtered_repo_files, + desc=tqdm_desc, + max_workers=max_workers, + tqdm_class=tqdm_class, + ) + + bytes_progress.set_description("Download complete") + + if dry_run: + assert all(isinstance(r, DryRunFileInfo) for r in results) + return results # type: ignore + + if local_dir is not None: + return str(os.path.realpath(local_dir)) + return snapshot_folder diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_space_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_space_api.py new file mode 100644 index 0000000000000000000000000000000000000000..391ec7e5b996cf6ab42b9b4f4790d0c5322b48a9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_space_api.py @@ -0,0 +1,352 @@ +# Copyright 2019-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from dataclasses import dataclass +from datetime import datetime +from enum import Enum +from typing import Literal + +from huggingface_hub.utils import parse_datetime + + +class SpaceStage(str, Enum): + """ + Enumeration of possible stage of a Space on the Hub. + + Value can be compared to a string: + ```py + assert SpaceStage.BUILDING == "BUILDING" + ``` + + Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceInfo.ts#L61 (private url). + """ + + # Copied from moon-landing > server > repo_types > SpaceInfo.ts (private repo) + NO_APP_FILE = "NO_APP_FILE" + CONFIG_ERROR = "CONFIG_ERROR" + BUILDING = "BUILDING" + BUILD_ERROR = "BUILD_ERROR" + RUNNING = "RUNNING" + RUNNING_BUILDING = "RUNNING_BUILDING" + RUNTIME_ERROR = "RUNTIME_ERROR" + DELETING = "DELETING" + STOPPED = "STOPPED" + PAUSED = "PAUSED" + APP_STARTING = "APP_STARTING" + RUNNING_APP_STARTING = "RUNNING_APP_STARTING" + + +class SpaceHardware(str, Enum): + """ + Enumeration of hardwares available to run your Space on the Hub. + + Value can be compared to a string: + ```py + assert SpaceHardware.CPU_BASIC == "cpu-basic" + ``` + + Taken from https://github.com/huggingface-internal/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts (private url). + """ + + # CPU + CPU_BASIC = "cpu-basic" + CPU_UPGRADE = "cpu-upgrade" + CPU_PERFORMANCE = "cpu-performance" + CPU_XL = "cpu-xl" + SPRX8 = "sprx8" + + # ZeroGPU + ZERO_A10G = "zero-a10g" + + # GPU + T4_SMALL = "t4-small" + T4_MEDIUM = "t4-medium" + L4X1 = "l4x1" + L4X4 = "l4x4" + L40SX1 = "l40sx1" + L40SX4 = "l40sx4" + L40SX8 = "l40sx8" + A10G_SMALL = "a10g-small" + A10G_LARGE = "a10g-large" + A10G_LARGEX2 = "a10g-largex2" + A10G_LARGEX4 = "a10g-largex4" + A100_LARGE = "a100-large" + A100X4 = "a100x4" + A100X8 = "a100x8" + H200 = "h200" + H200X2 = "h200x2" + H200X4 = "h200x4" + H200X8 = "h200x8" + + # Neuron + INF2X6 = "inf2x6" + + +class SpaceStorage(str, Enum): + """ + Enumeration of persistent storage available for your Space on the Hub. + + Value can be compared to a string: + ```py + assert SpaceStorage.SMALL == "small" + ``` + + Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts#L24 (private url). + """ + + SMALL = "small" + MEDIUM = "medium" + LARGE = "large" + + +@dataclass +class Volume: + """ + Describes a volume to mount in a Space or Job container. + + Args: + type (`str`): + Type of volume: `"bucket"`, `"model"`, `"dataset"`, or `"space"`. + source (`str`): + Source identifier, e.g. `"username/my-bucket"` or `"username/my-model"`. + mount_path (`str`): + Mount path inside the container, e.g. `"/data"`. Must start with `/`. + revision (`str` or `None`): + Git revision (only for repos, defaults to `"main"`). + read_only (`bool` or `None`): + Read-only mount. Forced `True` for repos, defaults to `False` for buckets. + path (`str` or `None`): + Subfolder prefix inside the bucket/repo to mount, e.g. `"path/to/dir"`. + """ + + type: Literal["bucket", "model", "dataset", "space"] + source: str + mount_path: str + revision: str | None = None + read_only: bool | None = None + path: str | None = None + + def __init__(self, **kwargs) -> None: + self.type = kwargs.get("type", "model") + self.source = kwargs["source"] + mount_path = kwargs.get("mountPath") + self.mount_path = mount_path if mount_path is not None else kwargs["mount_path"] + self.revision = kwargs.get("revision") + read_only = kwargs.get("readOnly") + self.read_only = read_only if read_only is not None else kwargs.get("read_only") + self.path = kwargs.get("path") + + def to_dict(self) -> dict: + """Serialize to the JSON payload expected by the Hub API.""" + data: dict = { + "type": self.type, + "source": self.source, + "mountPath": self.mount_path, + } + if self.revision is not None: + data["revision"] = self.revision + if self.read_only is not None: + data["readOnly"] = self.read_only + if self.path is not None: + data["path"] = self.path + return data + + def to_hf_handle(self) -> str: + """Return the volume as an HF handle in the format expected by the CLI.""" + path = f"/{self.path}" if self.path else "" + revision = f"@{self.revision}" if self.revision else "" + ro = {True: ":ro", False: ":rw", None: ""}.get(self.read_only, "") + return f"hf://{self.type}s/{self.source}{revision}{path}:{self.mount_path}{ro}" + + +@dataclass +class SpaceHotReloading: + status: Literal["created", "canceled"] + replica_statuses: list[tuple[str, str | None]] # See _hot_reloading_types.ApiCreateReloadResponse.res.status + raw: dict + + def __init__(self, data: dict) -> None: + self.status = data["status"] + self.replica_statuses = data["replicaStatuses"] + self.raw = data + + +@dataclass +class SpaceRuntime: + """ + Contains information about the current runtime of a Space. + + Args: + stage (`str`): + Current stage of the space. Example: RUNNING. + hardware (`str` or `None`): + Current hardware of the space. Example: "cpu-basic". Can be `None` if Space + is `BUILDING` for the first time. + requested_hardware (`str` or `None`): + Requested hardware. Can be different from `hardware` especially if the request + has just been made. Example: "t4-medium". Can be `None` if no hardware has + been requested yet. + sleep_time (`int` or `None`): + Number of seconds the Space will be kept alive after the last request. By default (if value is `None`), the + Space will never go to sleep if it's running on an upgraded hardware, while it will go to sleep after 48 + hours on a free 'cpu-basic' hardware. For more details, see https://huggingface.co/docs/hub/spaces-gpus#sleep-time. + volumes (`list[Volume]` or `None`): + List of volumes mounted in the Space. Each volume is a [`Volume`] object describing its type, source, + mount path, and optional settings. `None` if no volumes are attached. + raw (`dict`): + Raw response from the server. Contains more information about the Space + runtime like number of replicas, number of cpu, memory size,... + """ + + stage: SpaceStage + hardware: SpaceHardware | None + requested_hardware: SpaceHardware | None + sleep_time: int | None + storage: SpaceStorage | None + hot_reloading: SpaceHotReloading | None + volumes: list[Volume] | None + raw: dict + + def __init__(self, data: dict) -> None: + self.stage = data["stage"] + self.hardware = data.get("hardware", {}).get("current") + self.requested_hardware = data.get("hardware", {}).get("requested") + self.sleep_time = data.get("gcTimeout") + self.storage = data.get("storage") + self.hot_reloading = SpaceHotReloading(raw_hr) if (raw_hr := data.get("hotReloading")) is not None else None + raw_volumes = data.get("volumes") + self.volumes = [Volume(**v) for v in raw_volumes] if raw_volumes is not None else None + self.raw = data + + +@dataclass +class SpaceSecret: + """ + Contains information about a secret of a Space. + + Secret values are write-only and cannot be read back. Only the key, description, + and last update time are returned by the API. + + Args: + key (`str`): + Secret key. Example: `"GITHUB_API_KEY"` + description (`str` or None): + Description of the secret. Example: `"Github API key to access the Github API"`. + updated_at (`datetime` or None): + datetime of the last update of the secret (if the secret has been updated at least once). + """ + + key: str + description: str | None + updated_at: datetime | None + + def __init__(self, key: str, values: dict) -> None: + self.key = key + self.description = values.get("description") + updated_at = values.get("updatedAt") + self.updated_at = parse_datetime(updated_at) if updated_at is not None else None + + +@dataclass +class SpaceVariable: + """ + Contains information about the current variables of a Space. + + Args: + key (`str`): + Variable key. Example: `"MODEL_REPO_ID"` + value (`str`): + Variable value. Example: `"the_model_repo_id"`. + description (`str` or None): + Description of the variable. Example: `"Model Repo ID of the implemented model"`. + updatedAt (`datetime` or None): + datetime of the last update of the variable (if the variable has been updated at least once). + """ + + key: str + value: str + description: str | None + updated_at: datetime | None + + def __init__(self, key: str, values: dict) -> None: + self.key = key + self.value = values["value"] + self.description = values.get("description") + updated_at = values.get("updatedAt") + self.updated_at = parse_datetime(updated_at) if updated_at is not None else None + + +@dataclass +class SpaceSearchResult: + """A single result from the Spaces semantic search API. + + Returned by [`HfApi.search_spaces`]. + + Attributes: + id (`str`): + ID of the Space (e.g. `"username/repo-name"`). + author (`str`): + Author of the Space. + title (`str`): + Display title of the Space. + emoji (`str` or `None`): + Emoji icon of the Space. + sdk (`str` or `None`): + SDK used by the Space (e.g. `"gradio"`, `"docker"`, `"static"`). + likes (`int`): + Number of likes. + private (`bool`): + Whether the Space is private. + tags (`list[str]` or `None`): + List of tags. + runtime ([`SpaceRuntime`] or `None`): + Runtime information (stage, hardware, etc.). + ai_short_description (`str` or `None`): + AI-generated short description. + ai_category (`str` or `None`): + AI-generated category (e.g. `"Image Generation"`). + semantic_relevancy_score (`float` or `None`): + Semantic relevancy score (0-1) relative to the search query. + trending_score (`int` or `None`): + Trending score. + """ + + id: str + author: str + title: str + emoji: str | None + sdk: str | None + likes: int + private: bool + tags: list[str] | None + runtime: SpaceRuntime | None + ai_short_description: str | None + ai_category: str | None + semantic_relevancy_score: float | None + trending_score: int | None + + def __init__(self, data: dict) -> None: + runtime = data.get("runtime") + self.id = data["id"] + self.author = data.get("author", "") + self.title = data.get("title", "") + self.emoji = data.get("emoji") + self.sdk = data.get("sdk") + self.likes = data.get("likes", 0) + self.private = data.get("private", False) + self.tags = data.get("tags") + self.runtime = SpaceRuntime(runtime) if runtime else None + self.ai_short_description = data.get("ai_short_description") + self.ai_category = data.get("ai_category") + self.semantic_relevancy_score = data.get("semanticRelevancyScore") + self.trending_score = data.get("trendingScore") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_tensorboard_logger.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_tensorboard_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..c6a0d222990e25297feaa72c846b94212e0ebcfc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_tensorboard_logger.py @@ -0,0 +1,189 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains a logger to push training logs to the Hub, using Tensorboard.""" + +from pathlib import Path + +from ._commit_scheduler import CommitScheduler +from .errors import EntryNotFoundError +from .repocard import ModelCard +from .utils import experimental + + +# Depending on user's setup, SummaryWriter can come either from 'tensorboardX' +# or from 'torch.utils.tensorboard'. Both are compatible so let's try to load +# from either of them. +try: + from tensorboardX import SummaryWriter as _RuntimeSummaryWriter + + is_summary_writer_available = True +except ImportError: + try: + from torch.utils.tensorboard import SummaryWriter as _RuntimeSummaryWriter + + is_summary_writer_available = True + except ImportError: + # Dummy class to avoid failing at import. Will raise on instance creation. + class _DummySummaryWriter: + pass + + _RuntimeSummaryWriter = _DummySummaryWriter # type: ignore[assignment] # ty: ignore[conflicting-declarations] + is_summary_writer_available = False + + +class HFSummaryWriter(_RuntimeSummaryWriter): + """ + Wrapper around the tensorboard's `SummaryWriter` to push training logs to the Hub. + + Data is logged locally and then pushed to the Hub asynchronously. Pushing data to the Hub is done in a separate + thread to avoid blocking the training script. In particular, if the upload fails for any reason (e.g. a connection + issue), the main script will not be interrupted. Data is automatically pushed to the Hub every `commit_every` + minutes (default to every 5 minutes). + + > [!WARNING] + > `HFSummaryWriter` is experimental. Its API is subject to change in the future without prior notice. + + Args: + repo_id (`str`): + The id of the repo to which the logs will be pushed. + logdir (`str`, *optional*): + The directory where the logs will be written. If not specified, a local directory will be created by the + underlying `SummaryWriter` object. + commit_every (`int` or `float`, *optional*): + The frequency (in minutes) at which the logs will be pushed to the Hub. Defaults to 5 minutes. + squash_history (`bool`, *optional*): + Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is + useful to avoid degraded performances on the repo when it grows too large. + repo_type (`str`, *optional*): + The type of the repo to which the logs will be pushed. Defaults to "model". + repo_revision (`str`, *optional*): + The revision of the repo to which the logs will be pushed. Defaults to "main". + repo_private (`bool`, *optional*): + Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. + path_in_repo (`str`, *optional*): + The path to the folder in the repo where the logs will be pushed. Defaults to "tensorboard/". + repo_allow_patterns (`list[str]` or `str`, *optional*): + A list of patterns to include in the upload. Defaults to `"*.tfevents.*"`. Check out the + [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details. + repo_ignore_patterns (`list[str]` or `str`, *optional*): + A list of patterns to exclude in the upload. Check out the + [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details. + token (`str`, *optional*): + Authentication token. Will default to the stored token. See https://huggingface.co/settings/token for more + details + kwargs: + Additional keyword arguments passed to `SummaryWriter`. + + Examples: + ```diff + # Taken from https://pytorch.org/docs/stable/tensorboard.html + - from torch.utils.tensorboard import SummaryWriter + + from huggingface_hub import HFSummaryWriter + + import numpy as np + + - writer = SummaryWriter() + + writer = HFSummaryWriter(repo_id="username/my-trained-model") + + for n_iter in range(100): + writer.add_scalar('Loss/train', np.random.random(), n_iter) + writer.add_scalar('Loss/test', np.random.random(), n_iter) + writer.add_scalar('Accuracy/train', np.random.random(), n_iter) + writer.add_scalar('Accuracy/test', np.random.random(), n_iter) + ``` + + ```py + >>> from huggingface_hub import HFSummaryWriter + + # Logs are automatically pushed every 15 minutes (5 by default) + when exiting the context manager + >>> with HFSummaryWriter(repo_id="test_hf_logger", commit_every=15) as logger: + ... logger.add_scalar("a", 1) + ... logger.add_scalar("b", 2) + ``` + """ + + @experimental + def __new__(cls, *args, **kwargs) -> "HFSummaryWriter": + if not is_summary_writer_available: + raise ImportError( + "You must have `tensorboard` installed to use `HFSummaryWriter`. Please run `pip install --upgrade" + " tensorboardX` first." + ) + return super().__new__(cls) + + def __init__( + self, + repo_id: str, + *, + logdir: str | None = None, + commit_every: int | float = 5, + squash_history: bool = False, + repo_type: str | None = None, + repo_revision: str | None = None, + repo_private: bool | None = None, + path_in_repo: str | None = "tensorboard", + repo_allow_patterns: list[str] | str | None = "*.tfevents.*", + repo_ignore_patterns: list[str] | str | None = None, + token: str | None = None, + **kwargs, + ): + # Initialize SummaryWriter + super().__init__(logdir=logdir, **kwargs) + + # Check logdir has been correctly initialized and fail early otherwise. In practice, SummaryWriter takes care of it. + if not isinstance(self.logdir, str): + raise ValueError(f"`self.logdir` must be a string. Got '{self.logdir}' of type {type(self.logdir)}.") + + # Append logdir name to `path_in_repo` + if path_in_repo is None or path_in_repo == "": + path_in_repo = Path(self.logdir).name + else: + path_in_repo = path_in_repo.strip("/") + "/" + Path(self.logdir).name + + # Initialize scheduler + self.scheduler = CommitScheduler( + folder_path=self.logdir, + path_in_repo=path_in_repo, + repo_id=repo_id, + repo_type=repo_type, + revision=repo_revision, + private=repo_private, + token=token, + allow_patterns=repo_allow_patterns, + ignore_patterns=repo_ignore_patterns, + every=commit_every, + squash_history=squash_history, + ) + + # Exposing some high-level info at root level + self.repo_id = self.scheduler.repo_id + self.repo_type = self.scheduler.repo_type + self.repo_revision = self.scheduler.revision + + # Add `hf-summary-writer` tag to the model card metadata + try: + card = ModelCard.load(repo_id_or_path=self.repo_id, repo_type=self.repo_type) + except EntryNotFoundError: + card = ModelCard("") + tags = card.data.get("tags", []) + if "hf-summary-writer" not in tags: + tags.append("hf-summary-writer") + card.data["tags"] = tags + card.push_to_hub(repo_id=self.repo_id, repo_type=self.repo_type) + + def __exit__(self, exc_type, exc_val, exc_tb): + """Push to hub in a non-blocking way when exiting the logger's context manager.""" + super().__exit__(exc_type, exc_val, exc_tb) + future = self.scheduler.trigger() + future.result() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_upload_large_folder.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_upload_large_folder.py new file mode 100644 index 0000000000000000000000000000000000000000..2fd0045e6776d2170c5ef31548916ba0fd0470a1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_upload_large_folder.py @@ -0,0 +1,769 @@ +# Copyright 2024-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import enum +import logging +import os +import queue +import shutil +import sys +import threading +import time +import traceback +from datetime import datetime +from pathlib import Path +from threading import Lock +from typing import TYPE_CHECKING, Any +from urllib.parse import quote + +from ._commit_api import CommitOperationAdd, UploadInfo, _fetch_upload_modes +from ._local_folder import LocalUploadFileMetadata, LocalUploadFilePaths, get_local_upload_paths, read_upload_metadata +from .constants import DEFAULT_REVISION, REPO_TYPES +from .utils import DEFAULT_IGNORE_PATTERNS, _format_size, filter_repo_objects, tqdm +from .utils._runtime import is_xet_available +from .utils.sha import sha_fileobj + + +if TYPE_CHECKING: + from .hf_api import HfApi + +logger = logging.getLogger(__name__) + +WAITING_TIME_IF_NO_TASKS = 10 # seconds +MAX_NB_FILES_FETCH_UPLOAD_MODE = 100 +COMMIT_SIZE_SCALE: list[int] = [20, 50, 75, 100, 125, 200, 250, 400, 600, 1000] + +UPLOAD_BATCH_SIZE_XET = 256 # Max 256 files per upload batch for XET-enabled repos +UPLOAD_BATCH_SIZE_LFS = 1 # Otherwise, batches of 1 for regular LFS upload + +# Repository limits (from https://huggingface.co/docs/hub/repositories-recommendations) +MAX_FILES_PER_REPO = 100_000 # Recommended maximum number of files per repository +MAX_FILES_PER_FOLDER = 10_000 # Recommended maximum number of files per folder +MAX_FILE_SIZE_GB = 200 # Recommended maximum for individual file size (split larger files) +RECOMMENDED_FILE_SIZE_GB = 20 # Recommended maximum for individual file size + + +def _validate_upload_limits(paths_list: list[LocalUploadFilePaths]) -> None: + """ + Validate upload against repository limits and warn about potential issues. + + Args: + paths_list: List of file paths to be uploaded + + Warns about: + - Too many files in the repository (>100k) + - Too many entries (files or subdirectories) in a single folder (>10k) + - Files exceeding size limits (>20GB recommended, >200GB maximum) + """ + logger.info("Running validation checks on files to upload...") + + # Check 1: Total file count + if len(paths_list) > MAX_FILES_PER_REPO: + logger.warning( + f"You are about to upload {len(paths_list):,} files. " + f"This exceeds the recommended limit of {MAX_FILES_PER_REPO:,} files per repository.\n" + f"Consider:\n" + f" - Splitting your data into multiple repositories\n" + f" - Using fewer, larger files (e.g., parquet files)\n" + f" - See: https://huggingface.co/docs/hub/repositories-recommendations" + ) + + # Check 2: Files and subdirectories per folder + # Track immediate children (files and subdirs) for each folder + from collections import defaultdict + + entries_per_folder: dict[str, Any] = defaultdict(lambda: {"files": 0, "subdirs": set()}) + + for paths in paths_list: + path = Path(paths.path_in_repo) + parts = path.parts + + # Count this file in its immediate parent directory + parent = str(path.parent) if str(path.parent) != "." else "." + entries_per_folder[parent]["files"] += 1 + + # Track immediate subdirectories for each parent folder + # Walk through the path components to track parent-child relationships + for i, child in enumerate(parts[:-1]): + parent = "." if i == 0 else "/".join(parts[:i]) + entries_per_folder[parent]["subdirs"].add(child) + + # Check limits for each folder + for folder, data in entries_per_folder.items(): + file_count = data["files"] + subdir_count = len(data["subdirs"]) + total_entries = file_count + subdir_count + + if total_entries > MAX_FILES_PER_FOLDER: + folder_display = "root" if folder == "." else folder + logger.warning( + f"Folder '{folder_display}' contains {total_entries:,} entries " + f"({file_count:,} files and {subdir_count:,} subdirectories). " + f"This exceeds the recommended {MAX_FILES_PER_FOLDER:,} entries per folder.\n" + "Consider reorganising into sub-folders." + ) + + # Check 3: File sizes + large_files = [] + very_large_files = [] + + for paths in paths_list: + size = paths.file_path.stat().st_size + size_gb = size / 1_000_000_000 # Use decimal GB as per Hub limits + + if size_gb > MAX_FILE_SIZE_GB: + very_large_files.append((paths.path_in_repo, size_gb)) + elif size_gb > RECOMMENDED_FILE_SIZE_GB: + large_files.append((paths.path_in_repo, size_gb)) + + # Warn about very large files (>200GB) + if very_large_files: + files_str = "\n - ".join(f"{path}: {size:.1f}GB" for path, size in very_large_files[:5]) + more_str = f"\n ... and {len(very_large_files) - 5} more files" if len(very_large_files) > 5 else "" + logger.warning( + f"Found {len(very_large_files)} files exceeding the {MAX_FILE_SIZE_GB}GB recommended maximum:\n" + f" - {files_str}{more_str}\n" + f"Consider splitting these files into smaller chunks." + ) + + # Warn about large files (>20GB) + if large_files: + files_str = "\n - ".join(f"{path}: {size:.1f}GB" for path, size in large_files[:5]) + more_str = f"\n ... and {len(large_files) - 5} more files" if len(large_files) > 5 else "" + logger.warning( + f"Found {len(large_files)} files larger than {RECOMMENDED_FILE_SIZE_GB}GB (recommended limit):\n" + f" - {files_str}{more_str}\n" + f"Large files may slow down loading and processing." + ) + + logger.info("Validation checks complete.") + + +def upload_large_folder_internal( + api: "HfApi", + repo_id: str, + folder_path: str | Path, + *, + repo_type: str, # Repo type is required! + revision: str | None = None, + private: bool | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + num_workers: int | None = None, + print_report: bool = True, + print_report_every: int = 60, +): + """Upload a large folder to the Hub in the most resilient way possible. + + See [`HfApi.upload_large_folder`] for the full documentation. + """ + # 1. Check args and setup + if repo_type is None: + raise ValueError( + "For large uploads, `repo_type` is explicitly required. Please set it to `model`, `dataset` or `space`." + " If you are using the CLI, pass it as `--repo-type=model`." + ) + if repo_type not in REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}") + if revision is None: + revision = DEFAULT_REVISION + + folder_path = Path(folder_path).expanduser().resolve() + if not folder_path.is_dir(): + raise ValueError(f"Provided path: '{folder_path}' is not a directory") + + if ignore_patterns is None: + ignore_patterns = [] + elif isinstance(ignore_patterns, str): + ignore_patterns = [ignore_patterns] + ignore_patterns += DEFAULT_IGNORE_PATTERNS + + if num_workers is None: + nb_cores = os.cpu_count() or 1 + num_workers = max(nb_cores // 2, 1) # Use at most half of cpu cores + + # 2. Create repo if missing + repo_url = api.create_repo(repo_id=repo_id, repo_type=repo_type, private=private, exist_ok=True) + logger.info(f"Repo created: {repo_url}") + repo_id = repo_url.repo_id + + # Warn on too many commits + try: + commits = api.list_repo_commits(repo_id=repo_id, repo_type=repo_type, revision=revision) + commit_count = len(commits) + if commit_count > 500: + logger.warning( + f"\n{'=' * 80}\n" + f"WARNING: This repository has {commit_count} commits.\n" + f"Repositories with a large number of commits can experience performance issues.\n" + f"\n" + f"Consider squashing your commit history using `super_squash_history()`.\n" + "To do so, you need to stop this process, run the snippet below and restart the upload command." + f" from huggingface_hub import super_squash_history\n" + f" super_squash_history(repo_id='{repo_id}', repo_type='{repo_type}')\n" + f"\n" + f"Note: This is a non-revertible operation. See the documentation for more details:\n" + f"https://huggingface.co/docs/huggingface_hub/main/en/package_reference/hf_api#huggingface_hub.HfApi.super_squash_history\n" + f"{'=' * 80}\n" + ) + except Exception as e: + # Don't fail the upload if we can't check commit count + logger.debug(f"Could not check commit count: {e}") + + # 2.1 Check if xet is enabled to set batch file upload size + upload_batch_size = UPLOAD_BATCH_SIZE_XET if is_xet_available() else UPLOAD_BATCH_SIZE_LFS + + # 3. List files to upload + filtered_paths_list = filter_repo_objects( + (path.relative_to(folder_path).as_posix() for path in folder_path.glob("**/*") if path.is_file()), + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + ) + paths_list = [get_local_upload_paths(folder_path, relpath) for relpath in filtered_paths_list] + logger.info(f"Found {len(paths_list)} candidate files to upload") + + # Validate upload against repository limits + _validate_upload_limits(paths_list) + + logger.info("Starting upload...") + + # Read metadata for each file + items = [ + (paths, read_upload_metadata(folder_path, paths.path_in_repo)) + for paths in tqdm(paths_list, desc="Recovering from metadata files") + ] + + # 4. Start workers + status = LargeUploadStatus(items, upload_batch_size) + threads = [ + threading.Thread( + target=_worker_job, + kwargs={ + "status": status, + "api": api, + "repo_id": repo_id, + "repo_type": repo_type, + "revision": revision, + }, + ) + for _ in range(num_workers) + ] + + for thread in threads: + thread.start() + + # 5. Print regular reports + if print_report: + print("\n\n" + status.current_report()) + last_report_ts = time.time() + while True: + time.sleep(1) + if time.time() - last_report_ts >= print_report_every: + if print_report: + _print_overwrite(status.current_report()) + last_report_ts = time.time() + if status.is_done(): + logger.info("Is done: exiting main loop") + break + + for thread in threads: + thread.join() + + logger.info(status.current_report()) + logger.info("Upload is complete!") + + +#################### +# Logic to manage workers and synchronize tasks +#################### + + +class WorkerJob(enum.Enum): + SHA256 = enum.auto() + GET_UPLOAD_MODE = enum.auto() + PREUPLOAD_LFS = enum.auto() + COMMIT = enum.auto() + WAIT = enum.auto() # if no tasks are available but we don't want to exit + + +JOB_ITEM_T = tuple[LocalUploadFilePaths, LocalUploadFileMetadata] + + +class LargeUploadStatus: + """Contains information, queues and tasks for a large upload process.""" + + def __init__(self, items: list[JOB_ITEM_T], upload_batch_size: int = 1): + self.items = items + self.queue_sha256: "queue.Queue[JOB_ITEM_T]" = queue.Queue() + self.queue_get_upload_mode: "queue.Queue[JOB_ITEM_T]" = queue.Queue() + self.queue_preupload_lfs: "queue.Queue[JOB_ITEM_T]" = queue.Queue() + self.queue_commit: "queue.Queue[JOB_ITEM_T]" = queue.Queue() + self.lock = Lock() + + self.nb_workers_sha256: int = 0 + self.nb_workers_get_upload_mode: int = 0 + self.nb_workers_preupload_lfs: int = 0 + self.upload_batch_size: int = upload_batch_size + self.nb_workers_commit: int = 0 + self.nb_workers_waiting: int = 0 + self.last_commit_attempt: float | None = None + + self._started_at = datetime.now() + self._chunk_idx: int = 1 + self._chunk_lock: Lock = Lock() + + # Setup queues + for item in self.items: + paths, metadata = item + if metadata.sha256 is None: + self.queue_sha256.put(item) + elif metadata.upload_mode is None: + self.queue_get_upload_mode.put(item) + elif metadata.upload_mode == "lfs" and not metadata.is_uploaded: + self.queue_preupload_lfs.put(item) + elif not metadata.is_committed: + self.queue_commit.put(item) + else: + logger.debug(f"Skipping file {paths.path_in_repo} (already uploaded and committed)") + + def target_chunk(self) -> int: + with self._chunk_lock: + return COMMIT_SIZE_SCALE[self._chunk_idx] + + def update_chunk(self, success: bool, nb_items: int, duration: float) -> None: + with self._chunk_lock: + if not success: + logger.warning(f"Failed to commit {nb_items} files at once. Will retry with less files in next batch.") + self._chunk_idx -= 1 + elif nb_items >= COMMIT_SIZE_SCALE[self._chunk_idx] and duration < 40: + logger.info(f"Successfully committed {nb_items} at once. Increasing the limit for next batch.") + self._chunk_idx += 1 + + self._chunk_idx = max(0, min(self._chunk_idx, len(COMMIT_SIZE_SCALE) - 1)) + + def current_report(self) -> str: + """Generate a report of the current status of the large upload.""" + nb_hashed = 0 + size_hashed = 0 + nb_preuploaded = 0 + nb_lfs = 0 + nb_lfs_unsure = 0 + size_preuploaded = 0 + nb_committed = 0 + size_committed = 0 + total_size = 0 + ignored_files = 0 + total_files = 0 + + with self.lock: + for _, metadata in self.items: + if metadata.should_ignore: + ignored_files += 1 + continue + total_size += metadata.size + total_files += 1 + if metadata.sha256 is not None: + nb_hashed += 1 + size_hashed += metadata.size + if metadata.upload_mode == "lfs": + nb_lfs += 1 + if metadata.upload_mode is None: + nb_lfs_unsure += 1 + if metadata.is_uploaded: + nb_preuploaded += 1 + size_preuploaded += metadata.size + if metadata.is_committed: + nb_committed += 1 + size_committed += metadata.size + total_size_str = _format_size(total_size) + + now = datetime.now() + now_str = now.strftime("%Y-%m-%d %H:%M:%S") + elapsed = now - self._started_at + elapsed_str = str(elapsed).split(".")[0] # remove milliseconds + + message = "\n" + "-" * 10 + message += f" {now_str} ({elapsed_str}) " + message += "-" * 10 + "\n" + + message += "Files: " + message += f"hashed {nb_hashed}/{total_files} ({_format_size(size_hashed)}/{total_size_str}) | " + message += f"pre-uploaded: {nb_preuploaded}/{nb_lfs} ({_format_size(size_preuploaded)}/{total_size_str})" + if nb_lfs_unsure > 0: + message += f" (+{nb_lfs_unsure} unsure)" + message += f" | committed: {nb_committed}/{total_files} ({_format_size(size_committed)}/{total_size_str})" + message += f" | ignored: {ignored_files}\n" + + message += "Workers: " + message += f"hashing: {self.nb_workers_sha256} | " + message += f"get upload mode: {self.nb_workers_get_upload_mode} | " + message += f"pre-uploading: {self.nb_workers_preupload_lfs} | " + message += f"committing: {self.nb_workers_commit} | " + message += f"waiting: {self.nb_workers_waiting}\n" + message += "-" * 51 + + return message + + def is_done(self) -> bool: + with self.lock: + return all(metadata.is_committed or metadata.should_ignore for _, metadata in self.items) + + +def _worker_job( + status: LargeUploadStatus, + api: "HfApi", + repo_id: str, + repo_type: str, + revision: str, +): + """ + Main process for a worker. The worker will perform tasks based on the priority list until all files are uploaded + and committed. If no tasks are available, the worker will wait for 10 seconds before checking again. + + If a task fails for any reason, the item(s) are put back in the queue for another worker to pick up. + + Read `upload_large_folder` docstring for more information on how tasks are prioritized. + """ + while True: + next_job: tuple[WorkerJob, list[JOB_ITEM_T]] | None = None + + # Determine next task + next_job = _determine_next_job(status) + if next_job is None: + return + job, items = next_job + + # Perform task + match job: + case WorkerJob.SHA256: + item = items[0] # single item + try: + _compute_sha256(item) + status.queue_get_upload_mode.put(item) + except KeyboardInterrupt: + raise + except Exception as e: + logger.error(f"Failed to compute sha256: {e}") + traceback.format_exc() + status.queue_sha256.put(item) + + with status.lock: + status.nb_workers_sha256 -= 1 + + case WorkerJob.GET_UPLOAD_MODE: + try: + _get_upload_mode(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision) + except KeyboardInterrupt: + raise + except Exception as e: + logger.error(f"Failed to get upload mode: {e}") + traceback.format_exc() + + # Items are either: + # - dropped (if should_ignore) + # - put in LFS queue (if LFS) + # - put in commit queue (if regular) + # - or put back (if error occurred). + for item in items: + _, metadata = item + if metadata.should_ignore: + continue + match metadata.upload_mode: + case "lfs": + status.queue_preupload_lfs.put(item) + case "regular": + status.queue_commit.put(item) + case _: + status.queue_get_upload_mode.put(item) + + with status.lock: + status.nb_workers_get_upload_mode -= 1 + + case WorkerJob.PREUPLOAD_LFS: + try: + _preupload_lfs(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision) + for item in items: + status.queue_commit.put(item) + except KeyboardInterrupt: + raise + except Exception as e: + logger.error(f"Failed to preupload LFS: {e}") + traceback.format_exc() + for item in items: + status.queue_preupload_lfs.put(item) + + with status.lock: + status.nb_workers_preupload_lfs -= 1 + + case WorkerJob.COMMIT: + start_ts = time.time() + success = True + try: + _commit(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision) + except KeyboardInterrupt: + raise + except Exception as e: + logger.error(f"Failed to commit: {e}") + traceback.format_exc() + for item in items: + status.queue_commit.put(item) + success = False + duration = time.time() - start_ts + status.update_chunk(success, len(items), duration) + with status.lock: + status.last_commit_attempt = time.time() + status.nb_workers_commit -= 1 + + case WorkerJob.WAIT: + time.sleep(WAITING_TIME_IF_NO_TASKS) + with status.lock: + status.nb_workers_waiting -= 1 + + +def _determine_next_job(status: LargeUploadStatus) -> tuple[WorkerJob, list[JOB_ITEM_T]] | None: + with status.lock: + # 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file) + if ( + status.nb_workers_commit == 0 + and status.queue_commit.qsize() > 0 + and status.last_commit_attempt is not None + and time.time() - status.last_commit_attempt > 5 * 60 + ): + status.nb_workers_commit += 1 + logger.debug("Job: commit (more than 5 minutes since last commit attempt)") + return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk())) + + # 2. Commit if at least 100 files are ready to commit + elif status.nb_workers_commit == 0 and status.queue_commit.qsize() >= 150: + status.nb_workers_commit += 1 + logger.debug("Job: commit (>100 files ready)") + return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk())) + + # 3. Get upload mode if at least 100 files + elif status.queue_get_upload_mode.qsize() >= MAX_NB_FILES_FETCH_UPLOAD_MODE: + status.nb_workers_get_upload_mode += 1 + logger.debug(f"Job: get upload mode (>{MAX_NB_FILES_FETCH_UPLOAD_MODE} files ready)") + return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE)) + + # 4. Preupload LFS file if at least `status.upload_batch_size` files and no worker is preuploading LFS + elif status.queue_preupload_lfs.qsize() >= status.upload_batch_size and status.nb_workers_preupload_lfs == 0: + status.nb_workers_preupload_lfs += 1 + logger.debug("Job: preupload LFS (no other worker preuploading LFS)") + return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size)) + + # 5. Compute sha256 if at least 1 file and no worker is computing sha256 + elif status.queue_sha256.qsize() > 0 and status.nb_workers_sha256 == 0: + status.nb_workers_sha256 += 1 + logger.debug("Job: sha256 (no other worker computing sha256)") + return (WorkerJob.SHA256, _get_one(status.queue_sha256)) + + # 6. Get upload mode if at least 1 file and no worker is getting upload mode + elif status.queue_get_upload_mode.qsize() > 0 and status.nb_workers_get_upload_mode == 0: + status.nb_workers_get_upload_mode += 1 + logger.debug("Job: get upload mode (no other worker getting upload mode)") + return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE)) + + # 7. Preupload LFS file if at least `status.upload_batch_size` files + elif status.queue_preupload_lfs.qsize() >= status.upload_batch_size: + status.nb_workers_preupload_lfs += 1 + logger.debug("Job: preupload LFS") + return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size)) + + # 8. Compute sha256 if at least 1 file + elif status.queue_sha256.qsize() > 0: + status.nb_workers_sha256 += 1 + logger.debug("Job: sha256") + return (WorkerJob.SHA256, _get_one(status.queue_sha256)) + + # 9. Get upload mode if at least 1 file + elif status.queue_get_upload_mode.qsize() > 0: + status.nb_workers_get_upload_mode += 1 + logger.debug("Job: get upload mode") + return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE)) + + # 10. Preupload LFS file if at least 1 file + elif status.queue_preupload_lfs.qsize() > 0: + status.nb_workers_preupload_lfs += 1 + logger.debug("Job: preupload LFS") + return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size)) + + # 11. Commit if at least 1 file and 1 min since last commit attempt + elif ( + status.nb_workers_commit == 0 + and status.queue_commit.qsize() > 0 + and status.last_commit_attempt is not None + and time.time() - status.last_commit_attempt > 1 * 60 + ): + status.nb_workers_commit += 1 + logger.debug("Job: commit (1 min since last commit attempt)") + return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk())) + + # 12. Commit if at least 1 file all other queues are empty and all workers are waiting + # e.g. when it's the last commit + elif ( + status.nb_workers_commit == 0 + and status.queue_commit.qsize() > 0 + and status.queue_sha256.qsize() == 0 + and status.queue_get_upload_mode.qsize() == 0 + and status.queue_preupload_lfs.qsize() == 0 + and status.nb_workers_sha256 == 0 + and status.nb_workers_get_upload_mode == 0 + and status.nb_workers_preupload_lfs == 0 + ): + status.nb_workers_commit += 1 + logger.debug("Job: commit") + return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk())) + + # 13. If all queues are empty, exit + elif all(metadata.is_committed or metadata.should_ignore for _, metadata in status.items): + logger.info("All files have been processed! Exiting worker.") + return None + + # 14. If no task is available, wait + else: + status.nb_workers_waiting += 1 + logger.debug(f"No task available, waiting... ({WAITING_TIME_IF_NO_TASKS}s)") + return (WorkerJob.WAIT, []) + + +#################### +# Atomic jobs (sha256, get_upload_mode, preupload_lfs, commit) +#################### + + +def _compute_sha256(item: JOB_ITEM_T) -> None: + """Compute sha256 of a file and save it in metadata.""" + paths, metadata = item + if metadata.sha256 is None: + with paths.file_path.open("rb") as f: + metadata.sha256 = sha_fileobj(f).hex() + metadata.save(paths) + + +def _get_upload_mode(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None: + """Get upload mode for each file and update metadata. + + Also receive info if the file should be ignored. + """ + additions = [_build_hacky_operation(item) for item in items] + _fetch_upload_modes( + additions=additions, + repo_type=repo_type, + repo_id=repo_id, + headers=api._build_hf_headers(), + revision=quote(revision, safe=""), + endpoint=api.endpoint, + ) + for item, addition in zip(items, additions): + paths, metadata = item + metadata.upload_mode = addition._upload_mode + metadata.should_ignore = addition._should_ignore + metadata.remote_oid = addition._remote_oid + metadata.save(paths) + + +def _preupload_lfs(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None: + """Preupload LFS files and update metadata.""" + additions = [_build_hacky_operation(item) for item in items] + api.preupload_lfs_files( + repo_id=repo_id, + repo_type=repo_type, + revision=revision, + additions=additions, + ) + + for paths, metadata in items: + metadata.is_uploaded = True + metadata.save(paths) + + +def _commit(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None: + """Commit files to the repo.""" + additions = [_build_hacky_operation(item) for item in items] + api.create_commit( + repo_id=repo_id, + repo_type=repo_type, + revision=revision, + operations=additions, + commit_message="Add files using upload-large-folder tool", + ) + for paths, metadata in items: + metadata.is_committed = True + metadata.save(paths) + + +#################### +# Hacks with CommitOperationAdd to bypass checks/sha256 calculation +#################### + + +class HackyCommitOperationAdd(CommitOperationAdd): + def __post_init__(self) -> None: + if isinstance(self.path_or_fileobj, Path): + self.path_or_fileobj = str(self.path_or_fileobj) + + +def _build_hacky_operation(item: JOB_ITEM_T) -> HackyCommitOperationAdd: + paths, metadata = item + operation = HackyCommitOperationAdd(path_in_repo=paths.path_in_repo, path_or_fileobj=paths.file_path) + with paths.file_path.open("rb") as file: + sample = file.peek(512)[:512] + if metadata.sha256 is None: + raise ValueError("sha256 must have been computed by now!") + operation.upload_info = UploadInfo(sha256=bytes.fromhex(metadata.sha256), size=metadata.size, sample=sample) + operation._upload_mode = metadata.upload_mode # type: ignore + operation._should_ignore = metadata.should_ignore + operation._remote_oid = metadata.remote_oid + operation._is_uploaded = metadata.is_uploaded + if metadata.is_uploaded and metadata.upload_mode == "lfs": + operation.path_or_fileobj = b"" + return operation + + +#################### +# Misc helpers +#################### + + +def _get_one(queue: "queue.Queue[JOB_ITEM_T]") -> list[JOB_ITEM_T]: + return [queue.get()] + + +def _get_n(queue: "queue.Queue[JOB_ITEM_T]", n: int) -> list[JOB_ITEM_T]: + return [queue.get() for _ in range(min(queue.qsize(), n))] + + +def _print_overwrite(report: str) -> None: + """Print a report, overwriting the previous lines. + + Since tqdm in using `sys.stderr` to (re-)write progress bars, we need to use `sys.stdout` + to print the report. + + Note: works well only if no other process is writing to `sys.stdout`! + """ + report += "\n" + # Get terminal width + terminal_width = shutil.get_terminal_size().columns + + # Count number of lines that should be cleared + nb_lines = sum(len(line) // terminal_width + 1 for line in report.splitlines()) + + # Clear previous lines based on the number of lines in the report + for _ in range(nb_lines): + sys.stdout.write("\r\033[K") # Clear line + sys.stdout.write("\033[F") # Move cursor up one line + + # Print the new report, filling remaining space with whitespace + sys.stdout.write(report) + sys.stdout.write(" " * (terminal_width - len(report.splitlines()[-1]))) + sys.stdout.flush() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_webhooks_payload.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_webhooks_payload.py new file mode 100644 index 0000000000000000000000000000000000000000..976a97a1d30a5105d26f4cb3746be2c9d10d1e4b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_webhooks_payload.py @@ -0,0 +1,136 @@ +# Copyright 2023-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains data structures to parse the webhooks payload.""" + +from typing import Literal + +from .utils import is_pydantic_available + + +if is_pydantic_available(): + from pydantic import BaseModel +else: + # Define a dummy BaseModel to avoid import errors when pydantic is not installed + # Import error will be raised when trying to use the class + + class BaseModel: # type: ignore [no-redef] + def __init__(self, *args, **kwargs) -> None: + raise ImportError( + "You must have `pydantic` installed to use `WebhookPayload`. This is an optional dependency that" + " should be installed separately. Please run `pip install --upgrade pydantic` and retry." + ) + + +# This is an adaptation of the ReportV3 interface implemented in moon-landing. V0, V1 and V2 have been ignored as they +# are not in used anymore. To keep in sync when format is updated in +# https://github.com/huggingface/moon-landing/blob/main/server/lib/HFWebhooks.ts (internal link). + + +WebhookEvent_T = Literal[ + "create", + "delete", + "move", + "update", +] +RepoChangeEvent_T = Literal[ + "add", + "move", + "remove", + "update", +] +RepoType_T = Literal[ + "dataset", + "model", + "space", +] +DiscussionStatus_T = Literal[ + "closed", + "draft", + "open", + "merged", +] +SupportedWebhookVersion = Literal[3] + + +class ObjectId(BaseModel): + id: str + + +class WebhookPayloadUrl(BaseModel): + web: str + api: str | None = None + + +class WebhookPayloadMovedTo(BaseModel): + name: str + owner: ObjectId + + +class WebhookPayloadWebhook(ObjectId): + version: SupportedWebhookVersion + + +class WebhookPayloadEvent(BaseModel): + action: WebhookEvent_T + scope: str + + +class WebhookPayloadDiscussionChanges(BaseModel): + base: str + mergeCommitId: str | None = None + + +class WebhookPayloadComment(ObjectId): + author: ObjectId + hidden: bool + content: str | None = None + url: WebhookPayloadUrl + + +class WebhookPayloadDiscussion(ObjectId): + num: int + author: ObjectId + url: WebhookPayloadUrl + title: str + isPullRequest: bool + status: DiscussionStatus_T + changes: WebhookPayloadDiscussionChanges | None = None + pinned: bool | None = None + + +class WebhookPayloadRepo(ObjectId): + owner: ObjectId + head_sha: str | None = None + name: str + private: bool + subdomain: str | None = None + tags: list[str] | None = None + type: Literal["dataset", "model", "space"] + url: WebhookPayloadUrl + + +class WebhookPayloadUpdatedRef(BaseModel): + ref: str + oldSha: str | None = None + newSha: str | None = None + + +class WebhookPayload(BaseModel): + event: WebhookPayloadEvent + repo: WebhookPayloadRepo + discussion: WebhookPayloadDiscussion | None = None + comment: WebhookPayloadComment | None = None + webhook: WebhookPayloadWebhook + movedTo: WebhookPayloadMovedTo | None = None + updatedRefs: list[WebhookPayloadUpdatedRef] | None = None diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_webhooks_server.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_webhooks_server.py new file mode 100644 index 0000000000000000000000000000000000000000..662b16b4b43e9ebbd9fc40d03af888d60fe5e5e4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/_webhooks_server.py @@ -0,0 +1,376 @@ +# Copyright 2023-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Contains `WebhooksServer` and `webhook_endpoint` to create a webhook server easily.""" + +import atexit +import inspect +import os +from collections.abc import Callable +from functools import wraps +from typing import TYPE_CHECKING, Any, Optional + +from .utils import experimental, is_fastapi_available, is_gradio_available + + +if TYPE_CHECKING: + import gradio as gr + from fastapi import Request + +if is_fastapi_available(): + from fastapi import FastAPI, Request + from fastapi.responses import JSONResponse +else: + # Will fail at runtime if FastAPI is not available + FastAPI = Request = JSONResponse = None # type: ignore + + +_global_app: Optional["WebhooksServer"] = None +_is_local = os.environ.get("SPACE_ID") is None + + +@experimental +class WebhooksServer: + """ + The [`WebhooksServer`] class lets you create an instance of a Gradio app that can receive Huggingface webhooks. + These webhooks can be registered using the [`~WebhooksServer.add_webhook`] decorator. Webhook endpoints are added to + the app as a POST endpoint to the FastAPI router. Once all the webhooks are registered, the `launch` method has to be + called to start the app. + + It is recommended to accept [`WebhookPayload`] as the first argument of the webhook function. It is a Pydantic + model that contains all the information about the webhook event. The data will be parsed automatically for you. + + Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to set up your + WebhooksServer and deploy it on a Space. + + > [!WARNING] + > `WebhooksServer` is experimental. Its API is subject to change in the future. + + > [!WARNING] + > You must have `gradio` installed to use `WebhooksServer` (`pip install --upgrade gradio`). + + Args: + ui (`gradio.Blocks`, optional): + A Gradio UI instance to be used as the Space landing page. If `None`, a UI displaying instructions + about the configured webhooks is created. + webhook_secret (`str`, optional): + A secret key to verify incoming webhook requests. You can set this value to any secret you want as long as + you also configure it in your [webhooks settings panel](https://huggingface.co/settings/webhooks). You + can also set this value as the `WEBHOOK_SECRET` environment variable. If no secret is provided, the + webhook endpoints are opened without any security. + + Example: + + ```python + import gradio as gr + from huggingface_hub import WebhooksServer, WebhookPayload + + with gr.Blocks() as ui: + ... + + app = WebhooksServer(ui=ui, webhook_secret="my_secret_key") + + @app.add_webhook("/say_hello") + async def hello(payload: WebhookPayload): + return {"message": "hello"} + + app.launch() + ``` + """ + + def __new__(cls, *args, **kwargs) -> "WebhooksServer": + if not is_gradio_available(): + raise ImportError( + "You must have `gradio` installed to use `WebhooksServer`. Please run `pip install --upgrade gradio`" + " first." + ) + if not is_fastapi_available(): + raise ImportError( + "You must have `fastapi` installed to use `WebhooksServer`. Please run `pip install --upgrade fastapi`" + " first." + ) + return super().__new__(cls) + + def __init__( + self, + ui: Optional["gr.Blocks"] = None, + webhook_secret: str | None = None, + ) -> None: + self._ui = ui + + self.webhook_secret = webhook_secret or os.getenv("WEBHOOK_SECRET") + self.registered_webhooks: dict[str, Callable] = {} + _warn_on_empty_secret(self.webhook_secret) + + def add_webhook(self, path: str | None = None) -> Callable: + """ + Decorator to add a webhook to the [`WebhooksServer`] server. + + Args: + path (`str`, optional): + The URL path to register the webhook function. If not provided, the function name will be used as the + path. In any case, all webhooks are registered under `/webhooks`. + + Raises: + ValueError: If the provided path is already registered as a webhook. + + Example: + ```python + from huggingface_hub import WebhooksServer, WebhookPayload + + app = WebhooksServer() + + @app.add_webhook + async def trigger_training(payload: WebhookPayload): + if payload.repo.type == "dataset" and payload.event.action == "update": + # Trigger a training job if a dataset is updated + ... + + app.launch() + ``` + """ + # Usage: directly as decorator. Example: `@app.add_webhook` + if callable(path): + # If path is a function, it means it was used as a decorator without arguments + return self.add_webhook()(path) + + # Usage: provide a path. Example: `@app.add_webhook(...)` + @wraps(FastAPI.post) + def _inner_post(*args, **kwargs): + func = args[0] + abs_path = f"/webhooks/{(path or func.__name__).strip('/')}" + if abs_path in self.registered_webhooks: + raise ValueError(f"Webhook {abs_path} already exists.") + self.registered_webhooks[abs_path] = func + + return _inner_post + + def launch(self, prevent_thread_lock: bool = False, **launch_kwargs: Any) -> None: + """Launch the Gradio app and register webhooks to the underlying FastAPI server. + + Input parameters are forwarded to Gradio when launching the app. + """ + ui = self._ui or self._get_default_ui() + + # Start Gradio App + # - as non-blocking so that webhooks can be added afterwards + # - as shared if launch locally (to debug webhooks) + launch_kwargs.setdefault("share", _is_local) + self.fastapi_app, _, _ = ui.launch(prevent_thread_lock=True, **launch_kwargs) + + # Register webhooks to FastAPI app + for path, func in self.registered_webhooks.items(): + # Add secret check if required + if self.webhook_secret is not None: + func = _wrap_webhook_to_check_secret(func, webhook_secret=self.webhook_secret) + + # Add route to FastAPI app + self.fastapi_app.post(path)(func) + + # Print instructions and block main thread + space_host = os.environ.get("SPACE_HOST") + url = "https://" + space_host if space_host is not None else (ui.share_url or ui.local_url) + if url is None: + raise ValueError("Cannot find the URL of the app. Please provide a valid `ui` or update `gradio` version.") + url = url.strip("/") + message = "\nWebhooks are correctly setup and ready to use:" + message += "\n" + "\n".join(f" - POST {url}{webhook}" for webhook in self.registered_webhooks) + message += "\nGo to https://huggingface.co/settings/webhooks to setup your webhooks." + print(message) + + if not prevent_thread_lock: + ui.block_thread() + + def _get_default_ui(self) -> "gr.Blocks": + """Default UI if not provided (lists webhooks and provides basic instructions).""" + import gradio as gr + + with gr.Blocks() as ui: + gr.Markdown("# This is an app to process 🤗 Webhooks") + gr.Markdown( + "Webhooks are a foundation for MLOps-related features. They allow you to listen for new changes on" + " specific repos or to all repos belonging to particular set of users/organizations (not just your" + " repos, but any repo). Check out this [guide](https://huggingface.co/docs/hub/webhooks) to get to" + " know more about webhooks on the Huggingface Hub." + ) + gr.Markdown( + f"{len(self.registered_webhooks)} webhook(s) are registered:" + + "\n\n" + + "\n ".join( + f"- [{webhook_path}]({_get_webhook_doc_url(webhook.__name__, webhook_path)})" + for webhook_path, webhook in self.registered_webhooks.items() + ) + ) + gr.Markdown( + "Go to https://huggingface.co/settings/webhooks to setup your webhooks." + + "\nYou app is running locally. Please look at the logs to check the full URL you need to set." + if _is_local + else ( + "\nThis app is running on a Space. You can find the corresponding URL in the options menu" + " (top-right) > 'Embed the Space'. The URL looks like 'https://{username}-{repo_name}.hf.space'." + ) + ) + return ui + + +@experimental +def webhook_endpoint(path: str | None = None) -> Callable: + """Decorator to start a [`WebhooksServer`] and register the decorated function as a webhook endpoint. + + This is a helper to get started quickly. If you need more flexibility (custom landing page or webhook secret), + you can use [`WebhooksServer`] directly. You can register multiple webhook endpoints (to the same server) by using + this decorator multiple times. + + Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to set up your + server and deploy it on a Space. + + > [!WARNING] + > `webhook_endpoint` is experimental. Its API is subject to change in the future. + + > [!WARNING] + > You must have `gradio` installed to use `webhook_endpoint` (`pip install --upgrade gradio`). + + Args: + path (`str`, optional): + The URL path to register the webhook function. If not provided, the function name will be used as the path. + In any case, all webhooks are registered under `/webhooks`. + + Examples: + The default usage is to register a function as a webhook endpoint. The function name will be used as the path. + The server will be started automatically at exit (i.e. at the end of the script). + + ```python + from huggingface_hub import webhook_endpoint, WebhookPayload + + @webhook_endpoint + async def trigger_training(payload: WebhookPayload): + if payload.repo.type == "dataset" and payload.event.action == "update": + # Trigger a training job if a dataset is updated + ... + + # Server is automatically started at the end of the script. + ``` + + Advanced usage: register a function as a webhook endpoint and start the server manually. This is useful if you + are running it in a notebook. + + ```python + from huggingface_hub import webhook_endpoint, WebhookPayload + + @webhook_endpoint + async def trigger_training(payload: WebhookPayload): + if payload.repo.type == "dataset" and payload.event.action == "update": + # Trigger a training job if a dataset is updated + ... + + # Start the server manually + trigger_training.launch() + ``` + """ + if callable(path): + # If path is a function, it means it was used as a decorator without arguments + return webhook_endpoint()(path) + + @wraps(WebhooksServer.add_webhook) + def _inner(func: Callable) -> Callable: + app = _get_global_app() + app.add_webhook(path)(func) + if len(app.registered_webhooks) == 1: + # Register `app.launch` to run at exit (only once) + atexit.register(app.launch) + + @wraps(app.launch) + def _launch_now(): + # Run the app directly (without waiting atexit) + atexit.unregister(app.launch) + app.launch() + + func.launch = _launch_now # type: ignore + return func + + return _inner + + +def _get_global_app() -> WebhooksServer: + global _global_app + if _global_app is None: + _global_app = WebhooksServer() + return _global_app + + +def _warn_on_empty_secret(webhook_secret: str | None) -> None: + if webhook_secret is None: + print("Webhook secret is not defined. This means your webhook endpoints will be open to everyone.") + print( + "To add a secret, set `WEBHOOK_SECRET` as environment variable or pass it at initialization: " + "\n\t`app = WebhooksServer(webhook_secret='my_secret', ...)`" + ) + print( + "For more details about webhook secrets, please refer to" + " https://huggingface.co/docs/hub/webhooks#webhook-secret." + ) + else: + print("Webhook secret is correctly defined.") + + +def _get_webhook_doc_url(webhook_name: str, webhook_path: str) -> str: + """Returns the anchor to a given webhook in the docs (experimental)""" + return "/docs#/default/" + webhook_name + webhook_path.replace("/", "_") + "_post" + + +def _wrap_webhook_to_check_secret(func: Callable, webhook_secret: str) -> Callable: + """Wraps a webhook function to check the webhook secret before calling the function. + + This is a hacky way to add the `request` parameter to the function signature. Since FastAPI based itself on route + parameters to inject the values to the function, we need to hack the function signature to retrieve the `Request` + object (and hence the headers). A far cleaner solution would be to use a middleware. However, since + `fastapi==0.90.1`, a middleware cannot be added once the app has started. And since the FastAPI app is started by + Gradio internals (and not by us), we cannot add a middleware. + + This method is called only when a secret has been defined by the user. If a request is sent without the + "x-webhook-secret", the function will return a 401 error (unauthorized). If the header is sent but is incorrect, + the function will return a 403 error (forbidden). + + Inspired by https://stackoverflow.com/a/33112180. + """ + initial_sig = inspect.signature(func) + + @wraps(func) + async def _protected_func(request: Request, **kwargs): + request_secret = request.headers.get("x-webhook-secret") + if request_secret is None: + return JSONResponse({"error": "x-webhook-secret header not set."}, status_code=401) + if request_secret != webhook_secret: + return JSONResponse({"error": "Invalid webhook secret."}, status_code=403) + + # Inject `request` in kwargs if required + if "request" in initial_sig.parameters: + kwargs["request"] = request + + # Handle both sync and async routes + if inspect.iscoroutinefunction(func): + return await func(**kwargs) + else: + return func(**kwargs) + + # Update signature to include request + if "request" not in initial_sig.parameters: + _protected_func.__signature__ = initial_sig.replace( # type: ignore + parameters=( + inspect.Parameter(name="request", kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Request), + ) + + tuple(initial_sig.parameters.values()) + ) + + # Return protected route + return _protected_func diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/community.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/community.py new file mode 100644 index 0000000000000000000000000000000000000000..58e64100c48c461bb6d4dfb42230ffbf412bff57 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/community.py @@ -0,0 +1,363 @@ +""" +Data structures to interact with Discussions and Pull Requests on the Hub. + +See [the Discussions and Pull Requests guide](https://huggingface.co/docs/hub/repositories-pull-requests-discussions) +for more information on Pull Requests, Discussions, and the community tab. +""" + +from dataclasses import dataclass +from datetime import datetime +from typing import Literal, TypedDict + +from . import constants +from .utils import parse_datetime + + +DiscussionStatus = Literal["open", "closed", "merged", "draft"] + + +@dataclass +class Discussion: + """ + A Discussion or Pull Request on the Hub. + + This dataclass is not intended to be instantiated directly. + + Attributes: + title (`str`): + The title of the Discussion / Pull Request + status (`str`): + The status of the Discussion / Pull Request. + It must be one of: + * `"open"` + * `"closed"` + * `"merged"` (only for Pull Requests ) + * `"draft"` (only for Pull Requests ) + num (`int`): + The number of the Discussion / Pull Request. + repo_id (`str`): + The id (`"{namespace}/{repo_name}"`) of the repo on which + the Discussion / Pull Request was open. + repo_type (`str`): + The type of the repo on which the Discussion / Pull Request was open. + Possible values are: `"model"`, `"dataset"`, `"space"`. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + is_pull_request (`bool`): + Whether or not this is a Pull Request. + created_at (`datetime`): + The `datetime` of creation of the Discussion / Pull Request. + endpoint (`str`): + Endpoint of the Hub. Default is https://huggingface.co. + git_reference (`str`, *optional*): + (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise. + url (`str`): + (property) URL of the discussion on the Hub. + """ + + title: str + status: DiscussionStatus + num: int + repo_id: str + repo_type: str + author: str + is_pull_request: bool + created_at: datetime + endpoint: str + + @property + def git_reference(self) -> str | None: + """ + If this is a Pull Request , returns the git reference to which changes can be pushed. + Returns `None` otherwise. + """ + if self.is_pull_request: + return f"refs/pr/{self.num}" + return None + + @property + def url(self) -> str: + """Returns the URL of the discussion on the Hub.""" + if self.repo_type is None or self.repo_type == constants.REPO_TYPE_MODEL: + return f"{self.endpoint}/{self.repo_id}/discussions/{self.num}" + return f"{self.endpoint}/{self.repo_type}s/{self.repo_id}/discussions/{self.num}" + + +@dataclass +class DiscussionWithDetails(Discussion): + """ + Subclass of [`Discussion`]. + + Attributes: + title (`str`): + The title of the Discussion / Pull Request + status (`str`): + The status of the Discussion / Pull Request. + It can be one of: + * `"open"` + * `"closed"` + * `"merged"` (only for Pull Requests ) + * `"draft"` (only for Pull Requests ) + num (`int`): + The number of the Discussion / Pull Request. + repo_id (`str`): + The id (`"{namespace}/{repo_name}"`) of the repo on which + the Discussion / Pull Request was open. + repo_type (`str`): + The type of the repo on which the Discussion / Pull Request was open. + Possible values are: `"model"`, `"dataset"`, `"space"`. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + is_pull_request (`bool`): + Whether or not this is a Pull Request. + created_at (`datetime`): + The `datetime` of creation of the Discussion / Pull Request. + events (`list` of [`DiscussionEvent`]) + The list of [`DiscussionEvents`] in this Discussion or Pull Request. + conflicting_files (`Union[list[str], bool, None]`, *optional*): + A list of conflicting files if this is a Pull Request. + `None` if `self.is_pull_request` is `False`. + `True` if there are conflicting files but the list can't be retrieved. + target_branch (`str`, *optional*): + The branch into which changes are to be merged if this is a + Pull Request . `None` if `self.is_pull_request` is `False`. + merge_commit_oid (`str`, *optional*): + If this is a merged Pull Request , this is set to the OID / SHA of + the merge commit, `None` otherwise. + diff (`str`, *optional*): + The git diff if this is a Pull Request , `None` otherwise. + endpoint (`str`): + Endpoint of the Hub. Default is https://huggingface.co. + git_reference (`str`, *optional*): + (property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise. + url (`str`): + (property) URL of the discussion on the Hub. + """ + + events: list["DiscussionEvent"] + conflicting_files: list[str] | bool | None + target_branch: str | None + merge_commit_oid: str | None + diff: str | None + + +class DiscussionEventArgs(TypedDict): + id: str + type: str + created_at: datetime + author: str + _event: dict + + +@dataclass +class DiscussionEvent: + """ + An event in a Discussion or Pull Request. + + Use concrete classes: + * [`DiscussionComment`] + * [`DiscussionStatusChange`] + * [`DiscussionCommit`] + * [`DiscussionTitleChange`] + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + """ + + id: str + type: str + created_at: datetime + author: str + + _event: dict + """Stores the original event data, in case we need to access it later.""" + + +@dataclass +class DiscussionComment(DiscussionEvent): + """A comment in a Discussion / Pull Request. + + Subclass of [`DiscussionEvent`]. + + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + content (`str`): + The raw markdown content of the comment. Mentions, links and images are not rendered. + edited (`bool`): + Whether or not this comment has been edited. + hidden (`bool`): + Whether or not this comment has been hidden. + """ + + content: str + edited: bool + hidden: bool + + @property + def rendered(self) -> str: + """The rendered comment, as a HTML string""" + return self._event["data"]["latest"]["html"] + + @property + def last_edited_at(self) -> datetime: + """The last edit time, as a `datetime` object.""" + return parse_datetime(self._event["data"]["latest"]["updatedAt"]) + + @property + def last_edited_by(self) -> str: + """The last edit time, as a `datetime` object.""" + return self._event["data"]["latest"].get("author", {}).get("name", "deleted") + + @property + def edit_history(self) -> list[dict]: + """The edit history of the comment""" + return self._event["data"]["history"] + + @property + def number_of_edits(self) -> int: + return len(self.edit_history) + + +@dataclass +class DiscussionStatusChange(DiscussionEvent): + """A change of status in a Discussion / Pull Request. + + Subclass of [`DiscussionEvent`]. + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + new_status (`str`): + The status of the Discussion / Pull Request after the change. + It can be one of: + * `"open"` + * `"closed"` + * `"merged"` (only for Pull Requests ) + """ + + new_status: str + + +@dataclass +class DiscussionCommit(DiscussionEvent): + """A commit in a Pull Request. + + Subclass of [`DiscussionEvent`]. + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + summary (`str`): + The summary of the commit. + oid (`str`): + The OID / SHA of the commit, as a hexadecimal string. + """ + + summary: str + oid: str + + +@dataclass +class DiscussionTitleChange(DiscussionEvent): + """A rename event in a Discussion / Pull Request. + + Subclass of [`DiscussionEvent`]. + + Attributes: + id (`str`): + The ID of the event. An hexadecimal string. + type (`str`): + The type of the event. + created_at (`datetime`): + A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) + object holding the creation timestamp for the event. + author (`str`): + The username of the Discussion / Pull Request author. + Can be `"deleted"` if the user has been deleted since. + old_title (`str`): + The previous title for the Discussion / Pull Request. + new_title (`str`): + The new title. + """ + + old_title: str + new_title: str + + +def deserialize_event(event: dict) -> DiscussionEvent: + """Instantiates a [`DiscussionEvent`] from a dict""" + event_id: str = event["id"] + event_type: str = event["type"] + created_at = parse_datetime(event["createdAt"]) + + common_args: DiscussionEventArgs = { + "id": event_id, + "type": event_type, + "created_at": created_at, + "author": event.get("author", {}).get("name", "deleted"), + "_event": event, + } + + if event_type == "comment": + return DiscussionComment( + **common_args, + edited=event["data"]["edited"], + hidden=event["data"]["hidden"], + content=event["data"]["latest"]["raw"], + ) + if event_type == "status-change": + return DiscussionStatusChange( + **common_args, + new_status=event["data"]["status"], + ) + if event_type == "commit": + return DiscussionCommit( + **common_args, + summary=event["data"]["subject"], + oid=event["data"]["oid"], + ) + if event_type == "title-change": + return DiscussionTitleChange( + **common_args, + old_title=event["data"]["from"], + new_title=event["data"]["to"], + ) + + return DiscussionEvent(**common_args) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/constants.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..e27da7b83432bd5e26944b879246d96722357e54 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/constants.py @@ -0,0 +1,312 @@ +import os +import re +import typing +from typing import Literal + + +# Possible values for env variables + + +ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"} +ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"}) + + +def _is_true(value: str | None) -> bool: + if value is None: + return False + return value.upper() in ENV_VARS_TRUE_VALUES + + +def _as_int(value: str | None) -> int | None: + if value is None: + return None + return int(value) + + +# Constants for file downloads + +PYTORCH_WEIGHTS_NAME = "pytorch_model.bin" +TF2_WEIGHTS_NAME = "tf_model.h5" +TF_WEIGHTS_NAME = "model.ckpt" +FLAX_WEIGHTS_NAME = "flax_model.msgpack" +CONFIG_NAME = "config.json" +REPOCARD_NAME = "README.md" +EVAL_RESULTS_FOLDER = ".eval_results" +DEFAULT_ETAG_TIMEOUT = 10 +DEFAULT_DOWNLOAD_TIMEOUT = 10 +DEFAULT_REQUEST_TIMEOUT = 10 +DOWNLOAD_CHUNK_SIZE = 10 * 1024 * 1024 +MAX_HTTP_DOWNLOAD_SIZE = 50 * 1000 * 1000 * 1000 # 50 GB + +# Constants for serialization + +PYTORCH_WEIGHTS_FILE_PATTERN = "pytorch_model{suffix}.bin" # Unsafe pickle: use safetensors instead +SAFETENSORS_WEIGHTS_FILE_PATTERN = "model{suffix}.safetensors" +TF2_WEIGHTS_FILE_PATTERN = "tf_model{suffix}.h5" + +# Constants for safetensors repos + +SAFETENSORS_SINGLE_FILE = "model.safetensors" +SAFETENSORS_INDEX_FILE = "model.safetensors.index.json" +SAFETENSORS_MAX_HEADER_LENGTH = 25_000_000 + +# Timeout of aquiring file lock and logging the attempt +FILELOCK_LOG_EVERY_SECONDS = 10 + +# Git-related constants + +DEFAULT_REVISION = "main" +REGEX_COMMIT_OID = re.compile(r"[A-Fa-f0-9]{5,40}") + +HUGGINGFACE_CO_URL_HOME = "https://huggingface.co/" + +_staging_mode = _is_true(os.environ.get("HUGGINGFACE_CO_STAGING")) + +_HF_DEFAULT_ENDPOINT = "https://huggingface.co" +_HF_DEFAULT_STAGING_ENDPOINT = "https://hub-ci.huggingface.co" +ENDPOINT = os.getenv("HF_ENDPOINT", _HF_DEFAULT_ENDPOINT).rstrip("/") +HUGGINGFACE_CO_URL_TEMPLATE = ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}" + +if _staging_mode: + ENDPOINT = _HF_DEFAULT_STAGING_ENDPOINT + HUGGINGFACE_CO_URL_TEMPLATE = _HF_DEFAULT_STAGING_ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}" + +DATASETS_SERVER_ENDPOINT = "https://datasets-server.huggingface.co" + +HUGGINGFACE_HEADER_X_REPO_COMMIT = "X-Repo-Commit" +HUGGINGFACE_HEADER_X_LINKED_ETAG = "X-Linked-Etag" +HUGGINGFACE_HEADER_X_LINKED_SIZE = "X-Linked-Size" +HUGGINGFACE_HEADER_X_BILL_TO = "X-HF-Bill-To" + +INFERENCE_ENDPOINT = os.environ.get("HF_INFERENCE_ENDPOINT", "https://api-inference.huggingface.co") + +# See https://huggingface.co/docs/inference-endpoints/index +INFERENCE_ENDPOINTS_ENDPOINT = "https://api.endpoints.huggingface.cloud/v2" +INFERENCE_CATALOG_ENDPOINT = "https://endpoints.huggingface.co/api/catalog" + +# See https://api.endpoints.huggingface.cloud/#post-/v2/endpoint/-namespace- +INFERENCE_ENDPOINT_IMAGE_KEYS = [ + "custom", + "huggingface", + "huggingfaceNeuron", + "llamacpp", + "tei", + "tgi", + "tgiNeuron", +] + +# Proxy for third-party providers +INFERENCE_PROXY_TEMPLATE = "https://router.huggingface.co/{provider}" + +REPO_ID_SEPARATOR = "--" +# ^ this substring is not allowed in repo_ids on hf.co +# and is the canonical one we use for serialization of repo ids elsewhere. + + +REPO_TYPE_DATASET = "dataset" +REPO_TYPE_SPACE = "space" +REPO_TYPE_MODEL = "model" +REPO_TYPE_KERNEL = "kernel" +REPO_TYPES = [None, REPO_TYPE_MODEL, REPO_TYPE_DATASET, REPO_TYPE_SPACE] +REPO_TYPES_WITH_KERNEL = REPO_TYPES + [REPO_TYPE_KERNEL] +SPACES_SDK_TYPES = ["gradio", "streamlit", "docker", "static"] + +REPO_TYPES_URL_PREFIXES = { + REPO_TYPE_DATASET: "datasets/", + REPO_TYPE_SPACE: "spaces/", + REPO_TYPE_KERNEL: "kernels/", +} +REPO_TYPES_MAPPING = { + "datasets": REPO_TYPE_DATASET, + "spaces": REPO_TYPE_SPACE, + "models": REPO_TYPE_MODEL, + "kernels": REPO_TYPE_KERNEL, +} + +# HF Hub URIs (``hf://...``). See ``huggingface_hub/utils/_hf_uris.py`` +# and ``docs/source/en/package_reference/hf_uris.md`` for the full grammar. +HF_PROTOCOL = "hf://" +HfUriType = Literal["model", "dataset", "space", "kernel", "bucket"] +# Maps the plural URI prefix that may appear in a HF URI (e.g. ``datasets/``) +# to the canonical singular type name. Buckets are first-class HF URI types. +HF_URI_TYPE_PREFIXES: dict[str, HfUriType] = { + "models": "model", + "datasets": "dataset", + "spaces": "space", + "kernels": "kernel", + "buckets": "bucket", +} + + +DiscussionTypeFilter = Literal["all", "discussion", "pull_request"] +DISCUSSION_TYPES: tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionTypeFilter) +DiscussionStatusFilter = Literal["all", "open", "closed"] +DISCUSSION_STATUS: tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionStatusFilter) + +# Webhook subscription types +WEBHOOK_DOMAIN_T = Literal["repo", "discussions"] + +# default cache +default_home = os.path.join(os.path.expanduser("~"), ".cache") +HF_HOME = os.path.expandvars( + os.path.expanduser( + os.getenv( + "HF_HOME", + os.path.join(os.getenv("XDG_CACHE_HOME", default_home), "huggingface"), + ) + ) +) + +default_cache_path = os.path.join(HF_HOME, "hub") +default_assets_cache_path = os.path.join(HF_HOME, "assets") + +# Legacy env variables +HUGGINGFACE_HUB_CACHE = os.getenv("HUGGINGFACE_HUB_CACHE", default_cache_path) +HUGGINGFACE_ASSETS_CACHE = os.getenv("HUGGINGFACE_ASSETS_CACHE", default_assets_cache_path) + +# New env variables +HF_HUB_CACHE = os.path.expandvars( + os.path.expanduser( + os.getenv( + "HF_HUB_CACHE", + HUGGINGFACE_HUB_CACHE, + ) + ) +) +HF_ASSETS_CACHE = os.path.expandvars( + os.path.expanduser( + os.getenv( + "HF_ASSETS_CACHE", + HUGGINGFACE_ASSETS_CACHE, + ) + ) +) + +HF_HUB_OFFLINE = _is_true(os.environ.get("HF_HUB_OFFLINE") or os.environ.get("TRANSFORMERS_OFFLINE")) + + +def is_offline_mode() -> bool: + """Returns whether we are in offline mode for the Hub. + + When offline mode is enabled, all HTTP requests made with `get_session` will raise an `OfflineModeIsEnabled` exception. + + Example: + ```py + from huggingface_hub import is_offline_mode + + def list_files(repo_id: str): + if is_offline_mode(): + ... # list files from local cache (degraded experience but still functional) + else: + ... # list files from Hub (complete experience) + ``` + """ + return HF_HUB_OFFLINE + + +# File created to mark that the version check has been done. +# Check is performed once per 24 hours at most. +CHECK_FOR_UPDATE_DONE_PATH = os.path.join(HF_HOME, ".check_for_update_done") + +# Set to skip the CLI update check (PyPI query + "new version available" warning at startup). +HF_HUB_DISABLE_UPDATE_CHECK = _is_true(os.environ.get("HF_HUB_DISABLE_UPDATE_CHECK")) + +# If set, log level will be set to DEBUG and all requests made to the Hub will be logged +# as curl commands for reproducibility. +HF_DEBUG = _is_true(os.environ.get("HF_DEBUG")) + +# Opt-out from telemetry requests +HF_HUB_DISABLE_TELEMETRY = ( + _is_true(os.environ.get("HF_HUB_DISABLE_TELEMETRY")) # HF-specific env variable + or _is_true(os.environ.get("DISABLE_TELEMETRY")) + or _is_true(os.environ.get("DO_NOT_TRACK")) # https://consoledonottrack.com/ +) + +HF_TOKEN_PATH = os.path.expandvars( + os.path.expanduser( + os.getenv( + "HF_TOKEN_PATH", + os.path.join(HF_HOME, "token"), + ) + ) +) +HF_STORED_TOKENS_PATH = os.path.join(os.path.dirname(HF_TOKEN_PATH), "stored_tokens") + +if _staging_mode: + # In staging mode, we use a different cache to ensure we don't mix up production and staging data or tokens + # In practice in `huggingface_hub` tests, we monkeypatch these values with temporary directories. The following + # lines are only used in third-party libraries tests (e.g. `transformers`, `diffusers`, etc.). + _staging_home = os.path.join(os.path.expanduser("~"), ".cache", "huggingface_staging") + HUGGINGFACE_HUB_CACHE = os.path.join(_staging_home, "hub") + HF_TOKEN_PATH = os.path.join(_staging_home, "token") + +# Here, `True` will disable progress bars globally without possibility of enabling it +# programmatically. `False` will enable them without possibility of disabling them. +# If environment variable is not set (None), then the user is free to enable/disable +# them programmatically. +# TL;DR: env variable has priority over code +__HF_HUB_DISABLE_PROGRESS_BARS = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS") +HF_HUB_DISABLE_PROGRESS_BARS: bool | None = ( + _is_true(__HF_HUB_DISABLE_PROGRESS_BARS) if __HF_HUB_DISABLE_PROGRESS_BARS is not None else None +) + +# Disable symlinks in the cache (files are copied instead of symlinked) +HF_HUB_DISABLE_SYMLINKS: bool = _is_true(os.environ.get("HF_HUB_DISABLE_SYMLINKS")) + +# Disable warning on machines that do not support symlinks (e.g. Windows non-developer) +HF_HUB_DISABLE_SYMLINKS_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_SYMLINKS_WARNING")) + +# Disable warning when using experimental features +HF_HUB_DISABLE_EXPERIMENTAL_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_EXPERIMENTAL_WARNING")) + +# Disable sending the cached token by default is all HTTP requests to the Hub +HF_HUB_DISABLE_IMPLICIT_TOKEN: bool = _is_true(os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN")) + +HF_XET_HIGH_PERFORMANCE: bool = _is_true(os.environ.get("HF_XET_HIGH_PERFORMANCE")) + +# Bucket and mount path used when launching Jobs +HF_JOBS_ARTIFACTS_BUCKET_NAME: str = "jobs-artifacts" +HF_JOBS_ARTIFACTS_MOUNT_PATH: str = "/data" + +# hf_transfer is not used anymore. Let's warn user is case they set the env variable +if _is_true(os.environ.get("HF_HUB_ENABLE_HF_TRANSFER")) and not HF_XET_HIGH_PERFORMANCE: + import warnings + + warnings.warn( + "The `HF_HUB_ENABLE_HF_TRANSFER` environment variable is deprecated as 'hf_transfer' is not used anymore. " + "Please use `HF_XET_HIGH_PERFORMANCE` instead to enable high performance transfer with Xet. " + "Visit https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hfxethighperformance for more details.", + DeprecationWarning, + ) + +# Used to override the etag timeout on a system level +HF_HUB_ETAG_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_ETAG_TIMEOUT")) or DEFAULT_ETAG_TIMEOUT + +# Used to override the get request timeout on a system level +# Also used as a default timeout for other requests if not specified (kept the naming for legacy reasons) +HF_HUB_DOWNLOAD_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_DOWNLOAD_TIMEOUT")) or DEFAULT_DOWNLOAD_TIMEOUT + +# Allows to add information about the requester in the user-agent (e.g. partner name) +HF_HUB_USER_AGENT_ORIGIN: str | None = os.environ.get("HF_HUB_USER_AGENT_ORIGIN") + +# If OAuth didn't work after 2 redirects, there's likely a third-party cookie issue in the Space iframe view. +# In this case, we redirect the user to the non-iframe view. +OAUTH_MAX_REDIRECTS = 2 + +# OAuth-related environment variables injected by the Space +OAUTH_CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID") +OAUTH_CLIENT_SECRET = os.environ.get("OAUTH_CLIENT_SECRET") +OAUTH_SCOPES = os.environ.get("OAUTH_SCOPES") +OPENID_PROVIDER_URL = os.environ.get("OPENID_PROVIDER_URL") + +# Xet constants +HUGGINGFACE_HEADER_X_XET_ENDPOINT = "X-Xet-Cas-Url" +HUGGINGFACE_HEADER_X_XET_ACCESS_TOKEN = "X-Xet-Access-Token" +HUGGINGFACE_HEADER_X_XET_EXPIRATION = "X-Xet-Token-Expiration" +HUGGINGFACE_HEADER_X_XET_HASH = "X-Xet-Hash" +HUGGINGFACE_HEADER_X_XET_REFRESH_ROUTE = "X-Xet-Refresh-Route" +HUGGINGFACE_HEADER_LINK_XET_AUTH_KEY = "xet-auth" + +default_xet_cache_path = os.path.join(HF_HOME, "xet") +HF_XET_CACHE = os.getenv("HF_XET_CACHE", default_xet_cache_path) +HF_HUB_DISABLE_XET: bool = _is_true(os.environ.get("HF_HUB_DISABLE_XET")) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/dataclasses.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/dataclasses.py new file mode 100644 index 0000000000000000000000000000000000000000..645f0ba853ed3d7e3df5fcb91de5a4ddd0b74fee --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/dataclasses.py @@ -0,0 +1,684 @@ +import collections.abc +import inspect +import types +from collections.abc import Callable +from dataclasses import _MISSING_TYPE, MISSING, Field, field, fields, make_dataclass +from functools import lru_cache, wraps +from typing import ( + Annotated, + Any, + ForwardRef, + Literal, + Type, + TypeVar, + Union, + get_args, + get_origin, + overload, +) + + +try: + # Python 3.11+ + from typing import NotRequired, Required # type: ignore +except ImportError: + try: + # In case typing_extensions is installed + from typing_extensions import NotRequired, Required # type: ignore + except ImportError: + # Fallback: create dummy types that will never match + Required = type("Required", (), {}) # type: ignore + NotRequired = type("NotRequired", (), {}) # type: ignore + +from .errors import ( + StrictDataclassClassValidationError, + StrictDataclassDefinitionError, + StrictDataclassFieldValidationError, +) + + +Validator_T = Callable[[Any], None] +T = TypeVar("T") +TypedDictType = TypeVar("TypedDictType", bound=dict[str, Any]) + +_TYPED_DICT_DEFAULT_VALUE = object() # used as default value in TypedDict fields (to distinguish from None) + + +# The overload decorator helps type checkers understand the different return types +@overload +def strict(cls: Type[T]) -> Type[T]: ... + + +@overload +def strict(*, accept_kwargs: bool = False) -> Callable[[Type[T]], Type[T]]: ... + + +def strict(cls: Type[T] | None = None, *, accept_kwargs: bool = False) -> Type[T] | Callable[[Type[T]], Type[T]]: + """ + Decorator to add strict validation to a dataclass. + + This decorator must be used on top of `@dataclass` to ensure IDEs and static typing tools + recognize the class as a dataclass. + + Can be used with or without arguments: + - `@strict` + - `@strict(accept_kwargs=True)` + + Args: + cls: + The class to convert to a strict dataclass. + accept_kwargs (`bool`, *optional*): + If True, allows arbitrary keyword arguments in `__init__`. Defaults to False. + + Returns: + The enhanced dataclass with strict validation on field assignment. + + Example: + ```py + >>> from dataclasses import dataclass + >>> from huggingface_hub.dataclasses import as_validated_field, strict, validated_field + + >>> @as_validated_field + >>> def positive_int(value: int): + ... if not value >= 0: + ... raise ValueError(f"Value must be positive, got {value}") + + >>> @strict(accept_kwargs=True) + ... @dataclass + ... class User: + ... name: str + ... age: int = positive_int(default=10) + + # Initialize + >>> User(name="John") + User(name='John', age=10) + + # Extra kwargs are accepted + >>> User(name="John", age=30, lastname="Doe") + User(name='John', age=30, *lastname='Doe') + + # Invalid type => raises + >>> User(name="John", age="30") + huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age': + TypeError: Field 'age' expected int, got str (value: '30') + + # Invalid value => raises + >>> User(name="John", age=-1) + huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age': + ValueError: Value must be positive, got -1 + ``` + """ + + def wrap(cls: Type[T]) -> Type[T]: + if not hasattr(cls, "__dataclass_fields__"): + raise StrictDataclassDefinitionError( + f"Class '{cls.__name__}' must be a dataclass before applying @strict." + ) + + # List and store validators + field_validators: dict[str, list[Validator_T]] = {} + for f in fields(cls): # type: ignore [arg-type] + validators = [] + validators.append(_create_type_validator(f)) + custom_validator = f.metadata.get("validator") + if custom_validator is not None: + if not isinstance(custom_validator, list): + custom_validator = [custom_validator] + for validator in custom_validator: + if not _is_validator(validator): + raise StrictDataclassDefinitionError( + f"Invalid validator for field '{f.name}': {validator}. Must be a callable taking a single argument." + ) + validators.extend(custom_validator) + field_validators[f.name] = validators + cls.__validators__ = field_validators # type: ignore + + # Override __setattr__ to validate fields on assignment + original_setattr = cls.__setattr__ + + def __strict_setattr__(self: Any, name: str, value: Any) -> None: + """Custom __setattr__ method for strict dataclasses.""" + # Run all validators + for validator in self.__validators__.get(name, []): + try: + validator(value) + except (ValueError, TypeError) as e: + raise StrictDataclassFieldValidationError(field=name, cause=e) from e + + # If validation passed, set the attribute + original_setattr(self, name, value) + + cls.__setattr__ = __strict_setattr__ # type: ignore + + if accept_kwargs: + # (optional) Override __init__ to accept arbitrary keyword arguments + original_init = cls.__init__ + + @wraps(original_init) + def __init__(self, *args, **kwargs: Any) -> None: + # Extract only the fields that are part of the dataclass + dataclass_fields = {f.name for f in fields(cls)} # type: ignore [arg-type] + standard_kwargs = {k: v for k, v in kwargs.items() if k in dataclass_fields} + + # User shouldn't define custom `__init__` when `accepts_kwargs`, and instead + # are advised to move field manipulation to `__post_init__` (e.g., derive new field from existing ones) + # We need to call bare `__init__` here without `__post_init__` but the``original_init`` would call + # post-init right away with no kwargs. + if len(args) > 0: + raise ValueError( + f"When `accept_kwargs=True`, {cls.__name__} accepts only keyword arguments, " + f"but found `{len(args)}` positional args." + ) + + for f in fields(cls): # type: ignore + if f.name in standard_kwargs: + setattr(self, f.name, standard_kwargs[f.name]) + elif f.default is not MISSING: + setattr(self, f.name, f.default) + elif f.default_factory is not MISSING: + setattr(self, f.name, f.default_factory()) + else: + raise TypeError(f"Missing required field - '{f.name}'") + + # Pass any additional kwargs to `__post_init__` and let the object + # decide whether to set the attr or use for different purposes (e.g. BC checks) + additional_kwargs = {} + for name, value in kwargs.items(): + if name not in dataclass_fields: + additional_kwargs[name] = value + + self.__post_init__(**additional_kwargs) + + cls.__init__ = __init__ # type: ignore + + # Define a default __post_init__ if not defined + if not hasattr(cls, "__post_init__"): + + def __post_init__(self, **kwargs: Any) -> None: + """Default __post_init__ to accept additional kwargs.""" + for name, value in kwargs.items(): + setattr(self, name, value) + + cls.__post_init__ = __post_init__ # type: ignore + + # (optional) Override __repr__ to include additional kwargs + original_repr = cls.__repr__ + + @wraps(original_repr) + def __repr__(self) -> str: + # Call the original __repr__ to get the standard fields + standard_repr = original_repr(self) + + # Get additional kwargs + additional_kwargs = [ + # add a '*' in front of additional kwargs to let the user know they are not part of the dataclass + f"*{k}={v!r}" + for k, v in self.__dict__.items() + if k not in cls.__dataclass_fields__ # type: ignore [attr-defined] + ] + additional_repr = ", ".join(additional_kwargs) + + # Combine both representations + return f"{standard_repr[:-1]}, {additional_repr})" if additional_kwargs else standard_repr + + if cls.__dataclass_params__.repr is True: # type: ignore [attr-defined] + cls.__repr__ = __repr__ # type: ignore + + # List all public methods starting with `validate_` => class validators. + class_validators = [] + + for name in dir(cls): + if not name.startswith("validate_"): + continue + method = getattr(cls, name) + if not callable(method): + continue + if len(inspect.signature(method).parameters) != 1: + raise StrictDataclassDefinitionError( + f"Class '{cls.__name__}' has a class validator '{name}' that takes more than one argument." + " Class validators must take only 'self' as an argument. Methods starting with 'validate_'" + " are considered to be class validators." + ) + class_validators.append(method) + + cls.__class_validators__ = class_validators # type: ignore + + # Add `validate` method to the class, but first check if it already exists + def validate(self: T) -> None: + """Run class validators on the instance.""" + for validator in cls.__class_validators__: # type: ignore [attr-defined] + try: + validator(self) + except (ValueError, TypeError) as e: + raise StrictDataclassClassValidationError(validator=validator.__name__, cause=e) from e + + # Hack to be able to raise if `.validate()` already exists except if it was created by this decorator on a parent class + # (in which case we just override it) + validate.__is_defined_by_strict_decorator__ = True # type: ignore [attr-defined] + + if hasattr(cls, "validate"): + if not getattr(cls.validate, "__is_defined_by_strict_decorator__", False): # type: ignore [attr-defined] + raise StrictDataclassDefinitionError( + f"Class '{cls.__name__}' already implements a method called 'validate'." + " This method name is reserved when using the @strict decorator on a dataclass." + " If you want to keep your own method, please rename it." + ) + + cls.validate = validate # type: ignore + + # Run class validators after initialization + initial_init = cls.__init__ + + @wraps(initial_init) + def init_with_validate(self, *args, **kwargs) -> None: + """Run class validators after initialization.""" + initial_init(self, *args, **kwargs) # type: ignore [call-arg] + cls.validate(self) # type: ignore [attr-defined] + + setattr(cls, "__init__", init_with_validate) + + return cls + + # Return wrapped class or the decorator itself + return wrap(cls) if cls is not None else wrap + + +def validate_typed_dict(schema: type[TypedDictType], data: dict) -> None: + """ + Validate that a dictionary conforms to the types defined in a TypedDict class. + + Under the hood, the typed dict is converted to a strict dataclass and validated using the `@strict` decorator. + + Args: + schema (`type[TypedDictType]`): + The TypedDict class defining the expected structure and types. + data (`dict`): + The dictionary to validate. + + Raises: + `StrictDataclassFieldValidationError`: + If any field in the dictionary does not conform to the expected type. + + Example: + ```py + >>> from typing import Annotated, TypedDict + >>> from huggingface_hub.dataclasses import validate_typed_dict + + >>> def positive_int(value: int): + ... if not value >= 0: + ... raise ValueError(f"Value must be positive, got {value}") + + >>> class User(TypedDict): + ... name: str + ... age: Annotated[int, positive_int] + + >>> # Valid data + >>> validate_typed_dict(User, {"name": "John", "age": 30}) + + >>> # Invalid type for age + >>> validate_typed_dict(User, {"name": "John", "age": "30"}) + huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age': + TypeError: Field 'age' expected int, got str (value: '30') + + >>> # Invalid value for age + >>> validate_typed_dict(User, {"name": "John", "age": -1}) + huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age': + ValueError: Value must be positive, got -1 + ``` + """ + # Convert typed dict to dataclass + strict_cls = _build_strict_cls_from_typed_dict(schema) + + # Validate the data by instantiating the strict dataclass + strict_cls(**data) # will raise if validation fails + + +@lru_cache +def _build_strict_cls_from_typed_dict(schema: type[TypedDictType]) -> Type: + # Extract type hints from the TypedDict class + type_hints = _get_typed_dict_annotations(schema) + + # If the TypedDict is not total, wrap fields as NotRequired (unless explicitly Required or NotRequired) + if not getattr(schema, "__total__", True): + for key, value in type_hints.items(): + origin = get_origin(value) + + if origin is Annotated: + base, *meta = get_args(value) + if not _is_required_or_notrequired(base): + base = NotRequired[base] + type_hints[key] = Annotated[tuple([base] + list(meta))] # type: ignore + elif not _is_required_or_notrequired(value): + type_hints[key] = NotRequired[value] + + # Convert type hints to dataclass fields + fields = [] + for key, value in type_hints.items(): + if get_origin(value) is Annotated: + base, *meta = get_args(value) + fields.append((key, base, field(default=_TYPED_DICT_DEFAULT_VALUE, metadata={"validator": meta[0]}))) + else: + fields.append((key, value, field(default=_TYPED_DICT_DEFAULT_VALUE))) + + # Create a strict dataclass from the TypedDict fields + return strict(make_dataclass(schema.__name__, fields)) + + +def _get_typed_dict_annotations(schema: type[TypedDictType]) -> dict[str, Any]: + """Extract type annotations from a TypedDict class.""" + try: + # Available in Python 3.14+ + import annotationlib + + return annotationlib.get_annotations(schema) + except ImportError: + return { + # We do not use `get_type_hints` here to avoid evaluating ForwardRefs (which might fail). + # ForwardRefs are not validated by @strict anyway. + name: value if value is not None else type(None) + for name, value in schema.__dict__.get("__annotations__", {}).items() + } + + +def validated_field( + validator: list[Validator_T] | Validator_T, + default: Any | _MISSING_TYPE = MISSING, + default_factory: Callable[[], Any] | _MISSING_TYPE = MISSING, + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: dict | None = None, + **kwargs: Any, +) -> Any: + """ + Create a dataclass field with a custom validator. + + Useful to apply several checks to a field. If only applying one rule, check out the [`as_validated_field`] decorator. + + Args: + validator (`Callable` or `list[Callable]`): + A method that takes a value as input and raises ValueError/TypeError if the value is invalid. + Can be a list of validators to apply multiple checks. + **kwargs: + Additional arguments to pass to `dataclasses.field()`. + + Returns: + A field with the validator attached in metadata + """ + if not isinstance(validator, list): + validator = [validator] + if metadata is None: + metadata = {} + metadata["validator"] = validator + return field( # type: ignore + default=default, # type: ignore [arg-type] + default_factory=default_factory, # type: ignore [arg-type] + init=init, + repr=repr, + hash=hash, + compare=compare, + metadata=metadata, + **kwargs, + ) + + +def as_validated_field(validator: Validator_T): + """ + Decorates a validator function as a [`validated_field`] (i.e. a dataclass field with a custom validator). + + Args: + validator (`Callable`): + A method that takes a value as input and raises ValueError/TypeError if the value is invalid. + """ + + def _inner( + default: Any | _MISSING_TYPE = MISSING, + default_factory: Callable[[], Any] | _MISSING_TYPE = MISSING, + init: bool = True, + repr: bool = True, + hash: bool | None = None, + compare: bool = True, + metadata: dict | None = None, + **kwargs: Any, + ): + return validated_field( + validator, + default=default, + default_factory=default_factory, + init=init, + repr=repr, + hash=hash, + compare=compare, + metadata=metadata, + **kwargs, + ) + + return _inner + + +def type_validator(name: str, value: Any, expected_type: Any) -> None: + """Validate that 'value' matches 'expected_type'.""" + origin = get_origin(expected_type) + args = get_args(expected_type) + + if expected_type is Any: + return + elif expected_type is None: + _validate_none(name, value) + elif validator := _BASIC_TYPE_VALIDATORS.get(origin): + validator(name, value, args) + elif isinstance(expected_type, type): # simple types + _validate_simple_type(name, value, expected_type) + elif isinstance(expected_type, ForwardRef) or isinstance(expected_type, str): + return + elif origin is Required: + if value is _TYPED_DICT_DEFAULT_VALUE: + raise TypeError(f"Field '{name}' is required but missing.") + type_validator(name, value, args[0]) + elif origin is NotRequired: + if value is _TYPED_DICT_DEFAULT_VALUE: + return + type_validator(name, value, args[0]) + else: + raise TypeError(f"Unsupported type for field '{name}': {expected_type}") + + +def _validate_none(name: str, value: Any) -> None: + """Validate None type. + + 'None' is not a type, it's a special value. Type should be `NoneType` instead. + But in type annotations 'None' is accepted so we must support it. + """ + if value is not None: + raise TypeError(f"Field '{name}' expected None, got {type(value).__name__}") + + +def _validate_union(name: str, value: Any, args: tuple[Any, ...]) -> None: + """Validate that value matches one of the types in a Union.""" + errors = [] + for t in args: + try: + type_validator(name, value, t) + return # Valid if any type matches + except TypeError as e: + errors.append(str(e)) + + raise TypeError( + f"Field '{name}' with value {repr(value)} doesn't match any type in {args}. Errors: {'; '.join(errors)}" + ) + + +def _validate_literal(name: str, value: Any, args: tuple[Any, ...]) -> None: + """Validate Literal type.""" + if isinstance(value, bool): + if value not in [arg for arg in args if isinstance(arg, bool)]: + raise TypeError(f"Field '{name}' expected one of {args}, got {value}") + elif isinstance(value, int): + if value not in [arg for arg in args if isinstance(arg, int) and not isinstance(arg, bool)]: + raise TypeError(f"Field '{name}' expected one of {args}, got {value}") + elif value not in args: + raise TypeError(f"Field '{name}' expected one of {args}, got {value}") + + +def _validate_list(name: str, value: Any, args: tuple[Any, ...]) -> None: + """Validate list[T] type.""" + if not isinstance(value, list): + raise TypeError(f"Field '{name}' expected a list, got {type(value).__name__}") + + # Validate each item in the list + item_type = args[0] + for i, item in enumerate(value): + try: + type_validator(f"{name}[{i}]", item, item_type) + except TypeError as e: + raise TypeError(f"Invalid item at index {i} in list '{name}'") from e + + +def _validate_dict(name: str, value: Any, args: tuple[Any, ...]) -> None: + """Validate dict[K, V] type.""" + if not isinstance(value, dict): + raise TypeError(f"Field '{name}' expected a dict, got {type(value).__name__}") + + # Validate keys and values + key_type, value_type = args + for k, v in value.items(): + try: + type_validator(f"{name}.key", k, key_type) + type_validator(f"{name}[{k!r}]", v, value_type) + except TypeError as e: + raise TypeError(f"Invalid key or value in dict '{name}'") from e + + +def _validate_tuple(name: str, value: Any, args: tuple[Any, ...]) -> None: + """Validate Tuple type.""" + if not isinstance(value, tuple): + raise TypeError(f"Field '{name}' expected a tuple, got {type(value).__name__}") + + # Handle variable-length tuples: tuple[T, ...] + if len(args) == 2 and args[1] is Ellipsis: + for i, item in enumerate(value): + try: + type_validator(f"{name}[{i}]", item, args[0]) + except TypeError as e: + raise TypeError(f"Invalid item at index {i} in tuple '{name}'") from e + # Handle fixed-length tuples: tuple[T1, T2, ...] + elif len(args) != len(value): + raise TypeError(f"Field '{name}' expected a tuple of length {len(args)}, got {len(value)}") + else: + for i, (item, expected) in enumerate(zip(value, args)): + try: + type_validator(f"{name}[{i}]", item, expected) + except TypeError as e: + raise TypeError(f"Invalid item at index {i} in tuple '{name}'") from e + + +def _validate_set(name: str, value: Any, args: tuple[Any, ...]) -> None: + """Validate set[T] type.""" + if not isinstance(value, set): + raise TypeError(f"Field '{name}' expected a set, got {type(value).__name__}") + + # Validate each item in the set + item_type = args[0] + for i, item in enumerate(value): + try: + type_validator(f"{name} item", item, item_type) + except TypeError as e: + raise TypeError(f"Invalid item in set '{name}'") from e + + +def _validate_sequence(name: str, value: Any, args: tuple[Any, ...]) -> None: + """Validate Sequence or Sequence[T] type.""" + if not isinstance(value, collections.abc.Sequence): + raise TypeError(f"Field '{name}' expected a Sequence, got {type(value).__name__}") + + # If no type argument is provided (i.e., just `Sequence`), skip item validation + if not args: + return + + # Validate each item in the sequence + item_type = args[0] + for i, item in enumerate(value): + try: + type_validator(f"{name}[{i}]", item, item_type) + except TypeError as e: + raise TypeError(f"Invalid item at index {i} in sequence '{name}'") from e + + +def _validate_simple_type(name: str, value: Any, expected_type: type) -> None: + """Validate simple type (int, str, etc.).""" + if expected_type is int and isinstance(value, bool): + raise TypeError( + f"Field '{name}' expected {expected_type.__name__}, got {type(value).__name__} (value: {repr(value)})" + ) + if not isinstance(value, expected_type): + raise TypeError( + f"Field '{name}' expected {expected_type.__name__}, got {type(value).__name__} (value: {repr(value)})" + ) + + +def _create_type_validator(field: Field) -> Validator_T: + """Create a type validator function for a field.""" + # Hacky: we cannot use a lambda here because of reference issues + + def validator(value: Any) -> None: + type_validator(field.name, value, field.type) + + return validator + + +def _is_validator(validator: Any) -> bool: + """Check if a function is a validator. + + A validator is a Callable that can be called with a single positional argument. + The validator can have more arguments with default values. + + Basically, returns True if `validator(value)` is possible. + """ + if not callable(validator): + return False + + signature = inspect.signature(validator) + parameters = list(signature.parameters.values()) + if len(parameters) == 0: + return False + if parameters[0].kind not in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.VAR_POSITIONAL, + ): + return False + for parameter in parameters[1:]: + if parameter.default == inspect.Parameter.empty: + return False + return True + + +def _is_required_or_notrequired(type_hint: Any) -> bool: + """Helper to check if a type is Required/NotRequired.""" + return type_hint in (Required, NotRequired) or (get_origin(type_hint) in (Required, NotRequired)) + + +_BASIC_TYPE_VALIDATORS: dict[Any, Callable[[str, Any, tuple[Any, ...]], None]] = { + Union: _validate_union, + Literal: _validate_literal, + list: _validate_list, + dict: _validate_dict, + tuple: _validate_tuple, + set: _validate_set, + collections.abc.Sequence: _validate_sequence, +} + +# TODO: make it first class citizen when bumping to Python 3.10+ +_BASIC_TYPE_VALIDATORS[types.UnionType] = _validate_union # x | y syntax, available only Python 3.10+ + + +__all__ = [ + "strict", + "validate_typed_dict", + "validated_field", + "Validator_T", + "StrictDataclassClassValidationError", + "StrictDataclassDefinitionError", + "StrictDataclassFieldValidationError", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/errors.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..05b004e953965c631496062fe0ce38db126fb592 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/errors.py @@ -0,0 +1,494 @@ +"""Contains all custom errors.""" + +from pathlib import Path + +from httpx import HTTPError, Response + + +# CACHE ERRORS + + +class CacheNotFound(Exception): + """Exception thrown when the Huggingface cache is not found.""" + + cache_dir: str | Path + + def __init__(self, msg: str, cache_dir: str | Path, *args, **kwargs): + super().__init__(msg, *args, **kwargs) + self.cache_dir = cache_dir + + +class CorruptedCacheException(Exception): + """Exception for any unexpected structure in the Huggingface cache-system.""" + + +# HEADERS ERRORS + + +class LocalTokenNotFoundError(EnvironmentError): + """Raised if local token is required but not found.""" + + +# HTTP ERRORS + + +class OfflineModeIsEnabled(ConnectionError): + """Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable.""" + + +class HfHubHTTPError(HTTPError, OSError): + """ + HTTPError to inherit from for any custom HTTP Error raised in HF Hub. + + Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is + sent back by the server, it will be added to the error message. + + Added details: + - Request ID sourced from headers in order of precedence: "X-Request-Id", "X-Amzn-Trace-Id", "X-Amz-Cf-Id". + - Server error message from the header "X-Error-Message". + - Server error message if we can found one in the response body. + + Example: + ```py + import httpx + from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError + + response = get_session().post(...) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + print(str(e)) # formatted message + e.request_id, e.server_message # details returned by server + + # Complete the error message with additional information once it's raised + e.append_to_message("\n`create_commit` expects the repository to exist.") + raise + ``` + """ + + def __init__( + self, + message: str, + *, + response: Response, + server_message: str | None = None, + ): + self.request_id = ( + response.headers.get("x-request-id") + or response.headers.get("X-Amzn-Trace-Id") + or response.headers.get("x-amz-cf-id") + ) + self.server_message = server_message + self.response = response + self.request = response.request + super().__init__(message) + + def append_to_message(self, additional_message: str) -> None: + """Append additional information to the `HfHubHTTPError` initial message.""" + self.args = (self.args[0] + additional_message,) + self.args[1:] + + @classmethod + def _reconstruct_hf_hub_http_error( + cls, message: str, response: Response, server_message: str | None + ) -> "HfHubHTTPError": + return cls(message, response=response, server_message=server_message) + + def __reduce_ex__(self, protocol): + """Fix pickling of Exception subclass with kwargs. We need to override __reduce_ex__ of the parent class""" + return (self.__class__._reconstruct_hf_hub_http_error, (str(self), self.response, self.server_message)) + + +# INFERENCE CLIENT ERRORS + + +class InferenceTimeoutError(HTTPError, TimeoutError): + """Error raised when a model is unavailable or the request times out.""" + + +# INFERENCE ENDPOINT ERRORS + + +class InferenceEndpointError(Exception): + """Generic exception when dealing with Inference Endpoints.""" + + +class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError): + """Exception for timeouts while waiting for Inference Endpoint.""" + + +# SAFETENSORS ERRORS + + +class SafetensorsParsingError(Exception): + """Raised when failing to parse a safetensors file metadata. + + This can be the case if the file is not a safetensors file or does not respect the specification. + """ + + +class NotASafetensorsRepoError(Exception): + """Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a + `model.safetensors.index.json` file. + """ + + +# TEXT GENERATION ERRORS + + +class TextGenerationError(HTTPError): + """Generic error raised if text-generation went wrong.""" + + +# Text Generation Inference Errors +class ValidationError(TextGenerationError): + """Server-side validation error.""" + + +class GenerationError(TextGenerationError): + pass + + +class OverloadedError(TextGenerationError): + pass + + +class IncompleteGenerationError(TextGenerationError): + pass + + +class UnknownError(TextGenerationError): + pass + + +# VALIDATION ERRORS + + +class HFValidationError(ValueError): + """Generic exception thrown by `huggingface_hub` validators. + + Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError). + """ + + +class HfUriError(ValueError): + """Raised when an `hf://...` URI is malformed. + + See [`parse_hf_uri`] and the + [HF URIs reference](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/hf_uris) + for the canonical syntax. + + Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError). + """ + + def __init__(self, uri: str, msg: str): + self.uri = uri + self.msg = msg + full_msg = f"Invalid HF URI '{uri}'. {msg}" if uri else f"Invalid HF URI. {msg}" + super().__init__(full_msg) + + +# FILE METADATA ERRORS + + +class DryRunError(OSError): + """Error triggered when a dry run is requested but cannot be performed (e.g. invalid repo).""" + + +class FileMetadataError(OSError): + """Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash). + + Inherits from `OSError` for backward compatibility. + """ + + +# BUCKET ERRORS + + +class BucketNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a bucket that does not exist. + + Attributes: + bucket_id (`str` or `None`): + The bucket id (namespace/name) that was not found, if it could be determined from the request URL. + + Example: + + ```py + >>> from huggingface_hub import bucket_info + >>> bucket_info("") + (...) + huggingface_hub.errors.BucketNotFoundError: 404 Client Error. (Request ID: XXX) + + Bucket Not Found for url: https://huggingface.co/api/buckets/namespace/name. + Please make sure you specified the correct bucket id (namespace/name). + If the bucket is private, make sure you are authenticated and your token has the required permissions. + ``` + """ + + bucket_id: str | None = None + + +# REPOSITORY ERRORS + + +class RepositoryNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a hf.co URL with an invalid repository name, or + with a private repo name the user does not have access to. + + Attributes: + repo_id (`str` or `None`): + The repo id that was not found, if it could be determined from the request URL. + repo_type (`str` or `None`): + The repo type ("model", "dataset", or "space"), if it could be determined from the request URL. + + Example: + + ```py + >>> from huggingface_hub import model_info + >>> model_info("") + (...) + huggingface_hub.errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP) + + Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E. + Please make sure you specified the correct `repo_id` and `repo_type`. + If the repo is private, make sure you are authenticated and your token has the required permissions. + Invalid username or password. + ``` + """ + + repo_id: str | None = None + repo_type: str | None = None + + +class GatedRepoError(RepositoryNotFoundError): + """ + Raised when trying to access a gated repository for which the user is not on the + authorized list. + + Note: derives from `RepositoryNotFoundError` to ensure backward compatibility. + + Example: + + ```py + >>> from huggingface_hub import model_info + >>> model_info("") + (...) + huggingface_hub.errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa) + + Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model. + Access to model ardent-figment/gated-model is restricted and you are not in the authorized list. + Visit https://huggingface.co/ardent-figment/gated-model to ask for access. + ``` + """ + + +class DisabledRepoError(HfHubHTTPError): + """ + Raised when trying to access a repository that has been disabled by its author. + + Example: + + ```py + >>> from huggingface_hub import dataset_info + >>> dataset_info("laion/laion-art") + (...) + huggingface_hub.errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8) + + Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art. + Access to this resource is disabled. + ``` + """ + + +# REVISION ERROR + + +class RevisionNotFoundError(HfHubHTTPError): + """ + Raised when trying to access a hf.co URL with a valid repository but an invalid + revision. + + Attributes: + repo_id (`str` or `None`): + The repo id, if it could be determined from the request URL. + repo_type (`str` or `None`): + The repo type ("model", "dataset", or "space"), if it could be determined from the request URL. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', 'config.json', revision='') + (...) + huggingface_hub.errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX) + + Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json. + ``` + """ + + repo_id: str | None = None + repo_type: str | None = None + + +# ENTRY ERRORS +class EntryNotFoundError(Exception): + """ + Raised when entry not found, either locally or remotely. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', '') + (...) + huggingface_hub.errors.RemoteEntryNotFoundError (...) + >>> hf_hub_download('bert-base-cased', '', local_files_only=True) + (...) + huggingface_hub.utils.errors.LocalEntryNotFoundError (...) + ``` + """ + + +class RemoteEntryNotFoundError(HfHubHTTPError, EntryNotFoundError): + """ + Raised when trying to access a hf.co URL with a valid repository and revision + but an invalid filename. + + Attributes: + repo_id (`str` or `None`): + The repo id, if it could be determined from the request URL. + repo_type (`str` or `None`): + The repo type ("model", "dataset", or "space"), if it could be determined from the request URL. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', '') + (...) + huggingface_hub.errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x) + + Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E. + ``` + """ + + repo_id: str | None = None + repo_type: str | None = None + + +class LocalEntryNotFoundError(FileNotFoundError, EntryNotFoundError): + """ + Raised when trying to access a file or snapshot that is not on the disk when network is + disabled or unavailable (connection issue). The entry may exist on the Hub. + + Example: + + ```py + >>> from huggingface_hub import hf_hub_download + >>> hf_hub_download('bert-base-cased', '', local_files_only=True) + (...) + huggingface_hub.errors.LocalEntryNotFoundError: Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co look-ups and downloads online, set 'local_files_only' to False. + ``` + """ + + def __init__(self, message: str): + super().__init__(message) + + +# REQUEST ERROR +class BadRequestError(HfHubHTTPError, ValueError): + """ + Raised by `hf_raise_for_status` when the server returns a HTTP 400 error. + + Example: + + ```py + >>> resp = httpx.post("hf.co/api/check", ...) + >>> hf_raise_for_status(resp, endpoint_name="check") + huggingface_hub.errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX) + ``` + """ + + +# DDUF file format ERROR + + +class DDUFError(Exception): + """Base exception for errors related to the DDUF format.""" + + +class DDUFCorruptedFileError(DDUFError): + """Exception thrown when the DDUF file is corrupted.""" + + +class DDUFExportError(DDUFError): + """Base exception for errors during DDUF export.""" + + +class DDUFInvalidEntryNameError(DDUFExportError): + """Exception thrown when the entry name is invalid.""" + + +# STRICT DATACLASSES ERRORS + + +class StrictDataclassError(Exception): + """Base exception for strict dataclasses.""" + + +class StrictDataclassDefinitionError(StrictDataclassError): + """Exception thrown when a strict dataclass is defined incorrectly.""" + + +class StrictDataclassFieldValidationError(StrictDataclassError): + """Exception thrown when a strict dataclass fails validation for a given field.""" + + def __init__(self, field: str, cause: Exception): + error_message = f"Validation error for field '{field}':" + error_message += f"\n {cause.__class__.__name__}: {cause}" + super().__init__(error_message) + + +class StrictDataclassClassValidationError(StrictDataclassError): + """Exception thrown when a strict dataclass fails validation on a class validator.""" + + def __init__(self, validator: str, cause: Exception): + error_message = f"Class validation error for validator '{validator}':" + error_message += f"\n {cause.__class__.__name__}: {cause}" + super().__init__(error_message) + + +# XET ERRORS + + +class XetError(Exception): + """Base exception for errors related to Xet Storage.""" + + +class XetAuthorizationError(XetError): + """Exception thrown when the user does not have the right authorization to use Xet Storage.""" + + +class XetRefreshTokenError(XetError): + """Exception thrown when the refresh token is invalid.""" + + +class XetDownloadError(Exception): + """Exception thrown when the download from Xet Storage fails.""" + + +# CLI ERRORS + + +class CLIError(Exception): + """CLI error with clean message (no traceback by default).""" + + +class ConfirmationError(CLIError): + """Raised when a confirmation prompt is declined (non-interactive mode).""" + + +class CLIExtensionInstallError(CLIError): + """Error during CLI extension installation.""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/fastai_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/fastai_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2604e7b1e598d3d1c0b9dc8115e5e3c0a3fc3de2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/fastai_utils.py @@ -0,0 +1,414 @@ +import json +import os +from pathlib import Path +from pickle import DEFAULT_PROTOCOL, PicklingError +from typing import Any + +from packaging import version + +from huggingface_hub import constants, snapshot_download +from huggingface_hub.hf_api import HfApi +from huggingface_hub.utils import ( + SoftTemporaryDirectory, + get_fastai_version, + get_fastcore_version, + get_python_version, +) + +from .utils import logging, validate_hf_hub_args + + +logger = logging.get_logger(__name__) + + +def _check_fastai_fastcore_versions( + fastai_min_version: str = "2.4", + fastcore_min_version: str = "1.3.27", +): + """ + Checks that the installed fastai and fastcore versions are compatible for pickle serialization. + + Args: + fastai_min_version (`str`, *optional*): + The minimum fastai version supported. + fastcore_min_version (`str`, *optional*): + The minimum fastcore version supported. + + > [!TIP] + > Raises the following error: + > + > - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError) + > if the fastai or fastcore libraries are not available or are of an invalid version. + """ + + if (get_fastcore_version() or get_fastai_version()) == "N/A": + raise ImportError( + f"fastai>={fastai_min_version} and fastcore>={fastcore_min_version} are" + f" required. Currently using fastai=={get_fastai_version()} and" + f" fastcore=={get_fastcore_version()}." + ) + + current_fastai_version = version.Version(get_fastai_version()) + current_fastcore_version = version.Version(get_fastcore_version()) + + if current_fastai_version < version.Version(fastai_min_version): + raise ImportError( + "`push_to_hub_fastai` and `from_pretrained_fastai` require a" + f" fastai>={fastai_min_version} version, but you are using fastai version" + f" {get_fastai_version()} which is incompatible. Upgrade with `pip install" + " fastai==2.5.6`." + ) + + if current_fastcore_version < version.Version(fastcore_min_version): + raise ImportError( + "`push_to_hub_fastai` and `from_pretrained_fastai` require a" + f" fastcore>={fastcore_min_version} version, but you are using fastcore" + f" version {get_fastcore_version()} which is incompatible. Upgrade with" + " `pip install fastcore==1.3.27`." + ) + + +def _check_fastai_fastcore_pyproject_versions( + storage_folder: str, + fastai_min_version: str = "2.4", + fastcore_min_version: str = "1.3.27", +): + """ + Checks that the `pyproject.toml` file in the directory `storage_folder` has fastai and fastcore versions + that are compatible with `from_pretrained_fastai` and `push_to_hub_fastai`. If `pyproject.toml` does not exist + or does not contain versions for fastai and fastcore, then it logs a warning. + + Args: + storage_folder (`str`): + Folder to look for the `pyproject.toml` file. + fastai_min_version (`str`, *optional*): + The minimum fastai version supported. + fastcore_min_version (`str`, *optional*): + The minimum fastcore version supported. + + > [!TIP] + > Raises the following errors: + > + > - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError) + > if the `toml` module is not installed. + > - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError) + > if the `pyproject.toml` indicates a lower than minimum supported version of fastai or fastcore. + """ + + try: + import toml + except ModuleNotFoundError: + raise ImportError( + "`push_to_hub_fastai` and `from_pretrained_fastai` require the toml module." + " Install it with `pip install toml`." + ) + + # Checks that a `pyproject.toml`, with `build-system` and `requires` sections, exists in the repository. If so, get a list of required packages. + if not os.path.isfile(f"{storage_folder}/pyproject.toml"): + logger.warning( + "There is no `pyproject.toml` in the repository that contains the fastai" + " `Learner`. The `pyproject.toml` would allow us to verify that your fastai" + " and fastcore versions are compatible with those of the model you want to" + " load." + ) + return + pyproject_toml = toml.load(f"{storage_folder}/pyproject.toml") + + if "build-system" not in pyproject_toml.keys(): + logger.warning( + "There is no `build-system` section in the pyproject.toml of the repository" + " that contains the fastai `Learner`. The `build-system` would allow us to" + " verify that your fastai and fastcore versions are compatible with those" + " of the model you want to load." + ) + return + build_system_toml = pyproject_toml["build-system"] + + if "requires" not in build_system_toml.keys(): + logger.warning( + "There is no `requires` section in the pyproject.toml of the repository" + " that contains the fastai `Learner`. The `requires` would allow us to" + " verify that your fastai and fastcore versions are compatible with those" + " of the model you want to load." + ) + return + package_versions = build_system_toml["requires"] + + # Extracts contains fastai and fastcore versions from `pyproject.toml` if available. + # If the package is specified but not the version (e.g. "fastai" instead of "fastai=2.4"), the default versions are the highest. + fastai_packages = [pck for pck in package_versions if pck.startswith("fastai")] + if len(fastai_packages) == 0: + logger.warning("The repository does not have a fastai version specified in the `pyproject.toml`.") + # fastai_version is an empty string if not specified + else: + fastai_version = str(fastai_packages[0]).partition("=")[2] + if fastai_version != "" and version.Version(fastai_version) < version.Version(fastai_min_version): + raise ImportError( + "`from_pretrained_fastai` requires" + f" fastai>={fastai_min_version} version but the model to load uses" + f" {fastai_version} which is incompatible." + ) + + fastcore_packages = [pck for pck in package_versions if pck.startswith("fastcore")] + if len(fastcore_packages) == 0: + logger.warning("The repository does not have a fastcore version specified in the `pyproject.toml`.") + # fastcore_version is an empty string if not specified + else: + fastcore_version = str(fastcore_packages[0]).partition("=")[2] + if fastcore_version != "" and version.Version(fastcore_version) < version.Version(fastcore_min_version): + raise ImportError( + "`from_pretrained_fastai` requires" + f" fastcore>={fastcore_min_version} version, but you are using fastcore" + f" version {fastcore_version} which is incompatible." + ) + + +README_TEMPLATE = """--- +tags: +- fastai +--- + +# Amazing! + +🥳 Congratulations on hosting your fastai model on the Hugging Face Hub! + +# Some next steps +1. Fill out this model card with more information (see the template below and the [documentation here](https://huggingface.co/docs/hub/model-repos))! + +2. Create a demo in Gradio or Streamlit using 🤗 Spaces ([documentation here](https://huggingface.co/docs/hub/spaces)). + +3. Join the fastai community on the [Fastai Discord](https://discord.com/invite/YKrxeNn)! + +Greetings fellow fastlearner 🤝! Don't forget to delete this content from your model card. + + +--- + + +# Model card + +## Model description +More information needed + +## Intended uses & limitations +More information needed + +## Training and evaluation data +More information needed +""" + +PYPROJECT_TEMPLATE = f"""[build-system] +requires = ["setuptools>=40.8.0", "wheel", "python={get_python_version()}", "fastai={get_fastai_version()}", "fastcore={get_fastcore_version()}"] +build-backend = "setuptools.build_meta:__legacy__" +""" + + +def _create_model_card(repo_dir: Path): + """ + Creates a model card for the repository. + + Args: + repo_dir (`Path`): + Directory where model card is created. + """ + readme_path = repo_dir / "README.md" + + if not readme_path.exists(): + with readme_path.open("w", encoding="utf-8") as f: + f.write(README_TEMPLATE) + + +def _create_model_pyproject(repo_dir: Path): + """ + Creates a `pyproject.toml` for the repository. + + Args: + repo_dir (`Path`): + Directory where `pyproject.toml` is created. + """ + pyproject_path = repo_dir / "pyproject.toml" + + if not pyproject_path.exists(): + with pyproject_path.open("w", encoding="utf-8") as f: + f.write(PYPROJECT_TEMPLATE) + + +def _save_pretrained_fastai( + learner, + save_directory: str | Path, + config: dict[str, Any] | None = None, +): + """ + Saves a fastai learner to `save_directory` in pickle format using the default pickle protocol for the version of python used. + + Args: + learner (`Learner`): + The `fastai.Learner` you'd like to save. + save_directory (`str` or `Path`): + Specific directory in which you want to save the fastai learner. + config (`dict`, *optional*): + Configuration object. Will be uploaded as a .json file. Example: 'https://huggingface.co/espejelomar/fastai-pet-breeds-classification/blob/main/config.json'. + + > [!TIP] + > Raises the following error: + > + > - [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError) + > if the config file provided is not a dictionary. + """ + _check_fastai_fastcore_versions() + + os.makedirs(save_directory, exist_ok=True) + + # if the user provides config then we update it with the fastai and fastcore versions in CONFIG_TEMPLATE. + if config is not None: + if not isinstance(config, dict): + raise RuntimeError(f"Provided config should be a dict. Got: '{type(config)}'") + path = os.path.join(save_directory, constants.CONFIG_NAME) + with open(path, "w") as f: + json.dump(config, f) + + _create_model_card(Path(save_directory)) + _create_model_pyproject(Path(save_directory)) + + # learner.export saves the model in `self.path`. + learner.path = Path(save_directory) + os.makedirs(save_directory, exist_ok=True) + try: + learner.export( + fname="model.pkl", + pickle_protocol=DEFAULT_PROTOCOL, + ) + except PicklingError: + raise PicklingError( + "You are using a lambda function, i.e., an anonymous function. `pickle`" + " cannot pickle function objects and requires that all functions have" + " names. One possible solution is to name the function." + ) + + +@validate_hf_hub_args +def from_pretrained_fastai( + repo_id: str, + revision: str | None = None, +): + """ + Load pretrained fastai model from the Hub or from a local directory. + + Args: + repo_id (`str`): + The location where the pickled fastai.Learner is. It can be either of the two: + - Hosted on the Hugging Face Hub. E.g.: 'espejelomar/fatai-pet-breeds-classification' or 'distilgpt2'. + You can add a `revision` by appending `@` at the end of `repo_id`. E.g.: `dbmdz/bert-base-german-cased@main`. + Revision is the specific model version to use. Since we use a git-based system for storing models and other + artifacts on the Hugging Face Hub, it can be a branch name, a tag name, or a commit id. + - Hosted locally. `repo_id` would be a directory containing the pickle and a pyproject.toml + indicating the fastai and fastcore versions used to build the `fastai.Learner`. E.g.: `./my_model_directory/`. + revision (`str`, *optional*): + Revision at which the repo's files are downloaded. See documentation of `snapshot_download`. + + Returns: + The `fastai.Learner` model in the `repo_id` repo. + """ + _check_fastai_fastcore_versions() + + # Load the `repo_id` repo. + # `snapshot_download` returns the folder where the model was stored. + # `cache_dir` will be the default '/root/.cache/huggingface/hub' + if not os.path.isdir(repo_id): + storage_folder = snapshot_download( + repo_id=repo_id, + revision=revision, + library_name="fastai", + library_version=get_fastai_version(), + ) + else: + storage_folder = repo_id + + _check_fastai_fastcore_pyproject_versions(storage_folder) + + from fastai.learner import load_learner # type: ignore + + return load_learner(os.path.join(storage_folder, "model.pkl")) + + +@validate_hf_hub_args +def push_to_hub_fastai( + learner, + *, + repo_id: str, + commit_message: str = "Push FastAI model using huggingface_hub.", + private: bool | None = None, + token: str | None = None, + config: dict | None = None, + branch: str | None = None, + create_pr: bool | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + delete_patterns: list[str] | str | None = None, + api_endpoint: str | None = None, +): + """ + Upload learner checkpoint files to the Hub. + + Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use + `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more + details. + + Args: + learner (`Learner`): + The `fastai.Learner' you'd like to push to the Hub. + repo_id (`str`): + The repository id for your model in Hub in the format of "namespace/repo_name". The namespace can be your individual account or an organization to which you have write access (for example, 'stanfordnlp/stanza-de'). + commit_message (`str`, *optional*): + Message to commit while pushing. Will default to :obj:`"add model"`. + private (`bool`, *optional*): + Whether or not the repository created should be private. + If `None` (default), will default to been public except if the organization's default is private. + token (`str`, *optional*): + The Hugging Face account token to use as HTTP bearer authorization for remote files. If :obj:`None`, the token will be asked by a prompt. + config (`dict`, *optional*): + Configuration object to be saved alongside the model weights. + branch (`str`, *optional*): + The git branch on which to push the model. This defaults to + the default branch as specified in your repository, which + defaults to `"main"`. + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request from `branch` with that commit. + Defaults to `False`. + api_endpoint (`str`, *optional*): + The API endpoint to use when pushing the model to the hub. + allow_patterns (`list[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are pushed. + ignore_patterns (`list[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not pushed. + delete_patterns (`list[str]` or `str`, *optional*): + If provided, remote files matching any of the patterns will be deleted from the repo. + + Returns: + The url of the commit of your model in the given repository. + + > [!TIP] + > Raises the following error: + > + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if the user is not log on to the Hugging Face Hub. + """ + _check_fastai_fastcore_versions() + api = HfApi(endpoint=api_endpoint) + repo_id = api.create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True).repo_id + + # Push the files to the repo in a single commit + with SoftTemporaryDirectory() as tmp: + saved_path = Path(tmp) / repo_id + _save_pretrained_fastai(learner, saved_path, config=config) + return api.upload_folder( + repo_id=repo_id, + token=token, + folder_path=saved_path, + commit_message=commit_message, + revision=branch, + create_pr=create_pr, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + delete_patterns=delete_patterns, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/file_download.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/file_download.py new file mode 100644 index 0000000000000000000000000000000000000000..1c4ed1719d953cde05a9a73b34389049fb780361 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/file_download.py @@ -0,0 +1,1936 @@ +import copy +import errno +import os +import re +import shutil +import stat +import time +import uuid +import warnings +from dataclasses import dataclass +from pathlib import Path +from typing import Any, BinaryIO, Literal, NoReturn, overload +from urllib.parse import quote, urlparse + +import httpx +from tqdm.auto import tqdm as base_tqdm + +from . import constants +from ._local_folder import ( + _create_cachedir_tag, + get_local_download_paths, + read_download_metadata, + write_download_metadata, +) +from .errors import ( + FileMetadataError, + GatedRepoError, + HfHubHTTPError, + LocalEntryNotFoundError, + RemoteEntryNotFoundError, + RepositoryNotFoundError, + RevisionNotFoundError, +) +from .utils import ( + OfflineModeIsEnabled, + SoftTemporaryDirectory, + WeakFileLock, + XetFileData, + build_hf_headers, + hf_raise_for_status, + logging, + parse_xet_file_data_from_response, + refresh_xet_connection_info, + tqdm, + validate_hf_hub_args, +) +from .utils._http import ( + _DEFAULT_RETRY_ON_EXCEPTIONS, + _DEFAULT_RETRY_ON_STATUS_CODES, + _adjust_range_header, + _httpx_follow_relative_redirects_with_backoff, + http_stream_backoff, +) +from .utils._runtime import is_xet_available +from .utils.sha import sha_fileobj +from .utils.tqdm import _get_progress_bar_context + + +logger = logging.get_logger(__name__) + +# Return value when trying to load a file from cache but the file does not exist in the distant repo. +_CACHED_NO_EXIST = object() +_CACHED_NO_EXIST_T = Any + +# Regex to get filename from a "Content-Disposition" header for CDN-served files +HEADER_FILENAME_PATTERN = re.compile(r'filename="(?P.*?)";') + +# Regex to check if the revision IS directly a commit_hash +REGEX_COMMIT_HASH = re.compile(r"^[0-9a-f]{40}$") + +# Regex to check if the file etag IS a valid sha256 +REGEX_SHA256 = re.compile(r"^[0-9a-f]{64}$") + +_are_symlinks_supported_in_dir: dict[str, bool] = {} + +# Internal retry timeout for metadata fetch when no local file exists +_ETAG_RETRY_TIMEOUT = 60 + + +def are_symlinks_supported(cache_dir: str | Path | None = None) -> bool: + """Return whether the symlinks are supported on the machine. + + Since symlinks support can change depending on the mounted disk, we need to check + on the precise cache folder. By default, the default HF cache directory is checked. + + Args: + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + + Returns: [bool] Whether symlinks are supported in the directory. + """ + # Defaults to HF cache + if cache_dir is None: + cache_dir = constants.HF_HUB_CACHE + cache_dir = str(Path(cache_dir).expanduser().resolve()) # make it unique + + # If symlinks are explicitly disabled by the user, always return False + if constants.HF_HUB_DISABLE_SYMLINKS: + return False + + # Check symlink compatibility only once (per cache directory) at first time use + if cache_dir not in _are_symlinks_supported_in_dir: + _are_symlinks_supported_in_dir[cache_dir] = True + + os.makedirs(cache_dir, exist_ok=True) + with SoftTemporaryDirectory(dir=cache_dir) as tmpdir: + src_path = Path(tmpdir) / "dummy_file_src" + src_path.touch() + dst_path = Path(tmpdir) / "dummy_file_dst" + + # Relative source path as in `_create_symlink`` + relative_src = os.path.relpath(src_path, start=os.path.dirname(dst_path)) + try: + os.symlink(relative_src, dst_path) + except OSError: + # Likely running on Windows + _are_symlinks_supported_in_dir[cache_dir] = False + + if not constants.HF_HUB_DISABLE_SYMLINKS_WARNING: + message = ( + "`huggingface_hub` cache-system uses symlinks by default to" + " efficiently store duplicated files but your machine does not" + f" support them in {cache_dir}. Caching files will still work" + " but in a degraded version that might require more space on" + " your disk. This warning can be disabled by setting the" + " `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For" + " more details, see" + " https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations." + ) + if os.name == "nt": + message += ( + "\nTo support symlinks on Windows, you either need to" + " activate Developer Mode or to run Python as an" + " administrator. In order to activate developer mode," + " see this article:" + " https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development" + ) + warnings.warn(message) + + return _are_symlinks_supported_in_dir[cache_dir] + + +@dataclass(frozen=True) +class HfFileMetadata: + """Data structure containing information about a file versioned on the Hub. + + Returned by [`get_hf_file_metadata`] based on a URL. + + Args: + commit_hash (`str`, *optional*): + The commit_hash related to the file. + etag (`str`, *optional*): + Etag of the file on the server. + location (`str`): + Location where to download the file. Can be a Hub url or not (CDN). + size (`size`): + Size of the file. In case of an LFS file, contains the size of the actual + LFS file, not the pointer. + xet_file_data (`XetFileData`, *optional*): + Xet information for the file. This is only set if the file is stored using Xet storage. + """ + + commit_hash: str | None + etag: str | None + location: str + size: int | None + xet_file_data: XetFileData | None + + +@dataclass +class DryRunFileInfo: + """Information returned when performing a dry run of a file download. + + Returned by [`hf_hub_download`] when `dry_run=True`. + + Args: + commit_hash (`str`): + The commit_hash related to the file. + file_size (`int`): + Size of the file. In case of an LFS file, contains the size of the actual LFS file, not the pointer. + filename (`str`): + Name of the file in the repo. + is_cached (`bool`): + Whether the file is already cached locally. + will_download (`bool`): + Whether the file will be downloaded if `hf_hub_download` is called with `dry_run=False`. + In practice, will_download is `True` if the file is not cached or if `force_download=True`. + """ + + commit_hash: str + file_size: int + filename: str + local_path: str + is_cached: bool + will_download: bool + + +@validate_hf_hub_args +def hf_hub_url( + repo_id: str, + filename: str, + *, + subfolder: str | None = None, + repo_type: str | None = None, + revision: str | None = None, + endpoint: str | None = None, +) -> str: + """Construct the URL of a file from the given information. + + The resolved address can either be a huggingface.co-hosted url, or a link to + Cloudfront (a Content Delivery Network, or CDN) for large files which are + more than a few MBs. + + Args: + repo_id (`str`): + A namespace (user or an organization) name and a repo name separated + by a `/`. + filename (`str`): + The name of the file in the repo. + subfolder (`str`, *optional*): + An optional value corresponding to a folder inside the repo. + repo_type (`str`, *optional*): + Set to `"dataset"`, `"space"` or `"kernel"` if downloading from a dataset, space or kernel repo, + `None` or `"model"` if downloading from a model. Default is `None`. + revision (`str`, *optional*): + An optional Git revision id which can be a branch name, a tag, or a + commit hash. + + Example: + + ```python + >>> from huggingface_hub import hf_hub_url + + >>> hf_hub_url( + ... repo_id="julien-c/EsperBERTo-small", filename="pytorch_model.bin" + ... ) + 'https://huggingface.co/julien-c/EsperBERTo-small/resolve/main/pytorch_model.bin' + ``` + + > [!TIP] + > Notes: + > + > Cloudfront is replicated over the globe so downloads are way faster for + > the end user (and it also lowers our bandwidth costs). + > + > Cloudfront aggressively caches files by default (default TTL is 24 + > hours), however this is not an issue here because we implement a + > git-based versioning system on huggingface.co, which means that we store + > the files on S3/Cloudfront in a content-addressable way (i.e., the file + > name is its hash). Using content-addressable filenames means cache can't + > ever be stale. + > + > In terms of client-side caching from this library, we base our caching + > on the objects' entity tag (`ETag`), which is an identifier of a + > specific version of a resource [1]_. An object's ETag is: its git-sha1 + > if stored in git, or its sha256 if stored in git-lfs. + + References: + + - [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag + """ + if subfolder == "": + subfolder = None + if subfolder is not None: + filename = f"{subfolder}/{filename}" + + if repo_type not in constants.REPO_TYPES_WITH_KERNEL: + raise ValueError("Invalid repo type") + + if repo_type in constants.REPO_TYPES_URL_PREFIXES: + repo_id = constants.REPO_TYPES_URL_PREFIXES[repo_type] + repo_id + + if revision is None: + revision = constants.DEFAULT_REVISION + url = constants.HUGGINGFACE_CO_URL_TEMPLATE.format( + repo_id=repo_id, revision=quote(revision, safe=""), filename=quote(filename) + ) + # Update endpoint if provided + if endpoint is not None and url.startswith(constants.ENDPOINT): + url = endpoint + url[len(constants.ENDPOINT) :] + return url + + +def _get_file_length_from_http_response(response: httpx.Response) -> int | None: + """ + Get the length of the file from the HTTP response headers. + + This function extracts the file size from the HTTP response headers, either from the + `Content-Range` or `Content-Length` header, if available (in that order). + + Args: + response (`httpx.Response`): + The HTTP response object. + + Returns: + `int` or `None`: The length of the file in bytes, or None if not available. + """ + + # If HTTP response contains compressed body (e.g. gzip), the `Content-Length` header will + # contain the length of the compressed body, not the uncompressed file size. + # And at the start of transmission there's no way to know the uncompressed file size for gzip, + # thus we return None in that case. + content_encoding = response.headers.get("Content-Encoding", "identity").lower() + if content_encoding != "identity": + # gzip/br/deflate/zstd etc + return None + + content_range = response.headers.get("Content-Range") + if content_range is not None: + return int(content_range.rsplit("/")[-1]) + + content_length = response.headers.get("Content-Length") + if content_length is not None: + return int(content_length) + + return None + + +@validate_hf_hub_args +def http_get( + url: str, + temp_file: BinaryIO, + *, + resume_size: int = 0, + headers: dict[str, Any] | None = None, + expected_size: int | None = None, + displayed_filename: str | None = None, + tqdm_class: type[base_tqdm] | None = None, + _nb_retries: int = 5, + _tqdm_bar: tqdm | None = None, +) -> None: + """ + Download a remote file. Do not gobble up errors, and will return errors tailored to the Hugging Face Hub. + + If ConnectionError (SSLError) or ReadTimeout happen while streaming data from the server, it is most likely a + transient error (network outage?). We log a warning message and try to resume the download a few times before + giving up. The method gives up after 5 attempts if no new data has being received from the server. + + Args: + url (`str`): + The URL of the file to download. + temp_file (`BinaryIO`): + The file-like object where to save the file. + resume_size (`int`, *optional*): + The number of bytes already downloaded. If set to 0 (default), the whole file is download. If set to a + positive number, the download will resume at the given position. + headers (`dict`, *optional*): + Dictionary of HTTP Headers to send with the request. + expected_size (`int`, *optional*): + The expected size of the file to download. If set, the download will raise an error if the size of the + received content is different from the expected one. + displayed_filename (`str`, *optional*): + The filename of the file that is being downloaded. Value is used only to display a nice progress bar. If + not set, the filename is guessed from the URL or the `Content-Disposition` header. + """ + if expected_size is not None and resume_size == expected_size: + # If the file is already fully downloaded, we don't need to download it again. + return + + initial_headers = headers + headers = copy.deepcopy(headers) or {} + if resume_size > 0: + headers["Range"] = _adjust_range_header(headers.get("Range"), resume_size) + elif expected_size and expected_size > constants.MAX_HTTP_DOWNLOAD_SIZE: + # Any files over 50GB will not be available through basic http requests. + raise ValueError( + "The file is too large to be downloaded using the regular download method. " + " Install `hf_xet` with `pip install hf_xet` for xet-powered downloads." + ) + + with http_stream_backoff( + method="GET", + url=url, + headers=headers, + timeout=constants.HF_HUB_DOWNLOAD_TIMEOUT, + retry_on_exceptions=(), + retry_on_status_codes=(429,), + ) as response: + hf_raise_for_status(response) + + # If we requested a Range but got 200 back, the server ignored our Range header + # (e.g. CloudFront with Accept-Encoding: gzip). Reset file to avoid corruption. + if resume_size > 0 and response.status_code == 200: + temp_file.seek(0) + temp_file.truncate() + resume_size = 0 + + total: int | None = _get_file_length_from_http_response(response) + + if displayed_filename is None: + displayed_filename = url + content_disposition = response.headers.get("Content-Disposition") + if content_disposition is not None: + match = HEADER_FILENAME_PATTERN.search(content_disposition) + if match is not None: + # Means file is on CDN + displayed_filename = match.groupdict()["filename"] + + # Truncate filename if too long to display + if len(displayed_filename) > 40: + displayed_filename = f"(…){displayed_filename[-40:]}" + + consistency_error_message = ( + f"Consistency check failed: file should be of size {expected_size} but has size" + f" {{actual_size}} ({displayed_filename}).\nThis is usually due to network issues while downloading the file." + " Please retry with `force_download=True`." + ) + progress_cm = _get_progress_bar_context( + desc=displayed_filename, + log_level=logger.getEffectiveLevel(), + total=total, + initial=resume_size, + name="huggingface_hub.http_get", + tqdm_class=tqdm_class, + _tqdm_bar=_tqdm_bar, + ) + + with progress_cm as progress: + new_resume_size = resume_size + try: + for chunk in response.iter_bytes(chunk_size=constants.DOWNLOAD_CHUNK_SIZE): + if chunk: # filter out keep-alive new chunks + progress.update(len(chunk)) + temp_file.write(chunk) + new_resume_size += len(chunk) + # Some data has been downloaded from the server so we reset the number of retries. + _nb_retries = 5 + except (httpx.ConnectError, httpx.TimeoutException) as e: + # If ConnectionError (SSLError) or ReadTimeout happen while streaming data from the server, it is most likely + # a transient error (network outage?). We log a warning message and try to resume the download a few times + # before giving up. Tre retry mechanism is basic but should be enough in most cases. + if _nb_retries <= 0: + logger.warning("Error while downloading from %s: %s\nMax retries exceeded.", url, str(e)) + raise + logger.warning("Error while downloading from %s: %s\nTrying to resume download...", url, str(e)) + time.sleep(1) + return http_get( + url=url, + temp_file=temp_file, + resume_size=new_resume_size, + headers=initial_headers, + expected_size=expected_size, + tqdm_class=tqdm_class, + _nb_retries=_nb_retries - 1, + _tqdm_bar=_tqdm_bar, + ) + + if expected_size is not None and expected_size != temp_file.tell(): + raise OSError( + consistency_error_message.format( + actual_size=temp_file.tell(), + ) + ) + + +def xet_get( + *, + incomplete_path: Path, + xet_file_data: XetFileData, + headers: dict[str, str], + expected_size: int | None = None, + displayed_filename: str | None = None, + tqdm_class: type[base_tqdm] | None = None, + _tqdm_bar: tqdm | None = None, +) -> None: + """ + Download a file using Xet storage service. + + Args: + incomplete_path (`Path`): + The path to the file to download. + xet_file_data (`XetFileData`): + The file metadata needed to make the request to the xet storage service. + headers (`dict[str, str]`): + The headers to send to the xet storage service. + expected_size (`int`, *optional*): + The expected size of the file to download. If set, the download will raise an error if the size of the + received content is different from the expected one. + displayed_filename (`str`, *optional*): + The filename of the file that is being downloaded. Value is used only to display a nice progress bar. If + not set, the filename is guessed from the URL or the `Content-Disposition` header. + + **How it works:** + The file download system uses Xet storage, which is a content-addressable storage system that breaks files into chunks + for efficient storage and transfer. + + `hf_xet.download_files` manages downloading files by: + - Taking a list of files to download (each with its unique content hash) + - Connecting to a storage server (CAS server) that knows how files are chunked + - Using authentication to ensure secure access + - Providing progress updates during download + + Authentication works by regularly refreshing access tokens through `refresh_xet_connection_info` to maintain a valid + connection to the storage server. + + The download process works like this: + 1. Create a local cache folder at `~/.cache/huggingface/xet/chunk-cache` to store reusable file chunks + 2. Download files in parallel: + 2.1. Prepare to write the file to disk + 2.2. Ask the server "how is this file split into chunks?" using the file's unique hash + The server responds with: + - Which chunks make up the complete file + - Where each chunk can be downloaded from + 2.3. For each needed chunk: + - Checks if we already have it in our local cache + - If not, download it from cloud storage (S3) + - Save it to cache for future use + - Assemble the chunks in order to recreate the original file + + """ + try: + from hf_xet import PyXetDownloadInfo, download_files # type: ignore[no-redef] + except ImportError: + raise ValueError( + "To use optimized download using Xet storage, you need to install the hf_xet package. " + 'Try `pip install "huggingface_hub[hf_xet]"` or `pip install hf_xet`.' + ) + + connection_info = refresh_xet_connection_info(file_data=xet_file_data, headers=headers) + + def token_refresher() -> tuple[str, int]: + connection_info = refresh_xet_connection_info(file_data=xet_file_data, headers=headers) + if connection_info is None: + raise ValueError("Failed to refresh token using xet metadata.") + return connection_info.access_token, connection_info.expiration_unix_epoch + + xet_download_info = [ + PyXetDownloadInfo( + destination_path=str(incomplete_path.absolute()), hash=xet_file_data.file_hash, file_size=expected_size + ) + ] + + if not displayed_filename: + displayed_filename = incomplete_path.name + + # Truncate filename if too long to display + if len(displayed_filename) > 40: + displayed_filename = f"{displayed_filename[:40]}(…)" + + progress_cm = _get_progress_bar_context( + desc=displayed_filename, + log_level=logger.getEffectiveLevel(), + total=expected_size, + initial=0, + name="huggingface_hub.xet_get", + tqdm_class=tqdm_class, + _tqdm_bar=_tqdm_bar, + ) + + xet_headers = headers.copy() + xet_headers.pop("authorization", None) + + with progress_cm as progress: + + def progress_updater(progress_bytes: float): + progress.update(progress_bytes) + + download_files( + xet_download_info, + endpoint=connection_info.endpoint, + token_info=(connection_info.access_token, connection_info.expiration_unix_epoch), + token_refresher=token_refresher, + progress_updater=[progress_updater], + request_headers=xet_headers, + ) + + +def _normalize_etag(etag: str | None) -> str | None: + """Normalize ETag HTTP header, so it can be used to create nice filepaths. + + The HTTP spec allows two forms of ETag: + ETag: W/"" + ETag: "" + + For now, we only expect the second form from the server, but we want to be future-proof so we support both. For + more context, see `TestNormalizeEtag` tests and https://github.com/huggingface/huggingface_hub/pull/1428. + + Args: + etag (`str`, *optional*): HTTP header + + Returns: + `str` or `None`: string that can be used as a nice directory name. + Returns `None` if input is None. + """ + if etag is None: + return None + return etag.lstrip("W/").strip('"') + + +def _create_relative_symlink(src: str, dst: str, new_blob: bool = False) -> None: + """Alias method used in `transformers` conversion script.""" + return _create_symlink(src=src, dst=dst, new_blob=new_blob) + + +def _create_symlink(src: str, dst: str, new_blob: bool = False) -> None: + """Create a symbolic link named dst pointing to src. + + By default, it will try to create a symlink using a relative path. Relative paths have 2 advantages: + - If the cache_folder is moved (example: back-up on a shared drive), relative paths within the cache folder will + not break. + - Relative paths seems to be better handled on Windows. Issue was reported 3 times in less than a week when + changing from relative to absolute paths. See https://github.com/huggingface/huggingface_hub/issues/1398, + https://github.com/huggingface/diffusers/issues/2729 and https://github.com/huggingface/transformers/pull/22228. + NOTE: The issue with absolute paths doesn't happen on admin mode. + When creating a symlink from the cache to a local folder, it is possible that a relative path cannot be created. + This happens when paths are not on the same volume. In that case, we use absolute paths. + + + The result layout looks something like + └── [ 128] snapshots + ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f + │ ├── [ 52] README.md -> ../../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812 + │ └── [ 76] pytorch_model.bin -> ../../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + + If symlinks cannot be created on this platform (most likely to be Windows), the workaround is to avoid symlinks by + having the actual file in `dst`. If it is a new file (`new_blob=True`), we move it to `dst`. If it is not a new file + (`new_blob=False`), we don't know if the blob file is already referenced elsewhere. To avoid breaking existing + cache, the file is duplicated on the disk. + + In case symlinks are not supported, a warning message is displayed to the user once when loading `huggingface_hub`. + The warning message can be disabled with the `DISABLE_SYMLINKS_WARNING` environment variable. + """ + try: + os.remove(dst) + except OSError: + pass + + abs_src = os.path.abspath(os.path.expanduser(src)) + abs_dst = os.path.abspath(os.path.expanduser(dst)) + abs_dst_folder = os.path.dirname(abs_dst) + + # Use relative_dst in priority + try: + relative_src = os.path.relpath(abs_src, abs_dst_folder) + except ValueError: + # Raised on Windows if src and dst are not on the same volume. This is the case when creating a symlink to a + # local_dir instead of within the cache directory. + # See https://docs.python.org/3/library/os.path.html#os.path.relpath + relative_src = None + + try: + commonpath = os.path.commonpath([abs_src, abs_dst]) + _support_symlinks = are_symlinks_supported(commonpath) + except ValueError: + # Raised if src and dst are not on the same volume. Symlinks will still work on Linux/Macos. + # See https://docs.python.org/3/library/os.path.html#os.path.commonpath + _support_symlinks = os.name != "nt" and not constants.HF_HUB_DISABLE_SYMLINKS + except PermissionError: + # Permission error means src and dst are not in the same volume (e.g. destination path has been provided + # by the user via `local_dir`. Let's test symlink support there) + _support_symlinks = are_symlinks_supported(abs_dst_folder) + except OSError as e: + # OS error (errno=30) means that the commonpath is readonly on Linux/MacOS. + if e.errno == errno.EROFS: + _support_symlinks = are_symlinks_supported(abs_dst_folder) + else: + raise + + # Symlinks are supported => let's create a symlink. + if _support_symlinks: + src_rel_or_abs = relative_src or abs_src + logger.debug(f"Creating pointer from {src_rel_or_abs} to {abs_dst}") + try: + os.symlink(src_rel_or_abs, abs_dst) + return + except FileExistsError: + if os.path.islink(abs_dst) and os.path.realpath(abs_dst) == os.path.realpath(abs_src): + # `abs_dst` already exists and is a symlink to the `abs_src` blob. It is most likely that the file has + # been cached twice concurrently (exactly between `os.remove` and `os.symlink`). Do nothing. + return + else: + # Very unlikely to happen. Means a file `dst` has been created exactly between `os.remove` and + # `os.symlink` and is not a symlink to the `abs_src` blob file. Raise exception. + raise + except PermissionError: + # Permission error means src and dst are not in the same volume (e.g. download to local dir) and symlink + # is supported on both volumes but not between them. Let's just make a hard copy in that case. + pass + + # Symlinks are not supported => let's move or copy the file. + if new_blob: + logger.debug(f"Symlink not supported. Moving file from {abs_src} to {abs_dst}") + shutil.move(abs_src, abs_dst, copy_function=_copy_no_matter_what) + else: + logger.debug(f"Symlink not supported. Copying file from {abs_src} to {abs_dst}") + shutil.copyfile(abs_src, abs_dst) + + +def _cache_commit_hash_for_specific_revision(storage_folder: str, revision: str, commit_hash: str) -> None: + """Cache reference between a revision (tag, branch or truncated commit hash) and the corresponding commit hash. + + Does nothing if `revision` is already a proper `commit_hash` or reference is already cached. + """ + if revision != commit_hash: + ref_path = Path(storage_folder) / "refs" / revision + ref_path.parent.mkdir(parents=True, exist_ok=True) + if not ref_path.exists() or commit_hash != ref_path.read_text(): + # Update ref only if has been updated. Could cause useless error in case + # repo is already cached and user doesn't have write access to cache folder. + # See https://github.com/huggingface/huggingface_hub/issues/1216. + ref_path.write_text(commit_hash) + + +@validate_hf_hub_args +def repo_folder_name(*, repo_id: str, repo_type: str) -> str: + """Return a serialized version of a hf.co repo name and type, safe for disk storage + as a single non-nested folder. + + Example: models--julien-c--EsperBERTo-small + """ + # remove all `/` occurrences to correctly convert repo to directory name + parts = [f"{repo_type}s", *repo_id.split("/")] + return constants.REPO_ID_SEPARATOR.join(parts) + + +def _check_disk_space(expected_size: int, target_dir: str | Path) -> None: + """Check disk usage and log a warning if there is not enough disk space to download the file. + + Args: + expected_size (`int`): + The expected size of the file in bytes. + target_dir (`str`): + The directory where the file will be stored after downloading. + """ + + target_dir = Path(target_dir) # format as `Path` + for path in [target_dir] + list(target_dir.parents): # first check target_dir, then each parents one by one + try: + target_dir_free = shutil.disk_usage(path).free + if target_dir_free < expected_size: + warnings.warn( + "Not enough free disk space to download the file. " + f"The expected file size is: {expected_size / 1e6:.2f} MB. " + f"The target location {target_dir} only has {target_dir_free / 1e6:.2f} MB free disk space." + ) + return + except OSError: # raise on anything: file does not exist or space disk cannot be checked + pass + + +@overload +def hf_hub_download( + repo_id: str, + filename: str, + *, + subfolder: str | None = None, + repo_type: str | None = None, + revision: str | None = None, + library_name: str | None = None, + library_version: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + user_agent: dict | str | None = None, + force_download: bool = False, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + token: bool | str | None = None, + local_files_only: bool = False, + headers: dict[str, str] | None = None, + endpoint: str | None = None, + tqdm_class: type[base_tqdm] | None = None, + dry_run: Literal[False] = False, +) -> str: ... + + +@overload +def hf_hub_download( + repo_id: str, + filename: str, + *, + subfolder: str | None = None, + repo_type: str | None = None, + revision: str | None = None, + library_name: str | None = None, + library_version: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + user_agent: dict | str | None = None, + force_download: bool = False, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + token: bool | str | None = None, + local_files_only: bool = False, + headers: dict[str, str] | None = None, + endpoint: str | None = None, + tqdm_class: type[base_tqdm] | None = None, + dry_run: Literal[True] = True, +) -> DryRunFileInfo: ... + + +@overload +def hf_hub_download( + repo_id: str, + filename: str, + *, + subfolder: str | None = None, + repo_type: str | None = None, + revision: str | None = None, + library_name: str | None = None, + library_version: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + user_agent: dict | str | None = None, + force_download: bool = False, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + token: bool | str | None = None, + local_files_only: bool = False, + headers: dict[str, str] | None = None, + endpoint: str | None = None, + tqdm_class: type[base_tqdm] | None = None, + dry_run: bool = False, +) -> str | DryRunFileInfo: ... + + +@validate_hf_hub_args +def hf_hub_download( + repo_id: str, + filename: str, + *, + subfolder: str | None = None, + repo_type: str | None = None, + revision: str | None = None, + library_name: str | None = None, + library_version: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + user_agent: dict | str | None = None, + force_download: bool = False, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + token: bool | str | None = None, + local_files_only: bool = False, + headers: dict[str, str] | None = None, + endpoint: str | None = None, + tqdm_class: type[base_tqdm] | None = None, + dry_run: bool = False, +) -> str | DryRunFileInfo: + """Download a given file if it's not already present in the local cache. + + The new cache file layout looks like this: + - The cache directory contains one subfolder per repo_id (namespaced by repo type) + - inside each repo folder: + - refs is a list of the latest known revision => commit_hash pairs + - blobs contains the actual file blobs (identified by their git-sha or sha256, depending on + whether they're LFS files or not) + - snapshots contains one subfolder per commit, each "commit" contains the subset of the files + that have been resolved at that particular commit. Each filename is a symlink to the blob + at that particular commit. + + ``` + [ 96] . + └── [ 160] models--julien-c--EsperBERTo-small + ├── [ 160] blobs + │ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + │ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e + │ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812 + ├── [ 96] refs + │ └── [ 40] main + └── [ 128] snapshots + ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f + │ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812 + │ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + └── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48 + ├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e + └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + ``` + + If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this + option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir` + to store some metadata related to the downloaded files. While this mechanism is not as robust as the main + cache-system, it's optimized for regularly pulling the latest version of a repository. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + filename (`str`): + The name of the file in the repo. + subfolder (`str`, *optional*): + An optional value corresponding to a folder inside the model repo. + repo_type (`str`, *optional*): + Set to `"dataset"`, `"space"` or `"kernel"` if downloading from a dataset, space or kernel repo, + `None` or `"model"` if downloading from a model. Default is `None`. + revision (`str`, *optional*): + An optional Git revision id which can be a branch name, a tag, or a + commit hash. + library_name (`str`, *optional*): + The name of the library to which the object corresponds. + library_version (`str`, *optional*): + The version of the library. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_dir (`str` or `Path`, *optional*): + If provided, the downloaded file will be placed under this directory. + user_agent (`dict`, `str`, *optional*): + The user-agent info in the form of a dictionary or a string. + force_download (`bool`, *optional*, defaults to `False`): + Whether the file should be downloaded even if it already exists in + the local cache. + etag_timeout (`float`, *optional*, defaults to `10`): + When fetching ETag, how many seconds to wait for the server to send + data before giving up which is passed to `requests.request`. + token (`str`, `bool`, *optional*): + A token to be used for the download. + - If `True`, the token is read from the HuggingFace config + folder. + - If a string, it's used as the authentication token. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the + local cached file if it exists. + headers (`dict`, *optional*): + Additional headers to be sent with the request. + tqdm_class (`tqdm`, *optional*): + If provided, overwrites the default behavior for the progress bar. Passed + argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior. + Defaults to the custom HF progress bar that can be disabled by setting + `HF_HUB_DISABLE_PROGRESS_BARS` environment variable. + dry_run (`bool`, *optional*, defaults to `False`): + If `True`, perform a dry run without actually downloading the file. Returns a + [`DryRunFileInfo`] object containing information about what would be downloaded. + + Returns: + `str` or [`DryRunFileInfo`]: + - If `dry_run=False`: Local path of file or if networking is off, last version of file cached on disk. + - If `dry_run=True`: A [`DryRunFileInfo`] object containing download information. + + Raises: + [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + [`~utils.RemoteEntryNotFoundError`] + If the file to download cannot be found. + [`~utils.LocalEntryNotFoundError`] + If network is disabled or unavailable and file is not found in cache. + [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + If `token=True` but the token cannot be found. + [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) + If ETag cannot be determined. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If some parameter value is invalid. + + """ + if constants.HF_HUB_ETAG_TIMEOUT != constants.DEFAULT_ETAG_TIMEOUT: + # Respect environment variable above user value + etag_timeout = constants.HF_HUB_ETAG_TIMEOUT + + if cache_dir is None: + cache_dir = constants.HF_HUB_CACHE + if revision is None: + revision = constants.DEFAULT_REVISION + if isinstance(cache_dir, Path): + cache_dir = str(cache_dir) + if isinstance(local_dir, Path): + local_dir = str(local_dir) + + if subfolder == "": + subfolder = None + if subfolder is not None: + # This is used to create a URL, and not a local path, hence the forward slash. + filename = f"{subfolder}/{filename}" + + if repo_type is None: + repo_type = "model" + if repo_type not in constants.REPO_TYPES_WITH_KERNEL: + raise ValueError( + f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES_WITH_KERNEL)}" + ) + + hf_headers = build_hf_headers( + token=token, + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + headers=headers, + ) + + if local_dir is not None: + return _hf_hub_download_to_local_dir( + # Destination + local_dir=local_dir, + # File info + repo_id=repo_id, + repo_type=repo_type, + filename=filename, + revision=revision, + # HTTP info + endpoint=endpoint, + etag_timeout=etag_timeout, + headers=hf_headers, + token=token, + # Additional options + cache_dir=cache_dir, + force_download=force_download, + local_files_only=local_files_only, + tqdm_class=tqdm_class, + dry_run=dry_run, + ) + else: + return _hf_hub_download_to_cache_dir( + # Destination + cache_dir=cache_dir, + # File info + repo_id=repo_id, + filename=filename, + repo_type=repo_type, + revision=revision, + # HTTP info + endpoint=endpoint, + etag_timeout=etag_timeout, + headers=hf_headers, + token=token, + # Additional options + local_files_only=local_files_only, + force_download=force_download, + tqdm_class=tqdm_class, + dry_run=dry_run, + ) + + +def _hf_hub_download_to_cache_dir( + *, + # Destination + cache_dir: str, + # File info + repo_id: str, + filename: str, + repo_type: str, + revision: str, + # HTTP info + endpoint: str | None, + etag_timeout: float, + headers: dict[str, str], + token: bool | str | None, + # Additional options + local_files_only: bool, + force_download: bool, + tqdm_class: type[base_tqdm] | None, + dry_run: bool, +) -> str | DryRunFileInfo: + """Download a given file to a cache folder, if not already present. + + Method should not be called directly. Please use `hf_hub_download` instead. + """ + locks_dir = os.path.join(cache_dir, ".locks") + storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type)) + + # cross-platform transcription of filename, to be used as a local file path. + relative_filename = os.path.join(*filename.split("/")) + if os.name == "nt": + if relative_filename.startswith("..\\") or "\\..\\" in relative_filename: + raise ValueError( + f"Invalid filename: cannot handle filename '{relative_filename}' on Windows. Please ask the repository" + " owner to rename this file." + ) + + # if user provides a commit_hash and they already have the file on disk, shortcut everything. + if REGEX_COMMIT_HASH.match(revision): + pointer_path = _get_pointer_path(storage_folder, revision, relative_filename) + if os.path.exists(pointer_path): + if dry_run: + return DryRunFileInfo( + commit_hash=revision, + file_size=os.path.getsize(pointer_path), + filename=filename, + is_cached=True, + local_path=pointer_path, + will_download=force_download, + ) + if not force_download: + return pointer_path + + # Try to get metadata (etag, commit_hash, url, size) from the server. + # If we can't, a HEAD request error is returned. + (url_to_download, etag, commit_hash, expected_size, xet_file_data, head_call_error) = _get_metadata_or_catch_error( + repo_id=repo_id, + filename=filename, + repo_type=repo_type, + revision=revision, + endpoint=endpoint, + etag_timeout=etag_timeout, + headers=headers, + token=token, + local_files_only=local_files_only, + storage_folder=storage_folder, + relative_filename=relative_filename, + ) + + # etag can be None for several reasons: + # 1. we passed local_files_only. + # 2. we don't have a connection + # 3. Hub is down (HTTP 500, 503, 504) + # 4. repo is not found -for example private or gated- and invalid/missing token sent + # 5. Hub is blocked by a firewall or proxy is not set correctly. + # => Try to get the last downloaded one from the specified revision. + # + # If the specified revision is a commit hash, look inside "snapshots". + # If the specified revision is a branch or tag, look inside "refs". + if head_call_error is not None: + # Couldn't make a HEAD call => let's try to find a local file + if not force_download: + commit_hash = None + if REGEX_COMMIT_HASH.match(revision): + commit_hash = revision + else: + ref_path = os.path.join(storage_folder, "refs", revision) + if os.path.isfile(ref_path): + with open(ref_path) as f: + commit_hash = f.read() + + # Return pointer file if exists + if commit_hash is not None: + pointer_path = _get_pointer_path(storage_folder, commit_hash, relative_filename) + if os.path.exists(pointer_path): + if dry_run: + return DryRunFileInfo( + commit_hash=commit_hash, + file_size=os.path.getsize(pointer_path), + filename=filename, + is_cached=True, + local_path=pointer_path, + will_download=force_download, + ) + if not force_download: + return pointer_path + + if isinstance(head_call_error, _DEFAULT_RETRY_ON_EXCEPTIONS) or ( + isinstance(head_call_error, HfHubHTTPError) + and head_call_error.response.status_code in _DEFAULT_RETRY_ON_STATUS_CODES + ): + logger.info("No local file found. Retrying..") + (url_to_download, etag, commit_hash, expected_size, xet_file_data, head_call_error) = ( + _get_metadata_or_catch_error( + repo_id=repo_id, + filename=filename, + repo_type=repo_type, + revision=revision, + endpoint=endpoint, + etag_timeout=_ETAG_RETRY_TIMEOUT, + headers=headers, + token=token, + local_files_only=local_files_only, + storage_folder=storage_folder, + relative_filename=relative_filename, + retry_on_errors=True, + ) + ) + + # If still error, raise + if head_call_error is not None: + _raise_on_head_call_error(head_call_error, force_download, local_files_only) + + # From now on, etag, commit_hash, url and size are not None. + assert etag is not None, "etag must have been retrieved from server" + assert commit_hash is not None, "commit_hash must have been retrieved from server" + assert url_to_download is not None, "file location must have been retrieved from server" + assert expected_size is not None, "expected_size must have been retrieved from server" + blob_path = os.path.join(storage_folder, "blobs", etag) + pointer_path = _get_pointer_path(storage_folder, commit_hash, relative_filename) + + if dry_run: + is_cached = os.path.exists(pointer_path) or os.path.exists(blob_path) + return DryRunFileInfo( + commit_hash=commit_hash, + file_size=expected_size, + filename=filename, + is_cached=is_cached, + local_path=pointer_path, + will_download=force_download or not is_cached, + ) + + os.makedirs(os.path.dirname(blob_path), exist_ok=True) + os.makedirs(os.path.dirname(pointer_path), exist_ok=True) + + # Tag cache_dir so backup tools can skip it (CACHEDIR.TAG standard). + _create_cachedir_tag(Path(cache_dir)) + + # if passed revision is not identical to commit_hash + # then revision has to be a branch name or tag name. + # In that case store a ref. + _cache_commit_hash_for_specific_revision(storage_folder, revision, commit_hash) + + # Prevent parallel downloads of the same file with a lock. + # etag could be duplicated across repos, + lock_path = os.path.join(locks_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type), f"{etag}.lock") + + # Some Windows versions do not allow for paths longer than 255 characters. + # In this case, we must specify it as an extended path by using the "\\?\" prefix. + if ( + os.name == "nt" + and len(os.path.abspath(lock_path)) > 255 + and not os.path.abspath(lock_path).startswith("\\\\?\\") + ): + lock_path = "\\\\?\\" + os.path.abspath(lock_path) + + if ( + os.name == "nt" + and len(os.path.abspath(blob_path)) > 255 + and not os.path.abspath(blob_path).startswith("\\\\?\\") + ): + blob_path = "\\\\?\\" + os.path.abspath(blob_path) + + Path(lock_path).parent.mkdir(parents=True, exist_ok=True) + + # pointer already exists -> immediate return + if not force_download and os.path.exists(pointer_path): + return pointer_path + + # Blob exists but pointer must be (safely) created -> take the lock + if not force_download and os.path.exists(blob_path): + with WeakFileLock(lock_path): + if not os.path.exists(pointer_path): + _create_symlink(blob_path, pointer_path, new_blob=False) + return pointer_path + + # Local file doesn't exist or etag isn't a match => retrieve file from remote (or cache) + + with WeakFileLock(lock_path): + _download_to_tmp_and_move( + incomplete_path=Path(blob_path + ".incomplete"), + destination_path=Path(blob_path), + url_to_download=url_to_download, + headers=headers, + expected_size=expected_size, + filename=filename, + force_download=force_download, + etag=etag, + xet_file_data=xet_file_data, + tqdm_class=tqdm_class, + ) + if not os.path.exists(pointer_path): + _create_symlink(blob_path, pointer_path, new_blob=True) + + return pointer_path + + +def _hf_hub_download_to_local_dir( + *, + # Destination + local_dir: str | Path, + # File info + repo_id: str, + repo_type: str, + filename: str, + revision: str, + # HTTP info + endpoint: str | None, + etag_timeout: float, + headers: dict[str, str], + token: bool | str | None, + # Additional options + cache_dir: str, + force_download: bool, + local_files_only: bool, + tqdm_class: type[base_tqdm] | None, + dry_run: bool, +) -> str | DryRunFileInfo: + """Download a given file to a local folder, if not already present. + + Method should not be called directly. Please use `hf_hub_download` instead. + """ + # Some Windows versions do not allow for paths longer than 255 characters. + # In this case, we must specify it as an extended path by using the "\\?\" prefix. + if os.name == "nt" and len(os.path.abspath(local_dir)) > 255: + local_dir = "\\\\?\\" + os.path.abspath(local_dir) + local_dir = Path(local_dir) + paths = get_local_download_paths(local_dir=local_dir, filename=filename) + local_metadata = read_download_metadata(local_dir=local_dir, filename=filename) + + # Local file exists + metadata exists + commit_hash matches => return file + if ( + REGEX_COMMIT_HASH.match(revision) + and paths.file_path.is_file() + and local_metadata is not None + and local_metadata.commit_hash == revision + ): + local_file = str(paths.file_path) + if dry_run: + return DryRunFileInfo( + commit_hash=revision, + file_size=os.path.getsize(local_file), + filename=filename, + is_cached=True, + local_path=local_file, + will_download=force_download, + ) + if not force_download: + return local_file + + # Local file doesn't exist or commit_hash doesn't match => we need the etag + (url_to_download, etag, commit_hash, expected_size, xet_file_data, head_call_error) = _get_metadata_or_catch_error( + repo_id=repo_id, + filename=filename, + repo_type=repo_type, + revision=revision, + endpoint=endpoint, + etag_timeout=etag_timeout, + headers=headers, + token=token, + local_files_only=local_files_only, + ) + + if head_call_error is not None: + # No HEAD call but local file exists => default to local file + if paths.file_path.is_file(): + if dry_run or not force_download: + logger.warning( + f"Couldn't access the Hub to check for update but local file already exists. Defaulting to existing file. (error: {head_call_error})" + ) + local_path = str(paths.file_path) + if dry_run and local_metadata is not None: + return DryRunFileInfo( + commit_hash=local_metadata.commit_hash, + file_size=os.path.getsize(local_path), + filename=filename, + is_cached=True, + local_path=local_path, + will_download=force_download, + ) + if not force_download: + return local_path + elif not force_download: + if isinstance(head_call_error, _DEFAULT_RETRY_ON_EXCEPTIONS) or ( + isinstance(head_call_error, HfHubHTTPError) + and head_call_error.response.status_code in _DEFAULT_RETRY_ON_STATUS_CODES + ): + logger.info("No local file found. Retrying..") + (url_to_download, etag, commit_hash, expected_size, xet_file_data, head_call_error) = ( + _get_metadata_or_catch_error( + repo_id=repo_id, + filename=filename, + repo_type=repo_type, + revision=revision, + endpoint=endpoint, + etag_timeout=_ETAG_RETRY_TIMEOUT, + headers=headers, + token=token, + local_files_only=local_files_only, + retry_on_errors=True, + ) + ) + + # If still error, raise + if head_call_error is not None: + _raise_on_head_call_error(head_call_error, force_download, local_files_only) + + # From now on, etag, commit_hash, url and size are not None. + assert etag is not None, "etag must have been retrieved from server" + assert commit_hash is not None, "commit_hash must have been retrieved from server" + assert url_to_download is not None, "file location must have been retrieved from server" + assert expected_size is not None, "expected_size must have been retrieved from server" + + # Local file exists => check if it's up-to-date + if not force_download and paths.file_path.is_file(): + # etag matches => update metadata and return file + if local_metadata is not None and local_metadata.etag == etag: + write_download_metadata(local_dir=local_dir, filename=filename, commit_hash=commit_hash, etag=etag) + if dry_run: + return DryRunFileInfo( + commit_hash=commit_hash, + file_size=expected_size, + filename=filename, + is_cached=True, + local_path=str(paths.file_path), + will_download=False, + ) + return str(paths.file_path) + + # metadata is outdated + etag is a sha256 + # => means it's an LFS file (large) + # => let's compute local hash and compare + # => if match, update metadata and return file + if local_metadata is None and REGEX_SHA256.match(etag) is not None: + with open(paths.file_path, "rb") as f: + file_hash = sha_fileobj(f).hex() + if file_hash == etag: + write_download_metadata(local_dir=local_dir, filename=filename, commit_hash=commit_hash, etag=etag) + if dry_run: + return DryRunFileInfo( + commit_hash=commit_hash, + file_size=expected_size, + filename=filename, + is_cached=True, + local_path=str(paths.file_path), + will_download=False, + ) + return str(paths.file_path) + + # Local file doesn't exist or etag isn't a match => retrieve file from remote (or cache) + + # If we are lucky enough, the file is already in the cache => copy it + if not force_download: + cached_path = try_to_load_from_cache( + repo_id=repo_id, + filename=filename, + cache_dir=cache_dir, + revision=commit_hash, + repo_type=repo_type, + ) + if isinstance(cached_path, str): + with WeakFileLock(paths.lock_path): + paths.file_path.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(cached_path, paths.file_path) + write_download_metadata(local_dir=local_dir, filename=filename, commit_hash=commit_hash, etag=etag) + if dry_run: + return DryRunFileInfo( + commit_hash=commit_hash, + file_size=expected_size, + filename=filename, + is_cached=True, + local_path=str(paths.file_path), + will_download=False, + ) + return str(paths.file_path) + + if dry_run: + is_cached = paths.file_path.is_file() + return DryRunFileInfo( + commit_hash=commit_hash, + file_size=expected_size, + filename=filename, + is_cached=is_cached, + local_path=str(paths.file_path), + will_download=force_download or not is_cached, + ) + + # Otherwise, let's download the file! + with WeakFileLock(paths.lock_path): + paths.file_path.unlink(missing_ok=True) # delete outdated file first + _download_to_tmp_and_move( + incomplete_path=paths.incomplete_path(etag), + destination_path=paths.file_path, + url_to_download=url_to_download, + headers=headers, + expected_size=expected_size, + filename=filename, + force_download=force_download, + etag=etag, + xet_file_data=xet_file_data, + tqdm_class=tqdm_class, + ) + + write_download_metadata(local_dir=local_dir, filename=filename, commit_hash=commit_hash, etag=etag) + return str(paths.file_path) + + +@validate_hf_hub_args +def try_to_load_from_cache( + repo_id: str, + filename: str, + cache_dir: str | Path | None = None, + revision: str | None = None, + repo_type: str | None = None, +) -> str | _CACHED_NO_EXIST_T | None: + """ + Explores the cache to return the latest cached file for a given revision if found. + + This function will not raise any exception if the file in not cached. + + Args: + cache_dir (`str` or `os.PathLike`): + The folder where the cached files lie. + repo_id (`str`): + The ID of the repo on huggingface.co. + filename (`str`): + The filename to look for inside `repo_id`. + revision (`str`, *optional*): + The specific model version to use. Will default to `"main"` if it's not provided and no `commit_hash` is + provided either. + repo_type (`str`, *optional*): + The type of the repository. Will default to `"model"`. + + Returns: + `Optional[str]` or `_CACHED_NO_EXIST`: + Will return `None` if the file was not cached. Otherwise: + - The exact path to the cached file if it's found in the cache + - A special value `_CACHED_NO_EXIST` if the file does not exist at the given commit hash and this fact was + cached. + + Example: + + ```python + from huggingface_hub import try_to_load_from_cache, _CACHED_NO_EXIST + + filepath = try_to_load_from_cache() + if isinstance(filepath, str): + # file exists and is cached + ... + elif filepath is _CACHED_NO_EXIST: + # non-existence of file is cached + ... + else: + # file is not cached + ... + ``` + """ + if revision is None: + revision = "main" + if repo_type is None: + repo_type = "model" + if repo_type not in constants.REPO_TYPES_WITH_KERNEL: + raise ValueError( + f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES_WITH_KERNEL)}" + ) + if cache_dir is None: + cache_dir = constants.HF_HUB_CACHE + + repo_cache = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type)) + if not os.path.isdir(repo_cache): + # No cache for this model + return None + + refs_dir = os.path.join(repo_cache, "refs") + snapshots_dir = os.path.join(repo_cache, "snapshots") + no_exist_dir = os.path.join(repo_cache, ".no_exist") + + # Resolve refs (for instance to convert main to the associated commit sha) + if os.path.isdir(refs_dir): + revision_file = os.path.join(refs_dir, revision) + if os.path.isfile(revision_file): + with open(revision_file) as f: + revision = f.read() + + # Check if file is cached as "no_exist" + if os.path.isfile(os.path.join(no_exist_dir, revision, filename)): + return _CACHED_NO_EXIST + + # Check if revision folder exists + if not os.path.exists(snapshots_dir): + return None + cached_shas = os.listdir(snapshots_dir) + if revision not in cached_shas: + # No cache for this revision and we won't try to return a random revision + return None + + # Check if file exists in cache + cached_file = os.path.join(snapshots_dir, revision, filename) + return cached_file if os.path.isfile(cached_file) else None + + +@validate_hf_hub_args +def get_hf_file_metadata( + url: str, + token: bool | str | None = None, + timeout: float | None = constants.HF_HUB_ETAG_TIMEOUT, + library_name: str | None = None, + library_version: str | None = None, + user_agent: dict | str | None = None, + headers: dict[str, str] | None = None, + endpoint: str | None = None, + retry_on_errors: bool = False, +) -> HfFileMetadata: + """Fetch metadata of a file versioned on the Hub for a given url. + + Args: + url (`str`): + File url, for example returned by [`hf_hub_url`]. + token (`str` or `bool`, *optional*): + A token to be used for the download. + - If `True`, the token is read from the HuggingFace config + folder. + - If `False` or `None`, no token is provided. + - If a string, it's used as the authentication token. + timeout (`float`, *optional*, defaults to 10): + How many seconds to wait for the server to send metadata before giving up. + library_name (`str`, *optional*): + The name of the library to which the object corresponds. + library_version (`str`, *optional*): + The version of the library. + user_agent (`dict`, `str`, *optional*): + The user-agent info in the form of a dictionary or a string. + headers (`dict`, *optional*): + Additional headers to be sent with the request. + endpoint (`str`, *optional*): + Endpoint of the Hub. Defaults to . + retry_on_errors (`bool`, *optional*, defaults to `False`): + Whether to retry on errors (429, 5xx, timeout, network errors). + If False, no retry for fast fallback to local cache. + + Returns: + A [`HfFileMetadata`] object containing metadata such as location, etag, size and + commit_hash. + """ + hf_headers = build_hf_headers( + token=token, + library_name=library_name, + library_version=library_version, + user_agent=user_agent, + headers=headers, + ) + hf_headers["Accept-Encoding"] = "identity" # prevent any compression => we want to know the real size of the file + + # Retrieve metadata + response = _httpx_follow_relative_redirects_with_backoff( + method="HEAD", url=url, headers=hf_headers, timeout=timeout, retry_on_errors=retry_on_errors + ) + hf_raise_for_status(response) + + # Return + return HfFileMetadata( + commit_hash=response.headers.get(constants.HUGGINGFACE_HEADER_X_REPO_COMMIT), + # We favor a custom header indicating the etag of the linked resource, and we fall back to the regular etag header. + etag=_normalize_etag( + response.headers.get(constants.HUGGINGFACE_HEADER_X_LINKED_ETAG) or response.headers.get("ETag") + ), + # Either from response headers (if redirected) or defaults to request url + # Do not use directly `url` as we might have followed relative redirects. + location=response.headers.get("Location") or str(response.request.url), # type: ignore + size=_int_or_none( + response.headers.get(constants.HUGGINGFACE_HEADER_X_LINKED_SIZE) or response.headers.get("Content-Length") + ), + xet_file_data=parse_xet_file_data_from_response(response, endpoint=endpoint), # type: ignore + ) + + +def _get_metadata_or_catch_error( + *, + repo_id: str, + filename: str, + repo_type: str, + revision: str, + endpoint: str | None, + etag_timeout: float | None, + headers: dict[str, str], # mutated inplace! + token: bool | str | None, + local_files_only: bool, + relative_filename: str | None = None, # only used to store `.no_exists` in cache + storage_folder: str | None = None, # only used to store `.no_exists` in cache + retry_on_errors: bool = False, +) -> ( + # Either an exception is caught and returned + tuple[None, None, None, None, None, Exception] + | + # Or the metadata is returned as + # `(url_to_download, etag, commit_hash, expected_size, xet_file_data, None)` + tuple[str, str, str, int, XetFileData | None, None] +): + """Get metadata for a file on the Hub, safely handling network issues. + + Returns either the etag, commit_hash and expected size of the file, or the error + raised while fetching the metadata. + + NOTE: This function mutates `headers` inplace! It removes the `authorization` header + if the file is a LFS blob and the domain of the url is different from the + domain of the location (typically an S3 bucket). + """ + if local_files_only: + return ( + None, + None, + None, + None, + None, + OfflineModeIsEnabled( + f"Cannot access file since 'local_files_only=True' as been set. (repo_id: {repo_id}, repo_type: {repo_type}, revision: {revision}, filename: {filename})" + ), + ) + + url = hf_hub_url(repo_id, filename, repo_type=repo_type, revision=revision, endpoint=endpoint) + url_to_download: str = url + etag: str | None = None + commit_hash: str | None = None + expected_size: int | None = None + head_error_call: Exception | None = None + xet_file_data: XetFileData | None = None + + # Try to get metadata from the server. + # Do not raise yet if the file is not found or not accessible. + if not local_files_only: + try: + try: + metadata = get_hf_file_metadata( + url=url, + timeout=etag_timeout, + headers=headers, + token=token, + endpoint=endpoint, + retry_on_errors=retry_on_errors, + ) + except RemoteEntryNotFoundError as http_error: + if storage_folder is not None and relative_filename is not None: + # Cache the non-existence of the file + commit_hash = http_error.response.headers.get(constants.HUGGINGFACE_HEADER_X_REPO_COMMIT) + if commit_hash is not None: + no_exist_file_path = Path(storage_folder) / ".no_exist" / commit_hash / relative_filename + try: + no_exist_file_path.parent.mkdir(parents=True, exist_ok=True) + no_exist_file_path.touch() + except OSError as e: + logger.error( + f"Could not cache non-existence of file. Will ignore error and continue. Error: {e}" + ) + _cache_commit_hash_for_specific_revision(storage_folder, revision, commit_hash) + raise + + # Commit hash must exist + commit_hash = metadata.commit_hash + if commit_hash is None: + raise FileMetadataError( + "Distant resource does not seem to be on huggingface.co. It is possible that a configuration issue" + " prevents you from downloading resources from https://huggingface.co. Please check your firewall" + " and proxy settings and make sure your SSL certificates are updated." + ) + + # Etag must exist + # If we don't have any of those, raise an error. + etag = metadata.etag + if etag is None: + raise FileMetadataError( + "Distant resource does not have an ETag, we won't be able to reliably ensure reproducibility." + ) + + # Size must exist + expected_size = metadata.size + if expected_size is None: + raise FileMetadataError("Distant resource does not have a Content-Length.") + + xet_file_data = metadata.xet_file_data + + # In case of a redirect, save an extra redirect on the request.get call, + # and ensure we download the exact atomic version even if it changed + # between the HEAD and the GET (unlikely, but hey). + # + # If url domain is different => we are downloading from a CDN => url is signed => don't send auth + # If url domain is the same => redirect due to repo rename AND downloading a regular file => keep auth + if xet_file_data is None and url != metadata.location: + url_to_download = metadata.location + if urlparse(url).netloc != urlparse(metadata.location).netloc: + # Remove authorization header when downloading a LFS blob + headers.pop("authorization", None) + except httpx.ProxyError: + # Actually raise on proxy error + raise + except (httpx.ConnectError, httpx.TimeoutException, OfflineModeIsEnabled) as error: + # Otherwise, our Internet connection is down. + # etag is None + head_error_call = error + except (RevisionNotFoundError, RemoteEntryNotFoundError): + # The repo was found but the revision or entry doesn't exist on the Hub (never existed or got deleted) + raise + except HfHubHTTPError as error: + # Multiple reasons for an http error: + # - Repository is private and invalid/missing token sent + # - Repository is gated and invalid/missing token sent + # - Hub is down (error 500 or 504) + # => let's switch to 'local_files_only=True' to check if the files are already cached. + # (if it's not the case, the error will be re-raised) + head_error_call = error + except FileMetadataError as error: + # Multiple reasons for a FileMetadataError: + # - Wrong network configuration (proxy, firewall, SSL certificates) + # - Inconsistency on the Hub + # => let's switch to 'local_files_only=True' to check if the files are already cached. + # (if it's not the case, the error will be re-raised) + head_error_call = error + + if not (local_files_only or etag is not None or head_error_call is not None): + raise RuntimeError("etag is empty due to uncovered problems") + + return (url_to_download, etag, commit_hash, expected_size, xet_file_data, head_error_call) # type: ignore + + +def _raise_on_head_call_error(head_call_error: Exception, force_download: bool, local_files_only: bool) -> NoReturn: + """Raise an appropriate error when the HEAD call failed and we cannot locate a local file.""" + # No head call => we cannot force download. + if force_download: + if local_files_only: + raise ValueError("Cannot pass 'force_download=True' and 'local_files_only=True' at the same time.") + elif isinstance(head_call_error, OfflineModeIsEnabled): + raise ValueError("Cannot pass 'force_download=True' when offline mode is enabled.") from head_call_error + else: + raise ValueError("Force download failed due to the above error.") from head_call_error + + # No head call + couldn't find an appropriate file on disk => raise an error. + if local_files_only: + raise LocalEntryNotFoundError( + "Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable" + " hf.co look-ups and downloads online, set 'local_files_only' to False." + ) + elif isinstance(head_call_error, (RepositoryNotFoundError, GatedRepoError)) or ( + isinstance(head_call_error, HfHubHTTPError) and head_call_error.response.status_code == 401 + ): + # Repo not found or gated => let's raise the actual error + # Unauthorized => likely a token issue => let's raise the actual error + raise head_call_error + else: + # Otherwise: most likely a connection issue or Hub downtime => let's warn the user + raise LocalEntryNotFoundError( + "An error happened while trying to locate the file on the Hub and we cannot find the requested files" + " in the local cache. Please check your connection and try again or make sure your Internet connection" + " is on." + ) from head_call_error + + +def _download_to_tmp_and_move( + incomplete_path: Path, + destination_path: Path, + url_to_download: str, + headers: dict[str, str], + expected_size: int | None, + filename: str, + force_download: bool, + etag: str | None, + xet_file_data: XetFileData | None, + tqdm_class: type[base_tqdm] | None = None, +) -> None: + """Download content from a URL to a destination path. + + Internal logic: + - return early if file is already downloaded + - resume download if possible (from incomplete file) + - do not resume download if `force_download=True` + - check disk space before downloading + - download content to a temporary file + - set correct permissions on temporary file + - move the temporary file to the destination path + + Both `incomplete_path` and `destination_path` must be on the same volume to avoid a local copy. + """ + if destination_path.exists() and not force_download: + # Do nothing if already exists (except if force_download=True) + return + + if incomplete_path.exists() and force_download: + # By default, we will try to resume the download if possible. + # However, if the user has set `force_download=True`, then we should + # not resume the download => delete the incomplete file. + logger.debug(f"Removing incomplete file '{incomplete_path}' (force_download=True)") + incomplete_path.unlink(missing_ok=True) + + with incomplete_path.open("ab") as f: + resume_size = f.tell() + message = f"Downloading '{filename}' to '{incomplete_path}'" + if resume_size > 0 and expected_size is not None: + message += f" (resume from {resume_size}/{expected_size})" + logger.debug(message) + + if expected_size is not None: # might be None if HTTP header not set correctly + # Check disk space in both tmp and destination path + _check_disk_space(expected_size, incomplete_path.parent) + _check_disk_space(expected_size, destination_path.parent) + + if xet_file_data is not None and is_xet_available(): + logger.debug("Xet Storage is enabled for this repo. Downloading file from Xet Storage..") + xet_get( + incomplete_path=incomplete_path, + xet_file_data=xet_file_data, + headers=headers, + expected_size=expected_size, + displayed_filename=filename, + tqdm_class=tqdm_class, + ) + else: + if xet_file_data is not None and not constants.HF_HUB_DISABLE_XET: + logger.warning( + "Xet Storage is enabled for this repo, but the 'hf_xet' package is not installed. " + "Falling back to regular HTTP download. " + "For better performance, install the package with: `pip install huggingface_hub[hf_xet]` or `pip install hf_xet`" + ) + + http_get( + url_to_download, + f, + resume_size=resume_size, + headers=headers, + expected_size=expected_size, + tqdm_class=tqdm_class, + ) + + logger.debug(f"Download complete. Moving file to {destination_path}") + _chmod_and_move(incomplete_path, destination_path) + + +def _int_or_none(value: str | None) -> int | None: + try: + return int(value) # type: ignore + except (TypeError, ValueError): + return None + + +def _chmod_and_move(src: Path, dst: Path) -> None: + """Set correct permission before moving a blob from tmp directory to cache dir. + + Do not take into account the `umask` from the process as there is no convenient way + to get it that is thread-safe. + + See: + - About umask: https://docs.python.org/3/library/os.html#os.umask + - Thread-safety: https://stackoverflow.com/a/70343066 + - About solution: https://github.com/huggingface/huggingface_hub/pull/1220#issuecomment-1326211591 + - Fix issue: https://github.com/huggingface/huggingface_hub/issues/1141 + - Fix issue: https://github.com/huggingface/huggingface_hub/issues/1215 + """ + # Get umask by creating a temporary file in the cached repo folder. + tmp_file = dst.parent.parent / f"tmp_{uuid.uuid4()}" + try: + tmp_file.touch() + cache_dir_mode = Path(tmp_file).stat().st_mode + os.chmod(str(src), stat.S_IMODE(cache_dir_mode)) + except OSError as e: + logger.warning( + f"Could not set the permissions on the file '{src}'. Error: {e}.\nContinuing without setting permissions." + ) + finally: + try: + tmp_file.unlink() + except OSError: + # fails if `tmp_file.touch()` failed => do nothing + # See https://github.com/huggingface/huggingface_hub/issues/2359 + pass + + shutil.move(str(src), str(dst), copy_function=_copy_no_matter_what) + + +def _copy_no_matter_what(src: str, dst: str) -> None: + """Copy file from src to dst. + + If `shutil.copy2` fails, fallback to `shutil.copyfile`. + """ + try: + # Copy file with metadata and permission + # Can fail e.g. if dst is an S3 mount + shutil.copy2(src, dst) + except OSError: + # Copy only file content + shutil.copyfile(src, dst) + + +def _get_pointer_path(storage_folder: str, revision: str, relative_filename: str) -> str: + # Using `os.path.abspath` instead of `Path.resolve()` to avoid resolving symlinks + snapshot_path = os.path.join(storage_folder, "snapshots") + pointer_path = os.path.join(snapshot_path, revision, relative_filename) + if Path(os.path.abspath(snapshot_path)) not in Path(os.path.abspath(pointer_path)).parents: + raise ValueError( + "Invalid pointer path: cannot create pointer path in snapshot folder if" + f" `storage_folder='{storage_folder}'`, `revision='{revision}'` and" + f" `relative_filename='{relative_filename}'`." + ) + return pointer_path diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/hf_api.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/hf_api.py new file mode 100644 index 0000000000000000000000000000000000000000..75b9d2d6156ce9fd19ea1ef488ff958e8d21f8c3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/hf_api.py @@ -0,0 +1,14091 @@ +# Copyright 2019-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import inspect +import itertools +import json +import re +import struct +import time +import warnings +from collections import defaultdict +from collections.abc import Callable, Iterable, Iterator +from concurrent.futures import Future, ThreadPoolExecutor +from dataclasses import asdict, dataclass, field +from datetime import datetime, timezone +from functools import wraps +from itertools import islice +from pathlib import Path +from secrets import token_hex +from typing import TYPE_CHECKING, Any, BinaryIO, Literal, TypeVar, overload +from urllib.parse import quote, unquote + +import httpcore +import httpx +from tqdm.auto import tqdm as base_tqdm +from tqdm.contrib.concurrent import thread_map + +from huggingface_hub.utils._xet import ( + XetTokenType, + fetch_xet_connection_info_from_repo_info, + reset_xet_connection_info_cache_for_repo, +) + +from . import constants +from ._buckets import ( + BucketFile, + BucketFileMetadata, + BucketFolder, + BucketInfo, + BucketUrl, + SyncPlan, + _BucketAddFile, + _BucketCopyFile, + _BucketDeleteFile, + _split_bucket_id_and_prefix, + sync_bucket_internal, +) +from ._commit_api import ( + CommitOperation, + CommitOperationAdd, + CommitOperationCopy, + CommitOperationDelete, + _fetch_files_to_copy, + _fetch_upload_modes, + _prepare_commit_payload, + _upload_files, + _warn_on_overwriting_operations, +) +from ._dataset_viewer import DatasetParquetEntry +from ._eval_results import EvalResultEntry, parse_eval_result_entries +from ._inference_endpoints import InferenceEndpoint, InferenceEndpointScalingMetric, InferenceEndpointType +from ._jobs_api import JobHardware, JobInfo, JobSpec, ScheduledJobInfo, _create_job_spec +from ._space_api import ( + SpaceHardware, + SpaceRuntime, + SpaceSearchResult, + SpaceSecret, + SpaceStorage, + SpaceVariable, + Volume, +) +from ._upload_large_folder import upload_large_folder_internal +from .community import ( + Discussion, + DiscussionComment, + DiscussionStatusChange, + DiscussionTitleChange, + DiscussionWithDetails, + deserialize_event, +) +from .errors import ( + BadRequestError, + EntryNotFoundError, + GatedRepoError, + HfHubHTTPError, + LocalTokenNotFoundError, + RemoteEntryNotFoundError, + RepositoryNotFoundError, + RevisionNotFoundError, + XetAuthorizationError, + XetRefreshTokenError, +) +from .file_download import DryRunFileInfo, HfFileMetadata, get_hf_file_metadata, hf_hub_url +from .repocard_data import DatasetCardData, ModelCardData, SpaceCardData +from .utils import ( + DEFAULT_IGNORE_PATTERNS, + NotASafetensorsRepoError, + SafetensorsFileMetadata, + SafetensorsParsingError, + SafetensorsRepoMetadata, + TensorInfo, + are_progress_bars_disabled, + build_hf_headers, + chunk_iterable, + experimental, + filter_repo_objects, + fix_hf_endpoint_in_url, + get_session, + get_token, + hf_raise_for_status, + http_backoff, + logging, + paginate, + parse_datetime, + parse_xet_file_data_from_response, + refresh_xet_connection_info, + silent_tqdm, + validate_hf_hub_args, +) +from .utils import tqdm as hf_tqdm +from .utils._auth import _get_token_from_environment, _get_token_from_file, _get_token_from_google_colab +from .utils._deprecation import _deprecate_arguments, _deprecate_method +from .utils._http import _httpx_follow_relative_redirects_with_backoff +from .utils._typing import CallableT +from .utils._verification import collect_local_files, resolve_local_root, verify_maps +from .utils.endpoint_helpers import _is_emission_within_threshold +from .utils.tqdm import _get_progress_bar_context + + +if TYPE_CHECKING: + from .inference._providers import PROVIDER_T + from .utils._verification import FolderVerification + from .utils._xet_progress_reporting import XetProgressReporter + +R = TypeVar("R") # Return type +CollectionItemType_T = Literal["model", "dataset", "space", "paper", "collection", "bucket"] +CollectionSort_T = Literal["lastModified", "trending", "upvotes"] +RepoVisibility_T = Literal["public", "private", "protected"] + +ExpandModelProperty_T = Literal[ + "author", + "baseModels", + "cardData", + "childrenModelCount", + "config", + "createdAt", + "disabled", + "downloads", + "downloadsAllTime", + "evalResults", + "gated", + "gguf", + "inference", + "inferenceProviderMapping", + "lastModified", + "library_name", + "likes", + "mask_token", + "model-index", + "pipeline_tag", + "private", + "resourceGroup", + "safetensors", + "sha", + "siblings", + "spaces", + "tags", + "transformersInfo", + "trendingScore", + "usedStorage", + "widgetData", +] + +ExpandDatasetProperty_T = Literal[ + "author", + "cardData", + "citation", + "createdAt", + "description", + "disabled", + "downloads", + "downloadsAllTime", + "gated", + "lastModified", + "likes", + "mainSize", + "paperswithcode_id", + "private", + "resourceGroup", + "sha", + "siblings", + "tags", + "trendingScore", + "usedStorage", +] + +ExpandSpaceProperty_T = Literal[ + "author", + "cardData", + "createdAt", + "datasets", + "disabled", + "lastModified", + "likes", + "models", + "private", + "resourceGroup", + "runtime", + "sdk", + "sha", + "siblings", + "subdomain", + "tags", + "trendingScore", + "usedStorage", +] + +ModelSort_T = Literal["created_at", "downloads", "last_modified", "likes", "trending_score"] +DatasetSort_T = Literal["created_at", "downloads", "last_modified", "likes", "trending_score"] +SpaceSort_T = Literal["created_at", "last_modified", "likes", "trending_score"] +DailyPapersSort_T = Literal["publishedAt", "trending"] + +USERNAME_PLACEHOLDER = "hf_user" +_REGEX_DISCUSSION_URL = re.compile(r".*/discussions/(\d+)$") +_REGEX_HTTP_PROTOCOL = re.compile(r"https?://") + +_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE = ( + "\nNote: Creating a commit assumes that the repo already exists on the" + " Huggingface Hub. Please use `create_repo` if it's not the case." +) +_AUTH_CHECK_NO_REPO_ERROR_MESSAGE = ( + "\nNote: The repository either does not exist or you do not have access rights." + " Please check the repository ID and your access permissions." + " If this is a private repository, ensure that your token is correct." +) +_BUCKET_PATHS_INFO_BATCH_SIZE = 1000 +_BUCKET_BATCH_ADD_CHUNK_SIZE = 1000 +_BUCKET_BATCH_DELETE_CHUNK_SIZE = 1000 + +# Regex used to match special revisions with "/" in them (see #1710) +SPECIAL_REFS_REVISION_REGEX = re.compile( + r""" + (^refs\/convert\/\w+) # `refs/convert/parquet` revisions + | + (^refs\/pr\/\d+) # PR revisions + """, + re.VERBOSE, +) + +logger = logging.get_logger(__name__) + + +def _resolve_repo_visibility( + *, + private: bool | None, + visibility: RepoVisibility_T | None, + repo_type: str | None, +) -> RepoVisibility_T | None: + if private is not None and visibility is not None: + raise ValueError("Received both `private` and `visibility` arguments. Please provide only one of them.") + + if visibility is None: + if private is None: + return None + return "private" if private else "public" + + if visibility == "protected" and repo_type != constants.REPO_TYPE_SPACE: + raise ValueError("Only Spaces can be 'protected'. Please set visibility to 'public' or 'private'.") + return visibility + + +def repo_type_and_id_from_hf_id(hf_id: str, hub_url: str | None = None) -> tuple[str | None, str | None, str]: + """ + Returns the repo type and ID from a huggingface.co URL linking to a + repository + + Args: + hf_id (`str`): + An URL or ID of a repository on the HF hub. Accepted values are: + + - https://huggingface.co/// + - https://huggingface.co// + - hf://// + - hf:/// + - // + - / + - + hub_url (`str`, *optional*): + The URL of the HuggingFace Hub, defaults to https://huggingface.co + + Returns: + A tuple with three items: repo_type (`str` or `None`), namespace (`str` or + `None`) and repo_id (`str`). + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If URL cannot be parsed. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `repo_type` is unknown. + """ + input_hf_id = hf_id + + # Get the hub_url (with or without protocol) + full_hub_url = hub_url if hub_url is not None else constants.ENDPOINT + hub_url_without_protocol = _REGEX_HTTP_PROTOCOL.sub("", full_hub_url) + + # Check if hf_id is a URL containing the hub_url (check both with and without protocol) + hf_id_without_protocol = _REGEX_HTTP_PROTOCOL.sub("", hf_id) + is_hf_url = hub_url_without_protocol in hf_id_without_protocol and "@" not in hf_id + + HFFS_PREFIX = "hf://" + if hf_id.startswith(HFFS_PREFIX): # Remove "hf://" prefix if exists + hf_id = hf_id[len(HFFS_PREFIX) :] + + # If it's a URL, strip the endpoint prefix to get the path + if is_hf_url: + # Remove protocol if present + hf_id_normalized = _REGEX_HTTP_PROTOCOL.sub("", hf_id) + + # Remove the hub_url prefix to get the relative path + if hf_id_normalized.startswith(hub_url_without_protocol): + # Strip the hub URL and any leading slashes + hf_id = hf_id_normalized[len(hub_url_without_protocol) :].lstrip("/") + + url_segments = hf_id.split("/") + is_hf_id = len(url_segments) <= 3 + + namespace: str | None + if is_hf_url: + # For URLs, we need to extract repo_type, namespace, repo_id + # Expected format after stripping endpoint: [repo_type]/namespace/repo_id or namespace/repo_id + + if len(url_segments) >= 3: + # Check if first segment is a repo type + if url_segments[0] in constants.REPO_TYPES_MAPPING: + repo_type = constants.REPO_TYPES_MAPPING[url_segments[0]] + namespace = url_segments[1] + repo_id = url_segments[2] + elif url_segments[0] == "buckets": + # Special case for buckets + repo_type = "bucket" + namespace = url_segments[1] + repo_id = url_segments[2] + else: + # First segment is namespace + namespace = url_segments[0] + repo_id = url_segments[1] + repo_type = None + elif len(url_segments) == 2: + namespace = url_segments[0] + repo_id = url_segments[1] + + # Check if namespace is actually a repo type mapping + if namespace in constants.REPO_TYPES_MAPPING: + # Mean canonical dataset or model + repo_type = constants.REPO_TYPES_MAPPING[namespace] + namespace = None + elif namespace == "buckets": + # Special case for buckets + repo_type = "bucket" + namespace = None + else: + repo_type = None + else: + # Single segment + repo_id = url_segments[0] + namespace = None + repo_type = None + elif is_hf_id: + if len(url_segments) == 3: + # Passed // or // + repo_type, namespace, repo_id = url_segments[-3:] + elif len(url_segments) == 2: + if url_segments[0] in constants.REPO_TYPES_MAPPING: + # Passed '' or 'datasets/' for a canonical model or dataset + repo_type = constants.REPO_TYPES_MAPPING[url_segments[0]] + namespace = None + repo_id = hf_id.split("/")[-1] + elif url_segments[0] == "buckets": + # Special case for buckets + repo_type = "bucket" + namespace = None + repo_id = hf_id.split("/")[-1] + else: + # Passed / or / + namespace, repo_id = hf_id.split("/")[-2:] + repo_type = None + else: + # Passed + repo_id = url_segments[0] + namespace, repo_type = None, None + else: + raise ValueError(f"Unable to retrieve user and repo ID from the passed HF ID: {hf_id}") + + # Check if repo type is known (mapping "spaces" => "space" + empty value => `None`) + if repo_type in constants.REPO_TYPES_MAPPING: + repo_type = constants.REPO_TYPES_MAPPING[repo_type] + if repo_type == "": + repo_type = None + if repo_type not in constants.REPO_TYPES_WITH_KERNEL and repo_type != "bucket": + raise ValueError(f"Unknown `repo_type`: '{repo_type}' ('{input_hf_id}')") + + return repo_type, namespace, repo_id + + +def _parse_hf_copy_handle(hf_handle: str) -> _BucketCopyHandle | _RepoCopyHandle: + # TODO: Harmonize hf:// parsing. See https://github.com/huggingface/huggingface_hub/issues/3971 + if not hf_handle.startswith("hf://"): + raise ValueError(f"Invalid HF handle: '{hf_handle}'. Expected a path starting with 'hf://'.") + + path = hf_handle.removeprefix("hf://") + if path.startswith("buckets/"): + bucket_id, bucket_path = _split_bucket_id_and_prefix(path.removeprefix("buckets/")) + return _BucketCopyHandle( + bucket_id=bucket_id, + path=bucket_path.strip("/"), + ) + + path = path.strip("/") + if path == "": + raise ValueError(f"Invalid HF handle: '{hf_handle}'.") + + parts = path.split("/") + repo_type: str = constants.REPO_TYPE_MODEL + if parts[0] in constants.REPO_TYPES_MAPPING: + repo_type = constants.REPO_TYPES_MAPPING[parts[0]] + parts = parts[1:] + + if len(parts) < 2: + raise ValueError( + f"Invalid repo HF handle: '{hf_handle}'. Expected format 'hf:////path' or with explicit repo type prefix." + ) + + namespace, repo_name_with_revision = parts[0], parts[1] + remaining_parts = parts[2:] + revision: str | None = None + if "@" in repo_name_with_revision: + repo_name, revision = repo_name_with_revision.split("@", 1) + else: + repo_name = repo_name_with_revision + + if revision is None: + revision = constants.DEFAULT_REVISION + else: + revision = unquote(revision) + if remaining_parts: + maybe_special_ref = f"{revision}/{remaining_parts[0]}" + match = SPECIAL_REFS_REVISION_REGEX.match(maybe_special_ref) + if match is not None: + revision = match.group() + suffix = maybe_special_ref.removeprefix(revision).lstrip("/") + remaining_parts = ([suffix] if suffix else []) + remaining_parts[1:] + + repo_path = "/".join(remaining_parts).strip("/") + return _RepoCopyHandle( + repo_type=repo_type, # type: ignore + repo_id=f"{namespace}/{repo_name}", + revision=revision, + path=repo_path, + ) + + +@dataclass +class LastCommitInfo(dict): + oid: str + title: str + date: datetime + + def __post_init__(self): # hack to make LastCommitInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class BlobLfsInfo(dict): + size: int + sha256: str + pointer_size: int + + def __post_init__(self): # hack to make BlobLfsInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class BlobSecurityInfo(dict): + safe: bool # duplicate information with "status" field, keeping it for backward compatibility + status: str + av_scan: dict | None + pickle_import_scan: dict | None + + def __post_init__(self): # hack to make BlogSecurityInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class TransformersInfo(dict): + auto_model: str + custom_class: str | None = None + # possible `pipeline_tag` values: https://github.com/huggingface/huggingface.js/blob/3ee32554b8620644a6287e786b2a83bf5caf559c/packages/tasks/src/pipelines.ts#L72 + pipeline_tag: str | None = None + processor: str | None = None + + def __post_init__(self): # hack to make TransformersInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class SafeTensorsInfo(dict): + parameters: dict[str, int] + total: int + + def __post_init__(self): # hack to make SafeTensorsInfo backward compatible + self.update(asdict(self)) + + +@dataclass +class CommitInfo(str): + """Data structure containing information about a newly created commit. + + Returned by any method that creates a commit on the Hub: [`create_commit`], [`upload_file`], [`upload_folder`], + [`delete_file`], [`delete_folder`]. It inherits from `str` for backward compatibility but using methods specific + to `str` is deprecated. + + Attributes: + commit_url (`str`): + Url where to find the commit. + + commit_message (`str`): + The summary (first line) of the commit that has been created. + + commit_description (`str`): + Description of the commit that has been created. Can be empty. + + oid (`str`): + Commit hash id. Example: `"91c54ad1727ee830252e457677f467be0bfd8a57"`. + + pr_url (`str`, *optional*): + Url to the PR that has been created, if any. Populated when `create_pr=True` + is passed. + + pr_revision (`str`, *optional*): + Revision of the PR that has been created, if any. Populated when + `create_pr=True` is passed. Example: `"refs/pr/1"`. + + pr_num (`int`, *optional*): + Number of the PR discussion that has been created, if any. Populated when + `create_pr=True` is passed. Can be passed as `discussion_num` in + [`get_discussion_details`]. Example: `1`. + + repo_url (`RepoUrl`): + Repo URL of the commit containing info like repo_id, repo_type, etc. + """ + + commit_url: str + commit_message: str + commit_description: str + oid: str + _endpoint: str | None = field(default=None, repr=False) + pr_url: str | None = None + + # Computed from `commit_url` in `__post_init__` + repo_url: RepoUrl = field(init=False) + + # Computed from `pr_url` in `__post_init__` + pr_revision: str | None = field(init=False) + pr_num: int | None = field(init=False) + + def __new__(cls, *args, commit_url: str, **kwargs): + return str.__new__(cls, commit_url) + + def __post_init__(self): + """Populate pr-related fields after initialization. + + See https://docs.python.org/3.10/library/dataclasses.html#post-init-processing. + """ + # Repo info + self.repo_url = RepoUrl(self.commit_url.split("/commit/")[0], endpoint=self._endpoint) + + # PR info + if self.pr_url is not None: + self.pr_revision = _parse_revision_from_pr_url(self.pr_url) + self.pr_num = int(self.pr_revision.split("/")[-1]) + else: + self.pr_revision = None + self.pr_num = None + + +@dataclass +class AccessRequest: + """Data structure containing information about a user access request. + + Attributes: + username (`str`): + Username of the user who requested access. + fullname (`str`): + Fullname of the user who requested access. + email (`Optional[str]`): + Email of the user who requested access. + Can only be `None` in the /accepted list if the user was granted access manually. + timestamp (`datetime`): + Timestamp of the request. + status (`Literal["pending", "accepted", "rejected"]`): + Status of the request. Can be one of `["pending", "accepted", "rejected"]`. + fields (`dict[str, Any]`, *optional*): + Additional fields filled by the user in the gate form. + """ + + username: str + fullname: str + email: str | None + timestamp: datetime + status: Literal["pending", "accepted", "rejected"] + + # Additional fields filled by the user in the gate form + fields: dict[str, Any] | None = None + + +@dataclass +class WebhookWatchedItem: + """Data structure containing information about the items watched by a webhook. + + Attributes: + type (`Literal["dataset", "model", "org", "space", "user"]`): + Type of the item to be watched. Can be one of `["dataset", "model", "org", "space", "user"]`. + name (`str`): + Name of the item to be watched. Can be the username, organization name, model name, dataset name or space name. + """ + + type: Literal["dataset", "model", "org", "space", "user"] + name: str + + +@dataclass +class WebhookInfo: + """Data structure containing information about a webhook. + + One of `url` or `job` is specified, but not both. + + Attributes: + id (`str`): + ID of the webhook. + url (`str`, *optional*): + URL of the webhook. + job (`JobSpec`, *optional*): + Specifications of the Job to trigger. + watched (`list[WebhookWatchedItem]`): + List of items watched by the webhook, see [`WebhookWatchedItem`]. + domains (`list[WEBHOOK_DOMAIN_T]`): + List of domains the webhook is watching. Can be one of `["repo", "discussions"]`. + secret (`str`, *optional*): + Secret of the webhook. + disabled (`bool`): + Whether the webhook is disabled or not. + """ + + id: str + url: str | None + job: JobSpec | None + watched: list[WebhookWatchedItem] + domains: list[constants.WEBHOOK_DOMAIN_T] + secret: str | None + disabled: bool + + +class RepoUrl(str): + """Subclass of `str` describing a repo URL on the Hub. + + `RepoUrl` is returned by `HfApi.create_repo`. It inherits from `str` for backward + compatibility. At initialization, the URL is parsed to populate properties: + - endpoint (`str`) + - namespace (`Optional[str]`) + - repo_name (`str`) + - repo_id (`str`) + - repo_type (`Literal["model", "dataset", "space"]`) + - url (`str`) + + Args: + url (`Any`): + String value of the repo url. + endpoint (`str`, *optional*): + Endpoint of the Hub. Defaults to . + + Example: + ```py + >>> RepoUrl('https://huggingface.co/gpt2') + RepoUrl('https://huggingface.co/gpt2', endpoint='https://huggingface.co', repo_type='model', repo_id='gpt2') + + >>> RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co') + RepoUrl('https://hub-ci.huggingface.co/datasets/dummy_user/dummy_dataset', endpoint='https://hub-ci.huggingface.co', repo_type='dataset', repo_id='dummy_user/dummy_dataset') + + >>> RepoUrl('hf://datasets/my-user/my-dataset') + RepoUrl('hf://datasets/my-user/my-dataset', endpoint='https://huggingface.co', repo_type='dataset', repo_id='user/dataset') + + >>> HfApi.create_repo("dummy_model") + RepoUrl('https://huggingface.co/Wauplin/dummy_model', endpoint='https://huggingface.co', repo_type='model', repo_id='Wauplin/dummy_model') + ``` + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If URL cannot be parsed. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `repo_type` is unknown. + """ + + def __new__(cls, url: Any, endpoint: str | None = None): + url = fix_hf_endpoint_in_url(url, endpoint=endpoint) + return super().__new__(cls, url) + + def __init__(self, url: Any, endpoint: str | None = None) -> None: + super().__init__() + # Parse URL + self.endpoint = endpoint or constants.ENDPOINT + repo_type, namespace, repo_name = repo_type_and_id_from_hf_id(self, hub_url=self.endpoint) + + # Populate fields + self.namespace = namespace + self.repo_name = repo_name + self.repo_id = repo_name if namespace is None else f"{namespace}/{repo_name}" + self.repo_type = repo_type or constants.REPO_TYPE_MODEL + self.url = str(self) # just in case it's needed + + def __repr__(self) -> str: + return f"RepoUrl('{self}', endpoint='{self.endpoint}', repo_type='{self.repo_type}', repo_id='{self.repo_id}')" + + +@dataclass(frozen=True) +class _BucketCopyHandle: + bucket_id: str + path: str + + +@dataclass(frozen=True) +class _RepoCopyHandle: + repo_type: Literal["model", "dataset", "space"] + repo_id: str + revision: str + path: str + + +@dataclass +class RepoSibling: + """ + Contains basic information about a repo file inside a repo on the Hub. + + > [!TIP] + > All attributes of this class are optional except `rfilename`. This is because only the file names are returned when + > listing repositories on the Hub (with [`list_models`], [`list_datasets`] or [`list_spaces`]). If you need more + > information like file size, blob id or lfs details, you must request them specifically from one repo at a time + > (using [`model_info`], [`dataset_info`] or [`space_info`]) as it adds more constraints on the backend server to + > retrieve these. + + Attributes: + rfilename (str): + file name, relative to the repo root. + size (`int`, *optional*): + The file's size, in bytes. This attribute is defined when `files_metadata` argument of [`repo_info`] is set + to `True`. It's `None` otherwise. + blob_id (`str`, *optional*): + The file's git OID. This attribute is defined when `files_metadata` argument of [`repo_info`] is set to + `True`. It's `None` otherwise. + lfs (`BlobLfsInfo`, *optional*): + The file's LFS metadata. This attribute is defined when`files_metadata` argument of [`repo_info`] is set to + `True` and the file is stored with Git LFS. It's `None` otherwise. + """ + + rfilename: str + size: int | None = None + blob_id: str | None = None + lfs: BlobLfsInfo | None = None + + +@dataclass +class RepoFile: + """ + Contains information about a file on the Hub. + + Attributes: + path (str): + file path relative to the repo root. + size (`int`): + The file's size, in bytes. + blob_id (`str`): + The file's git OID. + lfs (`BlobLfsInfo`, *optional*): + The file's LFS metadata. + xet_hash (`str`, *optional*): + The file's Xet hash. + last_commit (`LastCommitInfo`, *optional*): + The file's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`] + are called with `expand=True`. + security (`BlobSecurityInfo`, *optional*): + The file's security scan metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`] + are called with `expand=True`. + """ + + path: str + size: int + blob_id: str + lfs: BlobLfsInfo | None = None + xet_hash: str | None = None + last_commit: LastCommitInfo | None = None + security: BlobSecurityInfo | None = None + + def __init__(self, **kwargs): + self.path = kwargs.pop("path") + self.size = kwargs.pop("size") + self.blob_id = kwargs.pop("oid") + lfs = kwargs.pop("lfs", None) + if lfs is not None: + lfs = BlobLfsInfo(size=lfs["size"], sha256=lfs["oid"], pointer_size=lfs["pointerSize"]) + self.lfs = lfs + self.xet_hash = kwargs.pop("xetHash", None) + last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None) + if last_commit is not None: + last_commit = LastCommitInfo( + oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"]) + ) + self.last_commit = last_commit + security = kwargs.pop("securityFileStatus", None) + if security is not None: + safe = security["status"] == "safe" + security = BlobSecurityInfo( + safe=safe, + status=security["status"], + av_scan=security["avScan"], + pickle_import_scan=security["pickleImportScan"], + ) + self.security = security + + # backwards compatibility + self.rfilename = self.path + self.lastCommit = self.last_commit + + +@dataclass +class RepoFolder: + """ + Contains information about a folder on the Hub. + + Attributes: + path (str): + folder path relative to the repo root. + tree_id (`str`): + The folder's git OID. + last_commit (`LastCommitInfo`, *optional*): + The folder's last commit metadata. Only defined if [`list_repo_tree`] and [`get_paths_info`] + are called with `expand=True`. + """ + + path: str + tree_id: str + last_commit: LastCommitInfo | None = None + + def __init__(self, **kwargs): + self.path = kwargs.pop("path") + self.tree_id = kwargs.pop("oid") + last_commit = kwargs.pop("lastCommit", None) or kwargs.pop("last_commit", None) + if last_commit is not None: + last_commit = LastCommitInfo( + oid=last_commit["id"], title=last_commit["title"], date=parse_datetime(last_commit["date"]) + ) + self.last_commit = last_commit + + +@dataclass +class InferenceProviderMapping: + provider: PROVIDER_T # Provider name + hf_model_id: str # ID of the model on the Hugging Face Hub + provider_id: str # ID of the model on the provider's side + status: Literal["error", "live", "staging"] + task: str + + adapter: str | None = None + adapter_weights_path: str | None = None + type: Literal["single-model", "tag-filter"] | None = None + + def __init__(self, **kwargs): + self.provider = kwargs.pop("provider") + self.hf_model_id = kwargs.pop("hf_model_id") + self.provider_id = kwargs.pop("providerId") + self.status = kwargs.pop("status") + self.task = kwargs.pop("task") + + self.adapter = kwargs.pop("adapter", None) + self.adapter_weights_path = kwargs.pop("adapterWeightsPath", None) + self.type = kwargs.pop("type", None) + self.__dict__.update(**kwargs) + + +@dataclass +class ModelInfo: + """ + Contains information about a model on the Hub. This object is returned by [`model_info`] and [`list_models`]. + + > [!TIP] + > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made. + > In general, the more specific the query, the more information is returned. On the contrary, when listing models + > using [`list_models`] only a subset of the attributes are returned. + + Attributes: + id (`str`): + ID of model. + author (`str`, *optional*): + Author of the model. + base_models (`list[str]`, *optional*): + List of base models this model is derived from. + card_data (`ModelCardData`, *optional*): + Model Card Metadata as a [`huggingface_hub.repocard_data.ModelCardData`] object. + children_model_count (`int`, *optional*): + Number of children models derived from this model. + config (`dict`, *optional*): + Model configuration. + created_at (`datetime`, *optional*): + Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`, + corresponding to the date when we began to store creation dates. + disabled (`bool`, *optional*): + Is the repo disabled. + downloads (`int`): + Number of downloads of the model over the last 30 days. + downloads_all_time (`int`): + Cumulated number of downloads of the model since its creation. + eval_results (`list[EvalResultEntry]`, *optional*): + Model's evaluation results. + gated (`Literal["auto", "manual", False]`, *optional*): + Is the repo gated. + If so, whether there is manual or automatic approval. + gguf (`dict`, *optional*): + GGUF information of the model. + inference (`Literal["warm"]`, *optional*): + Status of the model on Inference Providers. Warm if the model is served by at least one provider. + inference_provider_mapping (`list[InferenceProviderMapping]`, *optional*): + A list of [`InferenceProviderMapping`] ordered after the user's provider order. + last_modified (`datetime`, *optional*): + Date of last commit to the repo. + library_name (`str`, *optional*): + Library associated with the model. + likes (`int`): + Number of likes of the model. + mask_token (`str`, *optional*): + Mask token used by the model. + model_index (`dict`, *optional*): + Model index for evaluation. + pipeline_tag (`str`, *optional*): + Pipeline tag associated with the model. + private (`bool`): + Is the repo private. + resource_group (`dict`, *optional*): + Resource group information for the model. + safetensors (`SafeTensorsInfo`, *optional*): + Model's safetensors information. + security_repo_status (`dict`, *optional*): + Model's security scan status. + sha (`str`, *optional*): + Repo SHA at this particular revision. + siblings (`list[RepoSibling]`): + List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the model. + spaces (`list[str]`, *optional*): + List of spaces using the model. + tags (`list[str]`): + List of tags of the model. Compared to `card_data.tags`, contains extra tags computed by the Hub + (e.g. supported libraries, model's arXiv). + transformers_info (`TransformersInfo`, *optional*): + Transformers-specific info (auto class, processor, etc.) associated with the model. + trending_score (`int`, *optional*): + Trending score of the model. + used_storage (`int`, *optional*): + Size in bytes of the model on the Hub. + widget_data (`Any`, *optional*): + Widget data associated with the model. + """ + + id: str + author: str | None + base_models: list[str] | None + card_data: ModelCardData | None + children_model_count: int | None + config: dict | None + created_at: datetime | None + disabled: bool | None + downloads: int | None + downloads_all_time: int | None + eval_results: list[EvalResultEntry] | None + gated: Literal["auto", "manual", False] | None + gguf: dict | None + inference: Literal["warm"] | None + inference_provider_mapping: list[InferenceProviderMapping] | None + last_modified: datetime | None + library_name: str | None + likes: int | None + mask_token: str | None + model_index: dict | None + pipeline_tag: str | None + private: bool | None + resource_group: dict | None + safetensors: SafeTensorsInfo | None + security_repo_status: dict | None + sha: str | None + siblings: list[RepoSibling] | None + spaces: list[str] | None + tags: list[str] | None + transformers_info: TransformersInfo | None + trending_score: int | None + used_storage: int | None + widget_data: Any | None + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.author = kwargs.pop("author", None) + self.sha = kwargs.pop("sha", None) + last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None) + self.last_modified = parse_datetime(last_modified) if last_modified else None + created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None) + self.created_at = parse_datetime(created_at) if created_at else None + self.private = kwargs.pop("private", None) + self.gated = kwargs.pop("gated", None) + self.disabled = kwargs.pop("disabled", None) + self.downloads = kwargs.pop("downloads", None) + self.downloads_all_time = kwargs.pop("downloadsAllTime", None) + self.likes = kwargs.pop("likes", None) + self.library_name = kwargs.pop("library_name", None) + self.gguf = kwargs.pop("gguf", None) + + self.inference = kwargs.pop("inference", None) + + # little hack to simplify Inference Providers logic and make it backward and forward compatible + # right now, API returns a dict on model_info and a list on list_models. Let's harmonize to list. + mapping = kwargs.pop("inferenceProviderMapping", None) + if isinstance(mapping, list): + self.inference_provider_mapping = [ + InferenceProviderMapping(**{**value, "hf_model_id": self.id}) for value in mapping + ] + elif isinstance(mapping, dict): + self.inference_provider_mapping = [ + InferenceProviderMapping(**{**value, "hf_model_id": self.id, "provider": provider}) + for provider, value in mapping.items() + ] + elif mapping is None: + self.inference_provider_mapping = None + else: + raise ValueError( + f"Unexpected type for `inferenceProviderMapping`. Expecting `dict` or `list`. Got {mapping}." + ) + + self.tags = kwargs.pop("tags", None) + self.pipeline_tag = kwargs.pop("pipeline_tag", None) + self.mask_token = kwargs.pop("mask_token", None) + self.trending_score = kwargs.pop("trendingScore", None) + self.used_storage = kwargs.pop("usedStorage", None) + + card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None) + self.card_data = ( + ModelCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data + ) + + self.widget_data = kwargs.pop("widgetData", None) + self.model_index = kwargs.pop("model-index", None) or kwargs.pop("model_index", None) + self.config = kwargs.pop("config", None) + transformers_info = kwargs.pop("transformersInfo", None) or kwargs.pop("transformers_info", None) + self.transformers_info = TransformersInfo(**transformers_info) if transformers_info else None + siblings = kwargs.pop("siblings", None) + self.siblings = ( + [ + RepoSibling( + rfilename=sibling["rfilename"], + size=sibling.get("size"), + blob_id=sibling.get("blobId"), + lfs=( + BlobLfsInfo( + size=sibling["lfs"]["size"], + sha256=sibling["lfs"]["sha256"], + pointer_size=sibling["lfs"]["pointerSize"], + ) + if sibling.get("lfs") + else None + ), + ) + for sibling in siblings + ] + if siblings is not None + else None + ) + self.spaces = kwargs.pop("spaces", None) + safetensors = kwargs.pop("safetensors", None) + self.safetensors = ( + SafeTensorsInfo( + parameters=safetensors["parameters"], + total=safetensors["total"], + ) + if safetensors + else None + ) + self.security_repo_status = kwargs.pop("securityRepoStatus", None) + eval_results = kwargs.pop("evalResults", None) + self.eval_results = parse_eval_result_entries(eval_results) if eval_results else None + self.base_models = kwargs.pop("baseModels", None) + self.children_model_count = kwargs.pop("childrenModelCount", None) + self.resource_group = kwargs.pop("resourceGroup", None) + # backwards compatibility + self.lastModified = self.last_modified + self.cardData = self.card_data + self.transformersInfo = self.transformers_info + self.__dict__.update(**kwargs) + + +@dataclass +class DatasetInfo: + """ + Contains information about a dataset on the Hub. This object is returned by [`dataset_info`] and [`list_datasets`]. + + > [!TIP] + > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made. + > In general, the more specific the query, the more information is returned. On the contrary, when listing datasets + > using [`list_datasets`] only a subset of the attributes are returned. + + Attributes: + id (`str`): + ID of dataset. + author (`str`): + Author of the dataset. + card_data (`DatasetCardData`, *optional*): + Dataset Card Metadata as a [`huggingface_hub.repocard_data.DatasetCardData`] object. + citation (`str`, *optional*): + Citation information for the dataset. + created_at (`datetime`, *optional*): + Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`, + corresponding to the date when we began to store creation dates. + description (`str`, *optional*): + Description of the dataset. + disabled (`bool`, *optional*): + Is the repo disabled. + downloads (`int`): + Number of downloads of the dataset over the last 30 days. + downloads_all_time (`int`): + Cumulated number of downloads of the dataset since its creation. + gated (`Literal["auto", "manual", False]`, *optional*): + Is the repo gated. + If so, whether there is manual or automatic approval. + last_modified (`datetime`, *optional*): + Date of last commit to the repo. + likes (`int`): + Number of likes of the dataset. + main_size (`int`, *optional*): + Size in bytes of the main branch of the dataset. + paperswithcode_id (`str`, *optional*): + Papers with code ID of the dataset. + private (`bool`): + Is the repo private. + resource_group (`dict`, *optional*): + Resource group information for the dataset. + sha (`str`): + Repo SHA at this particular revision. + siblings (`list[RepoSibling]`): + List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the dataset. + tags (`list[str]`): + List of tags of the dataset. + trending_score (`int`, *optional*): + Trending score of the dataset. + used_storage (`int`, *optional*): + Size in bytes of the dataset on the Hub. + """ + + id: str + author: str | None + card_data: DatasetCardData | None + citation: str | None + created_at: datetime | None + description: str | None + disabled: bool | None + downloads: int | None + downloads_all_time: int | None + gated: Literal["auto", "manual", False] | None + last_modified: datetime | None + likes: int | None + main_size: int | None + paperswithcode_id: str | None + private: bool | None + resource_group: dict | None + sha: str | None + siblings: list[RepoSibling] | None + tags: list[str] | None + trending_score: int | None + used_storage: int | None + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.author = kwargs.pop("author", None) + self.sha = kwargs.pop("sha", None) + created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None) + self.created_at = parse_datetime(created_at) if created_at else None + last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None) + self.last_modified = parse_datetime(last_modified) if last_modified else None + self.private = kwargs.pop("private", None) + self.gated = kwargs.pop("gated", None) + self.disabled = kwargs.pop("disabled", None) + self.downloads = kwargs.pop("downloads", None) + self.downloads_all_time = kwargs.pop("downloadsAllTime", None) + self.likes = kwargs.pop("likes", None) + self.main_size = kwargs.pop("mainSize", None) + self.paperswithcode_id = kwargs.pop("paperswithcode_id", None) + self.tags = kwargs.pop("tags", None) + self.trending_score = kwargs.pop("trendingScore", None) + self.used_storage = kwargs.pop("usedStorage", None) + + card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None) + self.card_data = ( + DatasetCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data + ) + siblings = kwargs.pop("siblings", None) + self.siblings = ( + [ + RepoSibling( + rfilename=sibling["rfilename"], + size=sibling.get("size"), + blob_id=sibling.get("blobId"), + lfs=( + BlobLfsInfo( + size=sibling["lfs"]["size"], + sha256=sibling["lfs"]["sha256"], + pointer_size=sibling["lfs"]["pointerSize"], + ) + if sibling.get("lfs") + else None + ), + ) + for sibling in siblings + ] + if siblings is not None + else None + ) + self.citation = kwargs.pop("citation", None) + self.description = kwargs.pop("description", None) + self.resource_group = kwargs.pop("resourceGroup", None) + # backwards compatibility + self.lastModified = self.last_modified + self.cardData = self.card_data + self.__dict__.update(**kwargs) + + +@dataclass +class SpaceInfo: + """ + Contains information about a Space on the Hub. This object is returned by [`space_info`] and [`list_spaces`]. + + > [!TIP] + > Most attributes of this class are optional. This is because the data returned by the Hub depends on the query made. + > In general, the more specific the query, the more information is returned. On the contrary, when listing spaces + > using [`list_spaces`] only a subset of the attributes are returned. + + Attributes: + id (`str`): + ID of the Space. + author (`str`, *optional*): + Author of the Space. + card_data (`SpaceCardData`, *optional*): + Space Card Metadata as a [`huggingface_hub.repocard_data.SpaceCardData`] object. + created_at (`datetime`, *optional*): + Date of creation of the repo on the Hub. Note that the lowest value is `2022-03-02T23:29:04.000Z`, + corresponding to the date when we began to store creation dates. + datasets (`list[str]`, *optional*): + List of datasets used by the Space. + disabled (`bool`, *optional*): + Is the Space disabled. + gated (`Literal["auto", "manual", False]`, *optional*): + Is the repo gated. + If so, whether there is manual or automatic approval. + host (`str`, *optional*): + Host URL of the Space. + last_modified (`datetime`, *optional*): + Date of last commit to the repo. + likes (`int`): + Number of likes of the Space. + models (`list[str]`, *optional*): + List of models used by the Space. + private (`bool`): + Is the repo private. + resource_group (`dict`, *optional*): + Resource group information for the Space. + runtime (`SpaceRuntime`, *optional*): + Space runtime information as a [`huggingface_hub.hf_api.SpaceRuntime`] object. + sdk (`str`, *optional*): + SDK used by the Space. + sha (`str`, *optional*): + Repo SHA at this particular revision. + siblings (`list[RepoSibling]`): + List of [`huggingface_hub.hf_api.RepoSibling`] objects that constitute the Space. + subdomain (`str`, *optional*): + Subdomain of the Space. + tags (`list[str]`): + List of tags of the Space. + trending_score (`int`, *optional*): + Trending score of the Space. + used_storage (`int`, *optional*): + Size in bytes of the Space on the Hub. + """ + + id: str + author: str | None + card_data: SpaceCardData | None + created_at: datetime | None + datasets: list[str] | None + disabled: bool | None + gated: Literal["auto", "manual", False] | None + host: str | None + last_modified: datetime | None + likes: int | None + models: list[str] | None + private: bool | None + resource_group: dict | None + runtime: SpaceRuntime | None + sdk: str | None + sha: str | None + siblings: list[RepoSibling] | None + subdomain: str | None + tags: list[str] | None + trending_score: int | None + used_storage: int | None + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.author = kwargs.pop("author", None) + self.sha = kwargs.pop("sha", None) + created_at = kwargs.pop("createdAt", None) or kwargs.pop("created_at", None) + self.created_at = parse_datetime(created_at) if created_at else None + last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None) + self.last_modified = parse_datetime(last_modified) if last_modified else None + self.private = kwargs.pop("private", None) + self.gated = kwargs.pop("gated", None) + self.disabled = kwargs.pop("disabled", None) + self.host = kwargs.pop("host", None) + self.subdomain = kwargs.pop("subdomain", None) + self.likes = kwargs.pop("likes", None) + self.sdk = kwargs.pop("sdk", None) + self.tags = kwargs.pop("tags", None) + self.trending_score = kwargs.pop("trendingScore", None) + self.used_storage = kwargs.pop("usedStorage", None) + card_data = kwargs.pop("cardData", None) or kwargs.pop("card_data", None) + self.card_data = ( + SpaceCardData(**card_data, ignore_metadata_errors=True) if isinstance(card_data, dict) else card_data + ) + siblings = kwargs.pop("siblings", None) + self.siblings = ( + [ + RepoSibling( + rfilename=sibling["rfilename"], + size=sibling.get("size"), + blob_id=sibling.get("blobId"), + lfs=( + BlobLfsInfo( + size=sibling["lfs"]["size"], + sha256=sibling["lfs"]["sha256"], + pointer_size=sibling["lfs"]["pointerSize"], + ) + if sibling.get("lfs") + else None + ), + ) + for sibling in siblings + ] + if siblings is not None + else None + ) + runtime = kwargs.pop("runtime", None) + self.runtime = SpaceRuntime(runtime) if runtime else None + self.models = kwargs.pop("models", None) + self.datasets = kwargs.pop("datasets", None) + self.resource_group = kwargs.pop("resourceGroup", None) + # backwards compatibility + self.lastModified = self.last_modified + self.cardData = self.card_data + self.__dict__.update(**kwargs) + + +@dataclass +class KernelInfo: + """ + Contains information about a kernel repo on the Hub. This object is returned by [`kernel_info`]. + + Attributes: + id (`str`): + ID of the kernel repo. + author (`str`, *optional*): + Author of the kernel repo. + downloads (`int`, *optional*): + Number of downloads of the kernel repo over the last 30 days. + gated (`Literal["auto", "manual", False]`, *optional*): + Is the repo gated. If so, whether there is manual or automatic approval. + last_modified (`datetime`, *optional*): + Date of last commit to the repo. + likes (`int`, *optional*): + Number of likes of the kernel repo. + private (`bool`, *optional*): + Is the repo private. + sha (`str`, *optional*): + Repo SHA at this particular revision. + """ + + id: str + author: str | None + downloads: int | None + gated: Literal["auto", "manual", False] | None + last_modified: datetime | None + likes: int | None + private: bool | None + sha: str | None + + def __init__(self, **kwargs): + self.id = kwargs.pop("id") + self.author = kwargs.pop("author", None) + self.downloads = kwargs.pop("downloads", None) + self.gated = kwargs.pop("gated", None) + last_modified = kwargs.pop("lastModified", None) or kwargs.pop("last_modified", None) + self.last_modified = parse_datetime(last_modified) if last_modified else None + self.likes = kwargs.pop("likes", None) + self.private = kwargs.pop("private", None) + self.sha = kwargs.pop("sha", None) + + # future compatibility + self.__dict__.update(**kwargs) + + +@dataclass +class CollectionItem: + """ + Contains information about an item of a Collection (model, dataset, Space, paper, collection or bucket). + + Attributes: + item_object_id (`str`): + Unique ID of the item in the collection. + item_id (`str`): + ID of the underlying object on the Hub. Can be either a repo_id, a paper id, a collection slug + or a bucket id. + e.g. `"jbilcke-hf/ai-comic-factory"`, `"2307.09288"`, `"celinah/cerebras-function-calling-682607169c35fbfa98b30b9a"`. + item_type (`str`): + Type of the underlying object. Can be one of `"model"`, `"dataset"`, `"space"`, `"paper"`, `"collection"` + or `"bucket"`. + position (`int`): + Position of the item in the collection. + note (`str`, *optional*): + Note associated with the item, as plain text. + """ + + item_object_id: str # id in database + item_id: str # repo_id or paper id + item_type: str + position: int + note: str | None = None + + def __init__( + self, + _id: str, + id: str, + type: CollectionItemType_T, + position: int, + note: dict | None = None, + **kwargs, + ) -> None: + self.item_object_id: str = _id # id in database + self.item_id: str = id # repo_id or paper id + # if the item is a collection, override item_id with the slug + slug = kwargs.get("slug") + if slug is not None: + self.item_id = slug # collection slug + self.item_type: CollectionItemType_T = type + self.position: int = position + note_text = note.get("text") if note is not None else None + self.note = note_text if isinstance(note_text, str) else None + + +@dataclass +class Collection: + """ + Contains information about a Collection on the Hub. + + Attributes: + slug (`str`): + Slug of the collection. E.g. `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + title (`str`): + Title of the collection. E.g. `"Recent models"`. + owner (`str`): + Owner of the collection. E.g. `"TheBloke"`. + items (`list[CollectionItem]`): + List of items in the collection. + last_updated (`datetime`): + Date of the last update of the collection. + position (`int`): + Position of the collection in the list of collections of the owner. + private (`bool`): + Whether the collection is private or not. + theme (`str`): + Theme of the collection. E.g. `"green"`. + upvotes (`int`): + Number of upvotes of the collection. + description (`str`, *optional*): + Description of the collection, as plain text. + url (`str`): + (property) URL of the collection on the Hub. + """ + + slug: str + title: str + owner: str + items: list[CollectionItem] + last_updated: datetime + position: int + private: bool + theme: str + upvotes: int + description: str | None = None + + def __init__(self, **kwargs) -> None: + self.slug = kwargs.pop("slug") + self.title = kwargs.pop("title") + self.owner = kwargs.pop("owner") + self.items = [CollectionItem(**item) for item in kwargs.pop("items")] + self.last_updated = parse_datetime(kwargs.pop("lastUpdated")) + self.position = kwargs.pop("position") + self.private = kwargs.pop("private") + self.theme = kwargs.pop("theme") + self.upvotes = kwargs.pop("upvotes") + self.description = kwargs.pop("description", None) + endpoint = kwargs.pop("endpoint", None) + if endpoint is None: + endpoint = constants.ENDPOINT + self._url = f"{endpoint}/collections/{self.slug}" + + @property + def url(self) -> str: + """Returns the URL of the collection on the Hub.""" + return self._url + + +@dataclass +class GitRefInfo: + """ + Contains information about a git reference for a repo on the Hub. + + Attributes: + name (`str`): + Name of the reference (e.g. tag name or branch name). + ref (`str`): + Full git ref on the Hub (e.g. `"refs/heads/main"` or `"refs/tags/v1.0"`). + target_commit (`str`): + OID of the target commit for the ref (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`) + """ + + name: str + ref: str + target_commit: str + + +@dataclass +class GitRefs: + """ + Contains information about all git references for a repo on the Hub. + + Object is returned by [`list_repo_refs`]. + + Attributes: + branches (`list[GitRefInfo]`): + A list of [`GitRefInfo`] containing information about branches on the repo. + converts (`list[GitRefInfo]`): + A list of [`GitRefInfo`] containing information about "convert" refs on the repo. + Converts are refs used (internally) to push preprocessed data in Dataset repos. + tags (`list[GitRefInfo]`): + A list of [`GitRefInfo`] containing information about tags on the repo. + pull_requests (`list[GitRefInfo]`, *optional*): + A list of [`GitRefInfo`] containing information about pull requests on the repo. + Only returned if `include_prs=True` is set. + """ + + branches: list[GitRefInfo] + converts: list[GitRefInfo] + tags: list[GitRefInfo] + pull_requests: list[GitRefInfo] | None = None + + +@dataclass +class GitCommitInfo: + """ + Contains information about a git commit for a repo on the Hub. Check out [`list_repo_commits`] for more details. + + Attributes: + commit_id (`str`): + OID of the commit (e.g. `"e7da7f221d5bf496a48136c0cd264e630fe9fcc8"`) + authors (`list[str]`): + List of authors of the commit. + created_at (`datetime`): + Datetime when the commit was created. + title (`str`): + Title of the commit. This is a free-text value entered by the authors. + message (`str`): + Description of the commit. This is a free-text value entered by the authors. + formatted_title (`str`): + Title of the commit formatted as HTML. Only returned if `formatted=True` is set. + formatted_message (`str`): + Description of the commit formatted as HTML. Only returned if `formatted=True` is set. + """ + + commit_id: str + + authors: list[str] + created_at: datetime + title: str + message: str + + formatted_title: str | None + formatted_message: str | None + + +@dataclass +class UserLikes: + """ + Contains information about a user likes on the Hub. + + Attributes: + user (`str`): + Name of the user for which we fetched the likes. + total (`int`): + Total number of likes. + datasets (`list[str]`): + List of datasets liked by the user (as repo_ids). + kernels (`list[str]`): + List of kernels liked by the user (as repo_ids). + models (`list[str]`): + List of models liked by the user (as repo_ids). + spaces (`list[str]`): + List of spaces liked by the user (as repo_ids). + """ + + # Metadata + user: str + total: int + + # User likes + datasets: list[str] + kernels: list[str] + models: list[str] + spaces: list[str] + + +@dataclass +class Organization: + """ + Contains information about an organization on the Hub. + + Attributes: + avatar_url (`str`): + URL of the organization's avatar. + name (`str`): + Name of the organization on the Hub (unique). + fullname (`str`): + Organization's full name. + details (`str`, *optional*): + Organization's description. + is_verified (`bool`, *optional*): + Whether the organization is verified. + is_following (`bool`, *optional*): + Whether the authenticated user follows this organization. + num_users (`int`, *optional*): + Number of members in the organization. + num_models (`int`, *optional*): + Number of models owned by the organization. + num_spaces (`int`, *optional*): + Number of Spaces owned by the organization. + num_datasets (`int`, *optional*): + Number of datasets owned by the organization. + num_followers (`int`, *optional*): + Number of followers of the organization. + num_papers (`int`, *optional*): + Number of papers authored by the organization. + plan (`str`, *optional*): + The organization's plan (e.g., "enterprise", "team"). + """ + + avatar_url: str + name: str + fullname: str + details: str | None = None + is_verified: bool | None = None + is_following: bool | None = None + num_users: int | None = None + num_models: int | None = None + num_spaces: int | None = None + num_datasets: int | None = None + num_followers: int | None = None + num_papers: int | None = None + plan: str | None = None + + def __init__(self, **kwargs) -> None: + self.avatar_url = kwargs.pop("avatarUrl", "") + self.name = kwargs.pop("name", "") + self.fullname = kwargs.pop("fullname", "") + self.details = kwargs.pop("details", None) + self.is_verified = kwargs.pop("isVerified", None) + self.is_following = kwargs.pop("isFollowing", None) + self.num_users = kwargs.pop("numUsers", None) + self.num_models = kwargs.pop("numModels", None) + self.num_spaces = kwargs.pop("numSpaces", None) + self.num_datasets = kwargs.pop("numDatasets", None) + self.num_followers = kwargs.pop("numFollowers", None) + self.num_papers = kwargs.pop("numPapers", None) + self.plan = kwargs.pop("plan", None) + + # forward compatibility + self.__dict__.update(**kwargs) + + +@dataclass +class User: + """ + Contains information about a user on the Hub. + + Attributes: + username (`str`): + Name of the user on the Hub (unique). + fullname (`str`): + User's full name. + avatar_url (`str`): + URL of the user's avatar. + details (`str`, *optional*): + User's details. + is_following (`bool`, *optional*): + Whether the authenticated user is following this user. + is_pro (`bool`, *optional*): + Whether the user is a pro user. + num_models (`int`, *optional*): + Number of models created by the user. + num_datasets (`int`, *optional*): + Number of datasets created by the user. + num_spaces (`int`, *optional*): + Number of spaces created by the user. + num_discussions (`int`, *optional*): + Number of discussions initiated by the user. + num_papers (`int`, *optional*): + Number of papers authored by the user. + num_upvotes (`int`, *optional*): + Number of upvotes received by the user. + num_likes (`int`, *optional*): + Number of likes given by the user. + num_following (`int`, *optional*): + Number of users this user is following. + num_followers (`int`, *optional*): + Number of users following this user. + orgs (list of [`Organization`]): + List of organizations the user is part of. + """ + + # Metadata + username: str + fullname: str + avatar_url: str + details: str | None = None + is_following: bool | None = None + is_pro: bool | None = None + num_models: int | None = None + num_datasets: int | None = None + num_spaces: int | None = None + num_discussions: int | None = None + num_papers: int | None = None + num_upvotes: int | None = None + num_likes: int | None = None + num_following: int | None = None + num_followers: int | None = None + orgs: list[Organization] = field(default_factory=list) + + def __init__(self, **kwargs) -> None: + self.username = kwargs.pop("user", "") + self.fullname = kwargs.pop("fullname", "") + self.avatar_url = kwargs.pop("avatarUrl", "") + self.is_following = kwargs.pop("isFollowing", None) + self.is_pro = kwargs.pop("isPro", None) + self.details = kwargs.pop("details", None) + self.num_models = kwargs.pop("numModels", None) + self.num_datasets = kwargs.pop("numDatasets", None) + self.num_spaces = kwargs.pop("numSpaces", None) + self.num_discussions = kwargs.pop("numDiscussions", None) + self.num_papers = kwargs.pop("numPapers", None) + self.num_upvotes = kwargs.pop("numUpvotes", None) + self.num_likes = kwargs.pop("numLikes", None) + self.num_following = kwargs.pop("numFollowing", None) + self.num_followers = kwargs.pop("numFollowers", None) + self.user_type = kwargs.pop("type", None) + self.orgs = [Organization(**org) for org in kwargs.pop("orgs", [])] + + # forward compatibility + self.__dict__.update(**kwargs) + + +@dataclass +class PaperAuthor: + """ + Contains information about a paper author on the Hub. + + Attributes: + name (`str`): + Name of the author. + user (`User`, *optional*): + Information about the author as a [`User`] object. + status (`str`, *optional*): + Status of the author on the Hub. + status_last_changed_at (`datetime`, *optional*): + Date when the status of the author changed. + hidden (`bool`, *optional*): + Whether the author is hidden on the Hub. + """ + + name: str + user: User | None + status: str | None + status_last_changed_at: datetime | None + hidden: bool | None + + def __init__(self, **kwargs) -> None: + self.name = kwargs.pop("name", "") + user = kwargs.pop("user", None) + self.user = User(**user) if user else None + self.status = kwargs.pop("status", None) + status_last_changed_at = kwargs.pop("statusLastChangedAt", None) + self.status_last_changed_at = parse_datetime(status_last_changed_at) if status_last_changed_at else None + self.hidden = kwargs.pop("hidden", None) + + self.__dict__.update(**kwargs) + + +@dataclass +class PaperInfo: + """ + Contains information about a paper on the Hub. + + Attributes: + id (`str`): + arXiv paper ID. + authors (`list[PaperAuthor]`, *optional*): + Authors of the paper. + published_at (`datetime`, *optional*): + Date paper published. + title (`str`, *optional*): + Title of the paper. + summary (`str`, *optional*): + Summary of the paper. + upvotes (`int`, *optional*): + Number of upvotes for the paper on the Hub. + discussion_id (`str`, *optional*): + Discussion ID for the paper on the Hub. + source (`str`, *optional*): + Source of the paper. + comments (`int`, *optional*): + Number of comments for the paper on the Hub. + submitted_at (`datetime`, *optional*): + Date paper appeared in daily papers on the Hub. + submitted_by (`User`, *optional*): + Information about who submitted the daily paper. + ai_summary (`str`, *optional*): + AI summary of the paper. + ai_keywords (`list[str]`, *optional*): + AI keywords of the paper. + organization (`Organization`, *optional*): + Information about the organization associated with the paper. + project_page (`str`, *optional*): + URL of the project page for the paper. + github_repo (`str`, *optional*): + URL of the GitHub repository for the paper. + github_stars (`int`, *optional*): + Number of stars of the GitHub repository for the paper. + """ + + id: str + authors: list[PaperAuthor] | None + published_at: datetime | None + title: str | None + summary: str | None + upvotes: int | None + discussion_id: str | None + source: str | None + comments: int | None + submitted_at: datetime | None + submitted_by: User | None + ai_summary: str | None + ai_keywords: list[str] | None + organization: Organization | None + project_page: str | None + github_repo: str | None + github_stars: int | None + + def __init__(self, **kwargs) -> None: + paper = kwargs.pop("paper", {}) + self.id = kwargs.pop("id", None) or paper.pop("id", None) + authors = paper.pop("authors", None) or kwargs.pop("authors", None) + self.authors = [PaperAuthor(**author) for author in authors] if authors else None + published_at = paper.pop("publishedAt", None) or kwargs.pop("publishedAt", None) + self.published_at = parse_datetime(published_at) if published_at else None + self.title = kwargs.pop("title", None) + self.source = kwargs.pop("source", None) + self.summary = paper.pop("summary", None) or kwargs.pop("summary", None) + self.upvotes = paper.pop("upvotes", None) or kwargs.pop("upvotes", None) + self.discussion_id = paper.pop("discussionId", None) or kwargs.pop("discussionId", None) + self.comments = kwargs.pop("numComments", 0) + submitted_at = kwargs.pop("publishedAt", None) or kwargs.pop("submittedOnDailyAt", None) + self.submitted_at = parse_datetime(submitted_at) if submitted_at else None + submitted_by = kwargs.pop("submittedBy", None) or kwargs.pop("submittedOnDailyBy", None) + self.submitted_by = User(**submitted_by) if submitted_by else None + self.ai_summary = kwargs.pop("ai_summary", None) + self.ai_keywords = kwargs.pop("ai_keywords", None) + organization = kwargs.pop("organization", None) + self.organization = Organization(**organization) if organization else None + self.project_page = kwargs.pop("projectPage", None) + self.github_repo = kwargs.pop("githubRepo", None) + self.github_stars = kwargs.pop("githubStars", None) + + # forward compatibility + self.__dict__.update(**kwargs) + + +@dataclass +class LFSFileInfo: + """ + Contains information about a file stored as LFS on a repo on the Hub. + + Used in the context of listing and permanently deleting LFS files from a repo to free-up space. + See [`list_lfs_files`] and [`permanently_delete_lfs_files`] for more details. + + Git LFS files are tracked using SHA-256 object IDs, rather than file paths, to optimize performance + This approach is necessary because a single object can be referenced by multiple paths across different commits, + making it impractical to search and resolve these connections. Check out [our documentation](https://huggingface.co/docs/hub/storage-limits#advanced-track-lfs-file-references) + to learn how to know which filename(s) is(are) associated with each SHA. + + Attributes: + file_oid (`str`): + SHA-256 object ID of the file. This is the identifier to pass when permanently deleting the file. + filename (`str`): + Possible filename for the LFS object. See the note above for more information. + oid (`str`): + OID of the LFS object. + pushed_at (`datetime`): + Date the LFS object was pushed to the repo. + ref (`str`, *optional*): + Ref where the LFS object has been pushed (if any). + size (`int`): + Size of the LFS object. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> lfs_files = api.list_lfs_files("username/my-cool-repo") + + # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`. + # e.g. select only LFS files in the "checkpoints" folder + >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/")) + + # Permanently delete LFS files + >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete) + ``` + """ + + file_oid: str + filename: str + oid: str + pushed_at: datetime + ref: str | None + size: int + + def __init__(self, **kwargs) -> None: + self.file_oid = kwargs.pop("fileOid") + self.filename = kwargs.pop("filename") + self.oid = kwargs.pop("oid") + self.pushed_at = parse_datetime(kwargs.pop("pushedAt")) + self.ref = kwargs.pop("ref", None) + self.size = kwargs.pop("size") + + # forward compatibility + self.__dict__.update(**kwargs) + + +@dataclass +class DatasetLeaderboardEntry: + """Contains information about a single entry in a dataset leaderboard on the Hub. + + A leaderboard ranks models based on their evaluation scores on a given benchmark dataset. + This object is returned by [`get_dataset_leaderboard`]. To get evaluation results for a + specific model across benchmarks, see [`ModelInfo.eval_results`] (via [`model_info`] with + `expand=["evalResults"]`) and [`EvalResultEntry`]. + + Attributes: + rank (`int`): + Rank of the model on the leaderboard (1-indexed). + model_id (`str`): + ID of the model (e.g. `"meta-llama/Llama-3-8b"`). + value (`float`): + Evaluation score value. + filename (`str`): + Name of the result file containing the evaluation data. + verified (`bool`): + Whether the result has been verified. + source (`dict[str, Any]`): + Information about the source of the evaluation result. Contains keys like + `"url"`, `"name"`, and `"isExternal"`. + author (`User` or `Organization`): + The model author, parsed based on the `"type"` field in the API response. + pull_request (`int`, *optional*): + Pull request number associated with the leaderboard entry, if any. + notes (`str`, *optional*): + Notes associated with the leaderboard entry, if any. + """ + + rank: int + model_id: str + value: float + filename: str + verified: bool + source: dict[str, Any] + author: User | Organization + pull_request: int | None = None + notes: str | None = None + + def __init__(self, **kwargs) -> None: + self.rank = kwargs.pop("rank") + self.model_id = kwargs.pop("modelId") + self.value = kwargs.pop("value") + self.filename = kwargs.pop("filename") + self.verified = kwargs.pop("verified") + self.source = kwargs.pop("source") + author_data = dict(kwargs.pop("author")) + author_type = author_data.get("type") + if author_type == "org": + self.author = Organization(**author_data) + else: + author_data["user"] = author_data.pop("name", "") + self.author = User(**author_data) + self.pull_request = kwargs.pop("pullRequest", None) + self.notes = kwargs.pop("notes", None) + + # forward compatibility + self.__dict__.update(**kwargs) + + +def future_compatible(fn: CallableT) -> CallableT: + """Wrap a method of `HfApi` to handle `run_as_future=True`. + + A method flagged as "future_compatible" will be called in a thread if `run_as_future=True` and return a + `concurrent.futures.Future` instance. Otherwise, it will be called normally and return the result. + """ + sig = inspect.signature(fn) + args_params = list(sig.parameters)[1:] # remove "self" from list + + @wraps(fn) + def _inner(self, *args, **kwargs): + # Get `run_as_future` value if provided (default to False) + if "run_as_future" in kwargs: + run_as_future = kwargs["run_as_future"] + kwargs["run_as_future"] = False # avoid recursion error + else: + run_as_future = False + for param, value in zip(args_params, args): + if param == "run_as_future": + run_as_future = value + break + + # Call the function in a thread if `run_as_future=True` + if run_as_future: + return self.run_as_future(fn, self, *args, **kwargs) + + # Otherwise, call the function normally + return fn(self, *args, **kwargs) + + _inner.is_future_compatible = True # type: ignore + return _inner # type: ignore + + +def _get_safetensors_metadata_size(size_bytes: bytes, filename: str, context_msg: str) -> int: + """ + Parse and validate safetensors metadata size from the first 8 bytes. + + This is a shared helper function used by both remote and local safetensors parsing. + + Args: + size_bytes: First 8 bytes of the safetensors file. + filename: Filename for error messages. + context_msg: Additional context for error messages. + + Returns: + The metadata size as an integer. + + Raises: + SafetensorsParsingError: If size_bytes is too short or metadata size exceeds limit. + """ + if len(size_bytes) < 8: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' ({context_msg}): file is too small to be a valid " + "safetensors file." + ) + + metadata_size = struct.unpack(" constants.SAFETENSORS_MAX_HEADER_LENGTH: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' ({context_msg}): safetensors header is too big. " + f"Maximum supported size is {constants.SAFETENSORS_MAX_HEADER_LENGTH} bytes (got {metadata_size})." + ) + + return metadata_size + + +def _parse_safetensors_header(metadata_as_bytes: bytes, filename: str, context_msg: str) -> SafetensorsFileMetadata: + """ + Parse safetensors metadata from raw header bytes. + + This is a shared helper function used by both remote and local safetensors parsing. + + Args: + metadata_as_bytes: Raw bytes of the JSON metadata header (without the 8-byte size prefix). + filename: Filename for error messages. + context_msg: Additional context for error messages (e.g., repo info or local path). + + Returns: + SafetensorsFileMetadata object. + + Raises: + SafetensorsParsingError: If the header cannot be parsed. + """ + # Parse json header + try: + metadata_as_dict = json.loads(metadata_as_bytes.decode(errors="ignore")) + except json.JSONDecodeError as e: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' ({context_msg}): header is not json-encoded string. " + "Please make sure this is a correctly formatted safetensors file." + ) from e + + try: + return SafetensorsFileMetadata( + metadata=metadata_as_dict.get("__metadata__", {}), + tensors={ + key: TensorInfo( + dtype=tensor["dtype"], + shape=tensor["shape"], + data_offsets=tuple(tensor["data_offsets"]), # type: ignore + ) + for key, tensor in metadata_as_dict.items() + if key != "__metadata__" + }, + ) + except (KeyError, IndexError) as e: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' ({context_msg}): header format not recognized. " + "Please make sure this is a correctly formatted safetensors file." + ) from e + + +class HfApi: + """ + Client to interact with the Hugging Face Hub via HTTP. + + The client is initialized with some high-level settings used in all requests + made to the Hub (HF endpoint, authentication, user agents...). Using the `HfApi` + client is preferred but not mandatory as all of its public methods are exposed + directly at the root of `huggingface_hub`. + + Args: + endpoint (`str`, *optional*): + Endpoint of the Hub. Defaults to . + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + library_name (`str`, *optional*): + The name of the library that is making the HTTP request. Will be added to + the user-agent header. Example: `"transformers"`. + library_version (`str`, *optional*): + The version of the library that is making the HTTP request. Will be added + to the user-agent header. Example: `"4.24.0"`. + user_agent (`str`, `dict`, *optional*): + The user agent info in the form of a dictionary or a single string. It will + be completed with information about the installed packages. + headers (`dict`, *optional*): + Additional headers to be sent with each request. Example: `{"X-My-Header": "value"}`. + Headers passed here are taking precedence over the default headers. + """ + + def __init__( + self, + endpoint: str | None = None, + token: str | bool | None = None, + library_name: str | None = None, + library_version: str | None = None, + user_agent: dict | str | None = None, + headers: dict[str, str] | None = None, + ) -> None: + self.endpoint = endpoint if endpoint is not None else constants.ENDPOINT + self.token = token + self.library_name = library_name + self.library_version = library_version + self.user_agent = user_agent + self.headers = headers + self._thread_pool: ThreadPoolExecutor | None = None + + # /whoami-v2 is the only endpoint for which we may want to cache results + self._whoami_cache: dict[str, dict] = {} + + def run_as_future(self, fn: Callable[..., R], *args, **kwargs) -> Future[R]: + """ + Run a method in the background and return a Future instance. + + The main goal is to run methods without blocking the main thread (e.g. to push data during a training). + Background jobs are queued to preserve order but are not ran in parallel. If you need to speed-up your scripts + by parallelizing lots of call to the API, you must setup and use your own [ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor). + + Note: Most-used methods like [`upload_file`], [`upload_folder`] and [`create_commit`] have a `run_as_future: bool` + argument to directly call them in the background. This is equivalent to calling `api.run_as_future(...)` on them + but less verbose. + + Args: + fn (`Callable`): + The method to run in the background. + *args, **kwargs: + Arguments with which the method will be called. + + Return: + `Future`: a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) instance to + get the result of the task. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> future = api.run_as_future(api.whoami) # instant + >>> future.done() + False + >>> future.result() # wait until complete and return result + (...) + >>> future.done() + True + ``` + """ + if self._thread_pool is None: + self._thread_pool = ThreadPoolExecutor(max_workers=1) + self._thread_pool + return self._thread_pool.submit(fn, *args, **kwargs) + + @validate_hf_hub_args + def whoami(self, token: bool | str | None = None, *, cache: bool = False) -> dict: + """ + Call HF API to know "whoami". + + If passing `cache=True`, the result will be cached for subsequent calls for the duration of the Python process. This is useful if you plan to call + `whoami` multiple times as this endpoint is heavily rate-limited for security reasons. + + Args: + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + cache (`bool`, *optional*): + Whether to cache the result of the `whoami` call for subsequent calls. + If an error occurs during the first call, it won't be cached. + Defaults to `False`. + """ + # Get the effective token using the helper function get_token + token = self.token if token is None else token + if token is False: + raise ValueError("Cannot use `token=False` with `whoami` method as it requires authentication.") + if token is True or token is None: + token = get_token() + if token is None: + raise LocalTokenNotFoundError( + "Token is required to call the /whoami-v2 endpoint, but no token found. You must provide a token or be logged in to " + "Hugging Face with `hf auth login` or `huggingface_hub.login`. See https://huggingface.co/settings/tokens." + ) + + if cache and (cached_token := self._whoami_cache.get(token)): + return cached_token + + # Call Hub + output = self._inner_whoami(token=token) + + # Cache result and return + if cache: + self._whoami_cache[token] = output + return output + + def _inner_whoami(self, token: str) -> dict: + r = get_session().get( + f"{self.endpoint}/api/whoami-v2", + headers=self._build_hf_headers(token=token), + ) + try: + hf_raise_for_status(r) + except HfHubHTTPError as e: + if e.response.status_code == 401: + error_message = "Invalid user token." + # Check which token is the effective one and generate the error message accordingly + if token == _get_token_from_google_colab(): + error_message += " The token from Google Colab vault is invalid. Please update it from the UI." + elif token == _get_token_from_environment(): + error_message += ( + " The token from HF_TOKEN environment variable is invalid. " + "Note that HF_TOKEN takes precedence over `hf auth login`." + ) + elif token == _get_token_from_file(): + error_message += ( + " The token stored is invalid. Please run `hf auth login --force` to set a new token." + ) + raise HfHubHTTPError(error_message, response=e.response) from e + if e.response.status_code == 429: + error_message = ( + "You've hit the rate limit for the /whoami-v2 endpoint, which is intentionally strict for security reasons." + " If you're calling it often, consider caching the response with `whoami(..., cache=True)`." + ) + raise HfHubHTTPError(error_message, response=e.response) from e + raise + return r.json() + + def get_model_tags(self) -> dict: + """ + List all valid model tags as a nested namespace object + """ + path = f"{self.endpoint}/api/models-tags-by-type" + r = get_session().get(path) + hf_raise_for_status(r) + return r.json() + + def get_dataset_tags(self) -> dict: + """ + List all valid dataset tags as a nested namespace object. + """ + path = f"{self.endpoint}/api/datasets-tags-by-type" + r = get_session().get(path) + hf_raise_for_status(r) + return r.json() + + @_deprecate_arguments(version="2.0", deprecated_args=["model_name"], custom_message="Use `search` instead.") + @validate_hf_hub_args + def list_models( + self, + *, + # Search-query parameter + filter: str | Iterable[str] | None = None, + author: str | None = None, + apps: str | list[str] | None = None, + gated: bool | None = None, + inference: Literal["warm"] | None = None, + inference_provider: Literal["all"] | PROVIDER_T | list[PROVIDER_T] | None = None, + model_name: str | None = None, + trained_dataset: str | list[str] | None = None, + search: str | None = None, + pipeline_tag: str | None = None, + num_parameters: str | None = None, + emissions_thresholds: tuple[float, float] | None = None, + # Sorting and pagination parameters + sort: ModelSort_T | None = None, + limit: int | None = None, + # Additional data to fetch + expand: list[ExpandModelProperty_T] | None = None, + full: bool | None = None, + cardData: bool = False, + fetch_config: bool = False, + token: bool | str | None = None, + ) -> Iterable[ModelInfo]: + """ + List models hosted on the Huggingface Hub, given some filters. + + Args: + filter (`str` or `Iterable[str]`, *optional*): + A string or list of string to filter models on the Hub. + Models can be filtered by library, language, task, tags, and more. + author (`str`, *optional*): + A string which identify the author (user or organization) of the + returned models. + apps (`str` or `List`, *optional*): + A string or list of strings to filter models on the Hub that + support the specified apps. Example values include `"ollama"` or `["ollama", "vllm"]`. + gated (`bool`, *optional*): + A boolean to filter models on the Hub that are gated or not. By default, all models are returned. + If `gated=True` is passed, only gated models are returned. + If `gated=False` is passed, only non-gated models are returned. + inference (`Literal["warm"]`, *optional*): + If "warm", filter models on the Hub currently served by at least one provider. + inference_provider (`Literal["all"]` or `str`, *optional*): + A string to filter models on the Hub that are served by a specific provider. + Pass `"all"` to get all models served by at least one provider. + trained_dataset (`str` or `List`, *optional*): + A string tag or a list of string tags of the trained dataset for a + model on the Hub. + search (`str`, *optional*): + A string that will be contained in the returned model ids. + pipeline_tag (`str`, *optional*): + A string pipeline tag to filter models on the Hub by, such as `summarization`. + num_parameters (`str`, *optional*): + Filter models by parameter count. Accepts the same range syntax as the Hub UI and API, for example + `"min:6B,max:128B"`, `"min:6B"` or `"max:128B"`. + emissions_thresholds (`Tuple`, *optional*): + A tuple of two ints or floats representing a minimum and maximum + carbon footprint to filter the resulting models with in grams. + sort (`ModelSort_T`, *optional*): + The key with which to sort the resulting models. Possible values are "created_at", "downloads", + "last_modified", "likes" and "trending_score". + limit (`int`, *optional*): + The limit on the number of models fetched. Leaving this option + to `None` fetches all models. + expand (`list[ExpandModelProperty_T]`, *optional*): + List properties to return in the response. When used, only the properties in the list will be returned. + This parameter cannot be used if `full`, `cardData` or `fetch_config` are passed. + Possible values are `"author"`, `"cardData"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"evalResults"`, `"gated"`, `"gguf"`, `"inference"`, `"inferenceProviderMapping"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, and `"resourceGroup"`. + full (`bool`, *optional*): + Whether to fetch all model data, including the `last_modified`, + the `sha`, the files and the `tags`. This is set to `True` by + default when using a filter. + cardData (`bool`, *optional*): + Whether to grab the metadata for the model as well. Can contain + useful information such as carbon emissions, metrics, and + datasets trained on. + fetch_config (`bool`, *optional*): + Whether to fetch the model configs as well. This is not included + in `full` due to its size. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + model_name (`str`, *optional*): + (deprecated). Use `search` instead. + + Returns: + `Iterable[ModelInfo]`: an iterable of [`huggingface_hub.hf_api.ModelInfo`] objects. + + Example: + + ```python + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + + # List all models + >>> api.list_models() + + # List text classification models + >>> api.list_models(filter="text-classification") + + # List models from the KerasHub library + >>> api.list_models(filter="keras-hub") + + # List models served by Cohere + >>> api.list_models(inference_provider="cohere") + + # List models with "bert" in their name + >>> api.list_models(search="bert") + + # List models with "bert" in their name and pushed by google + >>> api.list_models(search="bert", author="google") + + # List models with 6B to 128B parameters + >>> api.list_models(num_parameters="min:6B,max:128B", sort="likes") + ``` + """ + if expand and (full or cardData or fetch_config): + raise ValueError("`expand` cannot be used if `full`, `cardData` or `fetch_config` are passed.") + + if emissions_thresholds is not None and not cardData: + raise ValueError("`emissions_thresholds` were passed without setting `cardData=True`.") + + path = f"{self.endpoint}/api/models" + headers = self._build_hf_headers(token=token) + params: dict[str, Any] = {} + + # Build the filter list + filter_list: list[str] = [] + if filter: + filter_list.extend([filter] if isinstance(filter, str) else filter) + if trained_dataset: + datasets = [trained_dataset] if isinstance(trained_dataset, str) else trained_dataset + filter_list.extend(f"dataset:{d}" if not d.startswith("dataset:") else d for d in datasets) + if len(filter_list) > 0: + params["filter"] = filter_list + + # Handle other query params + if author: + params["author"] = author + if apps: + if isinstance(apps, str): + apps = [apps] + params["apps"] = apps + if gated is not None: + params["gated"] = gated + if inference is not None: + params["inference"] = inference + if inference_provider is not None: + params["inference_provider"] = inference_provider + if pipeline_tag: + params["pipeline_tag"] = pipeline_tag + if num_parameters is not None: + params["num_parameters"] = num_parameters + search_list = [] + if model_name: # deprecated + search_list.append(model_name) + if search: + search_list.append(search) + if len(search_list) > 0: + params["search"] = search_list + if sort is not None: + params["sort"] = ( + "lastModified" + if sort == "last_modified" + else "trendingScore" + if sort == "trending_score" + else "createdAt" + if sort == "created_at" + else sort + ) + if limit is not None: + params["limit"] = limit + + # Request additional data + if full: + params["full"] = True + if fetch_config: + params["config"] = True + if cardData: + params["cardData"] = True + if expand: + params["expand"] = expand + + # `items` is a generator + items = paginate(path, params=params, headers=headers) + if limit is not None: + items = islice(items, limit) # Do not iterate over all pages + for item in items: + if "siblings" not in item: + item["siblings"] = None + model_info = ModelInfo(**item) + if emissions_thresholds is None or _is_emission_within_threshold(model_info, *emissions_thresholds): + yield model_info + + @validate_hf_hub_args + def list_datasets( + self, + *, + # Search-query parameter + filter: str | Iterable[str] | None = None, + author: str | None = None, + benchmark: Literal[True] | Literal["official"] | str | None = None, + dataset_name: str | None = None, + gated: bool | None = None, + language_creators: str | list[str] | None = None, + language: str | list[str] | None = None, + multilinguality: str | list[str] | None = None, + size_categories: str | list[str] | None = None, + task_categories: str | list[str] | None = None, + task_ids: str | list[str] | None = None, + search: str | None = None, + # Sorting and pagination parameters + sort: DatasetSort_T | None = None, + limit: int | None = None, + # Additional data to fetch + expand: list[ExpandDatasetProperty_T] | None = None, + full: bool | None = None, + token: bool | str | None = None, + ) -> Iterable[DatasetInfo]: + """ + List datasets hosted on the Huggingface Hub, given some filters. + + Args: + filter (`str` or `Iterable[str]`, *optional*): + A string or list of string to filter datasets on the hub. + author (`str`, *optional*): + A string which identify the author of the returned datasets. + benchmark (`True`, `"official"`, `str`, *optional*): + Filter datasets by benchmark. Can be `True` or `"official"` to return official benchmark datasets. + For future-compatibility, can also be a string representing the benchmark name (currently only "official" is supported). + dataset_name (`str`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by its name, such as `SQAC` or `wikineural` + gated (`bool`, *optional*): + A boolean to filter datasets on the Hub that are gated or not. By default, all datasets are returned. + If `gated=True` is passed, only gated datasets are returned. + If `gated=False` is passed, only non-gated datasets are returned. + language_creators (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub with how the data was curated, such as `crowdsourced` or + `machine_generated`. + language (`str` or `List`, *optional*): + A string or list of strings representing a two-character language to + filter datasets by on the Hub. + multilinguality (`str` or `List`, *optional*): + A string or list of strings representing a filter for datasets that + contain multiple languages. + size_categories (`str` or `List`, *optional*): + A string or list of strings that can be used to identify datasets on + the Hub by the size of the dataset such as `100K>> from huggingface_hub import HfApi + + >>> api = HfApi() + + # List all datasets + >>> api.list_datasets() + + + # List only the text classification datasets + >>> api.list_datasets(filter="task_categories:text-classification") + + + # List only the datasets in russian for language modeling + >>> api.list_datasets( + ... filter=("language:ru", "task_ids:language-modeling") + ... ) + + # List FiftyOne datasets (identified by the tag "fiftyone" in dataset card) + >>> api.list_datasets(tags="fiftyone") + ``` + + Example usage with the `search` argument: + + ```python + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + + # List all datasets with "text" in their name + >>> api.list_datasets(search="text") + + # List all datasets with "text" in their name made by google + >>> api.list_datasets(search="text", author="google") + ``` + """ + if expand and full: + raise ValueError("`expand` cannot be used if `full` is passed.") + + path = f"{self.endpoint}/api/datasets" + headers = self._build_hf_headers(token=token) + params: dict[str, Any] = {} + + # Build `filter` list + filter_list = [] + if filter is not None: + if isinstance(filter, str): + filter_list.append(filter) + else: + filter_list.extend(filter) + for key, value in ( + ("language_creators", language_creators), + ("language", language), + ("multilinguality", multilinguality), + ("size_categories", size_categories), + ("task_categories", task_categories), + ("task_ids", task_ids), + ): + if value: + if isinstance(value, str): + value = [value] + for value_item in value: + if not value_item.startswith(f"{key}:"): + data = f"{key}:{value_item}" + else: + data = value_item + filter_list.append(data) + if benchmark is not None: + if benchmark is True: # alias for official benchmark + benchmark = "official" + filter_list.append(f"benchmark:{benchmark}") + if len(filter_list) > 0: + params["filter"] = filter_list + + # Handle other query params + if author: + params["author"] = author + if gated is not None: + params["gated"] = gated + search_list = [] + if dataset_name: + search_list.append(dataset_name) + if search: + search_list.append(search) + if len(search_list) > 0: + params["search"] = search_list + if sort is not None: + params["sort"] = ( + "lastModified" + if sort == "last_modified" + else "trendingScore" + if sort == "trending_score" + else "createdAt" + if sort == "created_at" + else sort + ) + if limit is not None: + params["limit"] = limit + + # Request additional data + if expand: + params["expand"] = expand + if full: + params["full"] = True + + items = paginate(path, params=params, headers=headers) + if limit is not None: + items = islice(items, limit) # Do not iterate over all pages + for item in items: + if "siblings" not in item: + item["siblings"] = None + yield DatasetInfo(**item) + + @validate_hf_hub_args + def list_dataset_parquet_files( + self, + repo_id: str, + *, + config: str | None = None, + token: bool | str | None = None, + ) -> list[DatasetParquetEntry]: + """List parquet files available for a dataset on the Hub. + + All datasets hosted on the Hub are auto-converted to Parquet by the + [Dataset Viewer](https://huggingface.co/docs/dataset-viewer/parquet). + This method returns the list of parquet files with their URLs, configs, + splits and sizes. + + Args: + repo_id (`str`): + The dataset repository ID (e.g. `"username/dataset-name"`). + config (`str`, *optional*): + Filter by a specific config/subset name. When provided, only + parquet files for that config are returned. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `list[DatasetParquetEntry]`: a list of [`DatasetParquetEntry`] objects + containing config, split, url and size for each parquet file. + + Example: + ```python + >>> from huggingface_hub import list_dataset_parquet_files + >>> list_dataset_parquet_files("lhoestq/demo1") + >>> entries[0] + DatasetParquetEntry(config='default', split='train', url='https://huggingface.co/...', size=5038) + ``` + """ + if self.endpoint != constants._HF_DEFAULT_ENDPOINT: + raise ValueError( + "The Dataset Viewer is only available on the Hugging Face Hub" + f" (endpoint='{constants._HF_DEFAULT_ENDPOINT}'). It is not supported on" + f" third-party endpoints. (endpoint={self.endpoint})" + ) + + url = f"{constants.DATASETS_SERVER_ENDPOINT}/parquet" + params: dict[str, str] = {"dataset": repo_id} + if config is not None: + params["config"] = config + response = get_session().get(url, params=params, headers=self._build_hf_headers(token=token)) + hf_raise_for_status(response) + payload = response.json() + + return [ + DatasetParquetEntry( + config=file_info["config"], + split=file_info["split"], + url=file_info["url"], + size=file_info["size"], + ) + for file_info in payload.get("parquet_files", []) + ] + + @validate_hf_hub_args + def list_spaces( + self, + *, + # Search-query parameter + filter: str | Iterable[str] | None = None, + author: str | None = None, + search: str | None = None, + datasets: str | Iterable[str] | None = None, + models: str | Iterable[str] | None = None, + linked: bool = False, + # Sorting and pagination parameters + sort: SpaceSort_T | None = None, + limit: int | None = None, + # Additional data to fetch + expand: list[ExpandSpaceProperty_T] | None = None, + full: bool | None = None, + token: bool | str | None = None, + ) -> Iterable[SpaceInfo]: + """ + List spaces hosted on the Huggingface Hub, given some filters. + + Args: + filter (`str` or `Iterable`, *optional*): + A string tag or list of tags that can be used to identify Spaces on the Hub. + author (`str`, *optional*): + A string which identify the author of the returned Spaces. + search (`str`, *optional*): + A string that will be contained in the returned Spaces. + datasets (`str` or `Iterable`, *optional*): + Whether to return Spaces that make use of a dataset. + The name of a specific dataset can be passed as a string. + models (`str` or `Iterable`, *optional*): + Whether to return Spaces that make use of a model. + The name of a specific model can be passed as a string. + linked (`bool`, *optional*): + Whether to return Spaces that make use of either a model or a dataset. + sort (`SpaceSort_T`, *optional*): + The key with which to sort the resulting spaces. Possible values are "created_at", "last_modified", + "likes" and "trending_score". + limit (`int`, *optional*): + The limit on the number of Spaces fetched. Leaving this option + to `None` fetches all Spaces. + expand (`list[ExpandSpaceProperty_T]`, *optional*): + List properties to return in the response. When used, only the properties in the list will be returned. + This parameter cannot be used if `full` is passed. + Possible values are `"author"`, `"cardData"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"createdAt"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`. + full (`bool`, *optional*): + Whether to fetch all Spaces data, including the `last_modified`, `siblings` + and `card_data` fields. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[SpaceInfo]`: an iterable of [`huggingface_hub.hf_api.SpaceInfo`] objects. + """ + if expand and full: + raise ValueError("`expand` cannot be used if `full` is passed.") + + path = f"{self.endpoint}/api/spaces" + headers = self._build_hf_headers(token=token) + params: dict[str, Any] = {} + if filter is not None: + params["filter"] = filter + if author is not None: + params["author"] = author + if search is not None: + params["search"] = search + if sort is not None: + params["sort"] = ( + "lastModified" + if sort == "last_modified" + else "trendingScore" + if sort == "trending_score" + else "createdAt" + if sort == "created_at" + else sort + ) + if limit is not None: + params["limit"] = limit + if linked: + params["linked"] = True + if datasets is not None: + params["datasets"] = datasets + if models is not None: + params["models"] = models + + # Request additional data + if expand: + params["expand"] = expand + if full: + params["full"] = True + + items = paginate(path, params=params, headers=headers) + if limit is not None: + items = islice(items, limit) # Do not iterate over all pages + for item in items: + if "siblings" not in item: + item["siblings"] = None + yield SpaceInfo(**item) + + @validate_hf_hub_args + def search_spaces( + self, + query: str, + *, + filter: str | Iterable[str] | None = None, + sdk: str | list[str] | None = None, + include_non_running: bool = False, + token: bool | str | None = None, + ) -> Iterable[SpaceSearchResult]: + """Search Spaces on the Hub using semantic search. + + This endpoint uses semantic search (embedding-based) for multi-word queries + and full-text search for single-word queries. + + Args: + query (`str`): + The search query string. + filter (`str` or `Iterable[str]`, *optional*): + A string tag or list of tags to filter by. + sdk (`str` or `list[str]`, *optional*): + Filter by SDK (e.g. `"gradio"`, `"docker"`, `"static"`). + include_non_running (`bool`, *optional*): + Whether to include non-running Spaces in results. Defaults to `False`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[SpaceSearchResult]`: an iterable of [`SpaceSearchResult`] objects. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> results = list(api.search_spaces("generate image")) + >>> results[0].id + 'mrfakename/Z-Image-Turbo' + >>> results[0].ai_category + 'Image Generation' + ``` + """ + path = f"{self.endpoint}/api/spaces/semantic-search" + headers = self._build_hf_headers(token=token) + params: dict[str, Any] = {"q": query} + if filter is not None: + params["filter"] = filter + if sdk is not None: + params["sdk"] = sdk + if include_non_running: + params["includeNonRunning"] = True + + r = get_session().get(path, headers=headers, params=params) + hf_raise_for_status(r) + for item in r.json(): + yield SpaceSearchResult(item) + + @validate_hf_hub_args + def unlike( + self, + repo_id: str, + *, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> None: + """ + Unlike a given repo on the Hub (e.g. remove from favorite list). + + To prevent spam usage, it is not possible to `like` a repository from a script. + + See also [`list_liked_repos`]. + + Args: + repo_id (`str`): + The repository to unlike. Example: `"user/my-cool-model"`. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if unliking a dataset or space, `None` or + `"model"` if unliking a model. Default is `None`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + + Example: + ```python + >>> from huggingface_hub import list_liked_repos, unlike + >>> "gpt2" in list_liked_repos().models # we assume you have already liked gpt2 + True + >>> unlike("gpt2") + >>> "gpt2" in list_liked_repos().models + False + ``` + """ + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + response = get_session().delete( + url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/like", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(response) + + @validate_hf_hub_args + def list_liked_repos( + self, + user: str | None = None, + *, + token: bool | str | None = None, + ) -> UserLikes: + """ + List all public repos liked by a user on huggingface.co. + + This list is public so token is optional. If `user` is not passed, it defaults to + the logged in user. + + See also [`unlike`]. + + Args: + user (`str`, *optional*): + Name of the user for which you want to fetch the likes. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`UserLikes`]: object containing the user name and 3 lists of repo ids (1 for + models, 1 for datasets and 1 for Spaces). + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `user` is not passed and no token found (either from argument or from machine). + + Example: + ```python + >>> from huggingface_hub import list_liked_repos + + >>> likes = list_liked_repos("julien-c") + + >>> likes.user + "julien-c" + + >>> likes.models + ["osanseviero/streamlit_1.15", "Xhaheen/ChatGPT_HF", ...] + ``` + """ + # User is either provided explicitly or retrieved from current token. + if user is None: + me = self.whoami(token=token) + if me["type"] == "user": + user = me["name"] + else: + raise ValueError( + "Cannot list liked repos. You must provide a 'user' as input or be logged in as a user." + ) + + path = f"{self.endpoint}/api/users/{user}/likes" + headers = self._build_hf_headers(token=token) + + likes = list(paginate(path, params={}, headers=headers)) + # Looping over a list of items similar to: + # { + # 'createdAt': '2021-09-09T21:53:27.000Z', + # 'repo': { + # 'name': 'PaddlePaddle/PaddleOCR', + # 'type': 'space' + # } + # } + # Let's loop 3 times over the received list. Less efficient but more straightforward to read. + return UserLikes( + user=user, + total=len(likes), + kernels=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "kernel"], + models=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "model"], + datasets=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "dataset"], + spaces=[like["repo"]["name"] for like in likes if like["repo"]["type"] == "space"], + ) + + @validate_hf_hub_args + def list_repo_likers( + self, + repo_id: str, + *, + repo_type: str | None = None, + token: bool | str | None = None, + ) -> Iterable[User]: + """ + List all users who liked a given repo on the hugging Face Hub. + + See also [`list_liked_repos`]. + + Args: + repo_id (`str`): + The repository to retrieve . Example: `"user/my-cool-model"`. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + Returns: + `Iterable[User]`: an iterable of [`huggingface_hub.hf_api.User`] objects. + """ + + # Construct the API endpoint + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/likers" + for liker in paginate(path, params={}, headers=self._build_hf_headers(token=token)): + yield User(username=liker["user"], fullname=liker["fullname"], avatar_url=liker["avatarUrl"]) + + @validate_hf_hub_args + def model_info( + self, + repo_id: str, + *, + revision: str | None = None, + timeout: float | None = None, + securityStatus: bool | None = None, + files_metadata: bool = False, + expand: list[ExpandModelProperty_T] | None = None, + token: bool | str | None = None, + ) -> ModelInfo: + """ + Get info on one specific model on huggingface.co + + Model can be private if you pass an acceptable token or are logged in. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The revision of the model repository from which to get the + information. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + securityStatus (`bool`, *optional*): + Whether to retrieve the security status from the model + repository as well. The security status will be returned in the `security_repo_status` field. + files_metadata (`bool`, *optional*): + Whether or not to retrieve metadata for files in the repository + (size, LFS metadata, etc). Defaults to `False`. + expand (`list[ExpandModelProperty_T]`, *optional*): + List properties to return in the response. When used, only the properties in the list will be returned. + This parameter cannot be used if `securityStatus` or `files_metadata` are passed. + Possible values are `"author"`, `"baseModels"`, `"cardData"`, `"childrenModelCount"`, `"config"`, `"createdAt"`, `"disabled"`, `"downloads"`, `"downloadsAllTime"`, `"evalResults"`, `"gated"`, `"gguf"`, `"inference"`, `"inferenceProviderMapping"`, `"lastModified"`, `"library_name"`, `"likes"`, `"mask_token"`, `"model-index"`, `"pipeline_tag"`, `"private"`, `"safetensors"`, `"sha"`, `"siblings"`, `"spaces"`, `"tags"`, `"transformersInfo"`, `"trendingScore"`, `"widgetData"`, `"usedStorage"`, and `"resourceGroup"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`huggingface_hub.hf_api.ModelInfo`]: The model repository information. + + > [!TIP] + > Raises the following errors: + > + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.RevisionNotFoundError`] + > If the revision to download from cannot be found. + """ + if expand and (securityStatus or files_metadata): + raise ValueError("`expand` cannot be used if `securityStatus` or `files_metadata` are set.") + + headers = self._build_hf_headers(token=token) + path = ( + f"{self.endpoint}/api/models/{repo_id}" + if revision is None + else (f"{self.endpoint}/api/models/{repo_id}/revision/{quote(revision, safe='')}") + ) + params: dict = {} + if securityStatus: + params["securityStatus"] = True + if files_metadata: + params["blobs"] = True + if expand: + params["expand"] = expand + r = get_session().get(path, headers=headers, timeout=timeout, params=params) + hf_raise_for_status(r) + data = r.json() + return ModelInfo(**data) + + @validate_hf_hub_args + def dataset_info( + self, + repo_id: str, + *, + revision: str | None = None, + timeout: float | None = None, + files_metadata: bool = False, + expand: list[ExpandDatasetProperty_T] | None = None, + token: bool | str | None = None, + ) -> DatasetInfo: + """ + Get info on one specific dataset on huggingface.co. + + Dataset can be private if you pass an acceptable token. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The revision of the dataset repository from which to get the + information. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + files_metadata (`bool`, *optional*): + Whether or not to retrieve metadata for files in the repository + (size, LFS metadata, etc). Defaults to `False`. + expand (`list[ExpandDatasetProperty_T]`, *optional*): + List properties to return in the response. When used, only the properties in the list will be returned. + This parameter cannot be used if `files_metadata` is passed. + Possible values are `"author"`, `"cardData"`, `"citation"`, `"createdAt"`, `"disabled"`, `"description"`, `"downloads"`, `"downloadsAllTime"`, `"gated"`, `"lastModified"`, `"likes"`, `"mainSize"`, `"paperswithcode_id"`, `"private"`, `"siblings"`, `"sha"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`hf_api.DatasetInfo`]: The dataset repository information. + + > [!TIP] + > Raises the following errors: + > + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.RevisionNotFoundError`] + > If the revision to download from cannot be found. + """ + if expand and files_metadata: + raise ValueError("`expand` cannot be used if `files_metadata` is set.") + + headers = self._build_hf_headers(token=token) + path = ( + f"{self.endpoint}/api/datasets/{repo_id}" + if revision is None + else (f"{self.endpoint}/api/datasets/{repo_id}/revision/{quote(revision, safe='')}") + ) + params: dict = {} + if files_metadata: + params["blobs"] = True + if expand: + params["expand"] = expand + + r = get_session().get(path, headers=headers, timeout=timeout, params=params) + hf_raise_for_status(r) + data = r.json() + return DatasetInfo(**data) + + @validate_hf_hub_args + def get_dataset_leaderboard( + self, + repo_id: str, + *, + token: bool | str | None = None, + timeout: float | None = None, + ) -> list[DatasetLeaderboardEntry]: + """Get the leaderboard for a dataset on the Hub. + + The leaderboard ranks models based on their evaluation scores on the given benchmark + dataset. Not all datasets have leaderboards — only benchmark datasets with evaluation + results submitted to them. This gives a dataset-centric view of scores; for a model-centric + view, use [`model_info`] with `expand=["evalResults"]`. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. For example: `"allenai/olmOCR-bench"`. + token (`bool` or `str`, *optional*): + A valid user access token. Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + + Returns: + `list[DatasetLeaderboardEntry]`: A list of [`DatasetLeaderboardEntry`] objects representing + the leaderboard entries, sorted by rank. + + > [!TIP] + > Raises the following errors: + > + > - [`~utils.RepositoryNotFoundError`] + > If the repository cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.HfHubHTTPError`] + > If the dataset does not have a leaderboard. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> leaderboard = api.get_dataset_leaderboard("allenai/olmOCR-bench") + >>> leaderboard[0].model_id + 'datalab-to/chandra-ocr-2' + >>> leaderboard[0].rank + 1 + ``` + """ + headers = self._build_hf_headers(token=token) + path = f"{self.endpoint}/api/datasets/{repo_id}/leaderboard" + r = get_session().get(path, headers=headers, timeout=timeout) + hf_raise_for_status(r) + data = r.json() + return [DatasetLeaderboardEntry(**entry) for entry in data] + + @validate_hf_hub_args + def space_info( + self, + repo_id: str, + *, + revision: str | None = None, + timeout: float | None = None, + files_metadata: bool = False, + expand: list[ExpandSpaceProperty_T] | None = None, + token: bool | str | None = None, + ) -> SpaceInfo: + """ + Get info on one specific Space on huggingface.co. + + Space can be private if you pass an acceptable token. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The revision of the space repository from which to get the + information. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + files_metadata (`bool`, *optional*): + Whether or not to retrieve metadata for files in the repository + (size, LFS metadata, etc). Defaults to `False`. + expand (`list[ExpandSpaceProperty_T]`, *optional*): + List properties to return in the response. When used, only the properties in the list will be returned. + This parameter cannot be used if `full` is passed. + Possible values are `"author"`, `"cardData"`, `"createdAt"`, `"datasets"`, `"disabled"`, `"lastModified"`, `"likes"`, `"models"`, `"private"`, `"runtime"`, `"sdk"`, `"siblings"`, `"sha"`, `"subdomain"`, `"tags"`, `"trendingScore"`, `"usedStorage"`, and `"resourceGroup"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`~hf_api.SpaceInfo`]: The space repository information. + + > [!TIP] + > Raises the following errors: + > + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.RevisionNotFoundError`] + > If the revision to download from cannot be found. + """ + if expand and files_metadata: + raise ValueError("`expand` cannot be used if `files_metadata` is set.") + + headers = self._build_hf_headers(token=token) + path = ( + f"{self.endpoint}/api/spaces/{repo_id}" + if revision is None + else (f"{self.endpoint}/api/spaces/{repo_id}/revision/{quote(revision, safe='')}") + ) + params: dict = {} + if files_metadata: + params["blobs"] = True + if expand: + params["expand"] = expand + + r = get_session().get(path, headers=headers, timeout=timeout, params=params) + hf_raise_for_status(r) + data = r.json() + return SpaceInfo(**data) + + @validate_hf_hub_args + def kernel_info( + self, + repo_id: str, + *, + revision: str | None = None, + timeout: float | None = None, + token: bool | str | None = None, + ) -> KernelInfo: + """ + Get info on one specific kernel on huggingface.co. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + revision (`str`, *optional*): + The revision of the kernel repository from which to get the + information. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`~hf_api.ModelInfo`]: The kernel repository information. + """ + headers = self._build_hf_headers(token=token) + path = ( + f"{self.endpoint}/api/kernels/{repo_id}" + if revision is None + else (f"{self.endpoint}/api/kernels/{repo_id}/revision/{quote(revision, safe='')}") + ) + r = get_session().get(path, headers=headers, timeout=timeout) + hf_raise_for_status(r) + data = r.json() + return KernelInfo(**data) + + @validate_hf_hub_args + def repo_info( + self, + repo_id: str, + *, + revision: str | None = None, + repo_type: str | None = None, + timeout: float | None = None, + files_metadata: bool = False, + expand: ExpandModelProperty_T | ExpandDatasetProperty_T | ExpandSpaceProperty_T | None = None, + token: bool | str | None = None, + ) -> ModelInfo | DatasetInfo | SpaceInfo | KernelInfo: + """ + Get the info object for a given repo of a given type. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The revision of the repository from which to get the + information. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space, + `None` or `"model"` if getting repository info from a model. Default is `None`. + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + expand (`ExpandModelProperty_T` or `ExpandDatasetProperty_T` or `ExpandSpaceProperty_T`, *optional*): + List properties to return in the response. When used, only the properties in the list will be returned. + This parameter cannot be used if `files_metadata` is passed. + For an exhaustive list of available properties, check out [`model_info`], [`dataset_info`] or [`space_info`]. + files_metadata (`bool`, *optional*): + Whether or not to retrieve metadata for files in the repository + (size, LFS metadata, etc). Defaults to `False`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Union[SpaceInfo, DatasetInfo, ModelInfo]`: The repository information, as a + [`huggingface_hub.hf_api.DatasetInfo`], [`huggingface_hub.hf_api.ModelInfo`] + or [`huggingface_hub.hf_api.SpaceInfo`] object. + + > [!TIP] + > Raises the following errors: + > + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.RevisionNotFoundError`] + > If the revision to download from cannot be found. + """ + match repo_type: + case None | "model": + method = self.model_info + case "dataset": + method = self.dataset_info # type: ignore + case "space": + method = self.space_info # type: ignore + case "kernel": + # No expand/files_metadata for kernels + return self.kernel_info(repo_id, revision=revision, token=token, timeout=timeout) + case _: + raise ValueError("Unsupported repo type.") + return method( + repo_id, + revision=revision, + token=token, + timeout=timeout, + expand=expand, # type: ignore + files_metadata=files_metadata, + ) + + @validate_hf_hub_args + def repo_exists( + self, + repo_id: str, + *, + repo_type: str | None = None, + token: str | bool | None = None, + ) -> bool: + """ + Checks if a repository exists on the Hugging Face Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space, + `None` or `"model"` if getting repository info from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + True if the repository exists, False otherwise. + + Examples: + ```py + >>> from huggingface_hub import repo_exists + >>> repo_exists("google/gemma-7b") + True + >>> repo_exists("google/not-a-repo") + False + ``` + """ + try: + self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token) + return True + except GatedRepoError: + return True # we don't have access but it exists + except RepositoryNotFoundError: + return False + + @validate_hf_hub_args + def revision_exists( + self, + repo_id: str, + revision: str, + *, + repo_type: str | None = None, + token: str | bool | None = None, + ) -> bool: + """ + Checks if a specific revision exists on a repo on the Hugging Face Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`): + The revision of the repository to check. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space, + `None` or `"model"` if getting repository info from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + True if the repository and the revision exists, False otherwise. + + Examples: + ```py + >>> from huggingface_hub import revision_exists + >>> revision_exists("google/gemma-7b", "float16") + True + >>> revision_exists("google/gemma-7b", "not-a-revision") + False + ``` + """ + try: + self.repo_info(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token) + return True + except RevisionNotFoundError: + return False + except RepositoryNotFoundError: + return False + + @validate_hf_hub_args + def file_exists( + self, + repo_id: str, + filename: str, + *, + repo_type: str | None = None, + revision: str | None = None, + token: str | bool | None = None, + ) -> bool: + """ + Checks if a file exists in a repository on the Hugging Face Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + filename (`str`): + The name of the file to check, for example: + `"config.json"` + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if getting repository info from a dataset or a space, + `None` or `"model"` if getting repository info from a model. Default is `None`. + revision (`str`, *optional*): + The revision of the repository from which to get the information. Defaults to `"main"` branch. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + True if the file exists, False otherwise. + + Examples: + ```py + >>> from huggingface_hub import file_exists + >>> file_exists("bigcode/starcoder", "config.json") + True + >>> file_exists("bigcode/starcoder", "not-a-file") + False + >>> file_exists("bigcode/not-a-repo", "config.json") + False + ``` + """ + url = hf_hub_url( + repo_id=repo_id, repo_type=repo_type, revision=revision, filename=filename, endpoint=self.endpoint + ) + try: + if token is None: + token = self.token + get_hf_file_metadata(url, token=token) + return True + except GatedRepoError: # raise specifically on gated repo + raise + except (RepositoryNotFoundError, RemoteEntryNotFoundError, RevisionNotFoundError): + return False + + @validate_hf_hub_args + def list_repo_files( + self, + repo_id: str, + *, + revision: str | None = None, + repo_type: str | None = None, + token: str | bool | None = None, + ) -> list[str]: + """ + Get the list of files in a given repo. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + revision (`str`, *optional*): + The revision of the repository from which to get the information. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or space, `None` or `"model"` if uploading to + a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `list[str]`: the list of files in a given repository. + """ + return [ + f.rfilename + for f in self.list_repo_tree( + repo_id=repo_id, recursive=True, revision=revision, repo_type=repo_type, token=token + ) + if isinstance(f, RepoFile) + ] + + @validate_hf_hub_args + def list_repo_tree( + self, + repo_id: str, + path_in_repo: str | None = None, + *, + recursive: bool = False, + expand: bool = False, + revision: str | None = None, + repo_type: str | None = None, + token: str | bool | None = None, + ) -> Iterable[RepoFile | RepoFolder]: + """ + List a repo tree's files and folders and get information about them. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + path_in_repo (`str`, *optional*): + Relative path of the tree (folder) in the repo, for example: + `"checkpoints/1fec34a/results"`. Will default to the root tree (folder) of the repository. + recursive (`bool`, *optional*, defaults to `False`): + Whether to list tree's files and folders recursively. + expand (`bool`, *optional*, defaults to `False`): + Whether to fetch more information about the tree's files and folders (e.g. last commit and files' security scan results). This + operation is more expensive for the server so only 50 results are returned per page (instead of 1000). + As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it + takes to get the results. + revision (`str`, *optional*): + The revision of the repository from which to get the tree. Defaults to `"main"` branch. + repo_type (`str`, *optional*): + The type of the repository from which to get the tree (`"model"`, `"dataset"`, `"space"` or `"kernel"`). + Defaults to `"model"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[Union[RepoFile, RepoFolder]]`: + The information about the tree's files and folders, as an iterable of [`RepoFile`] and [`RepoFolder`] objects. The order of the files and folders is + not guaranteed. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + [`~utils.RemoteEntryNotFoundError`]: + If the tree (folder) does not exist (error 404) on the repo. + + Examples: + + Get information about a repo's tree. + ```py + >>> from huggingface_hub import list_repo_tree + >>> repo_tree = list_repo_tree("lysandre/arxiv-nlp") + >>> repo_tree + + >>> list(repo_tree) + [ + RepoFile(path='.gitattributes', size=391, blob_id='ae8c63daedbd4206d7d40126955d4e6ab1c80f8f', lfs=None, last_commit=None, security=None), + RepoFile(path='README.md', size=391, blob_id='43bd404b159de6fba7c2f4d3264347668d43af25', lfs=None, last_commit=None, security=None), + RepoFile(path='config.json', size=554, blob_id='2f9618c3a19b9a61add74f70bfb121335aeef666', lfs=None, last_commit=None, security=None), + RepoFile( + path='flax_model.msgpack', size=497764107, blob_id='8095a62ccb4d806da7666fcda07467e2d150218e', + lfs={'size': 497764107, 'sha256': 'd88b0d6a6ff9c3f8151f9d3228f57092aaea997f09af009eefd7373a77b5abb9', 'pointer_size': 134}, last_commit=None, security=None + ), + RepoFile(path='merges.txt', size=456318, blob_id='226b0752cac7789c48f0cb3ec53eda48b7be36cc', lfs=None, last_commit=None, security=None), + RepoFile( + path='pytorch_model.bin', size=548123560, blob_id='64eaa9c526867e404b68f2c5d66fd78e27026523', + lfs={'size': 548123560, 'sha256': '9be78edb5b928eba33aa88f431551348f7466ba9f5ef3daf1d552398722a5436', 'pointer_size': 134}, last_commit=None, security=None + ), + RepoFile(path='vocab.json', size=898669, blob_id='b00361fece0387ca34b4b8b8539ed830d644dbeb', lfs=None, last_commit=None, security=None)] + ] + ``` + + Get even more information about a repo's tree (last commit and files' security scan results) + ```py + >>> from huggingface_hub import list_repo_tree + >>> repo_tree = list_repo_tree("prompthero/openjourney-v4", expand=True) + >>> list(repo_tree) + [ + RepoFolder( + path='feature_extractor', + tree_id='aa536c4ea18073388b5b0bc791057a7296a00398', + last_commit={ + 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190', + 'title': 'Upload diffusers weights (#48)', + 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc) + } + ), + RepoFolder( + path='safety_checker', + tree_id='65aef9d787e5557373fdf714d6c34d4fcdd70440', + last_commit={ + 'oid': '47b62b20b20e06b9de610e840282b7e6c3d51190', + 'title': 'Upload diffusers weights (#48)', + 'date': datetime.datetime(2023, 3, 21, 9, 5, 27, tzinfo=datetime.timezone.utc) + } + ), + RepoFile( + path='model_index.json', + size=582, + blob_id='d3d7c1e8c3e78eeb1640b8e2041ee256e24c9ee1', + lfs=None, + last_commit={ + 'oid': 'b195ed2d503f3eb29637050a886d77bd81d35f0e', + 'title': 'Fix deprecation warning by changing `CLIPFeatureExtractor` to `CLIPImageProcessor`. (#54)', + 'date': datetime.datetime(2023, 5, 15, 21, 41, 59, tzinfo=datetime.timezone.utc) + }, + security={ + 'safe': True, + 'av_scan': {'virusFound': False, 'virusNames': None}, + 'pickle_import_scan': None + } + ) + ... + ] + ``` + """ + repo_type = repo_type or constants.REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION + headers = self._build_hf_headers(token=token) + + encoded_path_in_repo = "/" + quote(path_in_repo, safe="") if path_in_repo else "" + tree_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tree/{revision}{encoded_path_in_repo}" + for path_info in paginate(path=tree_url, headers=headers, params={"recursive": recursive, "expand": expand}): + yield (RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info)) + + @validate_hf_hub_args + def verify_repo_checksums( + self, + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + local_dir: str | Path | None = None, + cache_dir: str | Path | None = None, + token: str | bool | None = None, + ) -> FolderVerification: + """ + Verify local files for a repo against Hub checksums. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + repo_type (`str`, *optional*): + The type of the repository from which to get the tree (`"model"`, `"dataset"` or `"space"`. + Defaults to `"model"`. + revision (`str`, *optional*): + The revision of the repository from which to get the tree. Defaults to `"main"` branch. + local_dir (`str` or `Path`, *optional*): + The local directory to verify. + cache_dir (`str` or `Path`, *optional*): + The cache directory to verify. + token (Union[bool, str, None], optional): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`FolderVerification`]: a structured result containing the verification details. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + + """ + + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + + if local_dir is not None and cache_dir is not None: + raise ValueError("Pass either `local_dir` or `cache_dir`, not both.") + + root, remote_revision = resolve_local_root( + repo_id=repo_id, + repo_type=repo_type, + revision=revision, + cache_dir=Path(cache_dir) if cache_dir is not None else None, + local_dir=Path(local_dir) if local_dir is not None else None, + ) + local_by_path = collect_local_files(root) + + # get remote entries (only files, not folders) + remote_by_path: dict[str, RepoFile] = {} + for entry in self.list_repo_tree( + repo_id=repo_id, recursive=True, revision=remote_revision, repo_type=repo_type, token=token + ): + if isinstance(entry, RepoFile): + remote_by_path[entry.path] = entry + + return verify_maps( + remote_by_path=remote_by_path, + local_by_path=local_by_path, + revision=remote_revision, + verified_path=root, + ) + + @validate_hf_hub_args + def list_repo_refs( + self, + repo_id: str, + *, + repo_type: str | None = None, + include_pull_requests: bool = False, + token: str | bool | None = None, + ) -> GitRefs: + """ + Get the list of refs of a given repo (both tags and branches). + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"`, `"space"` or `"kernel"` if listing refs from a dataset, a Space or a Kernel, + `None` or `"model"` if listing from a model. Default is `None`. + include_pull_requests (`bool`, *optional*): + Whether to include refs from pull requests in the list. Defaults to `False`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> api.list_repo_refs("gpt2") + GitRefs(branches=[GitRefInfo(name='main', ref='refs/heads/main', target_commit='e7da7f221d5bf496a48136c0cd264e630fe9fcc8')], converts=[], tags=[]) + + >>> api.list_repo_refs("bigcode/the-stack", repo_type='dataset') + GitRefs( + branches=[ + GitRefInfo(name='main', ref='refs/heads/main', target_commit='18edc1591d9ce72aa82f56c4431b3c969b210ae3'), + GitRefInfo(name='v1.1.a1', ref='refs/heads/v1.1.a1', target_commit='f9826b862d1567f3822d3d25649b0d6d22ace714') + ], + converts=[], + tags=[ + GitRefInfo(name='v1.0', ref='refs/tags/v1.0', target_commit='c37a8cd1e382064d8aced5e05543c5f7753834da') + ] + ) + ``` + + Returns: + [`GitRefs`]: object containing all information about branches and tags for a + repo on the Hub. + """ + repo_type = repo_type or constants.REPO_TYPE_MODEL + response = get_session().get( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/refs", + headers=self._build_hf_headers(token=token), + params={"include_prs": 1} if include_pull_requests else {}, + ) + hf_raise_for_status(response) + data = response.json() + + def _format_as_git_ref_info(item: dict) -> GitRefInfo: + return GitRefInfo(name=item["name"], ref=item["ref"], target_commit=item["targetCommit"]) + + return GitRefs( + branches=[_format_as_git_ref_info(item) for item in data["branches"]], + converts=[_format_as_git_ref_info(item) for item in data["converts"]], + tags=[_format_as_git_ref_info(item) for item in data["tags"]], + pull_requests=[_format_as_git_ref_info(item) for item in data["pullRequests"]] + if include_pull_requests + else None, + ) + + @validate_hf_hub_args + def list_repo_commits( + self, + repo_id: str, + *, + repo_type: str | None = None, + token: bool | str | None = None, + revision: str | None = None, + formatted: bool = False, + ) -> list[GitCommitInfo]: + """ + Get the list of commits of a given revision for a repo on the Hub. + + Commits are sorted by date (last commit first). + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if + listing from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + formatted (`bool`): + Whether to return the HTML-formatted title and description of the commits. Defaults to False. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + + # Commits are sorted by date (last commit first) + >>> initial_commit = api.list_repo_commits("gpt2")[-1] + + # Initial commit is always a system commit containing the `.gitattributes` file. + >>> initial_commit + GitCommitInfo( + commit_id='9b865efde13a30c13e0a33e536cf3e4a5a9d71d8', + authors=['system'], + created_at=datetime.datetime(2019, 2, 18, 10, 36, 15, tzinfo=datetime.timezone.utc), + title='initial commit', + message='', + formatted_title=None, + formatted_message=None + ) + + # Create an empty branch by deriving from initial commit + >>> api.create_branch("gpt2", "new_empty_branch", revision=initial_commit.commit_id) + ``` + + Returns: + list[[`GitCommitInfo`]]: list of objects containing information about the commits for a repo on the Hub. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + """ + repo_type = repo_type or constants.REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION + + # Paginate over results and return the list of commits. + return [ + GitCommitInfo( + commit_id=item["id"], + authors=[author["user"] for author in item["authors"]], + created_at=parse_datetime(item["date"]), + title=item["title"], + message=item["message"], + formatted_title=item.get("formatted", {}).get("title"), + formatted_message=item.get("formatted", {}).get("message"), + ) + for item in paginate( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/commits/{revision}", + headers=self._build_hf_headers(token=token), + params={"expand[]": "formatted"} if formatted else {}, + ) + ] + + @validate_hf_hub_args + def get_paths_info( + self, + repo_id: str, + paths: list[str] | str, + *, + expand: bool = False, + revision: str | None = None, + repo_type: str | None = None, + token: str | bool | None = None, + ) -> list[RepoFile | RepoFolder]: + """ + Get information about a repo's paths. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + paths (`Union[list[str], str]`, *optional*): + The paths to get information about. If a path do not exist, it is ignored without raising + an exception. + expand (`bool`, *optional*, defaults to `False`): + Whether to fetch more information about the paths (e.g. last commit and files' security scan results). This + operation is more expensive for the server so only 50 results are returned per page (instead of 1000). + As pagination is implemented in `huggingface_hub`, this is transparent for you except for the time it + takes to get the results. + revision (`str`, *optional*): + The revision of the repository from which to get the information. Defaults to `"main"` branch. + repo_type (`str`, *optional*): + The type of the repository from which to get the information (`"model"`, `"dataset"` or `"space"`. + Defaults to `"model"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `list[Union[RepoFile, RepoFolder]]`: + The information about the paths, as a list of [`RepoFile`] and [`RepoFolder`] objects. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + + Example: + ```py + >>> from huggingface_hub import get_paths_info + >>> paths_info = get_paths_info("allenai/c4", ["README.md", "en"], repo_type="dataset") + >>> paths_info + [ + RepoFile(path='README.md', size=2379, blob_id='f84cb4c97182890fc1dbdeaf1a6a468fd27b4fff', lfs=None, last_commit=None, security=None), + RepoFolder(path='en', tree_id='dc943c4c40f53d02b31ced1defa7e5f438d5862e', last_commit=None) + ] + ``` + """ + repo_type = repo_type or constants.REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION + headers = self._build_hf_headers(token=token) + + response = get_session().post( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/paths-info/{revision}", + data={ + "paths": paths if isinstance(paths, list) else [paths], + "expand": expand, + }, + headers=headers, + ) + hf_raise_for_status(response) + paths_info = response.json() + return [ + RepoFile(**path_info) if path_info["type"] == "file" else RepoFolder(**path_info) + for path_info in paths_info + ] + + @validate_hf_hub_args + def super_squash_history( + self, + repo_id: str, + *, + branch: str | None = None, + commit_message: str | None = None, + repo_type: str | None = None, + token: str | bool | None = None, + ) -> None: + """Squash commit history on a branch for a repo on the Hub. + + Squashing the repo history is useful when you know you'll make hundreds of commits and you don't want to + clutter the history. Squashing commits can only be performed from the head of a branch. + + > [!WARNING] + > Once squashed, the commit history cannot be retrieved. This is a non-revertible operation. + + > [!WARNING] + > Once the history of a branch has been squashed, it is not possible to merge it back into another branch since + > their history will have diverged. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a `/`. + branch (`str`, *optional*): + The branch to squash. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The commit message to use for the squashed commit. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if listing commits from a dataset or a Space, `None` or `"model"` if + listing from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private but not authenticated or repo + does not exist. + [`~utils.RevisionNotFoundError`]: + If the branch to squash cannot be found. + [`~utils.BadRequestError`]: + If invalid reference for a branch. You cannot squash history on tags. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + + # Create repo + >>> repo_id = api.create_repo("test-squash").repo_id + + # Make a lot of commits. + >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"content") + >>> api.upload_file(repo_id=repo_id, path_in_repo="lfs.bin", path_or_fileobj=b"content") + >>> api.upload_file(repo_id=repo_id, path_in_repo="file.txt", path_or_fileobj=b"another_content") + + # Squash history + >>> api.super_squash_history(repo_id=repo_id) + ``` + """ + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + if repo_type not in constants.REPO_TYPES: + raise ValueError("Invalid repo type") + if branch is None: + branch = constants.DEFAULT_REVISION + + # Prepare request + url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/super-squash/{quote(branch, safe='')}" + headers = self._build_hf_headers(token=token) + commit_message = commit_message or f"Super-squash branch '{branch}' using huggingface_hub" + + # Super-squash + response = get_session().post(url=url, headers=headers, json={"message": commit_message}) + hf_raise_for_status(response) + + @validate_hf_hub_args + def list_lfs_files( + self, + repo_id: str, + *, + repo_type: str | None = None, + token: bool | str | None = None, + ) -> Iterable[LFSFileInfo]: + """ + List all LFS files in a repo on the Hub. + + This is primarily useful to count how much storage a repo is using and to eventually clean up large files + with [`permanently_delete_lfs_files`]. Note that this would be a permanent action that will affect all commits + referencing this deleted files and that cannot be undone. + + Args: + repo_id (`str`): + The repository for which you are listing LFS files. + repo_type (`str`, *optional*): + Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or + `"model"` if listing from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[LFSFileInfo]`: An iterator of [`LFSFileInfo`] objects. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> lfs_files = api.list_lfs_files("username/my-cool-repo") + + # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`. + # e.g. select only LFS files in the "checkpoints" folder + >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/")) + + # Permanently delete LFS files + >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete) + ``` + """ + # Prepare request + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/lfs-files" + headers = self._build_hf_headers(token=token) + + # Paginate over LFS items + for item in paginate(url, params={}, headers=headers): + yield LFSFileInfo(**item) + + @validate_hf_hub_args + def permanently_delete_lfs_files( + self, + repo_id: str, + lfs_files: Iterable[LFSFileInfo], + *, + rewrite_history: bool = True, + repo_type: str | None = None, + token: bool | str | None = None, + ) -> None: + """ + Permanently delete LFS files from a repo on the Hub. + + > [!WARNING] + > This is a permanent action that will affect all commits referencing the deleted files and might corrupt your + > repository. This is a non-revertible operation. Use it only if you know what you are doing. + + Args: + repo_id (`str`): + The repository for which you are listing LFS files. + lfs_files (`Iterable[LFSFileInfo]`): + An iterable of [`LFSFileInfo`] items to permanently delete from the repo. Use [`list_lfs_files`] to list + all LFS files from a repo. + rewrite_history (`bool`, *optional*, default to `True`): + Whether to rewrite repository history to remove file pointers referencing the deleted LFS files (recommended). + repo_type (`str`, *optional*): + Type of repository. Set to `"dataset"` or `"space"` if listing from a dataset or space, `None` or + `"model"` if listing from a model. Default is `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + ```py + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> lfs_files = api.list_lfs_files("username/my-cool-repo") + + # Filter files files to delete based on a combination of `filename`, `pushed_at`, `ref` or `size`. + # e.g. select only LFS files in the "checkpoints" folder + >>> lfs_files_to_delete = (lfs_file for lfs_file in lfs_files if lfs_file.filename.startswith("checkpoints/")) + + # Permanently delete LFS files + >>> api.permanently_delete_lfs_files("username/my-cool-repo", lfs_files_to_delete) + ``` + """ + # Prepare request + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/lfs-files/batch" + headers = self._build_hf_headers(token=token) + + # Delete LFS items by batches of 1000 + for batch in chunk_iterable(lfs_files, 1000): + shas = [item.file_oid for item in batch] + if len(shas) == 0: + return + payload = { + "deletions": { + "sha": shas, + "rewriteHistory": rewrite_history, + } + } + response = get_session().post(url, headers=headers, json=payload) + hf_raise_for_status(response) + + @_deprecate_arguments( + version="2.0", + deprecated_args={"space_storage"}, + custom_message="Use `space_volumes` to mount volumes on a Space.", + ) + @validate_hf_hub_args + def create_repo( + self, + repo_id: str, + *, + token: str | bool | None = None, + private: bool | None = None, + visibility: RepoVisibility_T | None = None, + repo_type: str | None = None, + exist_ok: bool = False, + resource_group_id: str | None = None, + space_sdk: str | None = None, + space_hardware: SpaceHardware | None = None, + space_storage: SpaceStorage | None = None, + space_sleep_time: int | None = None, + space_secrets: list[dict[str, str]] | None = None, + space_variables: list[dict[str, str]] | None = None, + space_volumes: list[Volume] | None = None, + ) -> RepoUrl: + """Create an empty repo on the HuggingFace Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + private (`bool`, *optional*): + Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists. Cannot be passed together with `visibility`. + visibility (`Literal["public", "private", "protected"]`, *optional*): + Visibility of the repo. Can be `"public"` or `"private"`, or `"protected"` for Spaces. If `None` + (default), the repo will be public unless the organization's default is private. This value is ignored + if the repo already exists. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if repo already exists. + resource_group_id (`str`, *optional*): + Resource group in which to create the repo. Resource groups is only available for Enterprise Hub organizations and + allow to define which members of the organization can access the resource. The ID of a resource group + can be found in the URL of the resource's page on the Hub (e.g. `"66670e5163145ca562cb1988"`). + To learn more about resource groups, see https://huggingface.co/docs/hub/en/security-resource-groups. + space_sdk (`str`, *optional*): + Choice of SDK to use if repo_type is "space". Can be "streamlit", "gradio", "docker", or "static". + space_hardware (`SpaceHardware` or `str`, *optional*): + Choice of Hardware if repo_type is "space". See [`SpaceHardware`] for a complete list. + space_storage (`SpaceStorage` or `str`, *optional*): + Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list. + space_sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want + your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure + the sleep time (value is fixed to 48 hours of inactivity). + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + space_secrets (`list[dict[str, str]]`, *optional*): + A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + space_variables (`list[dict[str, str]]`, *optional*): + A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables. + space_volumes (`list[Volume]`, *optional*): + A list of [`Volume`] objects to mount in the Space at creation time. Each volume has a `type` + (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), a `source` (repo or bucket ID), a `mount_path` + (path inside the container), and optional `revision`, `read_only`, and `path` fields. + Only applicable if repo_type is "space". + + Returns: + [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing + attributes like `endpoint`, `repo_type` and `repo_id`. + """ + organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id) + + path = f"{self.endpoint}/api/repos/create" + + if repo_type not in constants.REPO_TYPES_WITH_KERNEL: + raise ValueError("Invalid repo type") + + resolved_visibility = _resolve_repo_visibility(private=private, visibility=visibility, repo_type=repo_type) + + payload: dict[str, Any] = {"name": name, "organization": organization} + if resolved_visibility is not None: + payload["visibility"] = resolved_visibility + if repo_type is not None: + payload["type"] = repo_type + if repo_type == "space": + if space_sdk is None: + raise ValueError( + "No space_sdk provided. `create_repo` expects space_sdk to be one" + f" of {constants.SPACES_SDK_TYPES} when repo_type is 'space'`" + ) + if space_sdk not in constants.SPACES_SDK_TYPES: + raise ValueError(f"Invalid space_sdk. Please choose one of {constants.SPACES_SDK_TYPES}.") + payload["sdk"] = space_sdk + + if space_sdk is not None and repo_type != "space": + warnings.warn("Ignoring provided space_sdk because repo_type is not 'space'.") + + space_args: list[tuple[str, str, Any]] = [ + # input arg, payload key, value + ("space_hardware", "hardware", space_hardware), + ("space_storage", "storageTier", space_storage), + ("space_sleep_time", "sleepTimeSeconds", space_sleep_time), + ("space_secrets", "secrets", space_secrets), + ("space_variables", "variables", space_variables), + ("space_volumes", "volumes", [v.to_dict() for v in space_volumes] if space_volumes else None), + ] + + if repo_type == constants.REPO_TYPE_SPACE: + for _, key, value in space_args: + if value is not None: + payload[key] = value + if space_sleep_time is not None and space_hardware == SpaceHardware.CPU_BASIC: + warnings.warn( + "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more" + " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if" + " you want to set a custom sleep time, you need to upgrade to a paid Hardware.", + UserWarning, + ) + else: + if provided_space_args := [arg for arg, _, value in space_args if value is not None]: + warnings.warn(f"Ignoring provided {', '.join(provided_space_args)} because repo_type is not 'space'.") + + if resource_group_id is not None: + payload["resourceGroupId"] = resource_group_id + + headers = self._build_hf_headers(token=token) + while True: + r = get_session().post(path, headers=headers, json=payload) + if r.status_code == 409 and "Cannot create repo: another conflicting operation is in progress" in r.text: + # Since https://github.com/huggingface/moon-landing/pull/7272 (private repo), it is not possible to + # concurrently create repos on the Hub for a same user. This is rarely an issue, except when running + # tests. To avoid any inconvenience, we retry to create the repo for this specific error. + # NOTE: This could have being fixed directly in the tests but adding it here should fixed CIs for all + # dependent libraries. + # NOTE: If a fix is implemented server-side, we should be able to remove this retry mechanism. + logger.debug("Create repo failed due to a concurrency issue. Retrying...") + continue + break + + try: + hf_raise_for_status(r) + except HfHubHTTPError as err: + if exist_ok and err.response.status_code == 409: + # Repo already exists and `exist_ok=True` + pass + elif exist_ok and err.response.status_code == 403: + # No write permission on the namespace but repo might already exist + try: + self.repo_info(repo_id=repo_id, repo_type=repo_type, token=token) + if repo_type is None or repo_type == constants.REPO_TYPE_MODEL: + return RepoUrl(f"{self.endpoint}/{repo_id}") + return RepoUrl(f"{self.endpoint}/{constants.REPO_TYPES_URL_PREFIXES[repo_type]}{repo_id}") + except HfHubHTTPError: + raise err + else: + raise + + d = r.json() + return RepoUrl(d["url"], endpoint=self.endpoint) + + @validate_hf_hub_args + def delete_repo( + self, + repo_id: str, + *, + token: str | bool | None = None, + repo_type: str | None = None, + missing_ok: bool = False, + ) -> None: + """ + Delete a repo from the HuggingFace Hub. CAUTION: this is irreversible. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. + missing_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if repo does not exist. + + Raises: + [`~utils.RepositoryNotFoundError`] + If the repository to delete from cannot be found and `missing_ok` is set to False (default). + """ + organization, name = repo_id.split("/") if "/" in repo_id else (None, repo_id) + + path = f"{self.endpoint}/api/repos/delete" + + if repo_type not in constants.REPO_TYPES_WITH_KERNEL: + raise ValueError("Invalid repo type") + + json = {"name": name, "organization": organization} + if repo_type is not None: + json["type"] = repo_type + + headers = self._build_hf_headers(token=token) + r = get_session().request("DELETE", path, headers=headers, json=json) + reset_xet_connection_info_cache_for_repo(repo_type, repo_id) + try: + hf_raise_for_status(r) + except RepositoryNotFoundError: + if not missing_ok: + raise + + @validate_hf_hub_args + def update_repo_settings( + self, + repo_id: str, + *, + gated: Literal["auto", "manual", False] | None = None, + private: bool | None = None, + visibility: RepoVisibility_T | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + ) -> None: + """ + Update the settings of a repository, including gated access and visibility. + + To give more control over how repos are used, the Hub allows repo authors to enable + access requests for their repos, and also to change the visibility of the repo. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated by a /. + gated (`Literal["auto", "manual", False]`, *optional*): + The gated status for the repository. If set to `None` (default), the `gated` setting of the repository won't be updated. + * "auto": The repository is gated, and access requests are automatically approved or denied based on predefined criteria. + * "manual": The repository is gated, and access requests require manual approval. + * False : The repository is not gated, and anyone can access it. + private (`bool`, *optional*): + Whether the repository should be private. Cannot be passed together with `visibility`. + visibility (`Literal["public", "private", "protected"]`, *optional*): + Visibility of the repository. Can be `"public"` or `"private"`, or `"protected"` for Spaces. + token (`Union[str, bool, None]`, *optional*): + A valid user access token (string). Defaults to the locally saved token, + which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass False. + repo_type (`str`, *optional*): + The type of the repository to update settings from (`"model"`, `"dataset"` or `"space"`). + Defaults to `"model"`. + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If gated is not one of "auto", "manual", or False. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If repo_type is not one of the values in constants.REPO_TYPES. + [`~utils.HfHubHTTPError`]: + If the request to the Hugging Face Hub API fails. + [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + """ + + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL # default repo type + + resolved_visibility = _resolve_repo_visibility(private=private, visibility=visibility, repo_type=repo_type) + + # Prepare the JSON payload for the PUT request + payload: dict = {} + + if gated is not None: + if gated not in ["auto", "manual", False]: + raise ValueError(f"Invalid gated status, must be one of 'auto', 'manual', or False. Got '{gated}'.") + payload["gated"] = gated + + if resolved_visibility is not None: + payload["visibility"] = resolved_visibility + + if len(payload) == 0: + raise ValueError("At least one setting must be updated.") + + # Build headers + headers = self._build_hf_headers(token=token) + + r = get_session().put( + url=f"{self.endpoint}/api/{repo_type}s/{repo_id}/settings", + headers=headers, + json=payload, + ) + hf_raise_for_status(r) + + def move_repo( + self, + from_id: str, + to_id: str, + *, + repo_type: str | None = None, + token: str | bool | None = None, + ): + """ + Moving a repository from namespace1/repo_name1 to namespace2/repo_name2 + + Note there are certain limitations. For more information about moving + repositories, please see + https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo. + + Args: + from_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. Original repository identifier. + to_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. Final repository identifier. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + > [!TIP] + > Raises the following errors: + > + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + if len(from_id.split("/")) != 2: + raise ValueError(f"Invalid repo_id: {from_id}. It should have a namespace (:namespace:/:repo_name:)") + + if len(to_id.split("/")) != 2: + raise ValueError(f"Invalid repo_id: {to_id}. It should have a namespace (:namespace:/:repo_name:)") + + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL # Hub won't accept `None`. + + json = {"fromRepo": from_id, "toRepo": to_id, "type": repo_type} + + path = f"{self.endpoint}/api/repos/move" + headers = self._build_hf_headers(token=token) + r = get_session().post(path, headers=headers, json=json) + try: + hf_raise_for_status(r) + except HfHubHTTPError as e: + e.append_to_message( + "\nFor additional documentation please see" + " https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo." + ) + raise + + @overload + def create_commit( # type: ignore + self, + repo_id: str, + operations: Iterable[CommitOperation], + *, + commit_message: str, + commit_description: str | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + num_threads: int = 5, + parent_commit: str | None = None, + run_as_future: Literal[False] = ..., + _hot_reload: bool | None = None, + ) -> CommitInfo: ... + + @overload + def create_commit( + self, + repo_id: str, + operations: Iterable[CommitOperation], + *, + commit_message: str, + commit_description: str | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + num_threads: int = 5, + parent_commit: str | None = None, + run_as_future: Literal[True] = ..., + _hot_reload: bool | None = None, + ) -> Future[CommitInfo]: ... + + @validate_hf_hub_args + @future_compatible + def create_commit( + self, + repo_id: str, + operations: Iterable[CommitOperation], + *, + commit_message: str, + commit_description: str | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + num_threads: int = 5, + parent_commit: str | None = None, + run_as_future: bool = False, + _hot_reload: bool | None = None, + ) -> CommitInfo | Future[CommitInfo]: + """ + Creates a commit in the given repo, deleting & uploading files as needed. + + > [!WARNING] + > The input list of `CommitOperation` will be mutated during the commit process. Do not reuse the same objects + > for multiple commits. + + > [!WARNING] + > `create_commit` assumes that the repo already exists on the Hub. If you get a + > Client error 404, please make sure you are authenticated, that your token has the required permissions, + > and that `repo_id` and `repo_type` are set correctly. If repo does not exist, + > create it first using [`~hf_api.create_repo`]. + + > [!WARNING] + > `create_commit` is limited to 25k LFS files and a 1GB payload for regular files. + + Args: + repo_id (`str`): + The repository in which the commit will be created, for example: + `"username/custom_transformers"` + + operations (`Iterable` of [`~hf_api.CommitOperation`]): + An iterable of operations to include in the commit, either: + + - [`~hf_api.CommitOperationAdd`] to upload a file + - [`~hf_api.CommitOperationDelete`] to delete a file + - [`~hf_api.CommitOperationCopy`] to copy a file + + Operation objects will be mutated to include information relative to the upload. Do not reuse the + same objects for multiple commits. + + commit_message (`str`): + The summary (first line) of the commit that will be created. + + commit_description (`str`, *optional*): + The description of the commit that will be created + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + + num_threads (`int`, *optional*): + Number of concurrent threads for uploading files. Defaults to 5. + Setting it to 2 means at most 2 files will be uploaded concurrently. + + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. + Shorthands (7 first characters) are also supported. If specified and `create_pr` is `False`, + the commit will fail if `revision` does not point to `parent_commit`. If specified and `create_pr` + is `True`, the pull request will be created from `parent_commit`. Specifying `parent_commit` + ensures the repo has not changed before committing the changes, and can be especially useful + if the repo is updated / committed to concurrently. + run_as_future (`bool`, *optional*): + Whether or not to run this method in the background. Background jobs are run sequentially without + blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) + object. Defaults to `False`. + + Returns: + [`CommitInfo`] or `Future`: + Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit + url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will + contain the result when executed. + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If commit message is empty. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If parent commit is not a valid commit OID. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If a README.md file with an invalid metadata section is committed. In this case, the commit will fail + early, before trying to upload any file. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `create_pr` is `True` and revision is neither `None` nor `"main"`. + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + """ + if parent_commit is not None and not constants.REGEX_COMMIT_OID.fullmatch(parent_commit): + raise ValueError( + f"`parent_commit` is not a valid commit OID. It must match the following regex: {constants.REGEX_COMMIT_OID}" + ) + + if commit_message is None or len(commit_message) == 0: + raise ValueError("`commit_message` can't be empty, please pass a value.") + + commit_description = commit_description if commit_description is not None else "" + repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + unquoted_revision = revision or constants.DEFAULT_REVISION + revision = quote(unquoted_revision, safe="") + create_pr = create_pr if create_pr is not None else False + _hot_reload = _hot_reload if _hot_reload is not None else False + + headers = self._build_hf_headers(token=token) + + operations = list(operations) + additions = [op for op in operations if isinstance(op, CommitOperationAdd)] + copies = [op for op in operations if isinstance(op, CommitOperationCopy)] + nb_additions = len(additions) + nb_copies = len(copies) + nb_deletions = len(operations) - nb_additions - nb_copies + + for addition in additions: + if addition._is_committed: + raise ValueError( + f"CommitOperationAdd {addition} has already being committed and cannot be reused. Please create a" + " new CommitOperationAdd object if you want to create a new commit." + ) + + if repo_type != "dataset": + for addition in additions: + if addition.path_in_repo.endswith((".arrow", ".parquet")): + warnings.warn( + f"It seems that you are about to commit a data file ({addition.path_in_repo}) to a {repo_type}" + " repository. You are sure this is intended? If you are trying to upload a dataset, please" + " set `repo_type='dataset'` or `--repo-type=dataset` in a CLI." + ) + + logger.debug( + f"About to commit to the hub: {len(additions)} addition(s), {len(copies)} copie(s) and" + f" {nb_deletions} deletion(s)." + ) + + # If updating a README.md file, make sure the metadata format is valid + # It's better to fail early than to fail after all the files have been uploaded. + for addition in additions: + if addition.path_in_repo == "README.md": + with addition.as_file() as file: + content = file.read().decode() + self._validate_yaml(content, repo_type=repo_type, token=token) + # Skip other additions after `README.md` has been processed + break + + # If updating twice the same file or update then delete a file in a single commit + _warn_on_overwriting_operations(operations) + + self.preupload_lfs_files( + repo_id=repo_id, + additions=additions, + token=token, + repo_type=repo_type, + revision=unquoted_revision, # first-class methods take unquoted revision + create_pr=create_pr, + num_threads=num_threads, + free_memory=False, # do not remove `CommitOperationAdd.path_or_fileobj` on LFS files for "normal" users + ) + + files_to_copy = _fetch_files_to_copy( + copies=copies, + repo_type=repo_type, + repo_id=repo_id, + headers=headers, + revision=unquoted_revision, + endpoint=self.endpoint, + ) + # Remove no-op operations (files that have not changed) + operations_without_no_op = [] + for operation in operations: + if ( + isinstance(operation, CommitOperationAdd) + and operation._remote_oid is not None + and operation._remote_oid == operation._local_oid + ): + # File already exists on the Hub and has not changed: we can skip it. + logger.debug(f"Skipping upload for '{operation.path_in_repo}' as the file has not changed.") + continue + if ( + isinstance(operation, CommitOperationCopy) + and operation._dest_oid is not None + and operation._dest_oid == operation._src_oid + ): + # Source and destination files are identical - skip + logger.debug( + f"Skipping copy for '{operation.src_path_in_repo}' -> '{operation.path_in_repo}' as the content of the source file is the same as the destination file." + ) + continue + operations_without_no_op.append(operation) + if len(operations) != len(operations_without_no_op): + logger.info( + f"Removing {len(operations) - len(operations_without_no_op)} file(s) from commit that have not changed." + ) + + # Return early if empty commit + if len(operations_without_no_op) == 0: + logger.warning("No files have been modified since last commit. Skipping to prevent empty commit.") + + # Get latest commit info + try: + info = self.repo_info(repo_id=repo_id, repo_type=repo_type, revision=unquoted_revision, token=token) + except RepositoryNotFoundError as e: + e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE) + raise + + # Return commit info based on latest commit + url_prefix = self.endpoint + if repo_type is not None and repo_type != constants.REPO_TYPE_MODEL: + url_prefix = f"{url_prefix}/{repo_type}s" + return CommitInfo( + commit_url=f"{url_prefix}/{repo_id}/commit/{info.sha}", + commit_message=commit_message, + commit_description=commit_description, + oid=info.sha, # type: ignore + _endpoint=self.endpoint, + ) + + commit_payload = _prepare_commit_payload( + operations=operations, + files_to_copy=files_to_copy, + commit_message=commit_message, + commit_description=commit_description, + parent_commit=parent_commit, + ) + commit_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/commit/{revision}" + + def _payload_as_ndjson() -> Iterable[bytes]: + for item in commit_payload: + yield json.dumps(item).encode() + yield b"\n" + + headers = { + # See https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073 + "Content-Type": "application/x-ndjson", + **headers, + } + data = b"".join(_payload_as_ndjson()) + + params: dict[str, Any] = {} + if create_pr: + params["create_pr"] = "1" + if _hot_reload: + params["hot_reload"] = "1" + + try: + commit_resp = get_session().post(url=commit_url, headers=headers, content=data, params=params) + hf_raise_for_status(commit_resp, endpoint_name="commit") + except RepositoryNotFoundError as e: + e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE) + raise + except RemoteEntryNotFoundError as e: + if nb_deletions > 0 and "A file with this name doesn't exist" in str(e): + e.append_to_message( + "\nMake sure to differentiate file and folder paths in delete" + " operations with a trailing '/' or using `is_folder=True/False`." + ) + raise + + # Mark additions as committed (cannot be reused in another commit) + for addition in additions: + addition._is_committed = True + + commit_data = commit_resp.json() + return CommitInfo( + commit_url=commit_data["commitUrl"], + commit_message=commit_message, + commit_description=commit_description, + oid=commit_data["commitOid"], + pr_url=commit_data["pullRequestUrl"] if create_pr else None, + _endpoint=self.endpoint, + ) + + def preupload_lfs_files( + self, + repo_id: str, + additions: Iterable[CommitOperationAdd], + *, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + num_threads: int = 5, + free_memory: bool = True, + gitignore_content: str | None = None, + ): + """Pre-upload LFS files to S3 in preparation on a future commit. + + This method is useful if you are generating the files to upload on-the-fly and you don't want to store them + in memory before uploading them all at once. + + > [!WARNING] + > This is a power-user method. You shouldn't need to call it directly to make a normal commit. + > Use [`create_commit`] directly instead. + + > [!WARNING] + > Commit operations will be mutated during the process. In particular, the attached `path_or_fileobj` will be + > removed after the upload to save memory (and replaced by an empty `bytes` object). Do not reuse the same + > objects except to pass them to [`create_commit`]. If you don't want to remove the attached content from the + > commit operation object, pass `free_memory=False`. + + Args: + repo_id (`str`): + The repository in which you will commit the files, for example: `"username/custom_transformers"`. + + operations (`Iterable` of [`CommitOperationAdd`]): + The list of files to upload. Warning: the objects in this list will be mutated to include information + relative to the upload. Do not reuse the same objects for multiple commits. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + The type of repository to upload to (e.g. `"model"` -default-, `"dataset"` or `"space"`). + + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + + create_pr (`boolean`, *optional*): + Whether or not you plan to create a Pull Request with that commit. Defaults to `False`. + + num_threads (`int`, *optional*): + Number of concurrent threads for uploading files. Defaults to 5. + Setting it to 2 means at most 2 files will be uploaded concurrently. + + gitignore_content (`str`, *optional*): + The content of the `.gitignore` file to know which files should be ignored. The order of priority + is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present + in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub + (if any). + + Example: + ```py + >>> from huggingface_hub import CommitOperationAdd, preupload_lfs_files, create_commit, create_repo + + >>> repo_id = create_repo("test_preupload").repo_id + + # Generate and preupload LFS files one by one + >>> operations = [] # List of all `CommitOperationAdd` objects that will be generated + >>> for i in range(5): + ... content = ... # generate binary content + ... addition = CommitOperationAdd(path_in_repo=f"shard_{i}_of_5.bin", path_or_fileobj=content) + ... preupload_lfs_files(repo_id, additions=[addition]) # upload + free memory + ... operations.append(addition) + + # Create commit + >>> create_commit(repo_id, operations=operations, commit_message="Commit all shards") + ``` + """ + repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION + create_pr = create_pr if create_pr is not None else False + headers = self._build_hf_headers(token=token) + + # Check if a `gitignore` file is being committed to the Hub. + additions = list(additions) + if gitignore_content is None: + for addition in additions: + if addition.path_in_repo == ".gitignore": + with addition.as_file() as f: + gitignore_content = f.read().decode() + break + + # Filter out already uploaded files + new_additions = [addition for addition in additions if not addition._is_uploaded] + + # Check which new files are LFS + # For some items, we might have already fetched the upload mode (in case of upload_large_folder) + additions_no_upload_mode = [addition for addition in new_additions if addition._upload_mode is None] + if len(additions_no_upload_mode) > 0: + try: + _fetch_upload_modes( + additions=additions_no_upload_mode, + repo_type=repo_type, + repo_id=repo_id, + headers=headers, + revision=revision, + endpoint=self.endpoint, + create_pr=create_pr or False, + gitignore_content=gitignore_content, + ) + except RepositoryNotFoundError as e: + e.append_to_message(_CREATE_COMMIT_NO_REPO_ERROR_MESSAGE) + raise + + # Filter out regular files + new_lfs_additions = [addition for addition in new_additions if addition._upload_mode == "lfs"] + + # Filter out files listed in .gitignore + new_lfs_additions_to_upload = [] + for addition in new_lfs_additions: + if addition._should_ignore: + logger.debug(f"Skipping upload for LFS file '{addition.path_in_repo}' (ignored by gitignore file).") + else: + new_lfs_additions_to_upload.append(addition) + if len(new_lfs_additions) != len(new_lfs_additions_to_upload): + logger.info( + f"Skipped upload for {len(new_lfs_additions) - len(new_lfs_additions_to_upload)} LFS file(s) " + "(ignored by gitignore file)." + ) + # If no LFS files remain to upload, keep previous behavior and log explicitly + if len(new_lfs_additions_to_upload) == 0: + logger.debug("No LFS files to upload.") + return + # Prepare upload parameters + upload_kwargs = { + "additions": new_lfs_additions_to_upload, + "repo_type": repo_type, + "repo_id": repo_id, + "headers": headers, + "endpoint": self.endpoint, + # If `create_pr`, we don't want to check user permission on the revision as users with read permission + # should still be able to create PRs even if they don't have write permission on the target branch of the + # PR (i.e. `revision`). + "revision": revision if not create_pr else None, + } + _upload_files(**upload_kwargs, num_threads=num_threads, create_pr=create_pr) # type: ignore [arg-type] + for addition in new_lfs_additions_to_upload: + addition._is_uploaded = True + if free_memory: + addition.path_or_fileobj = b"" + + @overload + def upload_file( # type: ignore + self, + *, + path_or_fileobj: str | Path | bytes | BinaryIO, + path_in_repo: str, + repo_id: str, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + run_as_future: Literal[False] = ..., + _hot_reload: bool | None = None, + ) -> CommitInfo: ... + + @overload + def upload_file( + self, + *, + path_or_fileobj: str | Path | bytes | BinaryIO, + path_in_repo: str, + repo_id: str, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + run_as_future: Literal[True] = ..., + _hot_reload: bool | None = None, + ) -> Future[CommitInfo]: ... + + @validate_hf_hub_args + @future_compatible + def upload_file( + self, + *, + path_or_fileobj: str | Path | bytes | BinaryIO, + path_in_repo: str, + repo_id: str, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + run_as_future: bool = False, + _hot_reload: bool | None = None, + ) -> CommitInfo | Future[CommitInfo]: + """ + Upload a local file (up to 50 GB) to the given repo. The upload is done + through a HTTP post request, and doesn't require git or git-lfs to be + installed. + + Args: + path_or_fileobj (`str`, `Path`, `bytes`, or `IO`): + Path to a file on the local machine or binary data stream / + fileobj / buffer. + path_in_repo (`str`): + Relative filepath in the repo, for example: + `"checkpoints/1fec34a/weights.bin"` + repo_id (`str`): + The repository to which the file will be uploaded, for example: + `"username/custom_transformers"` + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit + commit_description (`str` *optional*) + The description of the generated commit + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + run_as_future (`bool`, *optional*): + Whether or not to run this method in the background. Background jobs are run sequentially without + blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) + object. Defaults to `False`. + + + Returns: + [`CommitInfo`] or `Future`: + Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit + url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will + contain the result when executed. + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.RevisionNotFoundError`] + > If the revision to download from cannot be found. + + > [!WARNING] + > `upload_file` assumes that the repo already exists on the Hub. If you get a + > Client error 404, please make sure you are authenticated, that your token has the required permissions, + > and that `repo_id` and `repo_type` are set correctly. If repo does not exist, + > create it first using [`~hf_api.create_repo`]. + + Example: + + ```python + >>> from huggingface_hub import upload_file + + >>> with open("./local/filepath", "rb") as fobj: + ... upload_file( + ... path_or_fileobj=fileobj, + ... path_in_repo="remote/file/path.h5", + ... repo_id="username/my-dataset", + ... repo_type="dataset", + ... token="my_token", + ... ) + + >>> upload_file( + ... path_or_fileobj=".\\\\local\\\\file\\\\path", + ... path_in_repo="remote/file/path.h5", + ... repo_id="username/my-model", + ... token="my_token", + ... ) + + >>> upload_file( + ... path_or_fileobj=".\\\\local\\\\file\\\\path", + ... path_in_repo="remote/file/path.h5", + ... repo_id="username/my-model", + ... token="my_token", + ... create_pr=True, + ... ) + ``` + """ + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + + commit_message = ( + commit_message if commit_message is not None else f"Upload {path_in_repo} with huggingface_hub" + ) + operation = CommitOperationAdd( + path_or_fileobj=path_or_fileobj, + path_in_repo=path_in_repo, + ) + + return self.create_commit( + repo_id=repo_id, + repo_type=repo_type, + operations=[operation], + commit_message=commit_message, + commit_description=commit_description, + token=token, + revision=revision, + create_pr=create_pr, + _hot_reload=_hot_reload, + parent_commit=parent_commit, + ) + + @overload + def upload_folder( # type: ignore + self, + *, + repo_id: str, + folder_path: str | Path, + path_in_repo: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + delete_patterns: list[str] | str | None = None, + run_as_future: Literal[False] = ..., + ) -> CommitInfo: ... + + @overload + def upload_folder( # type: ignore + self, + *, + repo_id: str, + folder_path: str | Path, + path_in_repo: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + delete_patterns: list[str] | str | None = None, + run_as_future: Literal[True] = ..., + ) -> Future[CommitInfo]: ... + + @validate_hf_hub_args + @future_compatible + def upload_folder( + self, + *, + repo_id: str, + folder_path: str | Path, + path_in_repo: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + delete_patterns: list[str] | str | None = None, + run_as_future: bool = False, + ) -> CommitInfo | Future[CommitInfo]: + """ + Upload a local folder to the given repo. The upload is done through a HTTP requests, and doesn't require git or + git-lfs to be installed. + + The structure of the folder will be preserved. Files with the same name already present in the repository will + be overwritten. Others will be left untouched. + + Use the `allow_patterns` and `ignore_patterns` arguments to specify which files to upload. These parameters + accept either a single pattern or a list of patterns. Patterns are Standard Wildcards (globbing patterns) as + documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). If both `allow_patterns` and + `ignore_patterns` are provided, both constraints apply. By default, all files from the folder are uploaded. + + Use the `delete_patterns` argument to specify remote files you want to delete. Input type is the same as for + `allow_patterns` (see above). If `path_in_repo` is also provided, the patterns are matched against paths + relative to this folder. For example, `upload_folder(..., path_in_repo="experiment", delete_patterns="logs/*")` + will delete any remote file under `./experiment/logs/`. Note that the `.gitattributes` file will not be deleted + even if it matches the patterns. + + Any `.git/` folder present in any subdirectory will be ignored. However, please be aware that the `.gitignore` + file is not taken into account. + + Uses `HfApi.create_commit` under the hood. + + Args: + repo_id (`str`): + The repository to which the file will be uploaded, for example: + `"username/custom_transformers"` + folder_path (`str` or `Path`): + Path to the folder to upload on the local file system + path_in_repo (`str`, *optional*): + Relative path of the directory in the repo, for example: + `"checkpoints/1fec34a/results"`. Will default to the root folder of the repository. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. Defaults to: + `f"Upload {path_in_repo} with huggingface_hub"` + commit_description (`str` *optional*): + The description of the generated commit + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. If `revision` is not + set, PR is opened against the `"main"` branch. If `revision` is set and is a branch, PR is opened + against this branch. If `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + allow_patterns (`list[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are uploaded. + ignore_patterns (`list[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not uploaded. + delete_patterns (`list[str]` or `str`, *optional*): + If provided, remote files matching any of the patterns will be deleted from the repo while committing + new files. This is useful if you don't know which files have already been uploaded. + Note: to avoid discrepancies the `.gitattributes` file is not deleted even if it matches the pattern. + run_as_future (`bool`, *optional*): + Whether or not to run this method in the background. Background jobs are run sequentially without + blocking the main thread. Passing `run_as_future=True` will return a [Future](https://docs.python.org/3/library/concurrent.futures.html#future-objects) + object. Defaults to `False`. + + Returns: + [`CommitInfo`] or `Future`: + Instance of [`CommitInfo`] containing information about the newly created commit (commit hash, commit + url, pr url, commit message,...). If `run_as_future=True` is passed, returns a Future object which will + contain the result when executed. + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + + > [!WARNING] + > `upload_folder` assumes that the repo already exists on the Hub. If you get a Client error 404, please make + > sure you are authenticated, that your token has the required permissions, and that `repo_id` and `repo_type` + > are set correctly. If repo does not exist, create it first using [`~hf_api.create_repo`]. + + > [!TIP] + > When dealing with a large folder (thousands of files or hundreds of GB), we recommend using [`~hf_api.upload_large_folder`] instead. + + Example: + + ```python + # Upload checkpoints folder except the log files + >>> upload_folder( + ... folder_path="local/checkpoints", + ... path_in_repo="remote/experiment/checkpoints", + ... repo_id="username/my-dataset", + ... repo_type="datasets", + ... token="my_token", + ... ignore_patterns="**/logs/*.txt", + ... ) + + # Upload checkpoints folder including logs while deleting existing logs from the repo + # Useful if you don't know exactly which log files have already being pushed + >>> upload_folder( + ... folder_path="local/checkpoints", + ... path_in_repo="remote/experiment/checkpoints", + ... repo_id="username/my-dataset", + ... repo_type="datasets", + ... token="my_token", + ... delete_patterns="**/logs/*.txt", + ... ) + + # Upload checkpoints folder while creating a PR + >>> upload_folder( + ... folder_path="local/checkpoints", + ... path_in_repo="remote/experiment/checkpoints", + ... repo_id="username/my-dataset", + ... repo_type="datasets", + ... token="my_token", + ... create_pr=True, + ... ) + ``` + """ + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + + # By default, upload folder to the root directory in repo. + if path_in_repo is None: + path_in_repo = "" + + # Do not upload .git folder + if ignore_patterns is None: + ignore_patterns = [] + elif isinstance(ignore_patterns, str): + ignore_patterns = [ignore_patterns] + ignore_patterns += DEFAULT_IGNORE_PATTERNS + + delete_operations = self._prepare_folder_deletions( + repo_id=repo_id, + repo_type=repo_type, + revision=constants.DEFAULT_REVISION if create_pr else revision, + token=token, + path_in_repo=path_in_repo, + delete_patterns=delete_patterns, + ) + add_operations = self._prepare_upload_folder_additions( + folder_path, + path_in_repo, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + token=token, + repo_type=repo_type, + ) + + # Optimize operations: if some files will be overwritten, we don't need to delete them first + if len(add_operations) > 0: + added_paths = {op.path_in_repo for op in add_operations} + delete_operations = [ + delete_op for delete_op in delete_operations if delete_op.path_in_repo not in added_paths + ] + commit_operations = delete_operations + add_operations + + commit_message = commit_message or "Upload folder using huggingface_hub" + + return self.create_commit( + repo_type=repo_type, + repo_id=repo_id, + operations=commit_operations, + commit_message=commit_message, + commit_description=commit_description, + token=token, + revision=revision, + create_pr=create_pr, + parent_commit=parent_commit, + ) + + @validate_hf_hub_args + def delete_file( + self, + path_in_repo: str, + repo_id: str, + *, + token: str | bool | None = None, + repo_type: str | None = None, + revision: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + ) -> CommitInfo: + """ + Deletes a file in the given repo. + + Args: + path_in_repo (`str`): + Relative filepath in the repo, for example: + `"checkpoints/1fec34a/weights.bin"` + repo_id (`str`): + The repository from which the file will be deleted, for example: + `"username/custom_transformers"` + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if the file is in a dataset or + space, `None` or `"model"` if in a model. Default is `None`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. Defaults to + `f"Delete {path_in_repo} with huggingface_hub"`. + commit_description (`str` *optional*) + The description of the generated commit + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + > - [`~utils.RevisionNotFoundError`] + > If the revision to download from cannot be found. + > - [`~utils.EntryNotFoundError`] + > If the file to download cannot be found. + + """ + commit_message = ( + commit_message if commit_message is not None else f"Delete {path_in_repo} with huggingface_hub" + ) + + operations = [CommitOperationDelete(path_in_repo=path_in_repo)] + + return self.create_commit( + repo_id=repo_id, + repo_type=repo_type, + token=token, + operations=operations, + revision=revision, + commit_message=commit_message, + commit_description=commit_description, + create_pr=create_pr, + parent_commit=parent_commit, + ) + + @validate_hf_hub_args + def delete_files( + self, + repo_id: str, + delete_patterns: list[str], + *, + token: bool | str | None = None, + repo_type: str | None = None, + revision: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + ) -> CommitInfo: + """ + Delete files from a repository on the Hub. + + If a folder path is provided, the entire folder is deleted as well as + all files it contained. + + Args: + repo_id (`str`): + The repository from which the folder will be deleted, for example: + `"username/custom_transformers"` + delete_patterns (`list[str]`): + List of files or folders to delete. Each string can either be + a file path, a folder path, or a wildcard pattern. Patterns are Standard + Wildcards (globbing patterns) as documented [here](https://tldp.org/LDP/GNU-Linux-Tools-Summary/html/x11655.htm). + The pattern matching is based on [`fnmatch`](https://docs.python.org/3/library/fnmatch.html). + Note that `fnmatch` matches `*` across path boundaries, unlike traditional Unix shell globbing. + E.g. `["file.txt", "folder/", "data/*.parquet"]` + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + to the stored token. + repo_type (`str`, *optional*): + Type of the repo to delete files from. Can be `"model"`, + `"dataset"` or `"space"`. Defaults to `"model"`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary (first line) of the generated commit. Defaults to + `f"Delete files using huggingface_hub"`. + commit_description (`str` *optional*) + The description of the generated commit. + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + """ + operations = self._prepare_folder_deletions( + repo_id=repo_id, repo_type=repo_type, delete_patterns=delete_patterns, path_in_repo="", revision=revision + ) + + if commit_message is None: + commit_message = f"Delete files {' '.join(delete_patterns)} with huggingface_hub" + + return self.create_commit( + repo_id=repo_id, + repo_type=repo_type, + token=token, + operations=operations, + revision=revision, + commit_message=commit_message, + commit_description=commit_description, + create_pr=create_pr, + parent_commit=parent_commit, + ) + + @validate_hf_hub_args + def delete_folder( + self, + path_in_repo: str, + repo_id: str, + *, + token: bool | str | None = None, + repo_type: str | None = None, + revision: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + ) -> CommitInfo: + """ + Deletes a folder in the given repo. + + Simple wrapper around [`create_commit`] method. + + Args: + path_in_repo (`str`): + Relative folder path in the repo, for example: `"checkpoints/1fec34a"`. + repo_id (`str`): + The repository from which the folder will be deleted, for example: + `"username/custom_transformers"` + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + to the stored token. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if the folder is in a dataset or + space, `None` or `"model"` if in a model. Default is `None`. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. Defaults to + `f"Delete folder {path_in_repo} with huggingface_hub"`. + commit_description (`str` *optional*) + The description of the generated commit. + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request with that commit. Defaults to `False`. + If `revision` is not set, PR is opened against the `"main"` branch. If + `revision` is set and is a branch, PR is opened against this branch. If + `revision` is set and is not a branch name (example: a commit oid), an + `RevisionNotFoundError` is returned by the server. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed to concurrently. + """ + return self.create_commit( + repo_id=repo_id, + repo_type=repo_type, + token=token, + operations=[CommitOperationDelete(path_in_repo=path_in_repo, is_folder=True)], + revision=revision, + commit_message=( + commit_message if commit_message is not None else f"Delete folder {path_in_repo} with huggingface_hub" + ), + commit_description=commit_description, + create_pr=create_pr, + parent_commit=parent_commit, + ) + + def upload_large_folder( + self, + repo_id: str, + folder_path: str | Path, + *, + repo_type: str, # Repo type is required! + revision: str | None = None, + private: bool | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + num_workers: int | None = None, + print_report: bool = True, + print_report_every: int = 60, + ) -> None: + """Upload a large folder to the Hub in the most resilient way possible. + + Several workers are started to upload files in an optimized way. Before being committed to a repo, files must be + hashed and be pre-uploaded if they are LFS files. Workers will perform these tasks for each file in the folder. + At each step, some metadata information about the upload process is saved in the folder under `.cache/.huggingface/` + to be able to resume the process if interrupted. The whole process might result in several commits. + + Args: + repo_id (`str`): + The repository to which the file will be uploaded. + E.g. `"HuggingFaceTB/smollm-corpus"`. + folder_path (`str` or `Path`): + Path to the folder to upload on the local file system. + repo_type (`str`): + Type of the repository. Must be one of `"model"`, `"dataset"` or `"space"`. + Unlike in all other `HfApi` methods, `repo_type` is explicitly required here. This is to avoid + any mistake when uploading a large folder to the Hub, and therefore prevent from having to re-upload + everything. + revision (`str`, `optional`): + The branch to commit to. If not provided, the `main` branch will be used. + private (`bool`, `optional`): + Whether the repository should be private. + If `None` (default), the repo will be public unless the organization's default is private. + allow_patterns (`list[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are uploaded. + ignore_patterns (`list[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not uploaded. + num_workers (`int`, *optional*): + Number of workers to start. Defaults to half of CPU cores (minimum 1). + A higher number of workers may speed up the process if your machine allows it. However, on machines with a + slower connection, it is recommended to keep the number of workers low to ensure better resumability. + Indeed, partially uploaded files will have to be completely re-uploaded if the process is interrupted. + print_report (`bool`, *optional*): + Whether to print a report of the upload progress. Defaults to True. + Report is printed to `sys.stdout` every X seconds (60 by defaults) and overwrites the previous report. + print_report_every (`int`, *optional*): + Frequency at which the report is printed. Defaults to 60 seconds. + + > [!TIP] + > A few things to keep in mind: + > - Repository limits still apply: https://huggingface.co/docs/hub/repositories-recommendations + > - Do not start several processes in parallel. + > - You can interrupt and resume the process at any time. + > - Do not upload the same folder to several repositories. If you need to do so, you must delete the local `.cache/.huggingface/` folder first. + + > [!WARNING] + > While being much more robust to upload large folders, `upload_large_folder` is more limited than [`upload_folder`] feature-wise. In practice: + > - you cannot set a custom `path_in_repo`. If you want to upload to a subfolder, you need to set the proper structure locally. + > - you cannot set a custom `commit_message` and `commit_description` since multiple commits are created. + > - you cannot delete from the repo while uploading. Please make a separate commit first. + > - you cannot create a PR directly. Please create a PR first (from the UI or using [`create_pull_request`]) and then commit to it by passing `revision`. + + **Technical details:** + + `upload_large_folder` process is as follow: + 1. (Check parameters and setup.) + 2. Create repo if missing. + 3. List local files to upload. + 4. Run validation checks and display warnings if repository limits might be exceeded: + - Warns if the total number of files exceeds 100k (recommended limit). + - Warns if any folder contains more than 10k files (recommended limit). + - Warns about files larger than 20GB (recommended) or 50GB (hard limit). + 5. Start workers. Workers can perform the following tasks: + - Hash a file. + - Get upload mode (regular or LFS) for a list of files. + - Pre-upload an LFS file. + - Commit a bunch of files. + Once a worker finishes a task, it will move on to the next task based on the priority list (see below) until + all files are uploaded and committed. + 6. While workers are up, regularly print a report to sys.stdout. + + Order of priority: + 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file). + 2. Commit if at least 150 files are ready to commit. + 3. Get upload mode if at least 10 files have been hashed. + 4. Pre-upload LFS file if at least 1 file and no worker is pre-uploading. + 5. Hash file if at least 1 file and no worker is hashing. + 6. Get upload mode if at least 1 file and no worker is getting upload mode. + 7. Pre-upload LFS file if at least 1 file. + 8. Hash file if at least 1 file to hash. + 9. Get upload mode if at least 1 file to get upload mode. + 10. Commit if at least 1 file to commit and at least 1 min since last commit attempt. + 11. Commit if at least 1 file to commit and all other queues are empty. + + Special rules: + - Only one worker can commit at a time. + - If no tasks are available, the worker waits for 10 seconds before checking again. + """ + return upload_large_folder_internal( + self, + repo_id=repo_id, + folder_path=folder_path, + repo_type=repo_type, + revision=revision, + private=private, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + num_workers=num_workers, + print_report=print_report, + print_report_every=print_report_every, + ) + + @validate_hf_hub_args + def get_hf_file_metadata( + self, + *, + url: str, + token: bool | str | None = None, + timeout: float | None = constants.HF_HUB_ETAG_TIMEOUT, + ) -> HfFileMetadata: + """Fetch metadata of a file versioned on the Hub for a given url. + + Args: + url (`str`): + File url, for example returned by [`hf_hub_url`]. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + timeout (`float`, *optional*, defaults to 10): + How many seconds to wait for the server to send metadata before giving up. + + Returns: + A [`HfFileMetadata`] object containing metadata such as location, etag, size and commit_hash. + """ + if token is None: + # Cannot do `token = token or self.token` as token can be `False`. + token = self.token + + return get_hf_file_metadata( + url=url, + token=token, + timeout=timeout, + library_name=self.library_name, + library_version=self.library_version, + user_agent=self.user_agent, + endpoint=self.endpoint, + ) + + @overload + def hf_hub_download( + self, + repo_id: str, + filename: str, + *, + subfolder: str | None = None, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + force_download: bool = False, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + token: bool | str | None = None, + local_files_only: bool = False, + tqdm_class: type[base_tqdm] | None = None, + dry_run: Literal[False] = False, + ) -> str: ... + + @overload + def hf_hub_download( + self, + repo_id: str, + filename: str, + *, + subfolder: str | None = None, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + force_download: bool = False, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + token: bool | str | None = None, + local_files_only: bool = False, + tqdm_class: type[base_tqdm] | None = None, + dry_run: Literal[True], + ) -> DryRunFileInfo: ... + + @validate_hf_hub_args + def hf_hub_download( + self, + repo_id: str, + filename: str, + *, + subfolder: str | None = None, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + force_download: bool = False, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + token: bool | str | None = None, + local_files_only: bool = False, + tqdm_class: type[base_tqdm] | None = None, + dry_run: bool = False, + ) -> str | DryRunFileInfo: + """Download a given file if it's not already present in the local cache. + + The new cache file layout looks like this: + - The cache directory contains one subfolder per repo_id (namespaced by repo type) + - inside each repo folder: + - refs is a list of the latest known revision => commit_hash pairs + - blobs contains the actual file blobs (identified by their git-sha or sha256, depending on + whether they're LFS files or not) + - snapshots contains one subfolder per commit, each "commit" contains the subset of the files + that have been resolved at that particular commit. Each filename is a symlink to the blob + at that particular commit. + + ``` + [ 96] . + └── [ 160] models--julien-c--EsperBERTo-small + ├── [ 160] blobs + │ ├── [321M] 403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + │ ├── [ 398] 7cb18dc9bafbfcf74629a4b760af1b160957a83e + │ └── [1.4K] d7edf6bd2a681fb0175f7735299831ee1b22b812 + ├── [ 96] refs + │ └── [ 40] main + └── [ 128] snapshots + ├── [ 128] 2439f60ef33a0d46d85da5001d52aeda5b00ce9f + │ ├── [ 52] README.md -> ../../blobs/d7edf6bd2a681fb0175f7735299831ee1b22b812 + │ └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + └── [ 128] bbc77c8132af1cc5cf678da3f1ddf2de43606d48 + ├── [ 52] README.md -> ../../blobs/7cb18dc9bafbfcf74629a4b760af1b160957a83e + └── [ 76] pytorch_model.bin -> ../../blobs/403450e234d65943a7dcf7e05a771ce3c92faa84dd07db4ac20f592037a1e4bd + ``` + + If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this + option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir` + to store some metadata related to the downloaded files. While this mechanism is not as robust as the main + cache-system, it's optimized for regularly pulling the latest version of a repository. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + filename (`str`): + The name of the file in the repo. + subfolder (`str`, *optional*): + An optional value corresponding to a folder inside the repository. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if downloading from a dataset or space, + `None` or `"model"` if downloading from a model. Default is `None`. + revision (`str`, *optional*): + An optional Git revision id which can be a branch name, a tag, or a + commit hash. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_dir (`str` or `Path`, *optional*): + If provided, the downloaded file will be placed under this directory. + force_download (`bool`, *optional*, defaults to `False`): + Whether the file should be downloaded even if it already exists in + the local cache. + etag_timeout (`float`, *optional*, defaults to `10`): + When fetching ETag, how many seconds to wait for the server to send + data before giving up which is passed to `httpx.request`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the + local cached file if it exists. + tqdm_class (`tqdm`, *optional*): + If provided, overwrites the default behavior for the progress bar. Passed + argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior. + Defaults to the custom HF progress bar that can be disabled by setting + `HF_HUB_DISABLE_PROGRESS_BARS` environment variable. + dry_run (`bool`, *optional*, defaults to `False`): + If `True`, perform a dry run without actually downloading the file. Returns a + [`DryRunFileInfo`] object containing information about what would be downloaded. + + Returns: + `str` or [`DryRunFileInfo`]: + - If `dry_run=False`: Local path of file or if networking is off, last version of file cached on disk. + - If `dry_run=True`: A [`DryRunFileInfo`] object containing download information. + + Raises: + [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + [`~utils.RemoteEntryNotFoundError`] + If the file to download cannot be found. + [`~utils.LocalEntryNotFoundError`] + If network is disabled or unavailable and file is not found in cache. + [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + If `token=True` but the token cannot be found. + [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) + If ETag cannot be determined. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If some parameter value is invalid. + """ + from .file_download import hf_hub_download + + if token is None: + # Cannot do `token = token or self.token` as token can be `False`. + token = self.token + + return hf_hub_download( + repo_id=repo_id, + filename=filename, + subfolder=subfolder, + repo_type=repo_type, + revision=revision, + endpoint=self.endpoint, + library_name=self.library_name, + library_version=self.library_version, + cache_dir=cache_dir, + local_dir=local_dir, + user_agent=self.user_agent, + force_download=force_download, + etag_timeout=etag_timeout, + token=token, + headers=self.headers, + local_files_only=local_files_only, + tqdm_class=tqdm_class, + dry_run=dry_run, + ) + + @overload + def snapshot_download( + self, + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + force_download: bool = False, + token: bool | str | None = None, + local_files_only: bool = False, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + max_workers: int = 8, + tqdm_class: type[base_tqdm] | None = None, + dry_run: Literal[False] = False, + ) -> str: ... + + @overload + def snapshot_download( + self, + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + force_download: bool = False, + token: bool | str | None = None, + local_files_only: bool = False, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + max_workers: int = 8, + tqdm_class: type[base_tqdm] | None = None, + dry_run: Literal[True], + ) -> list[DryRunFileInfo]: ... + + @validate_hf_hub_args + def snapshot_download( + self, + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + cache_dir: str | Path | None = None, + local_dir: str | Path | None = None, + etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT, + force_download: bool = False, + token: bool | str | None = None, + local_files_only: bool = False, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + max_workers: int = 8, + tqdm_class: type[base_tqdm] | None = None, + dry_run: bool = False, + ) -> str | list[DryRunFileInfo]: + """Download repo files. + + Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from + a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order + to keep their actual filename relative to that folder. You can also filter which files to download using + `allow_patterns` and `ignore_patterns`. + + If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this + option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir` + to store some metadata related to the downloaded files.While this mechanism is not as robust as the main + cache-system, it's optimized for regularly pulling the latest version of a repository. + + An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly + configured. It is also not possible to filter which files to download when cloning a repository using git. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if downloading from a dataset or space, + `None` or `"model"` if downloading from a model. Default is `None`. + revision (`str`, *optional*): + An optional Git revision id which can be a branch name, a tag, or a + commit hash. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_dir (`str` or `Path`, *optional*): + If provided, the downloaded files will be placed under this directory. + etag_timeout (`float`, *optional*, defaults to `10`): + When fetching ETag, how many seconds to wait for the server to send + data before giving up which is passed to `httpx.request`. + force_download (`bool`, *optional*, defaults to `False`): + Whether the file should be downloaded even if it already exists in the local cache. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the + local cached file if it exists. + allow_patterns (`list[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are downloaded. + ignore_patterns (`list[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not downloaded. + max_workers (`int`, *optional*): + Number of concurrent threads to download files (1 thread = 1 file download). + Defaults to 8. + tqdm_class (`tqdm`, *optional*): + If provided, overwrites the default behavior for the progress bar. Passed + argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior. + Note that the `tqdm_class` is not passed to each individual download. + Defaults to the custom HF progress bar that can be disabled by setting + `HF_HUB_DISABLE_PROGRESS_BARS` environment variable. + dry_run (`bool`, *optional*, defaults to `False`): + If `True`, perform a dry run without actually downloading the files. Returns a list of + [`DryRunFileInfo`] objects containing information about what would be downloaded. + + Returns: + `str` or list of [`DryRunFileInfo`]: + - If `dry_run=False`: Folder path of the repo snapshot. + - If `dry_run=True`: A list of [`DryRunFileInfo`] objects containing download information. + + Raises: + [`~utils.RepositoryNotFoundError`] + If the repository to download from cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + [`~utils.RevisionNotFoundError`] + If the revision to download from cannot be found. + [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError) + If `token=True` and the token cannot be found. + [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if + ETag cannot be determined. + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if some parameter value is invalid. + """ + from ._snapshot_download import snapshot_download + + if token is None: + # Cannot do `token = token or self.token` as token can be `False`. + token = self.token + + return snapshot_download( + repo_id=repo_id, + repo_type=repo_type, + revision=revision, + endpoint=self.endpoint, + cache_dir=cache_dir, + local_dir=local_dir, + library_name=self.library_name, + library_version=self.library_version, + user_agent=self.user_agent, + etag_timeout=etag_timeout, + force_download=force_download, + token=token, + local_files_only=local_files_only, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + max_workers=max_workers, + tqdm_class=tqdm_class, + headers=self.headers, + dry_run=dry_run, + ) + + def get_safetensors_metadata( + self, + repo_id: str, + *, + repo_type: str | None = None, + revision: str | None = None, + token: bool | str | None = None, + ) -> SafetensorsRepoMetadata: + """ + Parse metadata for a safetensors repo on the Hub. + + We first check if the repo has a single safetensors file or a sharded safetensors repo. If it's a single + safetensors file, we parse the metadata from this file. If it's a sharded safetensors repo, we parse the + metadata from the index file and then parse the metadata from each shard. + + To parse metadata from a single safetensors file, use [`parse_safetensors_file_metadata`]. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a + model. Default is `None`. + revision (`str`, *optional*): + The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the + head of the `"main"` branch. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`SafetensorsRepoMetadata`]: information related to safetensors repo. + + Raises: + [`NotASafetensorsRepoError`] + If the repo is not a safetensors repo i.e. doesn't have either a + `model.safetensors` or a `model.safetensors.index.json` file. + [`SafetensorsParsingError`] + If a safetensors file header couldn't be parsed correctly. + + Example: + ```py + # Parse repo with single weights file + >>> metadata = get_safetensors_metadata("bigscience/bloomz-560m") + >>> metadata + SafetensorsRepoMetadata( + metadata=None, + sharded=False, + weight_map={'h.0.input_layernorm.bias': 'model.safetensors', ...}, + files_metadata={'model.safetensors': SafetensorsFileMetadata(...)} + ) + >>> metadata.files_metadata["model.safetensors"].metadata + {'format': 'pt'} + + # Parse repo with sharded model + >>> metadata = get_safetensors_metadata("bigscience/bloom") + Parse safetensors files: 100%|██████████████████████████████████████████| 72/72 [00:12<00:00, 5.78it/s] + >>> metadata + SafetensorsRepoMetadata(metadata={'total_size': 352494542848}, sharded=True, weight_map={...}, files_metadata={...}) + >>> len(metadata.files_metadata) + 72 # All safetensors files have been fetched + + # Parse repo with sharded model + >>> get_safetensors_metadata("runwayml/stable-diffusion-v1-5") + NotASafetensorsRepoError: 'runwayml/stable-diffusion-v1-5' is not a safetensors repo. Couldn't find 'model.safetensors.index.json' or 'model.safetensors' files. + ``` + """ + if self.file_exists( # Single safetensors file => non-sharded model + repo_id=repo_id, + filename=constants.SAFETENSORS_SINGLE_FILE, + repo_type=repo_type, + revision=revision, + token=token, + ): + file_metadata = self.parse_safetensors_file_metadata( + repo_id=repo_id, + filename=constants.SAFETENSORS_SINGLE_FILE, + repo_type=repo_type, + revision=revision, + token=token, + ) + return SafetensorsRepoMetadata( + metadata=None, + sharded=False, + weight_map={ + tensor_name: constants.SAFETENSORS_SINGLE_FILE for tensor_name in file_metadata.tensors.keys() + }, + files_metadata={constants.SAFETENSORS_SINGLE_FILE: file_metadata}, + ) + elif self.file_exists( # Multiple safetensors files => sharded with index + repo_id=repo_id, + filename=constants.SAFETENSORS_INDEX_FILE, + repo_type=repo_type, + revision=revision, + token=token, + ): + # Fetch index + index_file = self.hf_hub_download( + repo_id=repo_id, + filename=constants.SAFETENSORS_INDEX_FILE, + repo_type=repo_type, + revision=revision, + token=token, + ) + with open(index_file) as f: + index = json.load(f) + + weight_map = index.get("weight_map", {}) + + # Fetch metadata per shard + files_metadata = {} + + def _parse(filename: str) -> None: + files_metadata[filename] = self.parse_safetensors_file_metadata( + repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, token=token + ) + + thread_map( + _parse, + set(weight_map.values()), + desc="Parse safetensors files", + tqdm_class=hf_tqdm, + ) + + return SafetensorsRepoMetadata( + metadata=index.get("metadata", None), + sharded=True, + weight_map=weight_map, + files_metadata=files_metadata, + ) + else: + # Not a safetensors repo + raise NotASafetensorsRepoError( + f"'{repo_id}' is not a safetensors repo. Couldn't find '{constants.SAFETENSORS_INDEX_FILE}' or '{constants.SAFETENSORS_SINGLE_FILE}' files." + ) + + def parse_safetensors_file_metadata( + self, + repo_id: str, + filename: str, + *, + repo_type: str | None = None, + revision: str | None = None, + token: bool | str | None = None, + ) -> SafetensorsFileMetadata: + """ + Parse metadata from a safetensors file on the Hub. + + To parse metadata from all safetensors files in a repo at once, use [`get_safetensors_metadata`]. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Args: + repo_id (`str`): + A user or an organization name and a repo name separated by a `/`. + filename (`str`): + The name of the file in the repo. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if the file is in a dataset or space, `None` or `"model"` if in a + model. Default is `None`. + revision (`str`, *optional*): + The git revision to fetch the file from. Can be a branch name, a tag, or a commit hash. Defaults to the + head of the `"main"` branch. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`SafetensorsFileMetadata`]: information related to a safetensors file. + + Raises: + [`NotASafetensorsRepoError`]: + If the repo is not a safetensors repo i.e. doesn't have either a + `model.safetensors` or a `model.safetensors.index.json` file. + [`SafetensorsParsingError`]: + If a safetensors file header couldn't be parsed correctly. + """ + url = hf_hub_url( + repo_id=repo_id, filename=filename, repo_type=repo_type, revision=revision, endpoint=self.endpoint + ) + _headers = self._build_hf_headers(token=token) + + context_msg = f"repo '{repo_id}', revision '{revision or constants.DEFAULT_REVISION}'" + + # 1. Fetch first 100kb + # Empirically, 97% of safetensors files have a metadata size < 100kb (over the top 1000 models on the Hub). + # We assume fetching 100kb is faster than making 2 GET requests. Therefore we always fetch the first 100kb to + # avoid the 2nd GET in most cases. + # See https://github.com/huggingface/huggingface_hub/pull/1855#discussion_r1404286419. + response = get_session().get(url, headers={**_headers, "range": "bytes=0-100000"}) + hf_raise_for_status(response) + + # 2. Parse and validate metadata size using shared helper + metadata_size = _get_safetensors_metadata_size(response.content[:8], filename, context_msg) + + # 3.a. Get metadata from payload + if metadata_size <= 100000: + metadata_as_bytes = response.content[8 : 8 + metadata_size] + else: # 3.b. Request full metadata + response = get_session().get(url, headers={**_headers, "range": f"bytes=8-{metadata_size + 7}"}) + hf_raise_for_status(response) + metadata_as_bytes = response.content + + # 4. Parse json header using shared helper + return _parse_safetensors_header(metadata_as_bytes, filename, context_msg) + + @validate_hf_hub_args + def create_branch( + self, + repo_id: str, + *, + branch: str, + revision: str | None = None, + token: bool | str | None = None, + repo_type: str | None = None, + exist_ok: bool = False, + ) -> None: + """ + Create a new branch for a repo on the Hub, starting from the specified revision (defaults to `main`). + To find a revision suiting your needs, you can use [`list_repo_refs`] or [`list_repo_commits`]. + + Args: + repo_id (`str`): + The repository in which the branch will be created. + Example: `"user/my-cool-model"`. + + branch (`str`): + The name of the branch to create. + + revision (`str`, *optional*): + The git revision to create the branch from. It can be a branch name or + the OID/SHA of a commit, as a hexadecimal string. Defaults to the head + of the `"main"` branch. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if creating a branch on a dataset or + space, `None` or `"model"` if tagging a model. Default is `None`. + + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if branch already exists. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + [`~utils.BadRequestError`]: + If invalid reference for a branch. Ex: `refs/pr/5` or 'refs/foo/bar'. + [`~utils.HfHubHTTPError`]: + If the branch already exists on the repo (error 409) and `exist_ok` is + set to `False`. + """ + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + branch = quote(branch, safe="") + + # Prepare request + branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}" + headers = self._build_hf_headers(token=token) + payload = {} + if revision is not None: + payload["startingPoint"] = revision + + # Create branch + response = get_session().post(url=branch_url, headers=headers, json=payload) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + if exist_ok and e.response.status_code == 409: + return + elif exist_ok and e.response.status_code == 403: + # No write permission on the namespace but branch might already exist + try: + refs = self.list_repo_refs(repo_id=repo_id, repo_type=repo_type, token=token) + for branch_ref in refs.branches: + if branch_ref.name == branch: + return # Branch already exists => do not raise + except HfHubHTTPError: + pass # We raise the original error if the branch does not exist + raise + + @validate_hf_hub_args + def delete_branch( + self, + repo_id: str, + *, + branch: str, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> None: + """ + Delete a branch from a repo on the Hub. + + Args: + repo_id (`str`): + The repository in which a branch will be deleted. + Example: `"user/my-cool-model"`. + + branch (`str`): + The name of the branch to delete. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if creating a branch on a dataset or + space, `None` or `"model"` if tagging a model. Default is `None`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + [`~utils.HfHubHTTPError`]: + If trying to delete a protected branch. Ex: `main` cannot be deleted. + [`~utils.HfHubHTTPError`]: + If trying to delete a branch that does not exist. + + """ + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + branch = quote(branch, safe="") + + # Prepare request + branch_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/branch/{branch}" + headers = self._build_hf_headers(token=token) + + # Delete branch + response = get_session().delete(url=branch_url, headers=headers) + hf_raise_for_status(response) + + @validate_hf_hub_args + def create_tag( + self, + repo_id: str, + *, + tag: str, + tag_message: str | None = None, + revision: str | None = None, + token: bool | str | None = None, + repo_type: str | None = None, + exist_ok: bool = False, + ) -> None: + """ + Tag a given commit of a repo on the Hub. + + Args: + repo_id (`str`): + The repository in which a commit will be tagged. + Example: `"user/my-cool-model"`. + + tag (`str`): + The name of the tag to create. + + tag_message (`str`, *optional*): + The description of the tag to create. + + revision (`str`, *optional*): + The git revision to tag. It can be a branch name or the OID/SHA of a + commit, as a hexadecimal string. Shorthands (7 first characters) are + also supported. Defaults to the head of the `"main"` branch. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if tagging a dataset or + space, `None` or `"model"` if tagging a model. Default is + `None`. + + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if tag already exists. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + [`~utils.RevisionNotFoundError`]: + If revision is not found (error 404) on the repo. + [`~utils.HfHubHTTPError`]: + If the branch already exists on the repo (error 409) and `exist_ok` is + set to `False`. + """ + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + revision = quote(revision, safe="") if revision is not None else constants.DEFAULT_REVISION + + # Prepare request + tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{revision}" + headers = self._build_hf_headers(token=token) + payload = {"tag": tag} + if tag_message is not None: + payload["message"] = tag_message + + # Tag + response = get_session().post(url=tag_url, headers=headers, json=payload) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + if not (e.response.status_code == 409 and exist_ok): + raise + + @validate_hf_hub_args + def delete_tag( + self, + repo_id: str, + *, + tag: str, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> None: + """ + Delete a tag from a repo on the Hub. + + Args: + repo_id (`str`): + The repository in which a tag will be deleted. + Example: `"user/my-cool-model"`. + + tag (`str`): + The name of the tag to delete. + + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if tagging a dataset or space, `None` or + `"model"` if tagging a model. Default is `None`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If repository is not found (error 404): wrong repo_id/repo_type, private + but not authenticated or repo does not exist. + [`~utils.RevisionNotFoundError`]: + If tag is not found. + """ + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + tag = quote(tag, safe="") + + # Prepare request + tag_url = f"{self.endpoint}/api/{repo_type}s/{repo_id}/tag/{tag}" + headers = self._build_hf_headers(token=token) + + # Un-tag + response = get_session().delete(url=tag_url, headers=headers) + hf_raise_for_status(response) + + @validate_hf_hub_args + def get_full_repo_name( + self, + model_id: str, + *, + organization: str | None = None, + token: bool | str | None = None, + ): + """ + Returns the repository name for a given model ID and optional + organization. + + Args: + model_id (`str`): + The name of the model. + organization (`str`, *optional*): + If passed, the repository name will be in the organization + namespace instead of the user namespace. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `str`: The repository name in the user's namespace + ({username}/{model_id}) if no organization is passed, and under the + organization namespace ({organization}/{model_id}) otherwise. + """ + if organization is None: + if "/" in model_id: + username = model_id.split("/")[0] + else: + username = self.whoami(token=token)["name"] # type: ignore + return f"{username}/{model_id}" + else: + return f"{organization}/{model_id}" + + @validate_hf_hub_args + def get_repo_discussions( + self, + repo_id: str, + *, + author: str | None = None, + discussion_type: constants.DiscussionTypeFilter | None = None, + discussion_status: constants.DiscussionStatusFilter | None = None, + repo_type: str | None = None, + token: bool | str | None = None, + ) -> Iterator[Discussion]: + """ + Fetches Discussions and Pull Requests for the given repo. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + author (`str`, *optional*): + Pass a value to filter by discussion author. `None` means no filter. + Default is `None`. + discussion_type (`str`, *optional*): + Set to `"pull_request"` to fetch only pull requests, `"discussion"` + to fetch only discussions. Set to `"all"` or `None` to fetch both. + Default is `None`. + discussion_status (`str`, *optional*): + Set to `"open"` (respectively `"closed"`) to fetch only open + (respectively closed) discussions. Set to `"all"` or `None` + to fetch both. + Default is `None`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if fetching from a dataset or + space, `None` or `"model"` if fetching from a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterator[Discussion]`: An iterator of [`Discussion`] objects. + + Example: + Collecting all discussions of a repo in a list: + + ```python + >>> from huggingface_hub import get_repo_discussions + >>> discussions_list = list(get_repo_discussions(repo_id="bert-base-uncased")) + ``` + + Iterating over discussions of a repo: + + ```python + >>> from huggingface_hub import get_repo_discussions + >>> for discussion in get_repo_discussions(repo_id="bert-base-uncased"): + ... print(discussion.num, discussion.title) + ``` + """ + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + if discussion_type is not None and discussion_type not in constants.DISCUSSION_TYPES: + raise ValueError(f"Invalid discussion_type, must be one of {constants.DISCUSSION_TYPES}") + if discussion_status is not None and discussion_status not in constants.DISCUSSION_STATUS: + raise ValueError(f"Invalid discussion_status, must be one of {constants.DISCUSSION_STATUS}") + + headers = self._build_hf_headers(token=token) + path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions" + + params: dict[str, str | int] = {} + if discussion_type is not None: + params["type"] = discussion_type + if discussion_status is not None: + params["status"] = discussion_status + if author is not None: + params["author"] = author + + def _fetch_discussion_page(page_index: int): + params["p"] = page_index + resp = get_session().get(path, headers=headers, params=params) + hf_raise_for_status(resp) + paginated_discussions = resp.json() + total = paginated_discussions["count"] + start = paginated_discussions["start"] + discussions = paginated_discussions["discussions"] + has_next = (start + len(discussions)) < total + return discussions, has_next + + has_next, page_index = True, 0 + + while has_next: + discussions, has_next = _fetch_discussion_page(page_index=page_index) + for discussion in discussions: + yield Discussion( + title=discussion["title"], + num=discussion["num"], + author=discussion.get("author", {}).get("name", "deleted"), + created_at=parse_datetime(discussion["createdAt"]), + status=discussion["status"], + repo_id=discussion["repo"]["name"], + repo_type=discussion["repo"]["type"], + is_pull_request=discussion["isPullRequest"], + endpoint=self.endpoint, + ) + page_index = page_index + 1 + + @validate_hf_hub_args + def get_discussion_details( + self, + repo_id: str, + discussion_num: int, + *, + repo_type: str | None = None, + token: bool | str | None = None, + ) -> DiscussionWithDetails: + """Fetches a Discussion's / Pull Request 's details from the Hub. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: [`DiscussionWithDetails`] + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + if not isinstance(discussion_num, int) or discussion_num <= 0: + raise ValueError("Invalid discussion_num, must be a positive integer") + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + + path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions/{discussion_num}" + headers = self._build_hf_headers(token=token) + resp = get_session().get(path, params={"diff": "1"}, headers=headers) + hf_raise_for_status(resp) + + discussion_details = resp.json() + is_pull_request = discussion_details["isPullRequest"] + + target_branch = discussion_details["changes"]["base"] if is_pull_request else None + conflicting_files = discussion_details["filesWithConflicts"] if is_pull_request else None + merge_commit_oid = discussion_details["changes"].get("mergeCommitId", None) if is_pull_request else None + + return DiscussionWithDetails( + title=discussion_details["title"], + num=discussion_details["num"], + author=discussion_details.get("author", {}).get("name", "deleted"), + created_at=parse_datetime(discussion_details["createdAt"]), + status=discussion_details["status"], + repo_id=discussion_details["repo"]["name"], + repo_type=discussion_details["repo"]["type"], + is_pull_request=discussion_details["isPullRequest"], + events=[deserialize_event(evt) for evt in discussion_details["events"]], + conflicting_files=conflicting_files, + target_branch=target_branch, + merge_commit_oid=merge_commit_oid, + diff=discussion_details.get("diff"), + endpoint=self.endpoint, + ) + + @validate_hf_hub_args + def create_discussion( + self, + repo_id: str, + title: str, + *, + token: bool | str | None = None, + description: str | None = None, + repo_type: str | None = None, + pull_request: bool = False, + ) -> DiscussionWithDetails: + """Creates a Discussion or Pull Request. + + Pull Requests created programmatically will be in `"draft"` status. + + Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`]. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + title (`str`): + The title of the discussion. It can be up to 200 characters long, + and must be at least 3 characters long. Leading and trailing whitespaces + will be stripped. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + description (`str`, *optional*): + An optional description for the Pull Request. + Defaults to `"Discussion opened with the huggingface_hub Python library"` + pull_request (`bool`, *optional*): + Whether to create a Pull Request or discussion. If `True`, creates a Pull Request. + If `False`, creates a discussion. Defaults to `False`. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + Returns: [`DiscussionWithDetails`] + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access.""" + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + + if description is not None: + description = description.strip() + description = ( + description + if description + else ( + f"{'Pull Request' if pull_request else 'Discussion'} opened with the" + " [huggingface_hub Python" + " library](https://huggingface.co/docs/huggingface_hub)" + ) + ) + + headers = self._build_hf_headers(token=token) + resp = get_session().post( + f"{self.endpoint}/api/{repo_type}s/{repo_id}/discussions", + json={ + "title": title.strip(), + "description": description, + "pullRequest": pull_request, + }, + headers=headers, + ) + hf_raise_for_status(resp) + num = resp.json()["num"] + return self.get_discussion_details( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=num, + token=token, + ) + + @validate_hf_hub_args + def create_pull_request( + self, + repo_id: str, + title: str, + *, + token: bool | str | None = None, + description: str | None = None, + repo_type: str | None = None, + ) -> DiscussionWithDetails: + """Creates a Pull Request . Pull Requests created programmatically will be in `"draft"` status. + + Creating a Pull Request with changes can also be done at once with [`HfApi.create_commit`]; + + This is a wrapper around [`HfApi.create_discussion`]. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + title (`str`): + The title of the discussion. It can be up to 200 characters long, + and must be at least 3 characters long. Leading and trailing whitespaces + will be stripped. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + description (`str`, *optional*): + An optional description for the Pull Request. + Defaults to `"Discussion opened with the huggingface_hub Python library"` + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + + Returns: [`DiscussionWithDetails`] + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access.""" + return self.create_discussion( + repo_id=repo_id, + title=title, + token=token, + description=description, + repo_type=repo_type, + pull_request=True, + ) + + def _post_discussion_changes( + self, + *, + repo_id: str, + discussion_num: int, + resource: str, + body: dict | None = None, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> httpx.Response: + """Internal utility to POST changes to a Discussion or Pull Request""" + if not isinstance(discussion_num, int) or discussion_num <= 0: + raise ValueError("Invalid discussion_num, must be a positive integer") + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + repo_id = f"{repo_type}s/{repo_id}" + + path = f"{self.endpoint}/api/{repo_id}/discussions/{discussion_num}/{resource}" + + headers = self._build_hf_headers(token=token) + resp = get_session().post(path, headers=headers, json=body) + hf_raise_for_status(resp) + return resp + + @validate_hf_hub_args + def comment_discussion( + self, + repo_id: str, + discussion_num: int, + comment: str, + *, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> DiscussionComment: + """Creates a new comment on the given Discussion. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + comment (`str`): + The content of the comment to create. Comments support markdown formatting. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`DiscussionComment`]: the newly created comment + + + Examples: + ```python + + >>> comment = \"\"\" + ... Hello @otheruser! + ... + ... # This is a title + ... + ... **This is bold**, *this is italic* and ~this is strikethrough~ + ... And [this](http://url) is a link + ... \"\"\" + + >>> HfApi().comment_discussion( + ... repo_id="username/repo_name", + ... discussion_num=34 + ... comment=comment + ... ) + # DiscussionComment(id='deadbeef0000000', type='comment', ...) + + ``` + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource="comment", + body={"comment": comment}, + ) + return deserialize_event(resp.json()["newMessage"]) # type: ignore + + @validate_hf_hub_args + def rename_discussion( + self, + repo_id: str, + discussion_num: int, + new_title: str, + *, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> DiscussionTitleChange: + """Renames a Discussion. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + new_title (`str`): + The new title for the discussion + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`DiscussionTitleChange`]: the title change event + + + Examples: + ```python + >>> new_title = "New title, fixing a typo" + >>> HfApi().rename_discussion( + ... repo_id="username/repo_name", + ... discussion_num=34 + ... new_title=new_title + ... ) + # DiscussionTitleChange(id='deadbeef0000000', type='title-change', ...) + + ``` + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource="title", + body={"title": new_title}, + ) + return deserialize_event(resp.json()["newTitle"]) # type: ignore + + @validate_hf_hub_args + def change_discussion_status( + self, + repo_id: str, + discussion_num: int, + new_status: Literal["open", "closed"], + *, + token: bool | str | None = None, + comment: str | None = None, + repo_type: str | None = None, + ) -> DiscussionStatusChange: + """Closes or re-opens a Discussion or Pull Request. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + new_status (`str`): + The new status for the discussion, either `"open"` or `"closed"`. + comment (`str`, *optional*): + An optional comment to post with the status change. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`DiscussionStatusChange`]: the status change event + + + Examples: + ```python + >>> new_title = "New title, fixing a typo" + >>> HfApi().rename_discussion( + ... repo_id="username/repo_name", + ... discussion_num=34 + ... new_title=new_title + ... ) + # DiscussionStatusChange(id='deadbeef0000000', type='status-change', ...) + + ``` + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + if new_status not in ["open", "closed"]: + raise ValueError("Invalid status, valid statuses are: 'open' and 'closed'") + body: dict[str, str] = {"status": new_status} + if comment and comment.strip(): + body["comment"] = comment.strip() + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource="status", + body=body, + ) + return deserialize_event(resp.json()["newStatus"]) # type: ignore + + @validate_hf_hub_args + def merge_pull_request( + self, + repo_id: str, + discussion_num: int, + *, + token: bool | str | None = None, + comment: str | None = None, + repo_type: str | None = None, + ): + """Merges a Pull Request. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + comment (`str`, *optional*): + An optional comment to post with the status change. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`DiscussionStatusChange`]: the status change event + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource="merge", + body={"comment": comment.strip()} if comment and comment.strip() else None, + ) + + @validate_hf_hub_args + def edit_discussion_comment( + self, + repo_id: str, + discussion_num: int, + comment_id: str, + new_content: str, + *, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> DiscussionComment: + """Edits a comment on a Discussion / Pull Request. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + comment_id (`str`): + The ID of the comment to edit. + new_content (`str`): + The new content of the comment. Comments support markdown formatting. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`DiscussionComment`]: the edited comment + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource=f"comment/{comment_id.lower()}/edit", + body={"content": new_content}, + ) + return deserialize_event(resp.json()["updatedComment"]) # type: ignore + + @validate_hf_hub_args + def hide_discussion_comment( + self, + repo_id: str, + discussion_num: int, + comment_id: str, + *, + token: bool | str | None = None, + repo_type: str | None = None, + ) -> DiscussionComment: + """Hides a comment on a Discussion / Pull Request. + + > [!WARNING] + > Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible. + + Args: + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + discussion_num (`int`): + The number of the Discussion or Pull Request . Must be a strictly positive integer. + comment_id (`str`): + The ID of the comment to edit. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if uploading to a dataset or + space, `None` or `"model"` if uploading to a model. Default is + `None`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`DiscussionComment`]: the hidden comment + + > [!TIP] + > Raises the following errors: + > + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the HuggingFace API returned an error + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if some parameter value is invalid + > - [`~utils.RepositoryNotFoundError`] + > If the repository to download from cannot be found. This may be because it doesn't exist, + > or because it is set to `private` and you do not have access. + """ + warnings.warn( + "Hidden comments' content cannot be retrieved anymore. Hiding a comment is irreversible.", + UserWarning, + ) + resp = self._post_discussion_changes( + repo_id=repo_id, + repo_type=repo_type, + discussion_num=discussion_num, + token=token, + resource=f"comment/{comment_id.lower()}/hide", + ) + return deserialize_event(resp.json()["updatedComment"]) # type: ignore + + @validate_hf_hub_args + def add_space_secret( + self, + repo_id: str, + key: str, + value: str, + *, + description: str | None = None, + token: bool | str | None = None, + ) -> None: + """Adds or updates a secret in a Space. + + Secrets allow to set secret keys or tokens to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + key (`str`): + Secret key. Example: `"GITHUB_API_KEY"` + value (`str`): + Secret value. Example: `"your_github_api_key"`. + description (`str`, *optional*): + Secret description. Example: `"Github API key to access the Github API"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + """ + payload = {"key": key, "value": value} + if description is not None: + payload["description"] = description + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/secrets", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + + @validate_hf_hub_args + def delete_space_secret(self, repo_id: str, key: str, *, token: bool | str | None = None) -> None: + """Deletes a secret from a Space. + + Secrets allow to set secret keys or tokens to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + key (`str`): + Secret key. Example: `"GITHUB_API_KEY"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + """ + r = get_session().request( + "DELETE", + f"{self.endpoint}/api/spaces/{repo_id}/secrets", + headers=self._build_hf_headers(token=token), + json={"key": key}, + ) + hf_raise_for_status(r) + + @validate_hf_hub_args + def get_space_secrets(self, repo_id: str, *, token: bool | str | None = None) -> dict[str, SpaceSecret]: + """Gets all secrets from a Space. + + Secret values are write-only and cannot be read back. Only the key, description, and last update time + are returned. + + Secrets allow to set secret keys or tokens to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + + Args: + repo_id (`str`): + ID of the repo to query. Example: `"bigcode/in-the-stack"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `dict[str, SpaceSecret]`: Dictionary of [`SpaceSecret`] objects keyed by secret name. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> api.get_space_secrets("username/my-space") + {'HF_TOKEN': SpaceSecret(key='HF_TOKEN', description='...', updated_at=datetime.datetime(...))} + ``` + """ + r = get_session().get( + f"{self.endpoint}/api/spaces/{repo_id}/secrets", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + return {k: SpaceSecret(k, v) for k, v in r.json().items()} + + @validate_hf_hub_args + def get_space_variables(self, repo_id: str, *, token: bool | str | None = None) -> dict[str, SpaceVariable]: + """Gets all variables from a Space. + + Variables allow to set environment variables to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables + + Args: + repo_id (`str`): + ID of the repo to query. Example: `"bigcode/in-the-stack"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + """ + r = get_session().get( + f"{self.endpoint}/api/spaces/{repo_id}/variables", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + return {k: SpaceVariable(k, v) for k, v in r.json().items()} + + @validate_hf_hub_args + def add_space_variable( + self, + repo_id: str, + key: str, + value: str, + *, + description: str | None = None, + token: bool | str | None = None, + ) -> dict[str, SpaceVariable]: + """Adds or updates a variable in a Space. + + Variables allow to set environment variables to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + key (`str`): + Variable key. Example: `"MODEL_REPO_ID"` + value (`str`): + Variable value. Example: `"the_model_repo_id"`. + description (`str`): + Description of the variable. Example: `"Model Repo ID of the implemented model"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + """ + payload = {"key": key, "value": value} + if description is not None: + payload["description"] = description + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/variables", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + return {k: SpaceVariable(k, v) for k, v in r.json().items()} + + @validate_hf_hub_args + def delete_space_variable( + self, repo_id: str, key: str, *, token: bool | str | None = None + ) -> dict[str, SpaceVariable]: + """Deletes a variable from a Space. + + Variables allow to set environment variables to a Space without hardcoding them. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + key (`str`): + Variable key. Example: `"MODEL_REPO_ID"` + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + """ + r = get_session().request( + "DELETE", + f"{self.endpoint}/api/spaces/{repo_id}/variables", + headers=self._build_hf_headers(token=token), + json={"key": key}, + ) + hf_raise_for_status(r) + return {k: SpaceVariable(k, v) for k, v in r.json().items()} + + @validate_hf_hub_args + def get_space_runtime(self, repo_id: str, *, token: bool | str | None = None) -> SpaceRuntime: + """Gets runtime information about a Space. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + """ + r = get_session().get( + f"{self.endpoint}/api/spaces/{repo_id}/runtime", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + def list_spaces_hardware(self, token: bool | str | None = None) -> list[JobHardware]: + """List available hardware options for Spaces. + + Returns: + `list[JobHardware]`: A list of available hardware configurations. + + Example: + + ```python + >>> from huggingface_hub import list_spaces_hardware + >>> hardware_list = list_spaces_hardware() + >>> hardware_list[0] + JobHardware(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', ...) + >>> hardware_list[0].name + 'cpu-basic' + ``` + """ + response = get_session().get( + f"{self.endpoint}/api/spaces/hardware", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(response) + return [JobHardware(**hardware) for hardware in response.json()] + + @validate_hf_hub_args + def request_space_hardware( + self, + repo_id: str, + hardware: SpaceHardware, + *, + token: bool | str | None = None, + sleep_time: int | None = None, + ) -> SpaceRuntime: + """Request new hardware for a Space. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + hardware (`str` or [`SpaceHardware`]): + Hardware on which to run the Space. Example: `"t4-medium"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want + your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure + the sleep time (value is fixed to 48 hours of inactivity). + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + + > [!TIP] + > It is also possible to request hardware directly when creating the Space repo! See [`create_repo`] for details. + """ + if sleep_time is not None and hardware == SpaceHardware.CPU_BASIC: + warnings.warn( + "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more" + " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if" + " you want to set a custom sleep time, you need to upgrade to a paid Hardware.", + UserWarning, + ) + payload: dict[str, Any] = {"flavor": hardware} + if sleep_time is not None: + payload["sleepTimeSeconds"] = sleep_time + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/hardware", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def set_space_sleep_time(self, repo_id: str, sleep_time: int, *, token: bool | str | None = None) -> SpaceRuntime: + """Set a custom sleep time for a Space running on upgraded hardware.. + + Your Space will go to sleep after X seconds of inactivity. You are not billed when your Space is in "sleep" + mode. If a new visitor lands on your Space, it will "wake it up". Only upgraded hardware can have a + configurable sleep time. To know more about the sleep stage, please refer to + https://huggingface.co/docs/hub/spaces-gpus#sleep-time. + + Args: + repo_id (`str`): + ID of the repo to update. Example: `"bigcode/in-the-stack"`. + sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want + your Space to pause (default behavior for upgraded hardware). For free hardware, you can't configure + the sleep time (value is fixed to 48 hours of inactivity). + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + + > [!TIP] + > It is also possible to set a custom sleep time when requesting hardware with [`request_space_hardware`]. + """ + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/sleeptime", + headers=self._build_hf_headers(token=token), + json={"seconds": sleep_time}, + ) + hf_raise_for_status(r) + runtime = SpaceRuntime(r.json()) + + hardware = runtime.requested_hardware or runtime.hardware + if hardware == SpaceHardware.CPU_BASIC: + warnings.warn( + "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more" + " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if" + " you want to set a custom sleep time, you need to upgrade to a paid Hardware.", + UserWarning, + ) + return runtime + + @validate_hf_hub_args + def pause_space(self, repo_id: str, *, token: bool | str | None = None) -> SpaceRuntime: + """Pause your Space. + + A paused Space stops executing until manually restarted by its owner. This is different from the sleeping + state in which free Spaces go after 48h of inactivity. Paused time is not billed to your account, no matter the + hardware you've selected. To restart your Space, use [`restart_space`] and go to your Space settings page. + + For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause). + + Args: + repo_id (`str`): + ID of the Space to pause. Example: `"Salesforce/BLIP2"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`SpaceRuntime`]: Runtime information about your Space including `stage=PAUSED` and requested hardware. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you + are not authenticated. + [`~utils.HfHubHTTPError`]: + 403 Forbidden: only the owner of a Space can pause it. If you want to manage a Space that you don't + own, either ask the owner by opening a Discussion or duplicate the Space. + [`~utils.BadRequestError`]: + If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide + a static Space, you can set it to private. + """ + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/pause", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def enable_space_dev_mode(self, repo_id: str, *, token: bool | str | None = None) -> SpaceRuntime: + """Enable dev mode on a Space. + + Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you + to restart your application without stopping the Space container itself. This feature is available as part of + a PRO or Team & Enterprise plan. See https://huggingface.co/docs/hub/spaces-dev-mode for more details. + + Args: + repo_id (`str`): + ID of the Space to enable dev mode. Example: `"Salesforce/BLIP2"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`SpaceRuntime`]: Runtime information about your Space. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you + are not authenticated. + [`~utils.HfHubHTTPError`]: + 403 Forbidden: only the owner of a Space can set dev mode. If you want to handle a Space that you don't + own, either ask the owner by opening a Discussion or duplicate the Space. + [`~utils.BadRequestError`]: + If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide + a static Space, you can set it to private. + """ + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/dev-mode", + headers=self._build_hf_headers(token=token), + json={"enabled": True}, + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def disable_space_dev_mode( + self, + repo_id: str, + *, + token: bool | str | None = None, + ) -> SpaceRuntime: + """Disable dev mode on a Space. + + Spaces Dev Mode eases the debugging of your application and makes iterating on Spaces faster by allowing you + to restart your application without stopping the Space container itself. This feature is available as part of + a PRO or Team & Enterprise plan. See https://huggingface.co/docs/hub/spaces-dev-mode for more details. + + Args: + repo_id (`str`): + ID of the Space to disable dev mode. Example: `"Salesforce/BLIP2"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`SpaceRuntime`]: Runtime information about your Space. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you + are not authenticated. + [`~utils.HfHubHTTPError`]: + 403 Forbidden: only the owner of a Space can set dev mode. If you want to handle a Space that you don't + own, either ask the owner by opening a Discussion or duplicate the Space. + [`~utils.BadRequestError`]: + If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide + a static Space, you can set it to private. + """ + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/dev-mode", + headers=self._build_hf_headers(token=token), + json={"enabled": False}, + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def restart_space( + self, repo_id: str, *, token: bool | str | None = None, factory_reboot: bool = False + ) -> SpaceRuntime: + """Restart your Space. + + This is the only way to programmatically restart a Space if you've put it on Pause (see [`pause_space`]). You + must be the owner of the Space to restart it. If you are using an upgraded hardware, your account will be + billed as soon as the Space is restarted. You can trigger a restart no matter the current state of a Space. + + For more details, please visit [the docs](https://huggingface.co/docs/hub/spaces-gpus#pause). + + Args: + repo_id (`str`): + ID of the Space to restart. Example: `"Salesforce/BLIP2"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + factory_reboot (`bool`, *optional*): + If `True`, the Space will be rebuilt from scratch without caching any requirements. + + Returns: + [`SpaceRuntime`]: Runtime information about your Space. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If your Space is not found (error 404). Most probably wrong repo_id or your space is private but you + are not authenticated. + [`~utils.HfHubHTTPError`]: + 403 Forbidden: only the owner of a Space can restart it. If you want to restart a Space that you don't + own, either ask the owner by opening a Discussion or duplicate the Space. + [`~utils.BadRequestError`]: + If your Space is a static Space. Static Spaces are always running and never billed. If you want to hide + a static Space, you can set it to private. + """ + params = {} + if factory_reboot: + params["factory"] = "true" + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/restart", headers=self._build_hf_headers(token=token), params=params + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + def _stream_sse_events( + self, + *, + url: str, + log_label: str, + timeout: int, + follow: bool, + token: bool | str | None = None, + skip_previous_events_on_retry: bool = True, + tolerated_status_codes: tuple[int, ...] = (), + tolerated_exception_types: tuple[type[Exception], ...] = (), + on_iteration_end: Callable[[], bool] | None = None, + ) -> Iterable[dict[str, Any]]: + # Shared SSE streaming loop with retry/backoff and event-index dedup. + # Used by Spaces logs and Jobs logs/metrics. Two retry styles: + # - on_iteration_end is None: retries are the only backstop (Spaces). + # - on_iteration_end is set: it polls authoritative state after every + # failed iteration; ReadTimeouts/tolerated errors fall through to it + # instead of consuming retries (Jobs). + nb_tries = 0 + max_retries = 5 if follow else 0 + min_wait_time = 1 + max_wait_time = 10 + sleep_time = 0 + start_event_idx = 0 + error_to_retry: Exception | None = None + while True: + if error_to_retry is not None: + logger.warning(f"'{error_to_retry}' thrown while requesting {log_label}") + logger.warning(f"Retrying in {sleep_time}s [Retry {nb_tries}/{max_retries}].") + error_to_retry = None + time.sleep(sleep_time) + try: + with get_session().stream( + "GET", + url, + headers=self._build_hf_headers(token=token), + timeout=timeout, + ) as response: + if response.status_code == 200: + event_idx = -1 + for line in response.iter_lines(): + if line and line.startswith("data: {"): + event_idx += 1 + if event_idx >= start_event_idx: + if skip_previous_events_on_retry: + start_event_idx += 1 + yield json.loads(line[len("data: ") :]) + break + elif response.status_code not in tolerated_status_codes: + hf_raise_for_status(response) + except HfHubHTTPError: + # Permanent HTTP error (404/403/...). Never retry — fail fast. + raise + except httpx.DecodingError: + # Response ended prematurely. + break + except KeyboardInterrupt: + break + except (httpx.HTTPError, httpcore.TimeoutException) as err: + is_no_new_line_timeout = isinstance(err, (httpx.ReadTimeout, httpcore.ReadTimeout)) + if is_no_new_line_timeout and not follow: + break # no-follow: timeout means the buffer is drained + if on_iteration_end is not None: + # Authoritative-state mode: ReadTimeouts and tolerated errors + # fall through to the post-iteration check without consuming + # retries. Note: ReadTimeout is handled here regardless of + # `tolerated_exception_types` — entries in that tuple only + # fire for non-timeout errors. + if is_no_new_line_timeout or type(err) in tolerated_exception_types: + pass + elif nb_tries >= max_retries: + raise + else: + nb_tries += 1 + sleep_time = min(max_wait_time, max(min_wait_time, sleep_time * 2)) + error_to_retry = err + else: + # Retry-only mode: every error in follow mode burns a retry. + if nb_tries >= max_retries: + if is_no_new_line_timeout: + break # follow mode, silent stream, retries exhausted: give up + raise + nb_tries += 1 + sleep_time = min(max_wait_time, max(min_wait_time, sleep_time * 2)) + error_to_retry = err + if on_iteration_end is not None and on_iteration_end(): + break + + def _fetch_space_logs_sse( + self, + *, + repo_id: str, + build: bool, + timeout: int, + follow: bool, + token: bool | str | None = None, + ) -> Iterable[dict[str, Any]]: + log_type = "build" if build else "run" + yield from self._stream_sse_events( + url=f"{self.endpoint}/api/spaces/{repo_id}/logs/{log_type}", + log_label=f"spaces /logs/{log_type} for repo_id={repo_id!r}", + timeout=timeout, + follow=follow, + token=token, + ) + + @validate_hf_hub_args + def fetch_space_logs( + self, + repo_id: str, + *, + build: bool = False, + follow: bool = False, + token: bool | str | None = None, + ) -> Iterable[str]: + """Fetch the run or build logs of a Space on the Hub. + + Useful for debugging a Space that is failing to build or crashing at runtime, + especially from a script or agentic workflow where reading logs in a browser + is not an option. + + Args: + repo_id (`str`): + ID of the Space. Example: `"bigcode/in-the-stack"`. + build (`bool`, *optional*, defaults to `False`): + If `True`, fetch the container build logs (useful when a Space is stuck + in `BUILD_ERROR`). If `False` (default), fetch the run logs, i.e. the + stdout/stderr of the running application. + follow (`bool`, *optional*, defaults to `False`): + If `True`, stream logs in real-time (blocking) until the server closes + the stream or `KeyboardInterrupt` is raised. If `False` (default), fetch + only the currently buffered logs and return immediately (non-blocking, + like `docker logs`). + token (`bool` or `str`, *optional*): + A valid user access token. Defaults to the locally saved token, which is + the recommended authentication method. Set to `False` to disable + authentication. See + https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Returns: + `Iterable[str]`: A generator yielding log lines as they become available. + + Example: + + ```python + >>> from huggingface_hub import fetch_space_logs + >>> # Non-blocking: print currently available run logs and exit. + >>> for line in fetch_space_logs("username/my-space"): + ... print(line, end="") + + >>> # Debug a build failure: + >>> for line in fetch_space_logs("username/my-space", build=True): + ... print(line, end="") + + >>> # Stream run logs until the server closes the stream. + >>> for line in fetch_space_logs("username/my-space", follow=True): + ... print(line, end="") + ``` + """ + # - Spaces /logs/{run|build} is SSE with `data: {"data": "...", "timestamp": "..."}` events. + # - Keep-alives are sent as empty `data:` messages (skipped by the `data: {` filter). + # - In no-follow mode we use a short read timeout to drain the buffer and return. + timeout = 120 if follow else 5 + for event in self._fetch_space_logs_sse( + repo_id=repo_id, + build=build, + timeout=timeout, + follow=follow, + token=token, + ): + yield event["data"] + + @_deprecate_arguments( + version="2.0", + deprecated_args={"space_storage"}, + custom_message="Use `space_volumes` to mount volumes on a Space.", + ) + @validate_hf_hub_args + def duplicate_repo( + self, + from_id: str, + to_id: str | None = None, + *, + repo_type: str | None = None, + private: bool | None = None, + visibility: RepoVisibility_T | None = None, + token: bool | str | None = None, + exist_ok: bool = False, + space_hardware: SpaceHardware | None = None, + space_storage: SpaceStorage | None = None, + space_sleep_time: int | None = None, + space_secrets: list[dict[str, str]] | None = None, + space_variables: list[dict[str, str]] | None = None, + space_volumes: list[Volume] | None = None, + ) -> RepoUrl: + """Duplicate a repo on the Hub (model, dataset, or Space). + + This performs a server-side copy that preserves full git history and LFS objects + without requiring a local download/upload round-trip. + + Args: + from_id (`str`): + ID of the repo to duplicate. Example: `"openai/gdpval"`. + to_id (`str`, *optional*): + ID of the new repo. Example: `"myorg/my-gdpval"`. If not provided, the new + repo will have the same name as the original repo, but in your account. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if duplicating a dataset or Space, + `None` or `"model"` if duplicating a model. Default is `None`. + private (`bool`, *optional*): + Whether the new repo should be private or not. Defaults to the same + privacy as the original repo. Cannot be passed together with `visibility`. + visibility (`Literal["public", "private", "protected"]`, *optional*): + Visibility of the new repo. Can be `"public"` or `"private"`, or `"protected"` for Spaces. Defaults + to the same visibility as the original repo. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if repo already exists. + space_hardware (`SpaceHardware` or `str`, *optional*): + Choice of Hardware if repo_type is "space". Example: `"t4-medium"`. See + [`SpaceHardware`] for a complete list. + space_storage (`SpaceStorage` or `str`, *optional*): + Choice of persistent storage tier if repo_type is "space". Example: + `"small"`. See [`SpaceStorage`] for a complete list. + space_sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. + Set to `-1` if you don't want your Space to sleep (default behavior for + upgraded hardware). For free hardware, you can't configure the sleep time + (value is fixed to 48 hours of inactivity). Only applicable if repo_type is "space". + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + space_secrets (`list[dict[str, str]]`, *optional*): + A list of secret keys to set in your Space. Each item is in the form + `{"key": ..., "value": ..., "description": ...}` where description is optional. + Only applicable if repo_type is "space". + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + space_variables (`list[dict[str, str]]`, *optional*): + A list of public environment variables to set in your Space. Each item is in + the form `{"key": ..., "value": ..., "description": ...}` where description + is optional. Only applicable if repo_type is "space". + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables. + space_volumes (`list[Volume]`, *optional*): + A list of [`Volume`] objects to mount in the Space at duplication time. Each volume has a `type` + (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), a `source` (repo or bucket ID), a `mount_path` + (path inside the container), and optional `revision`, `read_only`, and `path` fields. + Only applicable if repo_type is "space". + + Returns: + [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing + attributes like `endpoint`, `repo_type` and `repo_id`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + [`HfHubHTTPError`]: + If the HuggingFace API returned an error + + Example: + ```python + >>> from huggingface_hub import duplicate_repo + + # Duplicate a model to your account + >>> duplicate_repo("google/gemma-7b") + RepoUrl('https://huggingface.co/nateraw/gemma-7b',...) + + # Duplicate a dataset with a custom name + >>> duplicate_repo("openai/gdpval", to_id="myorg/my-gdpval", repo_type="dataset") + RepoUrl('https://huggingface.co/datasets/myorg/my-gdpval',...) + + # Duplicate a Space with custom hardware + >>> duplicate_repo("multimodalart/dreambooth-training", repo_type="space", space_hardware="t4-medium") + RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...) + ``` + """ + if repo_type not in constants.REPO_TYPES: + raise ValueError("Invalid repo type") + + resolved_visibility = _resolve_repo_visibility(private=private, visibility=visibility, repo_type=repo_type) + + # Map repo_type to API path segment + api_prefix = { + None: "models", + constants.REPO_TYPE_MODEL: "models", + constants.REPO_TYPE_DATASET: "datasets", + constants.REPO_TYPE_SPACE: "spaces", + }[repo_type] + + # Parse to_id if provided + parsed_to_id = RepoUrl(to_id) if to_id is not None else None + + # Infer target repo_id + to_namespace = ( + parsed_to_id.namespace + if parsed_to_id is not None and parsed_to_id.namespace is not None + else self.whoami(token)["name"] + ) + to_repo_name = parsed_to_id.repo_name if to_id is not None else RepoUrl(from_id).repo_name # type: ignore + + payload: dict[str, Any] = {"repository": f"{to_namespace}/{to_repo_name}"} + + if resolved_visibility is not None: + payload["visibility"] = resolved_visibility + + # Space-specific options + space_args: list[tuple[str, str, Any]] = [ + # input arg, payload key, value + ("space_hardware", "hardware", space_hardware), + ("space_storage", "storageTier", space_storage), + ("space_sleep_time", "sleepTimeSeconds", space_sleep_time), + ("space_secrets", "secrets", space_secrets), + ("space_variables", "variables", space_variables), + ("space_volumes", "volumes", [v.to_dict() for v in space_volumes] if space_volumes else None), + ] + + if repo_type == "space": + for _, key, value in space_args: + if value is not None: + payload[key] = value + if space_sleep_time is not None and space_hardware == SpaceHardware.CPU_BASIC: + warnings.warn( + "If your Space runs on the default 'cpu-basic' hardware, it will go to sleep if inactive for more" + " than 48 hours. This value is not configurable. If you don't want your Space to deactivate or if" + " you want to set a custom sleep time, you need to upgrade to a paid Hardware.", + UserWarning, + ) + else: + if provided_space_args := [arg for arg, _, value in space_args if value is not None]: + warnings.warn(f"Ignoring provided {', '.join(provided_space_args)} because repo_type is not 'space'.") + + r = get_session().post( + f"{self.endpoint}/api/{api_prefix}/{from_id}/duplicate", + headers=self._build_hf_headers(token=token), + json=payload, + ) + + try: + hf_raise_for_status(r) + except HfHubHTTPError as err: + if exist_ok and err.response.status_code == 409: + pass + else: + raise + + return RepoUrl(r.json()["url"], endpoint=self.endpoint) + + @_deprecate_method(version="2.0", message="Use `duplicate_repo` instead.") + @validate_hf_hub_args + def duplicate_space( + self, + from_id: str, + to_id: str | None = None, + *, + private: bool | None = None, + visibility: RepoVisibility_T | None = None, + token: bool | str | None = None, + exist_ok: bool = False, + hardware: SpaceHardware | None = None, + storage: SpaceStorage | None = None, + sleep_time: int | None = None, + secrets: list[dict[str, str]] | None = None, + variables: list[dict[str, str]] | None = None, + ) -> RepoUrl: + """Duplicate a Space. + + Programmatically duplicate a Space. The new Space will be created in your account and will be in the same state + as the original Space (running or paused). You can duplicate a Space no matter the current state of a Space. + + Args: + from_id (`str`): + ID of the Space to duplicate. Example: `"pharma/CLIP-Interrogator"`. + to_id (`str`, *optional*): + ID of the new Space. Example: `"dog/CLIP-Interrogator"`. If not provided, the new Space will have the same + name as the original Space, but in your account. + private (`bool`, *optional*): + Whether the new Space should be private or not. Defaults to the same privacy as the original Space. Cannot be passed together with `visibility`. + visibility (`Literal["public", "private", "protected"]`, *optional*): + Visibility of the new Space. Can be `"public"`, `"private"`, or `"protected"`. Defaults to the same + visibility as the original Space. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if repo already exists. + hardware (`SpaceHardware` or `str`, *optional*): + Choice of Hardware. Example: `"t4-medium"`. See [`SpaceHardware`] for a complete list. + storage (`SpaceStorage` or `str`, *optional*): + Choice of persistent storage tier. Example: `"small"`. See [`SpaceStorage`] for a complete list. + sleep_time (`int`, *optional*): + Number of seconds of inactivity to wait before a Space is put to sleep. Set to `-1` if you don't want + your Space to sleep (default behavior for upgraded hardware). For free hardware, you can't configure + the sleep time (value is fixed to 48 hours of inactivity). + See https://huggingface.co/docs/hub/spaces-gpus#sleep-time for more details. + secrets (`list[dict[str, str]]`, *optional*): + A list of secret keys to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets. + variables (`list[dict[str, str]]`, *optional*): + A list of public environment variables to set in your Space. Each item is in the form `{"key": ..., "value": ..., "description": ...}` where description is optional. + For more details, see https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables. + + Returns: + [`RepoUrl`]: URL to the newly created repo. Value is a subclass of `str` containing + attributes like `endpoint`, `repo_type` and `repo_id`. + + Raises: + [`~utils.RepositoryNotFoundError`]: + If one of `from_id` or `to_id` cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + [`HfHubHTTPError`]: + If the HuggingFace API returned an error + + Example: + ```python + >>> from huggingface_hub import duplicate_space + + # Duplicate a Space to your account + >>> duplicate_space("multimodalart/dreambooth-training") + RepoUrl('https://huggingface.co/spaces/nateraw/dreambooth-training',...) + + # Can set custom destination id and visibility flag. + >>> duplicate_space("multimodalart/dreambooth-training", to_id="my-dreambooth", visibility="private") + RepoUrl('https://huggingface.co/spaces/nateraw/my-dreambooth',...) + ``` + + > [!WARNING] + > `duplicate_space` is deprecated and will be removed in version 2.0. Use [`~HfApi.duplicate_repo`] instead. + """ + kwargs: dict[str, Any] = {} + if to_id is not None: + kwargs["to_id"] = to_id + return self.duplicate_repo( + from_id=from_id, + repo_type="space", + private=private, + visibility=visibility, + token=token, + exist_ok=exist_ok, + space_hardware=hardware, + space_storage=storage, + space_sleep_time=sleep_time, + space_secrets=secrets, + space_variables=variables, + **kwargs, + ) + + @_deprecate_method(version="2.0", message="Use `set_space_volumes` instead.") + @validate_hf_hub_args + def request_space_storage( + self, + repo_id: str, + storage: SpaceStorage, + *, + token: bool | str | None = None, + ) -> SpaceRuntime: + """Request persistent storage for a Space. + + > [!WARNING] + > `request_space_storage` is deprecated and will be removed in version 2.0. Use [`set_space_volumes`] instead. + + Args: + repo_id (`str`): + ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`. + storage (`str` or [`SpaceStorage`]): + Storage tier. Either 'small', 'medium', or 'large'. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + """ + payload: dict[str, SpaceStorage] = {"tier": storage} + r = get_session().post( + f"{self.endpoint}/api/spaces/{repo_id}/storage", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @_deprecate_method(version="2.0", message="Use `delete_space_volumes` instead.") + @validate_hf_hub_args + def delete_space_storage( + self, + repo_id: str, + *, + token: bool | str | None = None, + ) -> SpaceRuntime: + """Delete persistent storage for a Space. + + > [!WARNING] + > `delete_space_storage` is deprecated and will be removed in version 2.0. Use [`delete_space_volumes`] instead. + + Args: + repo_id (`str`): + ID of the Space to update. Example: `"open-llm-leaderboard/open_llm_leaderboard"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + Returns: + [`SpaceRuntime`]: Runtime information about a Space including Space stage and hardware. + Raises: + [`BadRequestError`] + If space has no persistent storage. + """ + r = get_session().delete( + f"{self.endpoint}/api/spaces/{repo_id}/storage", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + return SpaceRuntime(r.json()) + + @validate_hf_hub_args + def set_space_volumes( + self, + repo_id: str, + volumes: list[Volume], + *, + token: bool | str | None = None, + ) -> None: + """Set volumes for a Space. + + Sets (or replaces) the list of volumes mounted in the Space. Each volume gives the Space's container access + to a Hub resource (model, dataset, or storage bucket). + + Args: + repo_id (`str`): + ID of the Space to update. Example: `"username/my-space"`. + volumes (`list[Volume]`): + List of [`Volume`] objects to mount. Each volume has a `type` (`"bucket"`, `"model"`, `"dataset"`, or + `"space"`), a `source` (repo or bucket ID), a `mount_path` (path inside the container), and optional + `revision`, `read_only`, and `path` fields. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`BadRequestError`]: + If the Space is a static Space (volumes are not supported on static Spaces). + + Example: + ```python + >>> from huggingface_hub import HfApi, Volume + >>> api = HfApi() + >>> api.set_space_volumes( + ... "username/my-space", + ... volumes=[ + ... Volume(type="model", source="username/my-model", mount_path="/models", read_only=True), + ... Volume(type="bucket", source="username/my-bucket", mount_path="/data"), + ... ], + ... ) + ``` + """ + payload = {"volumes": [vol.to_dict() for vol in volumes]} + r = get_session().put( + f"{self.endpoint}/api/spaces/{repo_id}/volumes", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(r) + + @validate_hf_hub_args + def delete_space_volumes( + self, + repo_id: str, + *, + token: bool | str | None = None, + ) -> None: + """Remove all volumes from a Space. + + Args: + repo_id (`str`): + ID of the Space to update. Example: `"username/my-space"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`BadRequestError`]: + If the Space has no volumes attached. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> api.delete_space_volumes("username/my-space") + ``` + """ + r = get_session().delete( + f"{self.endpoint}/api/spaces/{repo_id}/volumes", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + + ####################### + # Inference Endpoints # + ####################### + + def list_inference_endpoints( + self, namespace: str | None = None, *, token: bool | str | None = None + ) -> list[InferenceEndpoint]: + """Lists all inference endpoints for the given namespace. + + Args: + namespace (`str`, *optional*): + The namespace to list endpoints for. Defaults to the current user. Set to `"*"` to list all endpoints + from all namespaces (i.e. personal namespace and all orgs the user belongs to). + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + list[`InferenceEndpoint`]: A list of all inference endpoints for the given namespace. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> api.list_inference_endpoints() + [InferenceEndpoint(name='my-endpoint', ...), ...] + ``` + """ + # Special case: list all endpoints for all namespaces the user has access to + if namespace == "*": + user = self.whoami(token=token) + + # List personal endpoints first + endpoints: list[InferenceEndpoint] = list_inference_endpoints(namespace=self._get_namespace(token=token)) + + # Then list endpoints for all orgs the user belongs to and ignore 401 errors (no billing or no access) + for org in user.get("orgs", []): + try: + endpoints += list_inference_endpoints(namespace=org["name"], token=token) + except HfHubHTTPError as error: + if error.response.status_code == 401: # Either no billing or user don't have access) + logger.debug("Cannot list Inference Endpoints for org '%s': %s", org["name"], error) + pass + + return endpoints + + # Normal case: list endpoints for a specific namespace + namespace = namespace or self._get_namespace(token=token) + + response = get_session().get( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return [ + InferenceEndpoint.from_raw(endpoint, namespace=namespace, token=token) + for endpoint in response.json()["items"] + ] + + def create_inference_endpoint( + self, + name: str, + *, + repository: str, + framework: str, + accelerator: str, + instance_size: str, + instance_type: str, + region: str, + vendor: str, + account_id: str | None = None, + min_replica: int = 1, + max_replica: int = 1, + scaling_metric: InferenceEndpointScalingMetric | None = None, + scaling_threshold: float | None = None, + scale_to_zero_timeout: int | None = None, + revision: str | None = None, + task: str | None = None, + custom_image: dict | None = None, + env: dict[str, str] | None = None, + secrets: dict[str, str] | None = None, + type: InferenceEndpointType = InferenceEndpointType.PROTECTED, + domain: str | None = None, + path: str | None = None, + cache_http_responses: bool | None = None, + tags: list[str] | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> InferenceEndpoint: + """Create a new Inference Endpoint. + + Args: + name (`str`): + The unique name for the new Inference Endpoint. + repository (`str`): + The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`). + framework (`str`): + The machine learning framework used for the model (e.g. `"custom"`). + accelerator (`str`): + The hardware accelerator to be used for inference (e.g. `"cpu"`). + instance_size (`str`): + The size or type of the instance to be used for hosting the model (e.g. `"x4"`). + instance_type (`str`): + The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`). + region (`str`): + The cloud region in which the Inference Endpoint will be created (e.g. `"us-east-1"`). + vendor (`str`): + The cloud provider or vendor where the Inference Endpoint will be hosted (e.g. `"aws"`). + account_id (`str`, *optional*): + The account ID used to link a VPC to a private Inference Endpoint (if applicable). + min_replica (`int`, *optional*): + The minimum number of replicas (instances) to keep running for the Inference Endpoint. To enable + scaling to zero, set this value to 0 and adjust `scale_to_zero_timeout` accordingly. Defaults to 1. + max_replica (`int`, *optional*): + The maximum number of replicas (instances) to scale to for the Inference Endpoint. Defaults to 1. + scaling_metric (`str` or [`InferenceEndpointScalingMetric `], *optional*): + The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided. Defaults to + None (meaning: let the HF Endpoints service specify the metric). + scaling_threshold (`float`, *optional*): + The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided. + Defaults to None (meaning: let the HF Endpoints service specify the threshold). + scale_to_zero_timeout (`int`, *optional*): + The duration in minutes before an inactive endpoint is scaled to zero, or no scaling to zero if + set to None and `min_replica` is not 0. Defaults to None. + revision (`str`, *optional*): + The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`). + task (`str`, *optional*): + The task on which to deploy the model (e.g. `"text-classification"`). + custom_image (`dict`, *optional*): + A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an + Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples). + env (`dict[str, str]`, *optional*): + Non-secret environment variables to inject in the container environment. + secrets (`dict[str, str]`, *optional*): + Secret values to inject in the container environment. + type ([`InferenceEndpointType]`, *optional*): + The type of the Inference Endpoint, which can be `"protected"` (default), `"public"` or `"private"`. + domain (`str`, *optional*): + The custom domain for the Inference Endpoint deployment, if setup the inference endpoint will be available at this domain (e.g. `"my-new-domain.cool-website.woof"`). + path (`str`, *optional*): + The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`). + cache_http_responses (`bool`, *optional*): + Whether to cache HTTP responses from the Inference Endpoint. Defaults to `False`. + tags (`list[str]`, *optional*): + A list of tags to associate with the Inference Endpoint. + namespace (`str`, *optional*): + The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`InferenceEndpoint`]: information about the updated Inference Endpoint. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> endpoint = api.create_inference_endpoint( + ... "my-endpoint-name", + ... repository="gpt2", + ... framework="pytorch", + ... task="text-generation", + ... accelerator="cpu", + ... vendor="aws", + ... region="us-east-1", + ... type="protected", + ... instance_size="x2", + ... instance_type="intel-icl", + ... ) + >>> endpoint + InferenceEndpoint(name='my-endpoint-name', status="pending",...) + + # Run inference on the endpoint + >>> endpoint.client.text_generation(...) + "..." + ``` + + ```python + # Start an Inference Endpoint running Zephyr-7b-beta on TGI + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> endpoint = api.create_inference_endpoint( + ... "aws-zephyr-7b-beta-0486", + ... repository="HuggingFaceH4/zephyr-7b-beta", + ... framework="pytorch", + ... task="text-generation", + ... accelerator="gpu", + ... vendor="aws", + ... region="us-east-1", + ... type="protected", + ... instance_size="x1", + ... instance_type="nvidia-a10g", + ... env={ + ... "MAX_BATCH_PREFILL_TOKENS": "2048", + ... "MAX_INPUT_LENGTH": "1024", + ... "MAX_TOTAL_TOKENS": "1512", + ... "MODEL_ID": "/repository" + ... }, + ... custom_image={ + ... "health_route": "/health", + ... "url": "ghcr.io/huggingface/text-generation-inference:1.1.0", + ... }, + ... secrets={"MY_SECRET_KEY": "secret_value"}, + ... tags=["dev", "text-generation"], + ... ) + ``` + + ```python + # Start an Inference Endpoint running ProsusAI/finbert while scaling to zero in 15 minutes + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> endpoint = api.create_inference_endpoint( + ... "finbert-classifier", + ... repository="ProsusAI/finbert", + ... framework="pytorch", + ... task="text-classification", + ... min_replica=0, + ... scale_to_zero_timeout=15, + ... accelerator="cpu", + ... vendor="aws", + ... region="us-east-1", + ... type="protected", + ... instance_size="x2", + ... instance_type="intel-icl", + ... ) + >>> endpoint.wait(timeout=300) + # Run inference on the endpoint + >>> endpoint.client.text_generation(...) + TextClassificationOutputElement(label='positive', score=0.8983615040779114) + ``` + + """ + namespace = namespace or self._get_namespace(token=token) + + if custom_image is not None: + image = ( + custom_image + if next(iter(custom_image)) in constants.INFERENCE_ENDPOINT_IMAGE_KEYS + else {"custom": custom_image} + ) + else: + image = {"huggingface": {}} + + payload: dict = { + "accountId": account_id, + "compute": { + "accelerator": accelerator, + "instanceSize": instance_size, + "instanceType": instance_type, + "scaling": { + "maxReplica": max_replica, + "minReplica": min_replica, + "scaleToZeroTimeout": scale_to_zero_timeout, + }, + }, + "model": { + "framework": framework, + "repository": repository, + "revision": revision, + "task": task, + "image": image, + }, + "name": name, + "provider": { + "region": region, + "vendor": vendor, + }, + "type": type, + } + if scaling_metric: + payload["compute"]["scaling"]["measure"] = {scaling_metric: scaling_threshold} # type: ignore + if env: + payload["model"]["env"] = env + if secrets: + payload["model"]["secrets"] = secrets + if domain is not None or path is not None: + payload["route"] = {} + if domain is not None: + payload["route"]["domain"] = domain + if path is not None: + payload["route"]["path"] = path + if cache_http_responses is not None: + payload["cacheHttpResponses"] = cache_http_responses + if tags is not None: + payload["tags"] = tags + + response = get_session().post( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + @experimental + @validate_hf_hub_args + def create_inference_endpoint_from_catalog( + self, + repo_id: str, + *, + name: str | None = None, + accelerator: Literal["cpu", "gpu", "neuron"] | str | None = None, + token: bool | str | None = None, + namespace: str | None = None, + ) -> InferenceEndpoint: + """Create a new Inference Endpoint from a model in the Hugging Face Inference Catalog. + + The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference + and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list + of available models in the catalog. + + Args: + repo_id (`str`): + The ID of the model in the catalog to deploy as an Inference Endpoint. + name (`str`, *optional*): + The unique name for the new Inference Endpoint. If not provided, a random name will be generated. + accelerator (`str`, *optional*): + The hardware accelerator to be used for inference. Possible values include `"cpu"`, `"gpu"`, and + `"neuron"`. If not provided, the server will use a default appropriate for the model. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + namespace (`str`, *optional*): + The namespace where the Inference Endpoint will be created. Defaults to the current user's namespace. + + Returns: + [`InferenceEndpoint`]: information about the new Inference Endpoint. + + > [!WARNING] + > `create_inference_endpoint_from_catalog` is experimental. Its API is subject to change in the future. Please provide feedback + > if you have any suggestions or requests. + """ + token = token or self.token or get_token() + payload: dict = { + "namespace": namespace or self._get_namespace(token=token), + "repoId": repo_id, + } + if name is not None: + payload["endpointName"] = name + if accelerator is not None: + payload["accelerator"] = accelerator + + response = get_session().post( + f"{constants.INFERENCE_CATALOG_ENDPOINT}/deploy", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(response) + data = response.json()["endpoint"] + return InferenceEndpoint.from_raw(data, namespace=data["name"], token=token) + + @experimental + @validate_hf_hub_args + def list_inference_catalog(self, *, token: bool | str | None = None) -> list[str]: + """List models available in the Hugging Face Inference Catalog. + + The goal of the Inference Catalog is to provide a curated list of models that are optimized for inference + and for which default configurations have been tested. See https://endpoints.huggingface.co/catalog for a list + of available models in the catalog. + + Use [`create_inference_endpoint_from_catalog`] to deploy a model from the catalog. + + Args: + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + + Returns: + List[`str`]: A list of model IDs available in the catalog. + > [!WARNING] + > `list_inference_catalog` is experimental. Its API is subject to change in the future. Please provide feedback + > if you have any suggestions or requests. + """ + response = get_session().get( + f"{constants.INFERENCE_CATALOG_ENDPOINT}/repo-list", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + return response.json()["models"] + + def get_inference_endpoint( + self, name: str, *, namespace: str | None = None, token: bool | str | None = None + ) -> InferenceEndpoint: + """Get information about an Inference Endpoint. + + Args: + name (`str`): + The name of the Inference Endpoint to retrieve information about. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`InferenceEndpoint`]: information about the requested Inference Endpoint. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> endpoint = api.get_inference_endpoint("my-text-to-image") + >>> endpoint + InferenceEndpoint(name='my-text-to-image', ...) + + # Get status + >>> endpoint.status + 'running' + >>> endpoint.url + 'https://my-text-to-image.region.vendor.endpoints.huggingface.cloud' + + # Run inference + >>> endpoint.client.text_to_image(...) + ``` + """ + namespace = namespace or self._get_namespace(token=token) + + response = get_session().get( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def update_inference_endpoint( + self, + name: str, + *, + # Compute update + accelerator: str | None = None, + instance_size: str | None = None, + instance_type: str | None = None, + min_replica: int | None = None, + max_replica: int | None = None, + scale_to_zero_timeout: int | None = None, + scaling_metric: InferenceEndpointScalingMetric | None = None, + scaling_threshold: float | None = None, + # Model update + repository: str | None = None, + framework: str | None = None, + revision: str | None = None, + task: str | None = None, + custom_image: dict | None = None, + env: dict[str, str] | None = None, + secrets: dict[str, str] | None = None, + # Route update + domain: str | None = None, + path: str | None = None, + # Other + cache_http_responses: bool | None = None, + tags: list[str] | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> InferenceEndpoint: + """Update an Inference Endpoint. + + This method allows the update of either the compute configuration, the deployed model, the route, or any combination. + All arguments are optional but at least one must be provided. + + For convenience, you can also update an Inference Endpoint using [`InferenceEndpoint.update`]. + + Args: + name (`str`): + The name of the Inference Endpoint to update. + + accelerator (`str`, *optional*): + The hardware accelerator to be used for inference (e.g. `"cpu"`). + instance_size (`str`, *optional*): + The size or type of the instance to be used for hosting the model (e.g. `"x4"`). + instance_type (`str`, *optional*): + The cloud instance type where the Inference Endpoint will be deployed (e.g. `"intel-icl"`). + min_replica (`int`, *optional*): + The minimum number of replicas (instances) to keep running for the Inference Endpoint. + max_replica (`int`, *optional*): + The maximum number of replicas (instances) to scale to for the Inference Endpoint. + scale_to_zero_timeout (`int`, *optional*): + The duration in minutes before an inactive endpoint is scaled to zero. + scaling_metric (`str` or [`InferenceEndpointScalingMetric `], *optional*): + The metric reference for scaling. Either "pendingRequests" or "hardwareUsage" when provided. + Defaults to None. + scaling_threshold (`float`, *optional*): + The scaling metric threshold used to trigger a scale up. Ignored when scaling metric is not provided. + Defaults to None. + repository (`str`, *optional*): + The name of the model repository associated with the Inference Endpoint (e.g. `"gpt2"`). + framework (`str`, *optional*): + The machine learning framework used for the model (e.g. `"custom"`). + revision (`str`, *optional*): + The specific model revision to deploy on the Inference Endpoint (e.g. `"6c0e6080953db56375760c0471a8c5f2929baf11"`). + task (`str`, *optional*): + The task on which to deploy the model (e.g. `"text-classification"`). + custom_image (`dict`, *optional*): + A custom Docker image to use for the Inference Endpoint. This is useful if you want to deploy an + Inference Endpoint running on the `text-generation-inference` (TGI) framework (see examples). + env (`dict[str, str]`, *optional*): + Non-secret environment variables to inject in the container environment + secrets (`dict[str, str]`, *optional*): + Secret values to inject in the container environment. + + domain (`str`, *optional*): + The custom domain for the Inference Endpoint deployment, if setup the inference endpoint will be available at this domain (e.g. `"my-new-domain.cool-website.woof"`). + path (`str`, *optional*): + The custom path to the deployed model, should start with a `/` (e.g. `"/models/google-bert/bert-base-uncased"`). + + cache_http_responses (`bool`, *optional*): + Whether to cache HTTP responses from the Inference Endpoint. + tags (`list[str]`, *optional*): + A list of tags to associate with the Inference Endpoint. + + namespace (`str`, *optional*): + The namespace where the Inference Endpoint will be updated. Defaults to the current user's namespace. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`InferenceEndpoint`]: information about the updated Inference Endpoint. + """ + namespace = namespace or self._get_namespace(token=token) + + # Populate only the fields that are not None + payload: dict = defaultdict(lambda: defaultdict(dict)) + if accelerator is not None: + payload["compute"]["accelerator"] = accelerator + if instance_size is not None: + payload["compute"]["instanceSize"] = instance_size + if instance_type is not None: + payload["compute"]["instanceType"] = instance_type + if max_replica is not None: + payload["compute"]["scaling"]["maxReplica"] = max_replica + if min_replica is not None: + payload["compute"]["scaling"]["minReplica"] = min_replica + if scale_to_zero_timeout is not None: + payload["compute"]["scaling"]["scaleToZeroTimeout"] = scale_to_zero_timeout + if scaling_metric: + payload["compute"]["scaling"]["measure"] = {scaling_metric: scaling_threshold} + if repository is not None: + payload["model"]["repository"] = repository + if framework is not None: + payload["model"]["framework"] = framework + if revision is not None: + payload["model"]["revision"] = revision + if task is not None: + payload["model"]["task"] = task + if custom_image is not None: + payload["model"]["image"] = {"custom": custom_image} + if env is not None: + payload["model"]["env"] = env + if secrets is not None: + payload["model"]["secrets"] = secrets + if domain is not None: + payload["route"]["domain"] = domain + if path is not None: + payload["route"]["path"] = path + if cache_http_responses is not None: + payload["cacheHttpResponses"] = cache_http_responses + if tags is not None: + payload["tags"] = tags + + response = get_session().put( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def delete_inference_endpoint( + self, name: str, *, namespace: str | None = None, token: bool | str | None = None + ) -> None: + """Delete an Inference Endpoint. + + This operation is not reversible. If you don't want to be charged for an Inference Endpoint, it is preferable + to pause it with [`pause_inference_endpoint`] or scale it to zero with [`scale_to_zero_inference_endpoint`]. + + For convenience, you can also delete an Inference Endpoint using [`InferenceEndpoint.delete`]. + + Args: + name (`str`): + The name of the Inference Endpoint to delete. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + """ + namespace = namespace or self._get_namespace(token=token) + response = get_session().delete( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + def pause_inference_endpoint( + self, name: str, *, namespace: str | None = None, token: bool | str | None = None + ) -> InferenceEndpoint: + """Pause an Inference Endpoint. + + A paused Inference Endpoint will not be charged. It can be resumed at any time using [`resume_inference_endpoint`]. + This is different than scaling the Inference Endpoint to zero with [`scale_to_zero_inference_endpoint`], which + would be automatically restarted when a request is made to it. + + For convenience, you can also pause an Inference Endpoint using [`pause_inference_endpoint`]. + + Args: + name (`str`): + The name of the Inference Endpoint to pause. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`InferenceEndpoint`]: information about the paused Inference Endpoint. + """ + namespace = namespace or self._get_namespace(token=token) + + response = get_session().post( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/pause", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def resume_inference_endpoint( + self, + name: str, + *, + namespace: str | None = None, + running_ok: bool = True, + token: bool | str | None = None, + ) -> InferenceEndpoint: + """Resume an Inference Endpoint. + + For convenience, you can also resume an Inference Endpoint using [`InferenceEndpoint.resume`]. + + Args: + name (`str`): + The name of the Inference Endpoint to resume. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + running_ok (`bool`, *optional*): + If `True`, the method will not raise an error if the Inference Endpoint is already running. Defaults to + `True`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`InferenceEndpoint`]: information about the resumed Inference Endpoint. + """ + namespace = namespace or self._get_namespace(token=token) + + response = get_session().post( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/resume", + headers=self._build_hf_headers(token=token), + ) + try: + hf_raise_for_status(response) + except HfHubHTTPError as error: + # If already running (and it's ok), then fetch current status and return + if running_ok and error.response.status_code == 400 and "already running" in error.response.text: + return self.get_inference_endpoint(name, namespace=namespace, token=token) + # Otherwise, raise the error + raise + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def scale_to_zero_inference_endpoint( + self, name: str, *, namespace: str | None = None, token: bool | str | None = None + ) -> InferenceEndpoint: + """Scale Inference Endpoint to zero. + + An Inference Endpoint scaled to zero will not be charged. It will be resume on the next request to it, with a + cold start delay. This is different than pausing the Inference Endpoint with [`pause_inference_endpoint`], which + would require a manual resume with [`resume_inference_endpoint`]. + + For convenience, you can also scale an Inference Endpoint to zero using [`InferenceEndpoint.scale_to_zero`]. + + Args: + name (`str`): + The name of the Inference Endpoint to scale to zero. + namespace (`str`, *optional*): + The namespace in which the Inference Endpoint is located. Defaults to the current user. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`InferenceEndpoint`]: information about the scaled-to-zero Inference Endpoint. + """ + namespace = namespace or self._get_namespace(token=token) + + response = get_session().post( + f"{constants.INFERENCE_ENDPOINTS_ENDPOINT}/endpoint/{namespace}/{name}/scale-to-zero", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + return InferenceEndpoint.from_raw(response.json(), namespace=namespace, token=token) + + def _get_namespace(self, token: bool | str | None = None) -> str: + """Get the default namespace for the current user.""" + me = self.whoami(token=token) + if me["type"] == "user": + return me["name"] + else: + raise ValueError( + "Cannot determine default namespace. You must provide a 'namespace' as input or be logged in as a" + " user." + ) + + ######################## + # Collection Endpoints # + ######################## + @validate_hf_hub_args + def list_collections( + self, + *, + owner: list[str] | str | None = None, + item: list[str] | str | None = None, + sort: CollectionSort_T | None = None, + limit: int | None = None, + token: bool | str | None = None, + ) -> Iterable[Collection]: + """List collections on the Huggingface Hub, given some filters. + + > [!WARNING] + > When listing collections, the item list per collection is truncated to 4 items maximum. To retrieve all items + > from a collection, you must use [`get_collection`]. + + Args: + owner (`list[str]` or `str`, *optional*): + Filter by owner's username. + item (`list[str]` or `str`, *optional*): + Filter collections containing a particular items. Example: `"models/teknium/OpenHermes-2.5-Mistral-7B"`, `"datasets/squad"` or `"papers/2311.12983"`. + sort (`Literal["lastModified", "trending", "upvotes"]`, *optional*): + Sort collections by last modified, trending or upvotes. + limit (`int`, *optional*): + Maximum number of collections to be returned. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[Collection]`: an iterable of [`Collection`] objects. + """ + # Construct the API endpoint + path = f"{self.endpoint}/api/collections" + headers = self._build_hf_headers(token=token) + params: dict = {} + if owner is not None: + params.update({"owner": owner}) + if item is not None: + params.update({"item": item}) + if sort is not None: + params.update({"sort": sort}) + if limit is not None: + params.update({"limit": limit}) + + # Paginate over the results until limit is reached + items = paginate(path, headers=headers, params=params) + if limit is not None: + items = islice(items, limit) # Do not iterate over all pages + + # Parse as Collection and return + for position, collection_data in enumerate(items): + yield Collection(position=position, **collection_data) + + def get_collection(self, collection_slug: str, *, token: bool | str | None = None) -> Collection: + """Gets information about a Collection on the Hub. + + Args: + collection_slug (`str`): + Slug of the collection of the Hub. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: [`Collection`] + + Example: + + ```py + >>> from huggingface_hub import get_collection + >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026") + >>> collection.title + 'Recent models' + >>> len(collection.items) + 37 + >>> collection.items[0] + CollectionItem( + item_object_id='651446103cd773a050bf64c2', + item_id='TheBloke/U-Amethyst-20B-AWQ', + item_type='model', + position=88, + note=None + ) + ``` + """ + r = get_session().get( + f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(r) + return Collection(**{**r.json(), "endpoint": self.endpoint}) + + def create_collection( + self, + title: str, + *, + namespace: str | None = None, + description: str | None = None, + private: bool = False, + exists_ok: bool = False, + token: bool | str | None = None, + ) -> Collection: + """Create a new Collection on the Hub. + + Args: + title (`str`): + Title of the collection to create. Example: `"Recent models"`. + namespace (`str`, *optional*): + Namespace of the collection to create (username or org). Will default to the owner name. + description (`str`, *optional*): + Description of the collection to create. + private (`bool`, *optional*): + Whether the collection should be private or not. Defaults to `False` (i.e. public collection). + exists_ok (`bool`, *optional*): + If `True`, do not raise an error if collection already exists. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: [`Collection`] + + Example: + + ```py + >>> from huggingface_hub import create_collection + >>> collection = create_collection( + ... title="ICCV 2023", + ... description="Portfolio of models, papers and demos I presented at ICCV 2023", + ... ) + >>> collection.slug + "username/iccv-2023-64f9a55bb3115b4f513ec026" + ``` + """ + if namespace is None: + namespace = self.whoami(token)["name"] + + payload = { + "title": title, + "namespace": namespace, + "private": private, + } + if description is not None: + payload["description"] = description + + r = get_session().post( + f"{self.endpoint}/api/collections", headers=self._build_hf_headers(token=token), json=payload + ) + try: + hf_raise_for_status(r) + except HfHubHTTPError as err: + if exists_ok and err.response.status_code == 409: + # Collection already exists and `exists_ok=True` + slug = r.json()["slug"] + return self.get_collection(slug, token=token) + else: + raise + return Collection(**{**r.json(), "endpoint": self.endpoint}) + + def update_collection_metadata( + self, + collection_slug: str, + *, + title: str | None = None, + description: str | None = None, + position: int | None = None, + private: bool | None = None, + theme: str | None = None, + token: bool | str | None = None, + ) -> Collection: + """Update metadata of a collection on the Hub. + + All arguments are optional. Only provided metadata will be updated. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + title (`str`): + Title of the collection to update. + description (`str`, *optional*): + Description of the collection to update. + position (`int`, *optional*): + New position of the collection in the list of collections of the user. + private (`bool`, *optional*): + Whether the collection should be private or not. + theme (`str`, *optional*): + Theme of the collection on the Hub. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: [`Collection`] + + Example: + + ```py + >>> from huggingface_hub import update_collection_metadata + >>> collection = update_collection_metadata( + ... collection_slug="username/iccv-2023-64f9a55bb3115b4f513ec026", + ... title="ICCV Oct. 2023" + ... description="Portfolio of models, datasets, papers and demos I presented at ICCV Oct. 2023", + ... private=False, + ... theme="pink", + ... ) + >>> collection.slug + "username/iccv-oct-2023-64f9a55bb3115b4f513ec026" + # ^collection slug got updated but not the trailing ID + ``` + """ + payload = { + "position": position, + "private": private, + "theme": theme, + "title": title, + "description": description, + } + r = get_session().patch( + f"{self.endpoint}/api/collections/{collection_slug}", + headers=self._build_hf_headers(token=token), + # Only send not-none values to the API + json={key: value for key, value in payload.items() if value is not None}, + ) + hf_raise_for_status(r) + return Collection(**{**r.json()["data"], "endpoint": self.endpoint}) + + def delete_collection( + self, collection_slug: str, *, missing_ok: bool = False, token: bool | str | None = None + ) -> None: + """Delete a collection on the Hub. + + Args: + collection_slug (`str`): + Slug of the collection to delete. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + missing_ok (`bool`, *optional*): + If `True`, do not raise an error if collection doesn't exists. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + + ```py + >>> from huggingface_hub import delete_collection + >>> collection = delete_collection("username/useless-collection-64f9a55bb3115b4f513ec026", missing_ok=True) + ``` + + > [!WARNING] + > This is a non-revertible action. A deleted collection cannot be restored. + """ + r = get_session().delete( + f"{self.endpoint}/api/collections/{collection_slug}", headers=self._build_hf_headers(token=token) + ) + try: + hf_raise_for_status(r) + except HfHubHTTPError as err: + if missing_ok and err.response.status_code == 404: + # Collection doesn't exists and `missing_ok=True` + return + else: + raise + + def add_collection_item( + self, + collection_slug: str, + item_id: str, + item_type: CollectionItemType_T, + *, + note: str | None = None, + exists_ok: bool = False, + token: bool | str | None = None, + ) -> Collection: + """Add an item to a collection on the Hub. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + item_id (`str`): + Id of the item to add to the collection. Use the repo_id for repos/spaces/datasets, + the paper id for papers, the slug of another collection (e.g. `"moonshotai/kimi-k2"`) + or a bucket id (e.g. `"namespace/bucket-name"`). + item_type (`str`): + Type of the item to add. Can be one of `"model"`, `"dataset"`, `"space"`, `"paper"`, `"collection"` + or `"bucket"`. + note (`str`, *optional*): + A note to attach to the item in the collection. The maximum size for a note is 500 characters. + exists_ok (`bool`, *optional*): + If `True`, do not raise an error if item already exists. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: [`Collection`] + + Raises: + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + [`HfHubHTTPError`]: + HTTP 404 if the item you try to add to the collection does not exist on the Hub. + [`HfHubHTTPError`]: + HTTP 409 if the item you try to add to the collection is already in the collection (and exists_ok=False) + + Example: + + ```py + >>> from huggingface_hub import add_collection_item + >>> collection = add_collection_item( + ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab", + ... item_id="pierre-loic/climate-news-articles", + ... item_type="dataset" + ... ) + >>> collection.items[-1].item_id + "pierre-loic/climate-news-articles" + # ^item got added to the collection on last position + + # Add item with a note + >>> add_collection_item( + ... collection_slug="davanstrien/climate-64f99dc2a5067f6b65531bab", + ... item_id="datasets/climate_fever", + ... item_type="dataset" + ... note="This dataset adopts the FEVER methodology that consists of 1,535 real-world claims regarding climate-change collected on the internet." + ... ) + (...) + ``` + """ + payload: dict[str, Any] = {"item": {"id": item_id, "type": item_type}} + if note is not None: + payload["note"] = note + r = get_session().post( + f"{self.endpoint}/api/collections/{collection_slug}/items", + headers=self._build_hf_headers(token=token), + json=payload, + ) + try: + hf_raise_for_status(r) + except HfHubHTTPError as err: + if exists_ok and err.response.status_code == 409: + # Item already exists and `exists_ok=True` + return self.get_collection(collection_slug, token=token) + else: + raise + return Collection(**{**r.json(), "endpoint": self.endpoint}) + + def update_collection_item( + self, + collection_slug: str, + item_object_id: str, + *, + note: str | None = None, + position: int | None = None, + token: bool | str | None = None, + ) -> None: + """Update an item in a collection. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + item_object_id (`str`): + ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id). + It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`. + note (`str`, *optional*): + A note to attach to the item in the collection. The maximum size for a note is 500 characters. + position (`int`, *optional*): + New position of the item in the collection. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + + ```py + >>> from huggingface_hub import get_collection, update_collection_item + + # Get collection first + >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026") + + # Update item based on its ID (add note + update position) + >>> update_collection_item( + ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026", + ... item_object_id=collection.items[-1].item_object_id, + ... note="Newly updated model!" + ... position=0, + ... ) + ``` + """ + payload = {"position": position, "note": note} + r = get_session().patch( + f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}", + headers=self._build_hf_headers(token=token), + # Only send not-none values to the API + json={key: value for key, value in payload.items() if value is not None}, + ) + hf_raise_for_status(r) + + def delete_collection_item( + self, + collection_slug: str, + item_object_id: str, + *, + missing_ok: bool = False, + token: bool | str | None = None, + ) -> None: + """Delete an item from a collection. + + Args: + collection_slug (`str`): + Slug of the collection to update. Example: `"TheBloke/recent-models-64f9a55bb3115b4f513ec026"`. + item_object_id (`str`): + ID of the item in the collection. This is not the id of the item on the Hub (repo_id or paper id). + It must be retrieved from a [`CollectionItem`] object. Example: `collection.items[0].item_object_id`. + missing_ok (`bool`, *optional*): + If `True`, do not raise an error if item doesn't exists. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + + ```py + >>> from huggingface_hub import get_collection, delete_collection_item + + # Get collection first + >>> collection = get_collection("TheBloke/recent-models-64f9a55bb3115b4f513ec026") + + # Delete item based on its ID + >>> delete_collection_item( + ... collection_slug="TheBloke/recent-models-64f9a55bb3115b4f513ec026", + ... item_object_id=collection.items[-1].item_object_id, + ... ) + ``` + """ + r = get_session().delete( + f"{self.endpoint}/api/collections/{collection_slug}/items/{item_object_id}", + headers=self._build_hf_headers(token=token), + ) + try: + hf_raise_for_status(r) + except HfHubHTTPError as err: + if missing_ok and err.response.status_code == 404: + # Item already deleted and `missing_ok=True` + return + else: + raise + + ########################## + # Manage access requests # + ########################## + + @validate_hf_hub_args + def list_pending_access_requests( + self, repo_id: str, *, repo_type: str | None = None, token: bool | str | None = None + ) -> Iterable[AccessRequest]: + """ + Get pending access requests for a given gated repo. + + A pending request means the user has requested access to the repo but the request has not been processed yet. + If the approval mode is automatic, this list should be empty. Pending requests can be accepted or rejected + using [`accept_access_request`] and [`reject_access_request`]. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to get access requests for. + repo_type (`str`, *optional*): + The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`, + `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will + be populated with user's answers. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + + Example: + ```py + >>> from huggingface_hub import list_pending_access_requests, accept_access_request + + # List pending requests + >>> requests = list(list_pending_access_requests("meta-llama/Llama-2-7b")) + >>> len(requests) + 411 + >>> requests[0] + [ + AccessRequest( + username='clem', + fullname='Clem 🤗', + email='***', + timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc), + status='pending', + fields=None, + ), + ... + ] + + # Accept Clem's request + >>> accept_access_request("meta-llama/Llama-2-7b", "clem") + ``` + """ + yield from self._list_access_requests(repo_id, "pending", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def list_accepted_access_requests( + self, repo_id: str, *, repo_type: str | None = None, token: bool | str | None = None + ) -> Iterable[AccessRequest]: + """ + Get accepted access requests for a given gated repo. + + An accepted request means the user has requested access to the repo and the request has been accepted. The user + can download any file of the repo. If the approval mode is automatic, this list should contains by default all + requests. Accepted requests can be cancelled or rejected at any time using [`cancel_access_request`] and + [`reject_access_request`]. A cancelled request will go back to the pending list while a rejected request will + go to the rejected list. In both cases, the user will lose access to the repo. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to get access requests for. + repo_type (`str`, *optional*): + The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`, + `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will + be populated with user's answers. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + + Example: + ```py + >>> from huggingface_hub import list_accepted_access_requests + + >>> requests = list(list_accepted_access_requests("meta-llama/Llama-2-7b")) + >>> len(requests) + 411 + >>> requests[0] + [ + AccessRequest( + username='clem', + fullname='Clem 🤗', + email='***', + timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc), + status='accepted', + fields=None, + ), + ... + ] + ``` + """ + yield from self._list_access_requests(repo_id, "accepted", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def list_rejected_access_requests( + self, repo_id: str, *, repo_type: str | None = None, token: bool | str | None = None + ) -> Iterable[AccessRequest]: + """ + Get rejected access requests for a given gated repo. + + A rejected request means the user has requested access to the repo and the request has been explicitly rejected + by a repo owner (either you or another user from your organization). The user cannot download any file of the + repo. Rejected requests can be accepted or cancelled at any time using [`accept_access_request`] and + [`cancel_access_request`]. A cancelled request will go back to the pending list while an accepted request will + go to the accepted list. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to get access requests for. + repo_type (`str`, *optional*): + The type of the repo to get access requests for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[AccessRequest]`: An iterable of [`AccessRequest`] objects. Each time contains a `username`, `email`, + `status` and `timestamp` attribute. If the gated repo has a custom form, the `fields` attribute will + be populated with user's answers. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + + Example: + ```py + >>> from huggingface_hub import list_rejected_access_requests + + >>> requests = list(list_rejected_access_requests("meta-llama/Llama-2-7b")) + >>> len(requests) + 411 + >>> requests[0] + [ + AccessRequest( + username='clem', + fullname='Clem 🤗', + email='***', + timestamp=datetime.datetime(2023, 11, 23, 18, 4, 53, 828000, tzinfo=datetime.timezone.utc), + status='rejected', + fields=None, + ), + ... + ] + ``` + """ + yield from self._list_access_requests(repo_id, "rejected", repo_type=repo_type, token=token) + + def _list_access_requests( + self, + repo_id: str, + status: Literal["accepted", "rejected", "pending"], + repo_type: str | None = None, + token: bool | str | None = None, + ) -> Iterable[AccessRequest]: + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + + for request in paginate( + f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/{status}", + params={}, + headers=self._build_hf_headers(token=token), + ): + yield AccessRequest( + username=request["user"]["user"], + fullname=request["user"]["fullname"], + email=request["user"].get("email"), + status=request["status"], + timestamp=parse_datetime(request["timestamp"]), + fields=request.get("fields"), # only if custom fields in form + ) + + @validate_hf_hub_args + def cancel_access_request( + self, repo_id: str, user: str, *, repo_type: str | None = None, token: bool | str | None = None + ) -> None: + """ + Cancel an access request from a user for a given gated repo. + + A cancelled request will go back to the pending list and the user will lose access to the repo. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to cancel access request for. + user (`str`): + The username of the user which access request should be cancelled. + repo_type (`str`, *optional*): + The type of the repo to cancel access request for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + [`HfHubHTTPError`]: + HTTP 404 if the user does not exist on the Hub. + [`HfHubHTTPError`]: + HTTP 404 if the user access request cannot be found. + [`HfHubHTTPError`]: + HTTP 404 if the user access request is already in the pending list. + """ + self._handle_access_request(repo_id, user, "pending", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def accept_access_request( + self, repo_id: str, user: str, *, repo_type: str | None = None, token: bool | str | None = None + ) -> None: + """ + Accept an access request from a user for a given gated repo. + + Once the request is accepted, the user will be able to download any file of the repo and access the community + tab. If the approval mode is automatic, you don't have to accept requests manually. An accepted request can be + cancelled or rejected at any time using [`cancel_access_request`] and [`reject_access_request`]. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to accept access request for. + user (`str`): + The username of the user which access request should be accepted. + repo_type (`str`, *optional*): + The type of the repo to accept access request for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + [`HfHubHTTPError`]: + HTTP 404 if the user does not exist on the Hub. + [`HfHubHTTPError`]: + HTTP 404 if the user access request cannot be found. + [`HfHubHTTPError`]: + HTTP 404 if the user access request is already in the accepted list. + """ + self._handle_access_request(repo_id, user, "accepted", repo_type=repo_type, token=token) + + @validate_hf_hub_args + def reject_access_request( + self, + repo_id: str, + user: str, + *, + repo_type: str | None = None, + rejection_reason: str | None, + token: bool | str | None = None, + ) -> None: + """ + Reject an access request from a user for a given gated repo. + + A rejected request will go to the rejected list. The user cannot download any file of the repo. Rejected + requests can be accepted or cancelled at any time using [`accept_access_request`] and [`cancel_access_request`]. + A cancelled request will go back to the pending list while an accepted request will go to the accepted list. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to reject access request for. + user (`str`): + The username of the user which access request should be rejected. + repo_type (`str`, *optional*): + The type of the repo to reject access request for. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + rejection_reason (`str`, *optional*): + Optional rejection reason that will be visible to the user (max 200 characters). + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + [`HfHubHTTPError`]: + HTTP 404 if the user does not exist on the Hub. + [`HfHubHTTPError`]: + HTTP 404 if the user access request cannot be found. + [`HfHubHTTPError`]: + HTTP 404 if the user access request is already in the rejected list. + """ + self._handle_access_request( + repo_id, user, "rejected", repo_type=repo_type, rejection_reason=rejection_reason, token=token + ) + + @validate_hf_hub_args + def _handle_access_request( + self, + repo_id: str, + user: str, + status: Literal["accepted", "rejected", "pending"], + repo_type: str | None = None, + rejection_reason: str | None = None, + token: bool | str | None = None, + ) -> None: + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + + payload = {"user": user, "status": status} + + if rejection_reason is not None: + if status != "rejected": + raise ValueError("`rejection_reason` can only be passed when rejecting an access request.") + payload["rejectionReason"] = rejection_reason + + response = get_session().post( + f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/handle", + headers=self._build_hf_headers(token=token), + json=payload, + ) + hf_raise_for_status(response) + + @validate_hf_hub_args + def grant_access( + self, repo_id: str, user: str, *, repo_type: str | None = None, token: bool | str | None = None + ) -> None: + """ + Grant access to a user for a given gated repo. + + Granting access don't require for the user to send an access request by themselves. The user is automatically + added to the accepted list meaning they can download the files You can revoke the granted access at any time + using [`cancel_access_request`] or [`reject_access_request`]. + + For more info about gated repos, see https://huggingface.co/docs/hub/models-gated. + + Args: + repo_id (`str`): + The id of the repo to grant access to. + user (`str`): + The username of the user to grant access. + repo_type (`str`, *optional*): + The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`HfHubHTTPError`]: + HTTP 400 if the repo is not gated. + [`HfHubHTTPError`]: + HTTP 400 if the user already has access to the repo. + [`HfHubHTTPError`]: + HTTP 403 if you only have read-only access to the repo. This can be the case if you don't have `write` + or `admin` role in the organization the repo belongs to or if you passed a `read` token. + [`HfHubHTTPError`]: + HTTP 404 if the user does not exist on the Hub. + """ + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + + response = get_session().post( + f"{constants.ENDPOINT}/api/{repo_type}s/{repo_id}/user-access-request/grant", + headers=self._build_hf_headers(token=token), + json={"user": user}, + ) + hf_raise_for_status(response) + return response.json() + + ################### + # Manage webhooks # + ################### + + @validate_hf_hub_args + def get_webhook(self, webhook_id: str, *, token: bool | str | None = None) -> WebhookInfo: + """Get a webhook by its id. + + Args: + webhook_id (`str`): + The unique identifier of the webhook to get. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`WebhookInfo`]: + Info about the webhook. + + Example: + ```python + >>> from huggingface_hub import get_webhook + >>> webhook = get_webhook("654bbbc16f2ec14d77f109cc") + >>> print(webhook) + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + job=None, + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + secret="my-secret", + domains=["repo", "discussion"], + disabled=False, + ) + ``` + """ + response = get_session().get( + f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + webhook_data = response.json()["webhook"] + + watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]] + + webhook = WebhookInfo( + id=webhook_data["id"], + url=webhook_data.get("url"), + job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None, + watched=watched_items, + domains=webhook_data["domains"], + secret=webhook_data.get("secret"), + disabled=webhook_data["disabled"], + ) + + return webhook + + @validate_hf_hub_args + def list_webhooks(self, *, token: bool | str | None = None) -> list[WebhookInfo]: + """List all configured webhooks. + + Args: + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `list[WebhookInfo]`: + List of webhook info objects. + + Example: + ```python + >>> from huggingface_hub import list_webhooks + >>> webhooks = list_webhooks() + >>> len(webhooks) + 2 + >>> webhooks[0] + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + secret="my-secret", + domains=["repo", "discussion"], + disabled=False, + ) + ``` + """ + response = get_session().get( + f"{constants.ENDPOINT}/api/settings/webhooks", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + webhooks_data = response.json() + + return [ + WebhookInfo( + id=webhook["id"], + url=webhook.get("url"), + job=JobSpec(**webhook["job"]) if webhook.get("job") else None, + watched=[WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook["watched"]], + domains=webhook["domains"], + secret=webhook.get("secret"), + disabled=webhook["disabled"], + ) + for webhook in webhooks_data + ] + + @validate_hf_hub_args + def create_webhook( + self, + *, + url: str | None = None, + job_id: str | None = None, + watched: list[dict | WebhookWatchedItem], + domains: list[constants.WEBHOOK_DOMAIN_T] | None = None, + secret: str | None = None, + token: bool | str | None = None, + ) -> WebhookInfo: + """Create a new webhook. + + The webhook can either send a payload to a URL, or trigger a Job to run on Hugging Face infrastructure. + This function should be called with one of `url` or `job_id`, but not both. + + Args: + url (`str`): + URL to send the payload to. + job_id (`str`): + ID of the source Job to trigger with the webhook payload in the environment variable WEBHOOK_PAYLOAD. + Additional environment variables are available for convenience: WEBHOOK_REPO_ID, WEBHOOK_REPO_TYPE and WEBHOOK_SECRET. + watched (`list[WebhookWatchedItem]`): + List of [`WebhookWatchedItem`] to be watched by the webhook. It can be users, orgs, models, datasets or spaces. + Watched items can also be provided as plain dictionaries. + domains (`list[Literal["repo", "discussion"]]`, optional): + List of domains to watch. It can be "repo", "discussion" or both. + secret (`str`, optional): + A secret to sign the payload with. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`WebhookInfo`]: + Info about the newly created webhook. + + Example: + + Create a webhook that sends a payload to a URL + ```python + >>> from huggingface_hub import create_webhook + >>> payload = create_webhook( + ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}], + ... url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + ... domains=["repo", "discussion"], + ... secret="my-secret", + ... ) + >>> print(payload) + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + job=None, + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + domains=["repo", "discussion"], + secret="my-secret", + disabled=False, + ) + ``` + + Run a Job and then create a webhook that triggers this Job + ```python + >>> from huggingface_hub import create_webhook, run_job + >>> job = run_job( + ... image="ubuntu", + ... command=["bash", "-c", r"echo An event occurred in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD"], + ... ) + >>> payload = create_webhook( + ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}], + ... job_id=job.id, + ... domains=["repo", "discussion"], + ... secret="my-secret", + ... ) + >>> print(payload) + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + url=None, + job=JobSpec( + docker_image='ubuntu', + space_id=None, + command=['bash', '-c', 'echo An event occurred in $WEBHOOK_REPO_ID: $WEBHOOK_PAYLOAD'], + arguments=[], + environment={}, + secrets=[], + flavor='cpu-basic', + timeout=None, + tags=None, + arch=None + ), + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + domains=["repo", "discussion"], + secret="my-secret", + disabled=False, + ) + ``` + """ + watched_dicts = [asdict(item) if isinstance(item, WebhookWatchedItem) else item for item in watched] + + post_webhooks_json: dict = {"watched": watched_dicts} + if domains is not None: + post_webhooks_json["domains"] = domains + if secret is not None: + post_webhooks_json["secret"] = secret + if url is not None and job_id is not None: + raise ValueError("Set `url` or `job_id` but not both.") + elif url is not None: + post_webhooks_json["url"] = url + elif job_id is not None: + post_webhooks_json["jobSourceId"] = job_id + else: + raise ValueError("Missing argument for webhook: `url` or `job_id`.") + + response = get_session().post( + f"{constants.ENDPOINT}/api/settings/webhooks", + json=post_webhooks_json, + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + webhook_data = response.json()["webhook"] + watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]] + + webhook = WebhookInfo( + id=webhook_data["id"], + url=webhook_data.get("url"), + job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None, + watched=watched_items, + domains=webhook_data["domains"], + secret=webhook_data.get("secret"), + disabled=webhook_data["disabled"], + ) + + return webhook + + @validate_hf_hub_args + def update_webhook( + self, + webhook_id: str, + *, + url: str | None = None, + watched: list[dict | WebhookWatchedItem] | None = None, + domains: list[constants.WEBHOOK_DOMAIN_T] | None = None, + secret: str | None = None, + token: bool | str | None = None, + ) -> WebhookInfo: + """Update an existing webhook. + + Args: + webhook_id (`str`): + The unique identifier of the webhook to be updated. + url (`str`, optional): + The URL to which the payload will be sent. + watched (`list[WebhookWatchedItem]`, optional): + List of items to watch. It can be users, orgs, models, datasets, or spaces. + Refer to [`WebhookWatchedItem`] for more details. Watched items can also be provided as plain dictionaries. + domains (`list[Literal["repo", "discussion"]]`, optional): + The domains to watch. This can include "repo", "discussion", or both. + secret (`str`, optional): + A secret to sign the payload with, providing an additional layer of security. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`WebhookInfo`]: + Info about the updated webhook. + + Example: + ```python + >>> from huggingface_hub import update_webhook + >>> updated_payload = update_webhook( + ... webhook_id="654bbbc16f2ec14d77f109cc", + ... url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + ... watched=[{"type": "user", "name": "julien-c"}, {"type": "org", "name": "HuggingFaceH4"}], + ... domains=["repo"], + ... secret="my-secret", + ... ) + >>> print(updated_payload) + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + job=None, + url="https://new.webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + domains=["repo"], + secret="my-secret", + disabled=False, + ``` + """ + if watched is None: + watched = [] + watched_dicts = [asdict(item) if isinstance(item, WebhookWatchedItem) else item for item in watched] + + update_json: dict = {"watched": watched_dicts} + if url is not None: + update_json["url"] = url + if domains is not None: + update_json["domains"] = domains + if secret is not None: + update_json["secret"] = secret + + response = get_session().post( + f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}", + json=update_json, + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + webhook_data = response.json()["webhook"] + + watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]] + + webhook = WebhookInfo( + id=webhook_data["id"], + url=webhook_data.get("url"), + job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None, + watched=watched_items, + domains=webhook_data["domains"], + secret=webhook_data.get("secret"), + disabled=webhook_data["disabled"], + ) + + return webhook + + @validate_hf_hub_args + def enable_webhook(self, webhook_id: str, *, token: bool | str | None = None) -> WebhookInfo: + """Enable a webhook (makes it "active"). + + Args: + webhook_id (`str`): + The unique identifier of the webhook to enable. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`WebhookInfo`]: + Info about the enabled webhook. + + Example: + ```python + >>> from huggingface_hub import enable_webhook + >>> enabled_webhook = enable_webhook("654bbbc16f2ec14d77f109cc") + >>> enabled_webhook + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + job=None, + url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + domains=["repo", "discussion"], + secret="my-secret", + disabled=False, + ) + ``` + """ + response = get_session().post( + f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}/enable", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + webhook_data = response.json()["webhook"] + + watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]] + + webhook = WebhookInfo( + id=webhook_data["id"], + url=webhook_data.get("url"), + job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None, + watched=watched_items, + domains=webhook_data["domains"], + secret=webhook_data.get("secret"), + disabled=webhook_data["disabled"], + ) + + return webhook + + @validate_hf_hub_args + def disable_webhook(self, webhook_id: str, *, token: bool | str | None = None) -> WebhookInfo: + """Disable a webhook (makes it "disabled"). + + Args: + webhook_id (`str`): + The unique identifier of the webhook to disable. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`WebhookInfo`]: + Info about the disabled webhook. + + Example: + ```python + >>> from huggingface_hub import disable_webhook + >>> disabled_webhook = disable_webhook("654bbbc16f2ec14d77f109cc") + >>> disabled_webhook + WebhookInfo( + id="654bbbc16f2ec14d77f109cc", + url="https://webhook.site/a2176e82-5720-43ee-9e06-f91cb4c91548", + jon=None, + watched=[WebhookWatchedItem(type="user", name="julien-c"), WebhookWatchedItem(type="org", name="HuggingFaceH4")], + domains=["repo", "discussion"], + secret="my-secret", + disabled=True, + ) + ``` + """ + response = get_session().post( + f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}/disable", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + webhook_data = response.json()["webhook"] + + watched_items = [WebhookWatchedItem(type=item["type"], name=item["name"]) for item in webhook_data["watched"]] + + webhook = WebhookInfo( + id=webhook_data["id"], + url=webhook_data.get("url"), + job=JobSpec(**webhook_data["job"]) if webhook_data.get("job") else None, + watched=watched_items, + domains=webhook_data["domains"], + secret=webhook_data.get("secret"), + disabled=webhook_data["disabled"], + ) + + return webhook + + @validate_hf_hub_args + def delete_webhook(self, webhook_id: str, *, token: bool | str | None = None) -> None: + """Delete a webhook. + + Args: + webhook_id (`str`): + The unique identifier of the webhook to delete. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended + method for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `None` + + Example: + ```python + >>> from huggingface_hub import delete_webhook + >>> delete_webhook("654bbbc16f2ec14d77f109cc") + ``` + """ + response = get_session().delete( + f"{constants.ENDPOINT}/api/settings/webhooks/{webhook_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + ############# + # Internals # + ############# + + def _build_hf_headers( + self, + token: bool | str | None = None, + library_name: str | None = None, + library_version: str | None = None, + user_agent: dict | str | None = None, + ) -> dict[str, str]: + """ + Alias for [`build_hf_headers`] that uses the token from [`HfApi`] client + when `token` is not provided. + """ + if token is None: + # Cannot do `token = token or self.token` as token can be `False`. + token = self.token + return build_hf_headers( + token=token, + library_name=library_name or self.library_name, + library_version=library_version or self.library_version, + user_agent=user_agent or self.user_agent, + headers=self.headers, + ) + + def _prepare_folder_deletions( + self, + repo_id: str, + repo_type: str | None, + revision: str | None, + path_in_repo: str, + delete_patterns: list[str] | str | None, + token: bool | str | None = None, + ) -> list[CommitOperationDelete]: + """Generate the list of Delete operations for a commit to delete files from a repo. + + List remote files and match them against the `delete_patterns` constraints. Returns a list of [`CommitOperationDelete`] + with the matching items. + + Note: `.gitattributes` file is essential to make a repo work properly on the Hub. This file will always be + kept even if it matches the `delete_patterns` constraints. + """ + if delete_patterns is None: + # If no delete patterns, no need to list and filter remote files + return [] + + # List remote files + filenames = self.list_repo_files(repo_id=repo_id, revision=revision, repo_type=repo_type, token=token) + + # Compute relative path in repo + if path_in_repo and path_in_repo not in (".", "./"): + path_in_repo = path_in_repo.strip("/") + "/" # harmonize + relpath_to_abspath = { + file[len(path_in_repo) :]: file for file in filenames if file.startswith(path_in_repo) + } + else: + relpath_to_abspath = {file: file for file in filenames} + + # Apply filter on relative paths and return + return [ + CommitOperationDelete(path_in_repo=relpath_to_abspath[relpath], is_folder=False) + for relpath in filter_repo_objects(relpath_to_abspath.keys(), allow_patterns=delete_patterns) + if relpath_to_abspath[relpath] != ".gitattributes" + ] + + def _prepare_upload_folder_additions( + self, + folder_path: str | Path, + path_in_repo: str, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + repo_type: str | None = None, + token: bool | str | None = None, + ) -> list[CommitOperationAdd]: + """Generate the list of Add operations for a commit to upload a folder. + + Files not matching the `allow_patterns` (allowlist) and `ignore_patterns` (denylist) + constraints are discarded. + """ + + folder_path = Path(folder_path).expanduser().resolve() + if not folder_path.is_dir(): + raise ValueError(f"Provided path: '{folder_path}' is not a directory") + + # List files from folder + relpath_to_abspath = { + path.relative_to(folder_path).as_posix(): path + for path in sorted(folder_path.glob("**/*")) # sorted to be deterministic + if path.is_file() + } + + # Filter files + # Patterns are applied on the path relative to `folder_path`. `path_in_repo` is prefixed after the filtering. + filtered_repo_objects = list( + filter_repo_objects( + relpath_to_abspath.keys(), allow_patterns=allow_patterns, ignore_patterns=ignore_patterns + ) + ) + + prefix = f"{path_in_repo.strip('/')}/" if path_in_repo else "" + + # If updating a README.md file, make sure the metadata format is valid + # It's better to fail early than to fail after all the files have been hashed. + if "README.md" in filtered_repo_objects: + self._validate_yaml( + content=relpath_to_abspath["README.md"].read_text(encoding="utf8"), + repo_type=repo_type, + token=token, + ) + if len(filtered_repo_objects) > 30: + log = logger.warning if len(filtered_repo_objects) > 200 else logger.info + log( + "It seems you are trying to upload a large folder at once. This might take some time and then fail if " + "the folder is too large. For such cases, it is recommended to upload in smaller batches or to use " + "`HfApi().upload_large_folder(...)`/`hf upload-large-folder` instead. For more details, " + "check out https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#upload-a-large-folder." + ) + + logger.info(f"Start hashing {len(filtered_repo_objects)} files.") + operations = [ + CommitOperationAdd( + path_or_fileobj=relpath_to_abspath[relpath], # absolute path on disk + path_in_repo=prefix + relpath, # "absolute" path in repo + ) + for relpath in filtered_repo_objects + ] + logger.info(f"Finished hashing {len(filtered_repo_objects)} files.") + return operations + + def _validate_yaml(self, content: str, *, repo_type: str | None = None, token: bool | str | None = None): + """ + Validate YAML from `README.md`, used before file hashing and upload. + + Args: + content (`str`): + Content of `README.md` to validate. + repo_type (`str`, *optional*): + The type of the repo to grant access to. Must be one of `model`, `dataset` or `space`. + Defaults to `model`. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + if YAML is invalid + """ + repo_type = repo_type if repo_type is not None else constants.REPO_TYPE_MODEL + headers = self._build_hf_headers(token=token) + + response = get_session().post( + f"{self.endpoint}/api/validate-yaml", + json={"content": content, "repoType": repo_type}, + headers=headers, + ) + # Handle warnings (example: empty metadata) + response_content = response.json() + message = "\n".join([f"- {warning.get('message')}" for warning in response_content.get("warnings", [])]) + if message: + warnings.warn(f"Warnings while validating metadata in README.md:\n{message}") + + # Raise on errors + try: + hf_raise_for_status(response) + except BadRequestError as e: + errors = response_content.get("errors", []) + message = "\n".join([f"- {error.get('message')}" for error in errors]) + raise ValueError(f"Invalid metadata in README.md.\n{message}") from e + + def get_user_overview(self, username: str, token: bool | str | None = None) -> User: + """ + Get an overview of a user on the Hub. + + Args: + username (`str`): + Username of the user to get an overview of. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `User`: A [`User`] object with the user's overview. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the user does not exist on the Hub. + """ + r = get_session().get( + f"{constants.ENDPOINT}/api/users/{username}/overview", headers=self._build_hf_headers(token=token) + ) + hf_raise_for_status(r) + return User(**r.json()) + + @validate_hf_hub_args + def get_organization_overview(self, organization: str, token: bool | str | None = None) -> Organization: + """ + Get an overview of an organization on the Hub. + + Args: + organization (`str`): + Name of the organization to get an overview of. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved token, which is the recommended method + for authentication (see https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Organization`: An [`Organization`] object with the organization's overview. + + Raises: + [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError): + HTTP 404 If the organization does not exist on the Hub. + """ + r = get_session().get( + f"{constants.ENDPOINT}/api/organizations/{organization}/overview", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + return Organization(**r.json()) + + @validate_hf_hub_args + def list_organization_followers(self, organization: str, token: bool | str | None = None) -> Iterable[User]: + """ + List followers of an organization on the Hub. + + Args: + organization (`str`): + Name of the organization to get the followers of. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[User]`: A list of [`User`] objects with the followers of the organization. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the organization does not exist on the Hub. + + """ + for follower in paginate( + path=f"{constants.ENDPOINT}/api/organizations/{organization}/followers", + params={}, + headers=self._build_hf_headers(token=token), + ): + yield User(**follower) + + def list_organization_members(self, organization: str, token: bool | str | None = None) -> Iterable[User]: + """ + List of members of an organization on the Hub. + + Args: + organization (`str`): + Name of the organization to get the members of. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[User]`: A list of [`User`] objects with the members of the organization. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the organization does not exist on the Hub. + + """ + for member in paginate( + path=f"{constants.ENDPOINT}/api/organizations/{organization}/members", + params={}, + headers=self._build_hf_headers(token=token), + ): + yield User(**member) + + def list_user_followers(self, username: str, token: bool | str | None = None) -> Iterable[User]: + """ + Get the list of followers of a user on the Hub. + + Args: + username (`str`): + Username of the user to get the followers of. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[User]`: A list of [`User`] objects with the followers of the user. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the user does not exist on the Hub. + + """ + for follower in paginate( + path=f"{constants.ENDPOINT}/api/users/{username}/followers", + params={}, + headers=self._build_hf_headers(token=token), + ): + yield User(**follower) + + def list_user_following(self, username: str, token: bool | str | None = None) -> Iterable[User]: + """ + Get the list of users followed by a user on the Hub. + + Args: + username (`str`): + Username of the user to get the users followed by. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[User]`: A list of [`User`] objects with the users followed by the user. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the user does not exist on the Hub. + + """ + for followed_user in paginate( + path=f"{constants.ENDPOINT}/api/users/{username}/following", + params={}, + headers=self._build_hf_headers(token=token), + ): + yield User(**followed_user) + + def list_papers( + self, + *, + query: str | None = None, + limit: int | None = None, + token: bool | str | None = None, + ) -> Iterable[PaperInfo]: + """ + List daily papers on the Hugging Face Hub given a search query. + + Args: + query (`str`, *optional*): + A search query string to find papers. + If provided, returns papers that match the query. + limit (`int`, *optional*): + The maximum number of papers to return. + token (Union[bool, str, None], *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects. + + Example: + + ```python + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + + # List all papers with "attention" in their title + >>> api.list_papers(query="attention") + ``` + """ + path = f"{self.endpoint}/api/papers/search" + params: dict[str, Any] = {} + if query: + params["q"] = query + if limit is not None: + params["limit"] = limit + r = get_session().get( + path, + params=params, + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(r) + for paper in r.json(): + yield PaperInfo(**paper) + + def paper_info(self, id: str) -> PaperInfo: + """ + Get information for a paper on the Hub. + + Args: + id (`str`, **optional**): + ArXiv id of the paper. + + Returns: + `PaperInfo`: A `PaperInfo` object. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the paper does not exist on the Hub. + """ + path = f"{self.endpoint}/api/papers/{id}" + r = get_session().get(path) + hf_raise_for_status(r) + return PaperInfo(**r.json()) + + def read_paper(self, id: str) -> str: + """ + Get the markdown content of a paper page on the Hub. + + Args: + id (`str`): + ArXiv id of the paper. + + Returns: + `str`: The paper page content as markdown. + + Raises: + [`HfHubHTTPError`]: + HTTP 404 If the paper does not exist on the Hub. + """ + path = f"{self.endpoint}/papers/{id}.md" + r = get_session().get(path) + hf_raise_for_status(r) + return r.text + + def list_daily_papers( + self, + *, + date: str | None = None, + token: bool | str | None = None, + week: str | None = None, + month: str | None = None, + submitter: str | None = None, + sort: DailyPapersSort_T | None = None, + p: int | None = None, + limit: int | None = None, + ) -> Iterable[PaperInfo]: + """ + List the daily papers published on a given date on the Hugging Face Hub. + + Args: + date (`str`, *optional*): + Date in ISO format (YYYY-MM-DD) for which to fetch daily papers. + Defaults to most recent ones. + token (Union[bool, str, None], *optional*): + A valid user access token (string). Defaults to the locally saved + token. To disable authentication, pass `False`. + week (`str`, *optional*): + Week in ISO format (YYYY-Www) for which to fetch daily papers. Example, `2025-W09`. + month (`str`, *optional*): + Month in ISO format (YYYY-MM) for which to fetch daily papers. Example, `2025-02`. + submitter (`str`, *optional*): + Username of the submitter to filter daily papers. + sort (`Literal["publishedAt", "trending"]`, *optional*): + Sort order for the daily papers. Can be either by `publishedAt` or by `trending`. + Defaults to `"publishedAt"` + p (`int`, *optional*): + Page number for pagination. Defaults to 0. + limit (`int`, *optional*): + Limit of papers to fetch. Defaults to 50. + + Returns: + `Iterable[PaperInfo]`: an iterable of [`huggingface_hub.hf_api.PaperInfo`] objects. + + Example: + + ```python + >>> from huggingface_hub import HfApi + + >>> api = HfApi() + >>> list(api.list_daily_papers(date="2025-10-29")) + ``` + """ + path = f"{self.endpoint}/api/daily_papers" + + params = { + k: v + for k, v in { + "p": p, + "limit": limit, + "sort": sort, + "date": date, + "week": week, + "month": month, + "submitter": submitter, + }.items() + if v is not None + } + + r = get_session().get(path, params=params, headers=self._build_hf_headers(token=token)) + hf_raise_for_status(r) + for paper in r.json(): + yield PaperInfo(**paper) + + def auth_check( + self, + repo_id: str, + *, + repo_type: str | None = None, + token: bool | str | None = None, + write: bool = False, + ) -> None: + """ + Check if the provided user token has access to a specific repository on the Hugging Face Hub. + + This method verifies whether the user, authenticated via the provided token, has access to the specified + repository. If the repository is not found or if the user lacks the required permissions to access it, + the method raises an appropriate exception. + + Args: + repo_id (`str`): + The repository to check for access. Format should be `"user/repo_name"`. + Example: `"user/my-cool-model"`. + + repo_type (`str`, *optional*): + The type of the repository. Should be one of `"model"`, `"dataset"`, or `"space"`. + If not specified, the default is `"model"`. + + token (`Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + write (`bool`, *optional*): + If `True`, checks whether the user has content write permission on the repository. + If `False` (default), only checks for read access. + + Raises: + [`~utils.RepositoryNotFoundError`]: + Raised if the repository does not exist, is private, or the user does not have access. This can + occur if the `repo_id` or `repo_type` is incorrect or if the repository is private but the user + is not authenticated. + + [`~utils.GatedRepoError`]: + Raised if the repository exists but is gated and the user is not authorized to access it. + + Example: + Check if the user has access to a repository: + + ```python + >>> from huggingface_hub import auth_check + >>> from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError + + try: + auth_check("user/my-cool-model") + except GatedRepoError: + # Handle gated repository error + print("You do not have permission to access this gated repository.") + except RepositoryNotFoundError: + # Handle repository not found error + print("The repository was not found or you do not have access.") + ``` + + In this example: + - If the user has access, the method completes successfully. + - If the repository is gated or does not exist, appropriate exceptions are raised, allowing the user + to handle them accordingly. + """ + headers = self._build_hf_headers(token=token) + if repo_type is None: + repo_type = constants.REPO_TYPE_MODEL + if repo_type not in constants.REPO_TYPES: + raise ValueError(f"Invalid repo type, must be one of {constants.REPO_TYPES}") + path = f"{self.endpoint}/api/{repo_type}s/{repo_id}/auth-check" + if write: + path = f"{path}/write" + r = get_session().get(path, headers=headers) + hf_raise_for_status(r) + + def run_job( + self, + *, + image: str, + command: list[str], + env: dict[str, Any] | None = None, + secrets: dict[str, Any] | None = None, + flavor: SpaceHardware | None = None, + timeout: int | float | str | None = None, + labels: dict[str, str] | None = None, + volumes: list[Volume] | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> JobInfo: + """ + Run compute Jobs on Hugging Face infrastructure. + + Args: + image (`str`): + The Docker image to use. + Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`. + Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`. + + command (`list[str]`): + The command to run. Example: `["echo", "hello"]`. + + env (`dict[str, Any]`, *optional*): + Defines the environment variables for the Job. + + secrets (`dict[str, Any]`, *optional*): + Defines the secret environment variables for the Job. + + flavor (`str`, *optional*): + Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values. + Defaults to `"cpu-basic"`. + + timeout (`Union[int, float, str]`, *optional*): + Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days). + Example: `300` or `"5m"` for 5 minutes. + + labels (`dict[str, str]`, *optional*): + Labels to attach to the job (key-value pairs). + + volumes (`list[Volume]`, *optional*): + Hugging Face Buckets or Repos to mount as volumes in the job container. + Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), + `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`). + + namespace (`str`, *optional*): + The namespace where the Job will be created. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + Run your first Job: + + ```python + >>> from huggingface_hub import run_job + >>> run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"]) + ``` + + Run a GPU Job: + + ```python + >>> from huggingface_hub import run_job + >>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel" + >>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"] + >>> run_job(image=image, command=command, flavor="a10g-small") + ``` + + Run a Job with volumes: + + ```python + >>> from huggingface_hub import Volume, run_job + >>> dataset_volume = Volume(type="dataset", source="HuggingFaceFW/fineweb", mount_path="/data") + >>> output_bucket_volume = Volume(type="bucket", source="username/my-bucket", mount_path="/output") + >>> image = "duckdb/duckdb" + >>> command = ["duckdb", "-c", "COPY (SELECT * FROM '/data/**/*.parquet' LIMIT 5) TO '/output/first-rows.parquet'"] + >>> run_job(image=image, command=command, volumes=[dataset_volume, output_bucket_volume]) + ``` + + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + job_spec = _create_job_spec( + image=image, + command=command, + env=env, + secrets=secrets, + flavor=flavor, + timeout=timeout, + labels=labels, + volumes=volumes, + ) + response = get_session().post( + f"{self.endpoint}/api/jobs/{namespace}", + json=job_spec, + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + job_info = response.json() + return JobInfo(**job_info, endpoint=self.endpoint) + + def _fetch_running_job_sse( + self, + *, + job_id: str, + route: str, + timeout: int, + skip_previous_events_on_retry: bool, + tolerated_status_codes: tuple[int, ...] = (), + tolerated_exception_types: tuple[type[Exception], ...] = (), + follow: bool = True, + namespace: str | None = None, + token: bool | str | None = None, + ) -> Iterable[dict[str, Any]]: + if namespace is None: + namespace = self.whoami(token=token)["name"] + + def has_job_finished() -> bool: + # We don't use http_backoff: this is the authoritative check that + # decides whether to keep streaming. + job_status_response = get_session().get( + f"{self.endpoint}/api/jobs/{namespace}/{job_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(job_status_response) + job_status = job_status_response.json() + return "status" in job_status and job_status["status"]["stage"] not in ("RUNNING", "UPDATING") + + yield from self._stream_sse_events( + url=f"{self.endpoint}/api/jobs/{namespace}/{job_id}/{route}", + log_label=f"jobs /{route} for {job_id=}", + timeout=timeout, + follow=follow, + token=token, + skip_previous_events_on_retry=skip_previous_events_on_retry, + tolerated_status_codes=tolerated_status_codes, + tolerated_exception_types=tolerated_exception_types, + on_iteration_end=has_job_finished, + ) + + def fetch_job_logs( + self, + *, + job_id: str, + namespace: str | None = None, + follow: bool = False, + token: bool | str | None = None, + ) -> Iterable[str]: + """ + Fetch all the logs from a compute Job on Hugging Face infrastructure. + + Args: + job_id (`str`): + ID of the Job. + + namespace (`str`, *optional*): + The namespace where the Job is running. Defaults to the current user's namespace. + + follow (`bool`, *optional*): + If `True`, stream logs in real-time until the job completes (blocking). + If `False` (default), fetch only the currently available logs and return immediately (non-blocking). + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + + ```python + >>> from huggingface_hub import fetch_job_logs, run_job + >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"]) + >>> for log in fetch_job_logs(job_id=job.id): + ... print(log) + Hello from HF compute! + + >>> # Non-blocking: fetch only currently available logs + >>> for log in fetch_job_logs(job_id=job.id, follow=False): + ... print(log) + ``` + """ + # - We need to retry because sometimes the /logs doesn't return logs when the job just started. + # (for example it can return only two lines: one for "Job started" and one empty line) + # - Timeouts can happen in case of build errors + # - ChunkedEncodingError can happen in case of stopped logging in the middle of streaming + # - Infinite empty log stream can happen in case of build error + # (the logs stream is infinite and empty except for the Job started message) + # - there is a ": keep-alive" every 30 seconds + + seconds_between_keep_alive = 30 + # When not following, use a short timeout: the server replays historical logs + # quickly, then pauses waiting for new events (~30s keep-alive). 5 seconds is + # enough to receive all buffered logs. + timeout = 4 * seconds_between_keep_alive if follow else 5 + for event in self._fetch_running_job_sse( + job_id=job_id, + route="logs", + timeout=timeout, + skip_previous_events_on_retry=True, + follow=follow, + namespace=namespace, + token=token, + ): + # timestamp = event["timestamp"] + if not event["data"].startswith("===== Job started"): + log = event["data"] + yield log + + def fetch_job_metrics( + self, + *, + job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> Iterable[dict[str, Any]]: + """ + Fetch all the live metrics from a compute Job on Hugging Face infrastructure. + + Args: + job_id (`str`): + ID of the Job. + + namespace (`str`, *optional*): + The namespace where the Job is running. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + + ```python + >>> from huggingface_hub import fetch_job_metrics, run_job + >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], flavor="a10g-small") + >>> for metrics in fetch_job_metrics(job_id=job.id): + ... print(metrics) + { + "cpu_usage_pct": 0, + "cpu_millicores": 3500, + "memory_used_bytes": 1306624, + "memory_total_bytes": 15032385536, + "rx_bps": 0, + "tx_bps": 0, + "gpus": { + "882fa930": { + "utilization": 0, + "memory_used_bytes": 0, + "memory_total_bytes": 22836000000 + } + }, + "replica": "57vr7" + } + ``` + """ + # - there is one "metric" event every second, like this: + # event: metric + # data: {"cpu_usage_pct":0,"cpu_millicores":3500,"memory_used_bytes":1417216,"memory_total_bytes":15032385536,"rx_bps":0,"tx_bps":0,"gpus":{"d901cd7f":{"utilization":0,"memory_used_bytes":0,"memory_total_bytes":22836000000}},"replica":"j6qz9"} + # - the stream doesn't end when the job finishes, so we rely on timeouts (httpx.NetworkError with Timeout as cause) + # - httpx.ReadTimeout can happen if the job is marked as running but the hardware is not available yet, that we can ignore + # - it returns an internal error 500 if the job has already finished, we simply ignore it + # - ChunkedEncodingError can happen in case of stopped logging in the middle of streaming + # - there is a ": keep-alive" every 30 seconds + seconds_between_events = 1 + yield from self._fetch_running_job_sse( + job_id=job_id, + route="metrics", + timeout=10 * seconds_between_events, + skip_previous_events_on_retry=False, + tolerated_status_codes=(500,), + namespace=namespace, + token=token, + ) + + def list_jobs( + self, + *, + timeout: int | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> list[JobInfo]: + """ + List compute Jobs on Hugging Face infrastructure. + + Args: + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + + namespace (`str`, *optional*): + The namespace from where it lists the jobs. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + """ + if namespace is None: + namespace = whoami(token=token)["name"] + response = get_session().get( + f"{self.endpoint}/api/jobs/{namespace}", + headers=self._build_hf_headers(token=token), + timeout=timeout, + ) + response.raise_for_status() + return [JobInfo(**job_info, endpoint=self.endpoint) for job_info in response.json()] + + def list_jobs_hardware(self, token: bool | str | None = None) -> list[JobHardware]: + """ + List available hardware options for Jobs on Hugging Face infrastructure. + + Returns: + `list[JobHardware]`: A list of available hardware configurations. + + Example: + + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + >>> hardware_list = api.list_jobs_hardware() + >>> hardware_list[0] + JobHardware(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute') + >>> hardware_list[0].name + 'cpu-basic' + + # Filter GPU options + >>> gpu_hardware = [hw for hw in hardware_list if hw.accelerator is not None] + >>> gpu_hardware[0].accelerator.model + 'T4' + ``` + """ + response = get_session().get(f"{self.endpoint}/api/jobs/hardware", headers=self._build_hf_headers(token=token)) + hf_raise_for_status(response) + return [JobHardware(**hardware) for hardware in response.json()] + + def inspect_job( + self, + *, + job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> JobInfo: + """ + Inspect a compute Job on Hugging Face infrastructure. + + Args: + job_id (`str`): + ID of the Job. + + namespace (`str`, *optional*): + The namespace where the Job is running. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + + ```python + >>> from huggingface_hub import inspect_job, run_job + >>> job = run_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"]) + >>> inspect_job(job.id) + JobInfo( + id='68780d00bbe36d38803f645f', + created_at=datetime.datetime(2025, 7, 16, 20, 35, 12, 808000, tzinfo=datetime.timezone.utc), + docker_image='python:3.12', + space_id=None, + command=['python', '-c', "print('Hello from HF compute!')"], + arguments=[], + environment={}, + secrets={}, + flavor='cpu-basic', + status=JobStatus(stage='RUNNING', message=None) + ) + ``` + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().get( + f"{self.endpoint}/api/jobs/{namespace}/{job_id}", + headers=self._build_hf_headers(token=token), + ) + response.raise_for_status() + return JobInfo(**response.json(), endpoint=self.endpoint) + + def cancel_job( + self, + *, + job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> None: + """ + Cancel a compute Job on Hugging Face infrastructure. + + Args: + job_id (`str`): + ID of the Job. + + namespace (`str`, *optional*): + The namespace where the Job is running. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + get_session().post( + f"{self.endpoint}/api/jobs/{namespace}/{job_id}/cancel", + headers=self._build_hf_headers(token=token), + ).raise_for_status() + + @experimental + def run_uv_job( + self, + script: str, + *, + script_args: list[str] | None = None, + dependencies: list[str] | None = None, + python: str | None = None, + image: str | None = None, + env: dict[str, Any] | None = None, + secrets: dict[str, Any] | None = None, + flavor: SpaceHardware | None = None, + timeout: int | float | str | None = None, + labels: dict[str, str] | None = None, + volumes: list[Volume] | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> JobInfo: + """ + Run a UV script Job on Hugging Face infrastructure. + + Args: + script (`str`): + Path or URL of the UV script, or a command. + + script_args (`list[str]`, *optional*) + Arguments to pass to the script or command. + + dependencies (`list[str]`, *optional*) + Dependencies to use to run the UV script. + + python (`str`, *optional*) + Use a specific Python version. Default is 3.12. + + image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"): + Use a custom Docker image with `uv` installed. + + env (`dict[str, Any]`, *optional*): + Defines the environment variables for the Job. + + secrets (`dict[str, Any]`, *optional*): + Defines the secret environment variables for the Job. + + flavor (`str`, *optional*): + Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values. + Defaults to `"cpu-basic"`. + + timeout (`Union[int, float, str]`, *optional*): + Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days). + Example: `300` or `"5m"` for 5 minutes. + + labels (`dict[str, str]`, *optional*): + Labels to attach to the job (key-value pairs). + + volumes (`list[Volume]`, *optional*): + Hugging Face Buckets or Repos to mount as volumes in the job container. + Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), + `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`). + + namespace (`str`, *optional*): + The namespace where the Job will be created. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + + Run a script from a URL: + + ```python + >>> from huggingface_hub import run_uv_job + >>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py" + >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"] + >>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small") + ``` + + Run a local script: + + ```python + >>> from huggingface_hub import run_uv_job + >>> script = "my_sft.py" + >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"] + >>> run_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small") + ``` + + Run a command: + + ```python + >>> from huggingface_hub import run_uv_job + >>> script = "lighteval" + >>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"] + >>> run_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small") + ``` + + Mount volumes, e.g. to save model checkpoints during training: + + ```python + >>> from huggingface_hub import Volume, run_uv_job + >>> script = "my_sft.py" + >>> script_args = ["--output_dir", "/training-outputs/training-v3-final", ...] + >>> checkpoints_bucket = Volume(type="bucket", source="username/my-bucket", mount_path="/training-outputs") + >>> run_uv_job(script, script_args=script_args, volumes=[checkpoints_bucket]) + ``` + """ + image = image or "ghcr.io/astral-sh/uv:python3.12-bookworm" + env = env or {} + secrets = secrets or {} + + # Build command + command, env, secrets, extra_volumes = self._create_uv_command_env_and_secrets( + script=script, + script_args=script_args, + dependencies=dependencies, + python=python, + env=env, + secrets=secrets, + namespace=namespace, + token=token, + volumes=volumes, + ) + if extra_volumes: + volumes = (volumes or []) + extra_volumes + # Create RunCommand args + return self.run_job( + image=image, + command=command, + env=env, + secrets=secrets, + flavor=flavor, + timeout=timeout, + labels=labels, + volumes=volumes, + namespace=namespace, + token=token, + ) + + def create_scheduled_job( + self, + *, + image: str, + command: list[str], + schedule: str, + suspend: bool | None = None, + concurrency: bool | None = None, + env: dict[str, Any] | None = None, + secrets: dict[str, Any] | None = None, + flavor: SpaceHardware | None = None, + timeout: int | float | str | None = None, + labels: dict[str, str] | None = None, + volumes: list[Volume] | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> ScheduledJobInfo: + """ + Create scheduled compute Jobs on Hugging Face infrastructure. + + Args: + image (`str`): + The Docker image to use. + Examples: `"ubuntu"`, `"python:3.12"`, `"pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel"`. + Example with an image from a Space: `"hf.co/spaces/lhoestq/duckdb"`. + + command (`list[str]`): + The command to run. Example: `["echo", "hello"]`. + + schedule (`str`): + One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a + CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday). + + suspend (`bool`, *optional*): + If True, the scheduled Job is suspended (paused). Defaults to False. + + concurrency (`bool`, *optional*): + If True, multiple instances of this Job can run concurrently. Defaults to False. + + env (`dict[str, Any]`, *optional*): + Defines the environment variables for the Job. + + secrets (`dict[str, Any]`, *optional*): + Defines the secret environment variables for the Job. + + flavor (`str`, *optional*): + Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values. + Defaults to `"cpu-basic"`. + + timeout (`Union[int, float, str]`, *optional*): + Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days). + Example: `300` or `"5m"` for 5 minutes. + + labels (`dict[str, str]`, *optional*): + Labels to attach to the job (key-value pairs). + + volumes (`list[Volume]`, *optional*): + Hugging Face Buckets or Repos to mount as volumes in the job container. + Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), + `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`). + + namespace (`str`, *optional*): + The namespace where the Job will be created. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + Create your first scheduled Job: + + ```python + >>> from huggingface_hub import create_scheduled_job + >>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly") + ``` + + Use a CRON schedule expression: + + ```python + >>> from huggingface_hub import create_scheduled_job + >>> create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('this runs every 5min')"], schedule="*/5 * * * *") + ``` + + Create a scheduled GPU Job: + + ```python + >>> from huggingface_hub import create_scheduled_job + >>> image = "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-devel" + >>> command = ["python", "-c", "import torch; print(f"This code ran with the following GPU: {torch.cuda.get_device_name()}")"] + >>> create_scheduled_job(image, command, flavor="a10g-small", schedule="@hourly") + ``` + + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + + # prepare payload to send to HF Jobs API + job_spec = _create_job_spec( + image=image, + command=command, + env=env, + secrets=secrets, + flavor=flavor, + timeout=timeout, + labels=labels, + volumes=volumes, + ) + input_json: dict[str, Any] = { + "jobSpec": job_spec, + "schedule": schedule, + } + if concurrency is not None: + input_json["concurrency"] = concurrency + if suspend is not None: + input_json["suspend"] = suspend + response = get_session().post( + f"{self.endpoint}/api/scheduled-jobs/{namespace}", + json=input_json, + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + scheduled_job_info = response.json() + return ScheduledJobInfo(**scheduled_job_info) + + def list_scheduled_jobs( + self, + *, + timeout: int | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> list[ScheduledJobInfo]: + """ + List scheduled compute Jobs on Hugging Face infrastructure. + + Args: + timeout (`float`, *optional*): + Whether to set a timeout for the request to the Hub. + + namespace (`str`, *optional*): + The namespace from where it lists the jobs. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().get( + f"{self.endpoint}/api/scheduled-jobs/{namespace}", + headers=self._build_hf_headers(token=token), + timeout=timeout, + ) + hf_raise_for_status(response) + return [ScheduledJobInfo(**scheduled_job_info) for scheduled_job_info in response.json()] + + def inspect_scheduled_job( + self, + *, + scheduled_job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> ScheduledJobInfo: + """ + Inspect a scheduled compute Job on Hugging Face infrastructure. + + Args: + scheduled_job_id (`str`): + ID of the scheduled Job. + + namespace (`str`, *optional*): + The namespace where the scheduled Job is. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + + ```python + >>> from huggingface_hub import inspect_job, create_scheduled_job + >>> scheduled_job = create_scheduled_job(image="python:3.12", command=["python", "-c" ,"print('Hello from HF compute!')"], schedule="@hourly") + >>> inspect_scheduled_job(scheduled_job.id) + ``` + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().get( + f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + return ScheduledJobInfo(**response.json()) + + def delete_scheduled_job( + self, + *, + scheduled_job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> None: + """ + Delete a scheduled compute Job on Hugging Face infrastructure. + + Args: + scheduled_job_id (`str`): + ID of the scheduled Job. + + namespace (`str`, *optional*): + The namespace where the scheduled Job is. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + response = get_session().delete( + f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + + def suspend_scheduled_job( + self, + *, + scheduled_job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> None: + """ + Suspend (pause) a scheduled compute Job on Hugging Face infrastructure. + + Args: + scheduled_job_id (`str`): + ID of the scheduled Job. + + namespace (`str`, *optional*): + The namespace where the scheduled Job is. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + get_session().post( + f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}/suspend", + headers=self._build_hf_headers(token=token), + ).raise_for_status() + + def resume_scheduled_job( + self, + *, + scheduled_job_id: str, + namespace: str | None = None, + token: bool | str | None = None, + ) -> None: + """ + Resume (unpause) a scheduled compute Job on Hugging Face infrastructure. + + Args: + scheduled_job_id (`str`): + ID of the scheduled Job. + + namespace (`str`, *optional*): + The namespace where the scheduled Job is. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + """ + if namespace is None: + namespace = self.whoami(token=token)["name"] + get_session().post( + f"{self.endpoint}/api/scheduled-jobs/{namespace}/{scheduled_job_id}/resume", + headers=self._build_hf_headers(token=token), + ).raise_for_status() + + @experimental + def create_scheduled_uv_job( + self, + script: str, + *, + script_args: list[str] | None = None, + schedule: str, + suspend: bool | None = None, + concurrency: bool | None = None, + dependencies: list[str] | None = None, + python: str | None = None, + image: str | None = None, + env: dict[str, Any] | None = None, + secrets: dict[str, Any] | None = None, + flavor: SpaceHardware | None = None, + timeout: int | float | str | None = None, + labels: dict[str, str] | None = None, + volumes: list[Volume] | None = None, + namespace: str | None = None, + token: bool | str | None = None, + ) -> ScheduledJobInfo: + """ + Run a UV script Job on Hugging Face infrastructure. + + Args: + script (`str`): + Path or URL of the UV script, or a command. + + script_args (`list[str]`, *optional*) + Arguments to pass to the script, or a command. + + schedule (`str`): + One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a + CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday). + + suspend (`bool`, *optional*): + If True, the scheduled Job is suspended (paused). Defaults to False. + + concurrency (`bool`, *optional*): + If True, multiple instances of this Job can run concurrently. Defaults to False. + + dependencies (`list[str]`, *optional*) + Dependencies to use to run the UV script. + + python (`str`, *optional*) + Use a specific Python version. Default is 3.12. + + image (`str`, *optional*, defaults to "ghcr.io/astral-sh/uv:python3.12-bookworm"): + Use a custom Docker image with `uv` installed. + + env (`dict[str, Any]`, *optional*): + Defines the environment variables for the Job. + + secrets (`dict[str, Any]`, *optional*): + Defines the secret environment variables for the Job. + + flavor (`str`, *optional*): + Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values. + Defaults to `"cpu-basic"`. + + timeout (`Union[int, float, str]`, *optional*): + Max duration for the Job: int/float with s (seconds, default), m (minutes), h (hours) or d (days). + Example: `300` or `"5m"` for 5 minutes. + + labels (`dict[str, str]`, *optional*): + Labels to attach to the job (key-value pairs). + + volumes (`list[Volume]`, *optional*): + Hugging Face Buckets or Repos to mount as volumes in the job container. + Each volume is a [`Volume`] with `type` (`"bucket"`, `"model"`, `"dataset"`, or `"space"`), + `source` (e.g. `"username/my-bucket"`), and `mount_path` (e.g. `"/data"`). + + namespace (`str`, *optional*): + The namespace where the Job will be created. Defaults to the current user's namespace. + + token `(Union[bool, str, None]`, *optional*): + A valid user access token. If not provided, the locally saved token will be used, which is the + recommended authentication method. Set to `False` to disable authentication. + Refer to: https://huggingface.co/docs/huggingface_hub/quick-start#authentication. + + Example: + + Schedule a script from a URL: + + ```python + >>> from huggingface_hub import create_scheduled_uv_job + >>> script = "https://raw.githubusercontent.com/huggingface/trl/refs/heads/main/trl/scripts/sft.py" + >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"] + >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly") + ``` + + Schedule a local script: + + ```python + >>> from huggingface_hub import create_scheduled_uv_job + >>> script = "my_sft.py" + >>> script_args = ["--model_name_or_path", "Qwen/Qwen2-0.5B", "--dataset_name", "trl-lib/Capybara", "--push_to_hub"] + >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["trl"], flavor="a10g-small", schedule="@weekly") + ``` + + Schedule a command: + + ```python + >>> from huggingface_hub import create_scheduled_uv_job + >>> script = "lighteval" + >>> script_args= ["endpoint", "inference-providers", "model_name=openai/gpt-oss-20b,provider=auto", "lighteval|gsm8k|0|0"] + >>> create_scheduled_uv_job(script, script_args=script_args, dependencies=["lighteval"], flavor="a10g-small", schedule="@weekly") + ``` + """ + image = image or "ghcr.io/astral-sh/uv:python3.12-bookworm" + # Build command + command, env, secrets, extra_volumes = self._create_uv_command_env_and_secrets( + script=script, + script_args=script_args, + dependencies=dependencies, + python=python, + env=env, + secrets=secrets, + namespace=namespace, + token=token, + volumes=volumes, + ) + if extra_volumes: + volumes = (volumes or []) + extra_volumes + # Create RunCommand args + return self.create_scheduled_job( + image=image, + command=command, + schedule=schedule, + suspend=suspend, + concurrency=concurrency, + env=env, + secrets=secrets, + flavor=flavor, + timeout=timeout, + labels=labels, + volumes=volumes, + namespace=namespace, + token=token, + ) + + def _create_uv_command_env_and_secrets( + self, + *, + script: str, + script_args: list[str] | None, + dependencies: list[str] | None, + python: str | None, + env: dict[str, Any] | None, + secrets: dict[str, Any] | None, + namespace: str | None, + token: bool | str | None, + volumes: list[Volume] | None = None, + ) -> tuple[list[str], dict[str, Any], dict[str, Any], list[Volume]]: + env = env or {} + secrets = secrets or {} + + # Build command + uv_args = [] + if dependencies: + for dependency in dependencies: + uv_args += ["--with", dependency] + if python: + uv_args += ["--python", python] + script_args = script_args or [] + + if namespace is None: + namespace = self.whoami(token=token)["name"] + + # Find the local files to pass to the job + local_files_to_include = {candidate for candidate in [script] + script_args if Path(candidate).is_file()} + # Fail early for missing scripts or config files + missing_local_files = { + candidate + for candidate in [script] + script_args + if not Path(candidate).is_file() + and Path(candidate).suffix in [".py", ".sh", ".yaml", ".yml", ".toml"] + and not candidate.startswith("https://") + and not candidate.startswith("http://") + } + if missing_local_files: + raise FileNotFoundError(", ".join(missing_local_files)) + + if len(local_files_to_include) == 0: + # Direct URL execution or command - no upload needed + command = ["uv", "run"] + uv_args + [script] + script_args + return command, env, secrets, [] + + # Find appropriate remote file names + remote_to_local_file_names: dict[str, str] = {} + for local_file_to_include in local_files_to_include: + local_file_path = Path(local_file_to_include) + # Sanitize spaces for predictable remote paths + remote_file_path = Path(local_file_path.name.replace(" ", "_")) + if remote_file_path.name in remote_to_local_file_names: + for i in itertools.count(): + remote_file_name = remote_file_path.with_stem(remote_file_path.stem + f"({i})").name + if remote_file_name not in remote_to_local_file_names: + remote_to_local_file_names[remote_file_name] = local_file_to_include + break + else: + remote_to_local_file_names[remote_file_path.name] = local_file_to_include + local_to_remote_file_names = { + local_file_to_include: remote_file_name + for remote_file_name, local_file_to_include in remote_to_local_file_names.items() + } + + # Local files are shipped to the job via a bucket mounted at /data. + existing_mount_paths = {v.mount_path for v in (volumes or [])} + if constants.HF_JOBS_ARTIFACTS_MOUNT_PATH in existing_mount_paths: + raise ValueError( + f"Mount path {constants.HF_JOBS_ARTIFACTS_MOUNT_PATH!r} is reserved for Jobs artifacts when running local scripts. Mount your volume at a different path." + ) + + extra_volumes = self._upload_scripts_to_bucket( + namespace=namespace, + remote_to_local_file_names=remote_to_local_file_names, + token=token, + ) + # Rewrite script and script_args to reference the mounted path. The bucket + # volume is scoped to the per-job subfolder (via `Volume.path`), so the job + # container sees the uploaded files directly at the mount root. + mount_path = constants.HF_JOBS_ARTIFACTS_MOUNT_PATH + if script in local_to_remote_file_names: + script = f"{mount_path}/{local_to_remote_file_names[script]}" + script_args = [ + f"{mount_path}/{local_to_remote_file_names[arg]}" if arg in local_to_remote_file_names else arg + for arg in script_args + ] + command = ["uv", "run"] + uv_args + [script] + script_args + return command, env, secrets, extra_volumes + + def _upload_scripts_to_bucket( + self, + *, + namespace: str, + remote_to_local_file_names: dict[str, str], + token: bool | str | None, + ) -> list[Volume]: + """Upload script files to a per-job subfolder in the artifacts bucket. + + Creates a bucket `/jobs-artifacts` (if it doesn't exist) and uploads + each script to `{timestamp}-{random}/{remote_name}` inside it. Returns a + [`Volume`] scoped to that bucket subfolder. Volume is in read-write mode so the Job can save data back to this bucket. + """ + bucket_id = f"{namespace}/{constants.HF_JOBS_ARTIFACTS_BUCKET_NAME}" + subfolder_id = f"{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S')}-{token_hex(3)}" + + bucket_url = self.create_bucket(bucket_id=bucket_id, exist_ok=True, token=token, private=True) + + add_ops: list[tuple[str | Path | bytes, str]] = [ + (Path(local_path), f"{subfolder_id}/{remote_name}") + for remote_name, local_path in remote_to_local_file_names.items() + ] + self.batch_bucket_files(bucket_id=bucket_id, add=add_ops, token=token) + print(f"Your script and Job artifacts will be saved in this bucket: {bucket_url.url}") + + volume = Volume( + type="bucket", + source=bucket_id, + mount_path=constants.HF_JOBS_ARTIFACTS_MOUNT_PATH, + path=subfolder_id, + read_only=False, + ) + return [volume] + + @validate_hf_hub_args + def create_bucket( + self, + bucket_id: str, + *, + private: bool | None = None, + resource_group_id: str | None = None, + exist_ok: bool = False, + token: bool | str | None = None, + ) -> BucketUrl: + """Create a bucket on the Hub. + + Args: + bucket_id (`str`): + A namespace (user or an organization) and a bucket name separated by a `/`. + If no namespace is provided, the bucket will be created in the current user's namespace. + private (`bool`, *optional*): + Whether to make the bucket private. If `None` (default), the bucket will be public unless the + organization's default is private. + resource_group_id (`str`, *optional*): + Resource group in which to create the bucket. Resource groups are only available for Enterprise Hub + organizations and allow to define which members of the organization can access the resource. The ID + of a resource group can be found in the URL of the resource's page on the Hub + (e.g. `"66670e5163145ca562cb1988"`). To learn more about resource groups, see + https://huggingface.co/docs/hub/en/security-resource-groups. + exist_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if the bucket already exists. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`BucketUrl`]: URL to the newly created bucket containing + attributes like `endpoint`, `namespace`, and `bucket_id`. + + Example: + ```python + >>> from huggingface_hub import create_bucket + + >>> url = create_bucket(bucket_id="my-bucket") + >>> url.bucket_id + 'user/my-bucket' + >>> url.url + 'https://huggingface.co/buckets/user/my-bucket' + >>> url.handle + 'hf://buckets/user/my-bucket' + + >>> create_bucket(bucket_id="my-bucket", private=True, exist_ok=True) + BucketUrl(...) + ``` + """ + payload: dict[str, Any] = {} + if private is not None: + payload["private"] = private + if resource_group_id is not None: + payload["resourceGroupId"] = resource_group_id + + if "/" not in bucket_id: + namespace, name = "me", bucket_id # "me" namespace refers to the current user + else: + bucket_id_parsed, prefix = _split_bucket_id_and_prefix(bucket_id) + if prefix: + raise ValueError(f"Invalid bucket ID: {bucket_id}") + namespace, name = bucket_id_parsed.split("/") + + response = get_session().post( + f"{self.endpoint}/api/buckets/{namespace}/{name}", + headers=self._build_hf_headers(token=token), + json=payload, + ) + try: + hf_raise_for_status(response) + except HfHubHTTPError as err: + if exist_ok and err.response.status_code == 409: + # Repo already exists and `exist_ok=True` + pass + elif exist_ok and err.response.status_code == 403: + # No write permission on the namespace but repo might already exist + try: + self.bucket_info(bucket_id=bucket_id, token=token) + return BucketUrl(f"{self.endpoint}/buckets/{bucket_id}", endpoint=self.endpoint) + except HfHubHTTPError: + raise err + else: + raise + return BucketUrl(response.json()["url"], endpoint=self.endpoint) + + @validate_hf_hub_args + def bucket_info( + self, + bucket_id: str, + *, + token: bool | str | None = None, + ) -> BucketInfo: + """Get information about a specific bucket on the Hub. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`BucketInfo`]: The bucket information. + + Raises: + [`~errors.BucketNotFoundError`]: If the bucket cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + Example: + ```python + >>> from huggingface_hub import bucket_info + >>> info = bucket_info(bucket_id="Wauplin/first-bucket") + >>> info.id + 'Wauplin/first-bucket' + >>> info.private + False + >>> info.created_at + datetime.datetime(2026, 2, 6, 17, 37, 57, tzinfo=datetime.timezone.utc) + >>> info.size + 551879671 + >>> info.total_files + 12 + ``` + """ + response = get_session().get( + f"{self.endpoint}/api/buckets/{bucket_id}", + headers=self._build_hf_headers(token=token), + ) + hf_raise_for_status(response) + return BucketInfo(**response.json()) + + @validate_hf_hub_args + def list_buckets( + self, + namespace: str | None = None, + *, + search: str | None = None, + token: bool | str | None = None, + ) -> Iterable[BucketInfo]: + """List buckets on the Hub under a certain namespace. + + Args: + namespace (`str`, *optional*): + List buckets under this namespace (user or organization). Defaults to listing user's buckets. + search (`str`, *optional*): + A search string to filter bucket names. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[BucketInfo]`: An iterable of [`BucketInfo`] objects. + + Example: + ```python + >>> from huggingface_hub import list_buckets + >>> for bucket in list_buckets(): # lists buckets in the user's namespace + ... print(bucket) + + >>> for bucket in list_buckets(namespace="huggingface"): # lists buckets in the "huggingface" organization + ... print(bucket) + + >>> for bucket in list_buckets(search="my-prefix"): # filter buckets by name + ... print(bucket) + ``` + """ + if namespace is None: + namespace = "me" + params: dict[str, Any] = {} + if search is not None: + params["search"] = search + for item in paginate( + f"{self.endpoint}/api/buckets/{namespace}", params=params, headers=self._build_hf_headers(token=token) + ): + yield BucketInfo(**item) + + @validate_hf_hub_args + def delete_bucket( + self, + bucket_id: str, + *, + missing_ok: bool = False, + token: bool | str | None = None, + ) -> None: + """Delete a bucket from the Hub. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + missing_ok (`bool`, *optional*, defaults to `False`): + If `True`, do not raise an error if the bucket does not exist. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`~errors.BucketNotFoundError`]: If the bucket cannot be found and `missing_ok` is set to `False` (default). + + Example: + ```python + >>> from huggingface_hub import delete_bucket + >>> delete_bucket(bucket_id="Wauplin/first-bucket") + >>> delete_bucket(bucket_id="Wauplin/first-bucket", missing_ok=True) + ``` + """ + response = get_session().delete( + f"{self.endpoint}/api/buckets/{bucket_id}", + headers=self._build_hf_headers(token=token), + ) + + reset_xet_connection_info_cache_for_repo("bucket", bucket_id) + try: + hf_raise_for_status(response) + except HfHubHTTPError as e: + if e.response.status_code != 404 or not missing_ok: + raise + + @validate_hf_hub_args + def move_bucket( + self, + from_id: str, + to_id: str, + *, + token: bool | str | None = None, + ) -> None: + """Move a bucket from "namespace1/repo_name1" to "namespace2/repo_name2" + + Note there are certain limitations. For more information about moving + repositories, please see + https://hf.co/docs/hub/repositories-settings#renaming-or-transferring-a-repo. + + Args: + from_id (`str`): + A namespace (user or an organization) and a bucket name separated + by a `/`. Original bucket identifier (e.g. `"username/my-bucket"`). + to_id (`str`): + A namespace (user or an organization) and a bucket name separated + by a `/`. Final bucket identifier (e.g. `"username/new-bucket-name"` + or `"organization/my-bucket"`). + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`~errors.BucketNotFoundError`]: + If the source bucket cannot be found. This may be because it doesn't exist, + or because it is set to `private` and you do not have access. + + Example: + ```python + >>> from huggingface_hub import move_bucket + + >>> # Rename a bucket within the same namespace + >>> move_bucket(from_id="username/old-name", to_id="username/new-name") + + >>> # Transfer a bucket to an organization + >>> move_bucket(from_id="username/my-bucket", to_id="my-org/my-bucket") + ``` + """ + if len(from_id.split("/")) != 2: + raise ValueError(f"Invalid repo_id: {from_id}. It should have a namespace (:namespace:/:repo_name:)") + + if len(to_id.split("/")) != 2: + raise ValueError(f"Invalid repo_id: {to_id}. It should have a namespace (:namespace:/:repo_name:)") + + json_payload = {"fromRepo": from_id, "toRepo": to_id, "type": "bucket"} + + path = f"{self.endpoint}/api/repos/move" + headers = self._build_hf_headers(token=token) + response = get_session().post(path, headers=headers, json=json_payload) + hf_raise_for_status(response) + + @validate_hf_hub_args + def list_bucket_tree( + self, + bucket_id: str, + prefix: str | None = None, + *, + recursive: bool | None = None, + token: str | bool | None = None, + ) -> Iterable[BucketFile | BucketFolder]: + """List files in a bucket. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + prefix (`str`, *optional*): + Filter results to files whose path starts with this prefix. + recursive (`bool`, *optional*): + If `True`, list files recursively. If `False` (default), list files and directories only at root. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[Union[BucketFile, BucketFolder]]`: An iterable of [`BucketFile`] and [`BucketFolder`] objects + containing file and directory information (path, etc.). + + Example: + ```python + >>> from huggingface_hub import list_bucket_tree + >>> for file_info in list_bucket_tree(bucket_id="username/my-bucket"): + ... print(file_info.path) + + >>> # Filter by prefix + >>> for file_info in list_bucket_tree(bucket_id="username/my-bucket", prefix="models/"): + ... print(file_info.path) + ``` + """ + encoded_prefix = "/" + quote(prefix, safe="") if prefix else "" + params = {} + if recursive is not None: + params["recursive"] = recursive + for item in paginate( + path=f"{self.endpoint}/api/buckets/{bucket_id}/tree{encoded_prefix}", + headers=self._build_hf_headers(token=token), + params=params, + ): + if item["type"] == "file": + yield BucketFile(**item) + elif item["type"] == "directory": + yield BucketFolder(**item) + + @validate_hf_hub_args + def get_bucket_paths_info( + self, + bucket_id: str, + paths: Iterable[str], + *, + token: str | bool | None = None, + ) -> Iterable[BucketFile]: + """ + Get information about a bucket's paths. + + Calls are made in batches of 1000 paths. Results are yielded as they are received. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + paths (`Iterable[str]`): + The paths to get information about. If a path does not exist, it is ignored without raising an exception. + Only file paths are supported. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + `Iterable[BucketFile]`: + The information about the paths, as an iterable of [`BucketFile`] objects. + + Example: + ```py + >>> from huggingface_hub import get_bucket_paths_info + >>> paths_info = get_bucket_paths_info("username/my-bucket", ["file.txt", "checkpoints/model.safetensors"]) + >>> for info in paths_info: + ... print(info) + BucketFile(type='file', path='file.txt', size=2379, xet_hash='96e637d9665bd35477b1908a23f2e254edfba0618dbd2d62f90a6baee7d139cf', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc)) + BucketFile(type='file', path='checkpoints/model.safetensors', size=2408828, xet_hash='3ed0e9fefe788ddd61d1e26eba67057e9740a064b009256fbafadf6bb95785ca', mtime=datetime.datetime(2024, 9, 25, 15, 31, 2, 346000, tzinfo=datetime.timezone.utc)) + ``` + """ + headers = self._build_hf_headers(token=token) + + for batch in chunk_iterable(paths, chunk_size=_BUCKET_PATHS_INFO_BATCH_SIZE): + response = http_backoff( + "POST", + f"{self.endpoint}/api/buckets/{bucket_id}/paths-info", + json={"paths": list(batch)}, + headers=headers, + ) + hf_raise_for_status(response) + for path_info in response.json(): + yield BucketFile(**path_info) + + @validate_hf_hub_args + def copy_files(self, source: str, destination: str, *, token: str | bool | None = None) -> None: + """Copy files between locations on the Hub. + + Copy files from a bucket or repository (model, dataset, space) to a bucket. Both individual files and + entire folders are supported. + + Currently, only bucket destinations are supported. Copying to a repository is not supported. + + When copying folders, a trailing `/` on the source path uses rsync-style semantics: copy the *contents* + of the folder into the destination, without nesting the source folder itself. Without a trailing `/`, + the source folder is nested inside the destination (like `cp -r`). + + When copying from a repository, `.gitattributes` files are automatically excluded since they are + git-specific metadata and not relevant in a bucket context. + + Args: + source (`str`): + Source location as an `hf://` handle. Can be a bucket path (e.g. `"hf://buckets/my-bucket/path/to/file"`) + or a repo path (e.g. `"hf://username/my-model/weights.bin"`, `"hf://datasets/username/my-dataset/data/"`). + destination (`str`): + Destination location as an `hf://` handle pointing to a bucket + (e.g. `"hf://buckets/my-bucket/target/path"`). + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError): + If the destination is not a bucket or if the source/destination handles are invalid. + + Example: + ```python + >>> from huggingface_hub import copy_files + + # Copy a single file between buckets + >>> copy_files("hf://buckets/my-bucket/data.bin", "hf://buckets/other-bucket/data.bin") + + # Copy a folder into another bucket (nests: backup/models/...) + >>> copy_files("hf://buckets/my-bucket/models", "hf://buckets/other-bucket/backup/") + + # Copy folder contents (trailing /): files go directly into backup/ + >>> copy_files("hf://buckets/my-bucket/models/", "hf://buckets/other-bucket/backup/") + + # Copy a file from a model repo to a bucket + >>> copy_files("hf://username/my-model/model.safetensors", "hf://buckets/my-bucket/") + + # Copy an entire dataset to a bucket + >>> copy_files("hf://datasets/username/my-dataset/", "hf://buckets/my-bucket/datasets/") + ``` + """ + # Rsync-style trailing slash on source: "copy contents of" instead of "copy directory into". + # Check before parsing strips the slash. + source_is_contents_only = source.endswith("/") + + source_handle = _parse_hf_copy_handle(source) + destination_handle = _parse_hf_copy_handle(destination) + + if isinstance(destination_handle, _RepoCopyHandle): + raise ValueError("Bucket-to-repo and repo-to-repo copy are not supported. Destination must be a bucket.") + + destination_bucket_id = destination_handle.bucket_id + destination_path = destination_handle.path + destination_is_directory = False + destination_exists_as_directory = False + + if destination_path == "": + # Bucket root always exists as a directory + destination_is_directory = True + destination_exists_as_directory = True + else: + # Check if destination matches an existing file + dest_path_info = list(self.get_bucket_paths_info(destination_bucket_id, [destination_path], token=token)) + if dest_path_info: + destination_is_directory = False + else: + # Check if destination is an existing "directory" (prefix with children) + destination_exists_as_directory = any( + self.list_bucket_tree(destination_bucket_id, prefix=destination_path, recursive=False, token=token) + ) + # Treat as directory if it exists as one, or if the user signaled with trailing slash + destination_is_directory = destination_exists_as_directory or destination.endswith("/") + + all_adds: list[tuple[str, str]] = [] + all_copies: list[_BucketCopyFile] = [] + pending_downloads: list[tuple[str, str]] = [] # (file_path, target_path) for non-xet files to download + + def _resolve_target_path(src_file_path: str, src_root_path: str | None, is_single_file: bool) -> str: + basename = src_file_path.rsplit("/", 1)[-1] + if is_single_file: + if destination_path == "": + return basename + if destination_is_directory: + return f"{destination_path.rstrip('/')}/{basename}" + return destination_path + + if src_root_path is None: + rel_path = src_file_path + elif src_file_path.startswith(src_root_path + "/"): + rel_path = src_file_path[len(src_root_path) + 1 :] + elif src_file_path == src_root_path: + rel_path = src_file_path.rsplit("/", 1)[-1] + else: + raise ValueError(f"Unexpected source path while copying folder: '{src_file_path}'.") + + if rel_path == "": + raise ValueError("Cannot copy an empty relative path.") + + # Rsync-style trailing slash on source means "copy contents of" — skip nesting. + # Without trailing slash, match `cp -r` behavior: nest source folder inside + # existing destination directory. Non-existing destination always uses rename semantics. + if destination_exists_as_directory and src_root_path is not None and not source_is_contents_only: + src_dir_basename = src_root_path.rsplit("/", 1)[-1] + rel_path = f"{src_dir_basename}/{rel_path}" + + if destination_path == "": + return rel_path + return f"{destination_path.rstrip('/')}/{rel_path}" + + def _build_copy_op( + target_path: str, xet_hash: str, size: int, source_repo_type: str, source_repo_id: str + ) -> _BucketCopyFile: + """Server-side copy by xet hash — no data transfer needed.""" + return _BucketCopyFile( + destination=target_path, + xet_hash=xet_hash, + source_repo_type=source_repo_type, + source_repo_id=source_repo_id, + size=size, + ) + + def _add_repo_file(file: RepoFile, target_path: str) -> None: + """Queue a repo file: copy-by-hash if xet-backed, otherwise download first.""" + if file.xet_hash is not None: + all_copies.append( + _build_copy_op( + target_path, + file.xet_hash, + file.size, + source_handle.repo_type, # type: ignore + source_handle.repo_id, # type: ignore + ) + ) + else: + pending_downloads.append((file.path, target_path)) + + # === Source is a bucket: always hash-based copy (no download needed) === + if isinstance(source_handle, _BucketCopyHandle): + source_path = source_handle.path + source_path_info = list(self.get_bucket_paths_info(source_handle.bucket_id, [source_path], token=token)) + + if source_path_info: + # Source path matched a single file + source_file = source_path_info[0] + target_path = _resolve_target_path(source_file.path, None, is_single_file=True) + all_copies.append( + _build_copy_op( + target_path, source_file.xet_hash, source_file.size, "bucket", source_handle.bucket_id + ) + ) + else: + # Source path is a folder (or prefix) — list and copy all matching files + for item in self.list_bucket_tree( + source_handle.bucket_id, prefix=source_path or None, recursive=True, token=token + ): + if not isinstance(item, BucketFile): + continue + if source_path and not (item.path == source_path or item.path.startswith(source_path + "/")): + continue + target_path = _resolve_target_path(item.path, source_path or None, is_single_file=False) + all_copies.append( + _build_copy_op(target_path, item.xet_hash, item.size, "bucket", source_handle.bucket_id) + ) + + # === Source is a repo: copy-by-hash if xet-backed, download otherwise === + else: + source_path = source_handle.path + source_repo_path_info: list[RepoFile | RepoFolder] = [] + if source_path != "": + source_repo_path_info = self.get_paths_info( + repo_id=source_handle.repo_id, + paths=[source_path], + repo_type=source_handle.repo_type, + revision=source_handle.revision, + token=token, + ) + + if len(source_repo_path_info) == 1 and isinstance(source_repo_path_info[0], RepoFile): + # Source path matched a single file — skip .gitattributes (git-specific metadata) + if source_repo_path_info[0].path.rsplit("/", 1)[-1] == ".gitattributes": + return + target_path = _resolve_target_path(source_repo_path_info[0].path, None, is_single_file=True) + _add_repo_file(source_repo_path_info[0], target_path) + else: + # Source path is a folder — list and copy all files recursively + for repo_item in self.list_repo_tree( + repo_id=source_handle.repo_id, + path_in_repo=source_path, + recursive=True, + repo_type=source_handle.repo_type, + revision=source_handle.revision, + token=token, + ): + if not isinstance(repo_item, RepoFile): + continue + # Skip .gitattributes files (git-specific metadata, not relevant in a bucket) + if repo_item.path.rsplit("/", 1)[-1] == ".gitattributes": + continue + target_path = _resolve_target_path(repo_item.path, source_path or None, is_single_file=False) + _add_repo_file(repo_item, target_path) + + # Raise if no source files were found + if not all_copies and not all_adds and not pending_downloads: + if isinstance(source_handle, _BucketCopyHandle): + raise EntryNotFoundError(f"No files found at '{source}' in bucket '{source_handle.bucket_id}'.") + else: + raise EntryNotFoundError( + f"No files found at '{source}' in {source_handle.repo_type} '{source_handle.repo_id}'." + ) + + # Download non-xet files in parallel + if pending_downloads: + + def _download_and_collect(item: tuple[str, str]) -> None: + file_path, target_path = item + local_path = self.hf_hub_download( + repo_id=source_handle.repo_id, # type: ignore + repo_type=source_handle.repo_type, # type: ignore + filename=file_path, + revision=source_handle.revision, # type: ignore + token=token, + tqdm_class=silent_tqdm, # type: ignore + ) + all_adds.append((local_path, target_path)) + + thread_map(_download_and_collect, pending_downloads, desc="Downloading text files for copy") + + # Send copies first (no upload needed), then adds (may need upload) + if all_copies: + for copy_chunk in chunk_iterable(all_copies, chunk_size=_BUCKET_BATCH_ADD_CHUNK_SIZE): + self._batch_bucket_files(destination_bucket_id, copy=list(copy_chunk), token=token) + if all_adds: + for add_chunk in chunk_iterable(all_adds, chunk_size=_BUCKET_BATCH_ADD_CHUNK_SIZE): + self._batch_bucket_files(destination_bucket_id, add=list(add_chunk), token=token) + + @validate_hf_hub_args + def batch_bucket_files( + self, + bucket_id: str, + *, + add: list[tuple[str | Path | bytes, str]] | None = None, + copy: list[tuple[str, str, str, str]] | None = None, + delete: list[str] | None = None, + token: str | bool | None = None, + ): + """Add, copy, and/or delete files in a bucket. + + This is a non-transactional operation. If an error occurs in the process, some files may have been uploaded, + copied, or deleted while others haven't. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + add (`list` of `tuple`, *optional*): + Files to upload. Each element is a `(source, destination)` tuple where `source` is a path to a local + file (`str` or `Path`) or raw `bytes` content, and `destination` is the path in the bucket. + copy (`list` of `tuple`, *optional*): + Files to copy by xet hash. Each element is a `(source_repo_type, source_repo_id, xet_hash, + destination)` tuple where: + - `source_repo_type` is the type of the source repository: `"model"`, `"dataset"`, `"space"`, or + `"bucket"`. + - `source_repo_id` is the ID of the source repository or bucket (e.g. `"username/my-model"`). + - `xet_hash` is the xet hash of the file to copy. + - `destination` is the destination path in the bucket. + This is a server-side operation — no data is downloaded or re-uploaded. + delete (`list` of `str`, *optional*): + Paths of files to delete from the bucket. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + ```python + >>> from huggingface_hub import batch_bucket_files + + # Upload files + >>> batch_bucket_files( + ... "username/my-bucket", + ... add=[ + ... ("./model.safetensors", "models/model.safetensors"), + ... (b'{{"key": "value"}}', "config.json"), + ... ], + ... ) + + # Copy xet files from another bucket or repo (server-side, no data transfer) + >>> batch_bucket_files( + ... "username/my-bucket", + ... copy=[ + ... ("bucket", "username/source-bucket", "", "models/model.safetensors"), + ... ("model", "username/my-model", "", "models/config.safetensors"), + ... ], + ... ) + + # Delete files + >>> batch_bucket_files("username/my-bucket", delete=["old-model.bin"]) + + # Upload and delete in one batch + >>> batch_bucket_files( + ... "username/my-bucket", + ... add=[("./new.txt", "new.txt")], + ... delete=["old.txt"], + ... ) + ``` + """ + add = add or [] + copy = copy or [] + delete = delete or [] + + # Small batch: do everything in one call + if len(add) + len(copy) + len(delete) <= _BUCKET_BATCH_ADD_CHUNK_SIZE: + self._batch_bucket_files(bucket_id, add=add, copy=copy, delete=delete, token=token) # type: ignore + return + + # Large batch: chunk copies first (no upload), then adds, then deletes + from .utils._xet_progress_reporting import XetProgressReporter + + if add and not are_progress_bars_disabled(): + progress = XetProgressReporter(total_files=len(add)) + else: + progress = None + + try: + for copy_chunk in chunk_iterable(copy, chunk_size=_BUCKET_BATCH_ADD_CHUNK_SIZE): + self._batch_bucket_files(bucket_id, copy=list(copy_chunk), token=token) + + for add_chunk in chunk_iterable(add, chunk_size=_BUCKET_BATCH_ADD_CHUNK_SIZE): + self._batch_bucket_files(bucket_id, add=list(add_chunk), token=token, _progress=progress) + + for delete_chunk in chunk_iterable(delete, chunk_size=_BUCKET_BATCH_DELETE_CHUNK_SIZE): + self._batch_bucket_files(bucket_id, delete=list(delete_chunk), token=token) + finally: + if progress is not None: + progress.close(False) + + return + + def _batch_bucket_files( + self, + bucket_id: str, + *, + add: list[tuple[str | Path | bytes, str] | _BucketAddFile] | None = None, + copy: list[tuple[str, str, str, str] | _BucketCopyFile] | None = None, + delete: list[str | _BucketDeleteFile] | None = None, + token: str | bool | None = None, + _progress: XetProgressReporter | None = None, + ): + """Internal method: process a single batch of bucket file operations (upload to XET + call /batch).""" + # Convert public API inputs to internal operation objects + operations: list[_BucketAddFile | _BucketCopyFile | _BucketDeleteFile] = [] + if add: + for add_item in add: + if isinstance(add_item, _BucketAddFile): + operations.append(add_item) + else: + source, destination = add_item + operations.append(_BucketAddFile(source=source, destination=destination)) + if copy: + for copy_item in copy: + if isinstance(copy_item, _BucketCopyFile): + operations.append(copy_item) + else: + source_repo_type, source_repo_id, xet_hash, destination = copy_item + operations.append( + _BucketCopyFile( + destination=destination, + xet_hash=xet_hash, + source_repo_type=source_repo_type, + source_repo_id=source_repo_id, + ) + ) + if delete: + for delete_item in delete: + if isinstance(delete_item, _BucketDeleteFile): + operations.append(delete_item) + else: + operations.append(_BucketDeleteFile(path=delete_item)) + + if not operations: + return + + from hf_xet import upload_bytes, upload_files + + from .utils._xet_progress_reporting import XetProgressReporter + + headers = self._build_hf_headers(token=token) + + add_operations = [op for op in operations if isinstance(op, _BucketAddFile)] + add_operations_to_upload = [op for op in add_operations if op.xet_hash is None] + add_bytes_operations = [op for op in add_operations if isinstance(op.source, bytes)] + add_path_operations = [op for op in add_operations if not isinstance(op.source, bytes)] + + if len(add_operations_to_upload) > 0: + try: + xet_connection_info = fetch_xet_connection_info_from_repo_info( + token_type=XetTokenType.WRITE, + repo_id=bucket_id, + repo_type="bucket", + headers=headers, + endpoint=self.endpoint, + ) + except HfHubHTTPError as e: + if e.response.status_code == 401: + raise XetAuthorizationError( + f"You are unauthorized to upload to xet storage for bucket/{bucket_id}. " + f"Please check that you have configured your access token with write access to the repo." + ) from e + raise + + xet_endpoint = xet_connection_info.endpoint + access_token_info = (xet_connection_info.access_token, xet_connection_info.expiration_unix_epoch) + + def token_refresher() -> tuple[str, int]: + new_xet_connection = fetch_xet_connection_info_from_repo_info( + token_type=XetTokenType.WRITE, + repo_id=bucket_id, + repo_type="bucket", + headers=headers, + endpoint=self.endpoint, + ) + if new_xet_connection is None: + raise XetRefreshTokenError("Failed to refresh xet token") + return new_xet_connection.access_token, new_xet_connection.expiration_unix_epoch + + owns_progress = _progress is None + if _progress is not None: + progress = _progress + progress_callback = progress.update_progress + elif not are_progress_bars_disabled(): + progress = XetProgressReporter() + progress_callback = progress.update_progress + else: + progress, progress_callback = None, None + + try: + # 2.a. Upload path files + xet_upload_infos = upload_files( + [str(op.source) for op in add_path_operations if op.xet_hash is None], + xet_endpoint, + access_token_info, + token_refresher, + progress_callback, + "bucket", + skip_sha256=True, + ) + for upload_info, op in zip( + xet_upload_infos, [op for op in add_path_operations if op.xet_hash is None] + ): + op.xet_hash = upload_info.hash + op.size = upload_info.filesize + + if progress is not None: + progress.notify_upload_complete() + + # 2.b. Upload bytes files + xet_upload_infos = upload_bytes( + [op.source for op in add_bytes_operations if op.xet_hash is None], + xet_endpoint, + access_token_info, + token_refresher, + progress_callback, + "bucket", + skip_sha256=True, + ) + for upload_info, op in zip( + xet_upload_infos, [op for op in add_bytes_operations if op.xet_hash is None] + ): + op.xet_hash = upload_info.hash + op.size = upload_info.filesize + + if progress is not None: + progress.notify_upload_complete() + finally: + if owns_progress and progress is not None: + progress.close(False) + + # 3. /batch call + def _payload_as_ndjson() -> Iterable[bytes]: + for op in operations: + if isinstance(op, _BucketAddFile): + payload = { + "type": "addFile", + "path": op.destination, + "xetHash": op.xet_hash, + "mtime": op.mtime, + } + if op.content_type is not None: + payload["contentType"] = op.content_type + elif isinstance(op, _BucketCopyFile): + payload = { + "type": "copyFile", + "path": op.destination, + "xetHash": op.xet_hash, + "sourceRepoType": op.source_repo_type, + "sourceRepoId": op.source_repo_id, + } + else: + payload = { + "type": "deleteFile", + "path": op.path, + } + yield json.dumps(payload).encode() + yield b"\n" + + headers = { + "Content-Type": "application/x-ndjson", + **headers, + } + data = b"".join(_payload_as_ndjson()) + + response = http_backoff( + "POST", f"{self.endpoint}/api/buckets/{bucket_id}/batch", headers=headers, content=data + ) + hf_raise_for_status(response) + + @validate_hf_hub_args + def get_bucket_file_metadata( + self, + bucket_id: str, + remote_path: str, + *, + token: str | bool | None = None, + ) -> BucketFileMetadata: + """Fetch metadata of a file in a bucket. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + remote_path (`str`): + The path of the file in the bucket. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Returns: + [`BucketFileMetadata`]: The file metadata containing size and xet information. + + Example: + ```python + >>> from huggingface_hub import get_bucket_file_metadata + >>> metadata = get_bucket_file_metadata( + ... bucket_id="username/my-bucket", + ... remote_path="models/model.safetensors", + ... ) + >>> metadata.size + 42000 + ``` + """ + response = _httpx_follow_relative_redirects_with_backoff( + "HEAD", + f"{self.endpoint}/buckets/{bucket_id}/resolve/{quote(remote_path, safe='')}", + headers=self._build_hf_headers(token=token), + retry_on_errors=True, + ) + + xet_file_data = parse_xet_file_data_from_response(response) + if xet_file_data is None: + raise ValueError(f"Could not parse xet file data for '{remote_path}' in bucket '{bucket_id}'.") + + size = response.headers.get("Content-Length") + if size is None: + raise ValueError(f"Could not get size for '{remote_path}' in bucket '{bucket_id}'.") + + return BucketFileMetadata(size=int(size), xet_file_data=xet_file_data) + + @validate_hf_hub_args + def download_bucket_files( + self, + bucket_id: str, + files: list[tuple[str | BucketFile, str | Path]], + *, + raise_on_missing_files: bool = False, + token: str | bool | None = None, + ) -> None: + """Download files from a bucket. + + Files input is a list of `(remote file, local file)` tuples where `remote file` is either the path of the file + in the bucket or a [`BucketFile`] object, and `local file` is the destination path on the local filesystem. + When passing a [`BucketFile`] object (obtained from [`list_bucket_tree`]), the method will skip the metadata + fetching step and directly download the files. + + Args: + bucket_id (`str`): + The ID of the bucket (e.g. `"username/my-bucket"`). + files (`list[tuple[Union[str, BucketFile], Union[str, Path]]]`): + Files to download as a list of tuple (source, destination). See description above for format details. + raise_on_missing_files (`bool`, *optional*): + If `True`, raise an [`EntryNotFoundError`] when a requested file does not exist in the bucket. If + `False` (default), missing files are skipped with a warning. + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + + Example: + ```python + >>> from huggingface_hub import download_bucket_files + + >>> download_bucket_files( + ... bucket_id="username/my-bucket", + ... files=[ + ... ("models/model.safetensors", "./local/model.safetensors"), + ... ("config.json", "./local/config.json"), + ... ], + ... ) + ``` + + ```python + >>> from huggingface_hub import download_bucket_files + + >>> parquet_files = [file for file in list_bucket_tree(bucket_id="username/my-bucket") if file.path.endswith(".parquet")] + >>> download_bucket_files( + ... bucket_id="username/my-bucket", + ... files=[(file, f"./local/{file.path}") for file in parquet_files], + ... ) + ``` + """ + from hf_xet import PyXetDownloadInfo, download_files # type: ignore[no-redef] + + headers = self._build_hf_headers(token=token) + + if len(files) == 0: + return + + # Resolve all string paths to BucketFile objects in a single batch request + str_paths = [path for path, _ in files if not isinstance(path, BucketFile)] + bucket_files_by_path: dict[str, BucketFile] = {} + if str_paths: + bucket_files_by_path = { + info.path: info for info in self.get_bucket_paths_info(bucket_id, str_paths, token=token) + } + + # Check for missing files + missing_paths = [path for path in str_paths if path not in bucket_files_by_path] + if missing_paths: + if raise_on_missing_files: + raise EntryNotFoundError( + f"{len(missing_paths)} file(s) not found in bucket '{bucket_id}': {', '.join(missing_paths)}" + ) + for path in missing_paths: + warnings.warn(f"File '{path}' not found in bucket '{bucket_id}'. Skipping.") + + xet_download_infos = [] + first_valid_bucket_file: BucketFile | None = None + for remote_file, local_path in files: + if not isinstance(remote_file, BucketFile): + if remote_file not in bucket_files_by_path: + continue # skip missing files (already warned above) + remote_file = bucket_files_by_path[remote_file] + if first_valid_bucket_file is None: + first_valid_bucket_file = remote_file + xet_download_infos.append( + PyXetDownloadInfo( + destination_path=str(Path(local_path).absolute()), + hash=remote_file.xet_hash, + file_size=remote_file.size, + ) + ) + + if len(xet_download_infos) == 0 or first_valid_bucket_file is None: + return + + # Fetch Xet connection info (same for all files) + remote_path = first_valid_bucket_file.path + + metadata = self.get_bucket_file_metadata(bucket_id, remote_path, token=token) + connection_info = refresh_xet_connection_info(file_data=metadata.xet_file_data, headers=headers) + + def token_refresher() -> tuple[str, int]: + connection_info = refresh_xet_connection_info(file_data=metadata.xet_file_data, headers=headers) + if connection_info is None: + raise ValueError("Failed to refresh token using xet metadata.") + return connection_info.access_token, connection_info.expiration_unix_epoch + + # Create empty files for zero-size files (no need to download them) + # and filter them out from xet_download_infos to avoid passing to xet library + non_zero_download_infos = [] + for download_info in xet_download_infos: + if download_info.file_size == 0: + dest_path = Path(download_info.destination_path) + if dest_path.exists(): + # already exists => make sure it's an empty file + if dest_path.is_dir(): + raise IsADirectoryError(f"Expected file but found directory at '{dest_path}'") + if dest_path.stat().st_size != 0: + dest_path.write_bytes(b"") + else: + # doesn't exist => create it + dest_path.parent.mkdir(parents=True, exist_ok=True) + dest_path.touch() + else: + non_zero_download_infos.append(download_info) + + # If only zero-size files, nothing more to download + if len(non_zero_download_infos) == 0: + return + + # Download files + progress_cm = _get_progress_bar_context( + desc="Downloading bucket files", + log_level=logger.getEffectiveLevel(), + total=sum(info.file_size for info in non_zero_download_infos), + initial=0, + name="huggingface_hub.download_bucket_files", + ) + + with progress_cm as progress: + + def progress_updater(progress_bytes: float): + progress.update(progress_bytes) + + download_files( + non_zero_download_infos, + endpoint=connection_info.endpoint, + token_info=(connection_info.access_token, connection_info.expiration_unix_epoch), + token_refresher=token_refresher, + progress_updater=[progress_updater] * len(non_zero_download_infos), + ) + + @validate_hf_hub_args + def sync_bucket( + self, + source: str | None = None, + dest: str | None = None, + *, + delete: bool = False, + ignore_times: bool = False, + ignore_sizes: bool = False, + existing: bool = False, + ignore_existing: bool = False, + include: list[str] | None = None, + exclude: list[str] | None = None, + filter_from: str | None = None, + plan: str | None = None, + apply: str | None = None, + dry_run: bool = False, + verbose: bool = False, + quiet: bool = False, + token: bool | str | None = None, + ) -> SyncPlan: + """Sync files between a local directory and a bucket. + + This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path + (``hf://buckets/...``) and the other must be a local directory path. + + Args: + source (`str`, *optional*): + Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``. + Required unless using ``apply``. + dest (`str`, *optional*): + Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``. + Required unless using ``apply``. + delete (`bool`, *optional*, defaults to `False`): + Delete destination files not present in source. + ignore_times (`bool`, *optional*, defaults to `False`): + Skip files only based on size, ignoring modification times. + ignore_sizes (`bool`, *optional*, defaults to `False`): + Skip files only based on modification times, ignoring sizes. + existing (`bool`, *optional*, defaults to `False`): + Skip creating new files on receiver (only update existing files). + ignore_existing (`bool`, *optional*, defaults to `False`): + Skip updating files that exist on receiver (only create new files). + include (`list[str]`, *optional*): + Include files matching patterns (fnmatch-style). + exclude (`list[str]`, *optional*): + Exclude files matching patterns (fnmatch-style). + filter_from (`str`, *optional*): + Path to a filter file with include/exclude rules. + plan (`str`, *optional*): + Save sync plan to this JSONL file instead of executing. + apply (`str`, *optional*): + Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed. + dry_run (`bool`, *optional*, defaults to `False`): + Print sync plan to stdout as JSONL without executing. + verbose (`bool`, *optional*, defaults to `False`): + Show detailed per-file operations. + quiet (`bool`, *optional*, defaults to `False`): + Suppress all output and progress bars. + token (Union[bool, str, None], optional): + A valid user access token. If not provided, the locally saved token will be used. + + Returns: + [`SyncPlan`]: The computed (or loaded) sync plan. + + Example: + ```python + >>> from huggingface_hub import HfApi + >>> api = HfApi() + + # Upload local directory to bucket + >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket") + + # Download bucket to local directory + >>> api.sync_bucket("hf://buckets/username/my-bucket", "./data") + + # Sync with delete and filtering + >>> api.sync_bucket( + ... "./data", + ... "hf://buckets/username/my-bucket", + ... delete=True, + ... include=["*.safetensors"], + ... ) + + # Dry run: preview what would be synced + >>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True) + >>> plan.summary() + {'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096} + + # Save plan for review, then apply + >>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl") + >>> api.sync_bucket(apply="sync-plan.jsonl") + ``` + """ + return sync_bucket_internal( + source=source, + dest=dest, + api=self, + delete=delete, + ignore_times=ignore_times, + ignore_sizes=ignore_sizes, + existing=existing, + ignore_existing=ignore_existing, + include=include, + exclude=exclude, + filter_from=filter_from, + plan=plan, + apply=apply, + dry_run=dry_run, + verbose=verbose, + quiet=quiet, + token=token, + ) + + +def _parse_revision_from_pr_url(pr_url: str) -> str: + """Safely parse revision number from a PR url. + + Example: + ```py + >>> _parse_revision_from_pr_url("https://huggingface.co/bigscience/bloom/discussions/2") + "refs/pr/2" + ``` + """ + re_match = re.match(_REGEX_DISCUSSION_URL, pr_url) + if re_match is None: + raise RuntimeError(f"Unexpected response from the hub, expected a Pull Request URL but got: '{pr_url}'") + return f"refs/pr/{re_match[1]}" + + +def parse_local_safetensors_file_metadata(path: str | Path) -> SafetensorsFileMetadata: + """ + Parse metadata from a local safetensors file. + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Args: + path (`str` or `Path`): + Path to the safetensors file. + + Returns: + [`SafetensorsFileMetadata`]: information related to the safetensors file. + + Raises: + [`SafetensorsParsingError`]: + If the safetensors file header couldn't be parsed correctly. + `FileNotFoundError`: + If the file does not exist. + + Example: + ```py + >>> metadata = parse_local_safetensors_file_metadata("path/to/model.safetensors") + >>> metadata + SafetensorsFileMetadata( + metadata={'format': 'pt'}, + tensors={'layer.weight': TensorInfo(dtype='F32', shape=[512, 512], ...}, ...} + ) + >>> metadata.parameter_count + {'F32': 262144} + ``` + """ + path = Path(path) + filename = path.name + context_msg = f"path '{path}'" + + with open(path, "rb") as f: + # 1. Read first 8 bytes and parse/validate metadata size using shared helper + size_bytes = f.read(8) + metadata_size = _get_safetensors_metadata_size(size_bytes, filename, context_msg) + + # 2. Read metadata bytes + metadata_as_bytes = f.read(metadata_size) + if len(metadata_as_bytes) < metadata_size: + raise SafetensorsParsingError( + f"Failed to parse safetensors header for '{filename}' ({context_msg}): file is truncated. Expected " + f"{metadata_size} bytes of metadata but got {len(metadata_as_bytes)}." + ) + + # 3. Parse using shared helper + return _parse_safetensors_header(metadata_as_bytes, filename, context_msg) + + +def get_local_safetensors_metadata(path: str | Path) -> SafetensorsRepoMetadata: + """ + Parse metadata for a local safetensors file or folder. + + Supports: + - Single safetensors file (e.g., `model.safetensors`) + - Directory with non-sharded model (contains `model.safetensors`) + - Directory with sharded model (contains `model.safetensors.index.json`) + + For more details regarding the safetensors format, check out https://huggingface.co/docs/safetensors/index#format. + + Args: + path (`str` or `Path`): + Path to a safetensors file or directory containing safetensors files. + + Returns: + [`SafetensorsRepoMetadata`]: information related to the safetensors repo. + + Raises: + [`NotASafetensorsRepoError`]: + If the path is not a valid safetensors file or folder (i.e., doesn't have either a + `model.safetensors` or a `model.safetensors.index.json` file). + [`SafetensorsParsingError`]: + If a safetensors file header couldn't be parsed correctly. + `FileNotFoundError`: + If the path does not exist. + + Example: + ```py + # Parse single safetensors file + >>> metadata = get_local_safetensors_metadata("path/to/model.safetensors") + >>> metadata + SafetensorsRepoMetadata(metadata=None, sharded=False, weight_map={...}, files_metadata={...}) + + # Parse directory with sharded model + >>> metadata = get_local_safetensors_metadata("path/to/model_folder") + >>> metadata + SafetensorsRepoMetadata(metadata={'total_size': ...}, sharded=True, weight_map={...}, files_metadata={...}) + >>> len(metadata.files_metadata) + 3 # Number of safetensors shards + ``` + """ + path = Path(path) + + # Case 1: Direct path to a safetensors file + if path.is_file(): + file_metadata = parse_local_safetensors_file_metadata(path) + return SafetensorsRepoMetadata( + metadata=None, + sharded=False, + weight_map={tensor_name: path.name for tensor_name in file_metadata.tensors.keys()}, + files_metadata={path.name: file_metadata}, + ) + + # Case 2: Directory + if not path.is_dir(): + raise FileNotFoundError(f"Path '{path}' does not exist.") + + single_file_path = path / constants.SAFETENSORS_SINGLE_FILE + index_file_path = path / constants.SAFETENSORS_INDEX_FILE + + # Case 2a: Non-sharded model (single model.safetensors file) + if single_file_path.exists(): + file_metadata = parse_local_safetensors_file_metadata(single_file_path) + return SafetensorsRepoMetadata( + metadata=None, + sharded=False, + weight_map={ + tensor_name: constants.SAFETENSORS_SINGLE_FILE for tensor_name in file_metadata.tensors.keys() + }, + files_metadata={constants.SAFETENSORS_SINGLE_FILE: file_metadata}, + ) + + # Case 2b: Sharded model (model.safetensors.index.json) + if index_file_path.exists(): + with open(index_file_path) as f: + index = json.load(f) + + weight_map = index.get("weight_map", {}) + + # Parse metadata from each shard + files_metadata = {} + for shard_filename in set(weight_map.values()): + shard_path = path / shard_filename + files_metadata[shard_filename] = parse_local_safetensors_file_metadata(shard_path) + + return SafetensorsRepoMetadata( + metadata=index.get("metadata", None), + sharded=True, + weight_map=weight_map, + files_metadata=files_metadata, + ) + + # Not a valid safetensors folder + raise NotASafetensorsRepoError( + f"'{path}' is not a valid safetensors folder. Couldn't find '{constants.SAFETENSORS_INDEX_FILE}' or " + f"'{constants.SAFETENSORS_SINGLE_FILE}' files." + ) + + +api = HfApi() + +whoami = api.whoami +auth_check = api.auth_check + +list_models = api.list_models +model_info = api.model_info + +list_datasets = api.list_datasets +list_dataset_parquet_files = api.list_dataset_parquet_files +dataset_info = api.dataset_info +get_dataset_leaderboard = api.get_dataset_leaderboard + +list_spaces = api.list_spaces +search_spaces = api.search_spaces +space_info = api.space_info + +kernel_info = api.kernel_info + +list_papers = api.list_papers +paper_info = api.paper_info +read_paper = api.read_paper +list_daily_papers = api.list_daily_papers + +repo_exists = api.repo_exists +revision_exists = api.revision_exists +file_exists = api.file_exists +repo_info = api.repo_info +list_repo_files = api.list_repo_files +list_repo_refs = api.list_repo_refs +list_repo_commits = api.list_repo_commits +list_repo_tree = api.list_repo_tree +get_paths_info = api.get_paths_info +verify_repo_checksums = api.verify_repo_checksums + +get_model_tags = api.get_model_tags +get_dataset_tags = api.get_dataset_tags + +create_commit = api.create_commit +create_repo = api.create_repo +delete_repo = api.delete_repo +update_repo_settings = api.update_repo_settings +move_repo = api.move_repo +upload_file = api.upload_file +upload_folder = api.upload_folder +delete_file = api.delete_file +delete_folder = api.delete_folder +delete_files = api.delete_files +upload_large_folder = api.upload_large_folder +preupload_lfs_files = api.preupload_lfs_files +create_branch = api.create_branch +delete_branch = api.delete_branch +create_tag = api.create_tag +delete_tag = api.delete_tag +get_full_repo_name = api.get_full_repo_name + +# Danger-zone API +super_squash_history = api.super_squash_history +list_lfs_files = api.list_lfs_files +permanently_delete_lfs_files = api.permanently_delete_lfs_files + +# Safetensors helpers +get_safetensors_metadata = api.get_safetensors_metadata +parse_safetensors_file_metadata = api.parse_safetensors_file_metadata + +# Background jobs +run_as_future = api.run_as_future + +# Activity API +list_liked_repos = api.list_liked_repos +list_repo_likers = api.list_repo_likers +unlike = api.unlike + +# Community API +get_discussion_details = api.get_discussion_details +get_repo_discussions = api.get_repo_discussions +create_discussion = api.create_discussion +create_pull_request = api.create_pull_request +change_discussion_status = api.change_discussion_status +comment_discussion = api.comment_discussion +edit_discussion_comment = api.edit_discussion_comment +rename_discussion = api.rename_discussion +merge_pull_request = api.merge_pull_request + +# Space API +get_space_secrets = api.get_space_secrets +add_space_secret = api.add_space_secret +delete_space_secret = api.delete_space_secret +get_space_variables = api.get_space_variables +add_space_variable = api.add_space_variable +delete_space_variable = api.delete_space_variable +get_space_runtime = api.get_space_runtime +list_spaces_hardware = api.list_spaces_hardware +request_space_hardware = api.request_space_hardware +set_space_sleep_time = api.set_space_sleep_time +pause_space = api.pause_space +restart_space = api.restart_space +duplicate_repo = api.duplicate_repo +duplicate_space = api.duplicate_space +request_space_storage = api.request_space_storage +delete_space_storage = api.delete_space_storage +set_space_volumes = api.set_space_volumes +delete_space_volumes = api.delete_space_volumes +enable_space_dev_mode = api.enable_space_dev_mode +disable_space_dev_mode = api.disable_space_dev_mode +fetch_space_logs = api.fetch_space_logs + +# Inference Endpoint API +list_inference_endpoints = api.list_inference_endpoints +create_inference_endpoint = api.create_inference_endpoint +get_inference_endpoint = api.get_inference_endpoint +update_inference_endpoint = api.update_inference_endpoint +delete_inference_endpoint = api.delete_inference_endpoint +pause_inference_endpoint = api.pause_inference_endpoint +resume_inference_endpoint = api.resume_inference_endpoint +scale_to_zero_inference_endpoint = api.scale_to_zero_inference_endpoint +create_inference_endpoint_from_catalog = api.create_inference_endpoint_from_catalog +list_inference_catalog = api.list_inference_catalog + +# Collections API +get_collection = api.get_collection +list_collections = api.list_collections +create_collection = api.create_collection +update_collection_metadata = api.update_collection_metadata +delete_collection = api.delete_collection +add_collection_item = api.add_collection_item +update_collection_item = api.update_collection_item +delete_collection_item = api.delete_collection_item +delete_collection_item = api.delete_collection_item + +# Access requests API +list_pending_access_requests = api.list_pending_access_requests +list_accepted_access_requests = api.list_accepted_access_requests +list_rejected_access_requests = api.list_rejected_access_requests +cancel_access_request = api.cancel_access_request +accept_access_request = api.accept_access_request +reject_access_request = api.reject_access_request +grant_access = api.grant_access + +# Webhooks API +create_webhook = api.create_webhook +disable_webhook = api.disable_webhook +delete_webhook = api.delete_webhook +enable_webhook = api.enable_webhook +get_webhook = api.get_webhook +list_webhooks = api.list_webhooks +update_webhook = api.update_webhook + + +# User API +get_user_overview = api.get_user_overview +get_organization_overview = api.get_organization_overview +list_organization_followers = api.list_organization_followers +list_organization_members = api.list_organization_members +list_user_followers = api.list_user_followers +list_user_following = api.list_user_following + +# Jobs API +run_job = api.run_job +fetch_job_logs = api.fetch_job_logs +fetch_job_metrics = api.fetch_job_metrics +list_jobs = api.list_jobs +list_jobs_hardware = api.list_jobs_hardware +inspect_job = api.inspect_job +cancel_job = api.cancel_job +run_uv_job = api.run_uv_job +create_scheduled_job = api.create_scheduled_job +list_scheduled_jobs = api.list_scheduled_jobs +inspect_scheduled_job = api.inspect_scheduled_job +delete_scheduled_job = api.delete_scheduled_job +suspend_scheduled_job = api.suspend_scheduled_job +resume_scheduled_job = api.resume_scheduled_job +create_scheduled_uv_job = api.create_scheduled_uv_job + +# Buckets API +create_bucket = api.create_bucket +bucket_info = api.bucket_info +list_buckets = api.list_buckets +delete_bucket = api.delete_bucket +move_bucket = api.move_bucket +list_bucket_tree = api.list_bucket_tree +get_bucket_paths_info = api.get_bucket_paths_info +copy_files = api.copy_files +batch_bucket_files = api.batch_bucket_files +get_bucket_file_metadata = api.get_bucket_file_metadata +download_bucket_files = api.download_bucket_files +sync_bucket = api.sync_bucket diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/hf_file_system.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/hf_file_system.py new file mode 100644 index 0000000000000000000000000000000000000000..4fb007827073228f8422c51ba418b7197647aabe --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/hf_file_system.py @@ -0,0 +1,1446 @@ +import os +import tempfile +import threading +from collections import deque +from collections.abc import Iterable, Iterator +from contextlib import ExitStack +from copy import deepcopy +from dataclasses import dataclass, field +from datetime import datetime +from itertools import chain +from pathlib import Path, PurePosixPath +from typing import Any, NoReturn, Union +from urllib.parse import quote, unquote + +import fsspec +import httpx +from fsspec.callbacks import _DEFAULT_CALLBACK, NoOpCallback, TqdmCallback +from fsspec.config import apply_config +from fsspec.utils import isfilelike + +from . import constants +from ._commit_api import CommitOperationCopy, CommitOperationDelete +from .errors import ( + BucketNotFoundError, + EntryNotFoundError, + HfHubHTTPError, + RepositoryNotFoundError, + RevisionNotFoundError, +) +from .file_download import hf_hub_url, http_get +from .hf_api import SPECIAL_REFS_REVISION_REGEX, BucketFile, BucketFolder, HfApi, LastCommitInfo, RepoFile, RepoFolder +from .utils import HFValidationError, hf_raise_for_status, http_backoff, http_stream_backoff +from .utils.insecure_hashlib import md5 + + +@dataclass +class HfFileSystemResolvedPath: + """Top level Data structure containing information about a resolved Hugging Face file system path.""" + + root: str + path: str + + def unresolve(self) -> str: + return f"{self.root}/{self.path}".rstrip("/") + + +@dataclass +class HfFileSystemResolvedRepositoryPath(HfFileSystemResolvedPath): + """Data structure containing information about a resolved path in a repository.""" + + repo_type: str + repo_id: str + revision: str + path_in_repo: str + root: str = field(init=False) + path: str = field(init=False) + # The part placed after '@' in the initial path. It can be a quoted or unquoted refs revision. + # Used to reconstruct the unresolved path to return to the user. + _raw_revision: str | None = field(default=None, repr=False) + + def __post_init__(self): + repo_path = constants.REPO_TYPES_URL_PREFIXES.get(self.repo_type, "") + self.repo_id + if self._raw_revision: + self.root = f"{repo_path}@{self._raw_revision}" + elif self.revision != constants.DEFAULT_REVISION: + self.root = f"{repo_path}@{safe_revision(self.revision)}" + else: + self.root = repo_path + self.path = self.path_in_repo + + +@dataclass +class HfFileSystemResolvedBucketPath(HfFileSystemResolvedPath): + """Data structure containing information about a resolved path in a bucket.""" + + bucket_id: str + root: str = field(init=False) + + def __post_init__(self): + self.root = "buckets/" + self.bucket_id + + +# We need to improve fsspec.spec._Cached which is AbstractFileSystem's metaclass +_cached_base: Any = type(fsspec.AbstractFileSystem) + + +class _Cached(_cached_base): + """ + Metaclass for caching HfFileSystem instances according to the args. + + This creates an additional reference to the filesystem, which prevents the + filesystem from being garbage collected when all *user* references go away. + A call to the :meth:`AbstractFileSystem.clear_instance_cache` must *also* + be made for a filesystem instance to be garbage collected. + + This is a slightly modified version of `fsspec.spec._Cached` to improve it. + In particular in `_tokenize` the pid isn't taken into account for the + `fs_token` used to identify cached instances. The `fs_token` logic is also + robust to defaults values and the order of the args. Finally new instances + reuse the states from sister instances in the main thread. + """ + + def __init__(cls, *args, **kwargs): + # Hack: override https://github.com/fsspec/filesystem_spec/blob/dcb167e8f50e6273d4cfdfc4cab8fc5aa4c958bf/fsspec/spec.py#L53 + super().__init__(*args, **kwargs) + # Note: we intentionally create a reference here, to avoid garbage + # collecting instances when all other references are gone. To really + # delete a FileSystem, the cache must be cleared. + cls._cache = {} + + def __call__(cls, *args, **kwargs): + # Hack: override https://github.com/fsspec/filesystem_spec/blob/dcb167e8f50e6273d4cfdfc4cab8fc5aa4c958bf/fsspec/spec.py#L65 + # Apply fsspec config (env vars / config files) before tokenizing so that + # HfFileSystem picks up defaults the same way other fsspec filesystems do. + kwargs = apply_config(cls, kwargs) + skip = kwargs.pop("skip_instance_cache", False) + fs_token = cls._tokenize(cls, threading.get_ident(), *args, **kwargs) + fs_token_main_thread = cls._tokenize(cls, threading.main_thread().ident, *args, **kwargs) + if not skip and cls.cachable and fs_token in cls._cache: + # reuse cached instance + cls._latest = fs_token + return cls._cache[fs_token] + else: + # create new instance + obj = type.__call__(cls, *args, **kwargs) + if not skip and cls.cachable and fs_token_main_thread in cls._cache: + # reuse the cache from the main thread instance in the new instance + instance_state = cls._cache[fs_token_main_thread]._get_instance_state() + for attr, state_value in instance_state.items(): + setattr(obj, attr, state_value) + obj._fs_token_ = fs_token + obj.storage_args = args + obj.storage_options = kwargs + if cls.cachable and not skip: + cls._latest = fs_token + cls._cache[fs_token] = obj + return obj + + +class HfFileSystem(fsspec.AbstractFileSystem, metaclass=_Cached): # ty: ignore[conflicting-metaclass] + """ + Access a remote Hugging Face Hub repository as if were a local file system. + + > [!WARNING] + > [`HfFileSystem`] provides fsspec compatibility, which is useful for libraries that require it (e.g., reading + > Hugging Face datasets directly with `pandas`). However, it introduces additional overhead due to this compatibility + > layer. For better performance and reliability, it's recommended to use `HfApi` methods when possible. + + The file system supports paths for the `hf://` protocol, which follows those URL schemes: + + * Models, Datasets and Spaces repositories: + + ``` + hf://[@]/ + hf://datasets/[@]/ + hf://spaces/[@]/ + ``` + + * Buckets (generic storage): + + ``` + hf://buckets// + ``` + + Note: when using the [`HfFileSystem`] directly, passing the `hf://` protocol prefix is optional in paths. + + Args: + endpoint (`str`, *optional*): + Endpoint of the Hub. Defaults to . + token (`bool` or `str`, *optional*): + A valid user access token (string). Defaults to the locally saved + token, which is the recommended method for authentication (see + https://huggingface.co/docs/huggingface_hub/quick-start#authentication). + To disable authentication, pass `False`. + block_size (`int`, *optional*): + Block size for reading and writing files. + expand_info (`bool`, *optional*): + Whether to expand the information of the files. + **storage_options (`dict`, *optional*): + Additional options for the filesystem. See [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.__init__). + + Usage: + + ```python + >>> from huggingface_hub import hffs + + >>> # List files + >>> hffs.glob("my-username/my-model/*.bin") + ['my-username/my-model/pytorch_model.bin'] + >>> hffs.ls("datasets/my-username/my-dataset", detail=False) + ['datasets/my-username/my-dataset/.gitattributes', 'datasets/my-username/my-dataset/README.md', 'datasets/my-username/my-dataset/data.json'] + + >>> # Read/write files + >>> with hffs.open("my-username/my-model/pytorch_model.bin") as f: + ... data = f.read() + >>> with hffs.open("my-username/my-model/pytorch_model.bin", "wb") as f: + ... f.write(data) + ``` + + Specify a token for authentication: + ```python + >>> from huggingface_hub import HfFileSystem + >>> hffs = HfFileSystem(token=token) + ``` + """ + + root_marker = "" + protocol = "hf" + + def __init__( + self, + *args, + endpoint: str | None = None, + token: bool | str | None = None, + block_size: int | None = None, + expand_info: bool | None = None, + **storage_options, + ): + super().__init__(*args, **storage_options) + self.endpoint = endpoint or constants.ENDPOINT + self.token = token + self._api = HfApi(endpoint=endpoint, token=token) + self.block_size = block_size + self.expand_info = expand_info + # Maps (repo_type, repo_id, revision) to a 2-tuple with: + # * the 1st element indicating whether the repository and the revision exist + # * the 2nd element being the exception raised if the repository or revision doesn't exist + self._repo_and_revision_exists_cache: dict[tuple[str, str, str | None], tuple[bool, Exception | None]] = {} + # Same for buckets + self._bucket_exists_cache: dict[str, tuple[bool, Exception | None]] = {} + # Note: special case for buckets: revision is always None + # Maps parent directory path to path infos + self.dircache: dict[str, list[dict[str, Any]]] = {} + + @classmethod + def _tokenize(cls, threading_ident: int, *args, **kwargs) -> str: + """Deterministic token for caching""" + # make fs_token robust to default values and to kwargs order + kwargs["endpoint"] = kwargs.get("endpoint") or constants.ENDPOINT + kwargs["token"] = kwargs.get("token") + kwargs = {key: kwargs[key] for key in sorted(kwargs)} + # contrary to fsspec, we don't include pid here + tokenize_args = (cls, threading_ident, args, kwargs) + h = md5(str(tokenize_args).encode()) + return h.hexdigest() + + def _repo_and_revision_exist( + self, repo_type: str, repo_id: str, revision: str | None + ) -> tuple[bool, Exception | None]: + if (repo_type, repo_id, revision) not in self._repo_and_revision_exists_cache: + try: + self._api.repo_info( + repo_id, revision=revision, repo_type=repo_type, timeout=constants.HF_HUB_ETAG_TIMEOUT + ) + except (RepositoryNotFoundError, HFValidationError) as e: + self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = False, e + self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = False, e + except RevisionNotFoundError as e: + self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = False, e + self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = True, None + else: + self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = True, None + self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = True, None + return self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] + + def _bucket_exists(self, bucket_id: str) -> tuple[bool, Exception | None]: + if bucket_id not in self._bucket_exists_cache: + try: + self._api.bucket_info(bucket_id) + except BucketNotFoundError as e: + self._bucket_exists_cache[bucket_id] = False, e + else: + self._bucket_exists_cache[bucket_id] = True, None + return self._bucket_exists_cache[bucket_id] + + def resolve_path( + self, path: str, revision: str | None = None + ) -> HfFileSystemResolvedRepositoryPath | HfFileSystemResolvedBucketPath: + """ + Resolve a Hugging Face file system path into its components. + + Args: + path (`str`): + Path to resolve. + revision (`str`, *optional*): + The revision of the repo to resolve. Defaults to the revision specified in the path. + + Returns: + [`HfFileSystemResolvedPath`]: Resolved path information containing `repo_type`, `repo_id`, `revision` and `path_in_repo`. + + Raises: + `ValueError`: + If path contains conflicting revision information. + `NotImplementedError`: + If trying to list repositories. + """ + + def _align_revision_in_path_with_revision(revision_in_path: str | None, revision: str | None) -> str | None: + if revision is not None: + if revision_in_path is not None and revision_in_path != revision: + raise ValueError( + f'Revision specified in path ("{revision_in_path}") and in `revision` argument ("{revision}")' + " are not the same." + ) + else: + revision = revision_in_path + return revision + + path = self._strip_protocol(path) + if not path: + # can't list repositories at root + raise NotImplementedError("Access to buckets and repositories lists is not implemented.") + elif path.split("/")[0] == "buckets": + bucket_id = "/".join(path.split("/")[1:3]) + path = "/".join(path.split("/")[3:]) + bucket_exists, err = self._bucket_exists(bucket_id) + if not bucket_exists: + _raise_file_not_found(path, err) + return HfFileSystemResolvedBucketPath(bucket_id=bucket_id, path=path) + elif path.split("/")[0] + "/" in constants.REPO_TYPES_URL_PREFIXES.values(): + if "/" not in path: + # can't list repositories at the repository type level + raise NotImplementedError("Access to repositories lists is not implemented.") + repo_type, path = path.split("/", 1) + repo_type = constants.REPO_TYPES_MAPPING[repo_type] + else: + repo_type = constants.REPO_TYPE_MODEL + if path.count("/") > 0: + if "@" in "/".join(path.split("/")[:2]): + repo_id, revision_in_path = path.split("@", 1) + if "/" in revision_in_path: + match = SPECIAL_REFS_REVISION_REGEX.search(revision_in_path) + if match is not None and revision in (None, match.group()): + # Handle `refs/convert/parquet` and PR revisions separately + path_in_repo = SPECIAL_REFS_REVISION_REGEX.sub("", revision_in_path).lstrip("/") + revision_in_path = match.group() + else: + revision_in_path, path_in_repo = revision_in_path.split("/", 1) + else: + path_in_repo = "" + revision = _align_revision_in_path_with_revision(unquote(revision_in_path), revision) + repo_and_revision_exist, err = self._repo_and_revision_exist(repo_type, repo_id, revision) + if not repo_and_revision_exist: + _raise_file_not_found(path, err) + else: + revision_in_path = None + repo_id_with_namespace = "/".join(path.split("/")[:2]) + path_in_repo_with_namespace = "/".join(path.split("/")[2:]) + repo_id_without_namespace = path.split("/")[0] + path_in_repo_without_namespace = "/".join(path.split("/")[1:]) + repo_id = repo_id_with_namespace + path_in_repo = path_in_repo_with_namespace + repo_and_revision_exist, err = self._repo_and_revision_exist(repo_type, repo_id, revision) + if not repo_and_revision_exist: + if isinstance(err, (RepositoryNotFoundError, HFValidationError)): + repo_id = repo_id_without_namespace + path_in_repo = path_in_repo_without_namespace + repo_and_revision_exist, _ = self._repo_and_revision_exist(repo_type, repo_id, revision) + if not repo_and_revision_exist: + _raise_file_not_found(path, err) + else: + _raise_file_not_found(path, err) + else: + repo_id = path + path_in_repo = "" + if "@" in path: + repo_id, revision_in_path = path.split("@", 1) + revision = _align_revision_in_path_with_revision(unquote(revision_in_path), revision) + else: + revision_in_path = None + repo_and_revision_exist, _ = self._repo_and_revision_exist(repo_type, repo_id, revision) + if not repo_and_revision_exist: + raise NotImplementedError("Access to repositories lists is not implemented.") + + revision = revision if revision is not None else constants.DEFAULT_REVISION + return HfFileSystemResolvedRepositoryPath( + repo_type, repo_id, revision, path_in_repo, _raw_revision=revision_in_path + ) + + def invalidate_cache(self, path: str | None = None) -> None: + """ + Clear the cache for a given path. + + For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.invalidate_cache). + + Args: + path (`str`, *optional*): + Path to clear from cache. If not provided, clear the entire cache. + + """ + if not path: + self.dircache.clear() + self._repo_and_revision_exists_cache.clear() + else: + resolved_path = self.resolve_path(path) + path = resolved_path.unresolve() + while path: + self.dircache.pop(path, None) + path = self._parent(path) + + # Only clear repo cache if path is to repo root + if not resolved_path.path: + if isinstance(resolved_path, HfFileSystemResolvedRepositoryPath): + self._repo_and_revision_exists_cache.pop( + (resolved_path.repo_type, resolved_path.repo_id, None), None + ) + self._repo_and_revision_exists_cache.pop( + (resolved_path.repo_type, resolved_path.repo_id, resolved_path.revision), None + ) + else: + self._bucket_exists_cache.pop(resolved_path.bucket_id, None) + + def _open( # type: ignore + self, + path: str, + mode: str = "rb", + block_size: int | None = None, + revision: str | None = None, + **kwargs, + ) -> Union["HfFileSystemFile", "HfFileSystemStreamFile"]: + block_size = block_size if block_size is not None else self.block_size + if block_size is not None: + kwargs["block_size"] = block_size + if "a" in mode: + raise NotImplementedError("Appending to remote files is not yet supported.") + if block_size == 0: + return HfFileSystemStreamFile(self, path, mode=mode, revision=revision, **kwargs) + else: + return HfFileSystemFile(self, path, mode=mode, revision=revision, **kwargs) + + def _rm(self, path: str, revision: str | None = None, **kwargs) -> None: + resolved_path = self.resolve_path(path, revision=revision) + if isinstance(resolved_path, HfFileSystemResolvedBucketPath): + self._api.batch_bucket_files(resolved_path.bucket_id, delete=[resolved_path.path]) + else: + self._api.delete_file( + path_in_repo=resolved_path.path_in_repo, + repo_id=resolved_path.repo_id, + token=self.token, + repo_type=resolved_path.repo_type, + revision=resolved_path.revision, + commit_message=kwargs.get("commit_message"), + commit_description=kwargs.get("commit_description"), + ) + self.invalidate_cache(path=resolved_path.unresolve()) + + def rm( + self, + path: str, + recursive: bool = False, + maxdepth: int | None = None, + revision: str | None = None, + **kwargs, + ) -> None: + """ + Delete files from a repository. + + For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.rm). + + > [!WARNING] + > Note: When possible, use `HfApi.delete_file()` for better performance. + + Args: + path (`str`): + Path to delete. + recursive (`bool`, *optional*): + If True, delete directory and all its contents. Defaults to False. + maxdepth (`int`, *optional*): + Maximum number of subdirectories to visit when deleting recursively. + revision (`str`, *optional*): + The git revision to delete from. + + """ + resolved_path = self.resolve_path(path, revision=revision) + paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth, revision=revision) + if isinstance(resolved_path, HfFileSystemResolvedBucketPath): + delete = [self.resolve_path(path).path for path in paths if not self.isdir(path)] + self._api.batch_bucket_files(resolved_path.bucket_id, delete=delete) + else: + paths_in_repo = [self.resolve_path(path).path for path in paths if not self.isdir(path)] + operations = [CommitOperationDelete(path_in_repo=path_in_repo) for path_in_repo in paths_in_repo] + commit_message = f"Delete {path} " + commit_message += "recursively " if recursive else "" + commit_message += f"up to depth {maxdepth} " if maxdepth is not None else "" + # TODO: use `commit_description` to list all the deleted paths? + self._api.create_commit( + repo_id=resolved_path.repo_id, + repo_type=resolved_path.repo_type, + token=self.token, + operations=operations, + revision=resolved_path.revision, + commit_message=kwargs.get("commit_message", commit_message), + commit_description=kwargs.get("commit_description"), + ) + self.invalidate_cache(path=resolved_path.unresolve()) + + def ls( + self, path: str, detail: bool = True, refresh: bool = False, revision: str | None = None, **kwargs + ) -> list[str | dict[str, Any]]: + """ + List the contents of a directory. + + For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.ls). + + > [!WARNING] + > Note: When possible, use `HfApi.list_repo_tree()` for better performance. + + Args: + path (`str`): + Path to the directory. + detail (`bool`, *optional*): + If True, returns a list of dictionaries containing file information. If False, + returns a list of file paths. Defaults to True. + refresh (`bool`, *optional*): + If True, bypass the cache and fetch the latest data. Defaults to False. + revision (`str`, *optional*): + The git revision to list from. + + Returns: + `list[Union[str, dict[str, Any]]]`: List of file paths (if detail=False) or list of file information + dictionaries (if detail=True). + """ + resolved_path = self.resolve_path(path, revision=revision) + path = resolved_path.unresolve() + try: + out = self._ls_tree(path, refresh=refresh, revision=revision, **kwargs) + except EntryNotFoundError: + # Path could be a file + if not resolved_path.path: + _raise_file_not_found(path, None) + try: + out = self._ls_tree(self._parent(path), refresh=refresh, revision=revision, **kwargs) + except EntryNotFoundError: + out = [] + out = [o for o in out if o["name"] == path] + if len(out) == 0: + _raise_file_not_found(path, None) + return out if detail else [o["name"] for o in out] + + def _ls_tree( + self, + path: str, + recursive: bool = False, + refresh: bool = False, + revision: str | None = None, + expand_info: bool | None = None, + maxdepth: int | None = None, + ): + expand_info = ( + expand_info if expand_info is not None else (self.expand_info if self.expand_info is not None else False) + ) + resolved_path = self.resolve_path(path, revision=revision) + path = resolved_path.unresolve() + root_path = resolved_path.root + maxdepth = maxdepth if recursive else 1 + + out = [] + if path in self.dircache and not refresh: + cached_path_infos = self.dircache[path] + out.extend(cached_path_infos) + dirs_not_in_dircache = [] + if recursive: + # Use BFS to traverse the cache and build the "recursive "output + # (The Hub uses a so-called "tree first" strategy for the tree endpoint but we sort the output to follow the spec so the result is (eventually) the same) + depth = 2 + dirs_to_visit = deque( + [(depth, path_info) for path_info in cached_path_infos if path_info["type"] == "directory"] + ) + while dirs_to_visit: + depth, dir_info = dirs_to_visit.popleft() + if maxdepth is None or depth <= maxdepth: + if dir_info["name"] not in self.dircache: + dirs_not_in_dircache.append(dir_info["name"]) + else: + cached_path_infos = self.dircache[dir_info["name"]] + out.extend(cached_path_infos) + dirs_to_visit.extend( + [ + (depth + 1, path_info) + for path_info in cached_path_infos + if path_info["type"] == "directory" + ] + ) + + dirs_not_expanded = [] + if expand_info and isinstance(resolved_path, HfFileSystemResolvedRepositoryPath): + # Check if there are directories in repos with non-expanded entries + dirs_not_expanded = [self._parent(o["name"]) for o in out if o["last_commit"] is None] + + if (recursive and dirs_not_in_dircache) or (expand_info and dirs_not_expanded): + # If the dircache is incomplete, find the common path of the missing and non-expanded entries + # and extend the output with the result of `_ls_tree(common_path, recursive=True)` + common_prefix = os.path.commonprefix(dirs_not_in_dircache + dirs_not_expanded) + # Get the parent directory if the common prefix itself is not a directory + common_path = ( + common_prefix.rstrip("/") + if common_prefix.endswith("/") + or common_prefix == root_path + or common_prefix in chain(dirs_not_in_dircache, dirs_not_expanded) + else self._parent(common_prefix) + ) + if maxdepth is not None: + common_path_depth = common_path[len(path) :].count("/") + maxdepth -= common_path_depth + out = [o for o in out if not o["name"].startswith(common_path + "/")] + for cached_path in list(self.dircache): + if cached_path.startswith(common_path + "/"): + self.dircache.pop(cached_path, None) + self.dircache.pop(common_path, None) + out.extend( + self._ls_tree( + common_path, + recursive=recursive, + refresh=True, + revision=revision, + expand_info=expand_info, + maxdepth=maxdepth, + ) + ) + else: + tree: Iterable[RepoFile | RepoFolder | BucketFile | BucketFolder] + if isinstance(resolved_path, HfFileSystemResolvedBucketPath): + tree = self._list_bucket_tree_with_folders( + resolved_path.bucket_id, + prefix=resolved_path.path, + recursive=recursive, + ) + else: + tree = self._api.list_repo_tree( + resolved_path.repo_id, + resolved_path.path, + recursive=recursive, + expand=expand_info, + revision=resolved_path.revision, + repo_type=resolved_path.repo_type, + ) + for path_info in tree: + cache_path = root_path + "/" + path_info.path + if isinstance(path_info, RepoFile): + cache_path_info = { + "name": cache_path, + "size": path_info.size, + "type": "file", + "blob_id": path_info.blob_id, + "lfs": path_info.lfs, + "xet_hash": path_info.xet_hash, + "last_commit": path_info.last_commit, + "security": path_info.security, + } + elif isinstance(path_info, BucketFile): + cache_path_info = { + "name": cache_path, + "size": path_info.size, + "type": "file", + "xet_hash": path_info.xet_hash, + "mtime": path_info.mtime, + "uploaded_at": path_info.uploaded_at, + } + elif isinstance(path_info, RepoFolder): + cache_path_info = { + "name": cache_path, + "size": 0, + "type": "directory", + "tree_id": path_info.tree_id, + "last_commit": path_info.last_commit, + } + else: + cache_path_info = { + "name": cache_path, + "size": 0, + "type": "directory", + "uploaded_at": path_info.uploaded_at, + } + parent_path = self._parent(cache_path_info["name"]) + self.dircache.setdefault(parent_path, []).append(cache_path_info) + depth = cache_path[len(path) :].count("/") + if maxdepth is None or depth <= maxdepth: + out.append(cache_path_info) + return out + + def _list_bucket_tree_with_folders( + self, bucket_id: str, prefix: str, recursive: bool + ) -> Iterable[BucketFile | BucketFolder]: + """Same as `HfApi.list_bucket_tree` but always includes folders""" + bucket_files = self._api.list_bucket_tree(bucket_id, prefix, recursive=recursive) + bucket_folders: dict[str, BucketFolder] = {} + min_depth = 1 + prefix.count("/") if prefix else 0 + out: list[BucketFile | BucketFolder] = [] + + for bucket_entry in bucket_files: + out.append(bucket_entry) + + # If recursive=False, both files and folders are returned by the server => nothing to do + if not recursive: + continue + + # Otherwise, let's rebuild BucketFolders manually + for parent_bucket_folder_str in list(PurePosixPath(bucket_entry.path).parents)[: -min_depth - 1]: + parent_bucket_folder = BucketFolder( + type="directory", path=str(parent_bucket_folder_str), uploaded_at=bucket_entry.uploaded_at + ) + + # If folder not visited yet, add it + if parent_bucket_folder.path not in bucket_folders: + out.append(parent_bucket_folder) + bucket_folders[parent_bucket_folder.path] = parent_bucket_folder + continue + + # Otherwise, get back BucketFolder object and update its 'uploaded_at' + if parent_bucket_folder.uploaded_at is not None: + bucket_folder = bucket_folders[parent_bucket_folder.path] + if bucket_folder.uploaded_at is None or ( + bucket_folder.uploaded_at < parent_bucket_folder.uploaded_at + ): + bucket_folder.uploaded_at = parent_bucket_folder.uploaded_at + + if not out: + raise EntryNotFoundError(f"File not found in bucket '{bucket_id}': '{prefix}'") + return out + + def walk(self, path: str, *args, **kwargs) -> Iterator[tuple[str, list[str], list[str]]]: + """ + Return all files below the given path. + + For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.walk). + + Args: + path (`str`): + Root path to list files from. + + Returns: + `Iterator[tuple[str, list[str], list[str]]]`: An iterator of (path, list of directory names, list of file names) tuples. + """ + path = self.resolve_path(path, revision=kwargs.get("revision")).unresolve() + yield from super().walk(path, *args, **kwargs) + + def glob(self, path: str, maxdepth: int | None = None, **kwargs) -> list[str]: + """ + Find files by glob-matching. + + For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.glob). + + Args: + path (`str`): + Path pattern to match. + + Returns: + `list[str]`: List of paths matching the pattern. + """ + path = self.resolve_path(path, revision=kwargs.get("revision")).unresolve() + return super().glob(path, maxdepth=maxdepth, **kwargs) + + def find( + self, + path: str, + maxdepth: int | None = None, + withdirs: bool = False, + detail: bool = False, + refresh: bool = False, + revision: str | None = None, + **kwargs, + ) -> list[str] | dict[str, dict[str, Any]]: + """ + List all files below path. + + For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.find). + + Args: + path (`str`): + Root path to list files from. + maxdepth (`int`, *optional*): + Maximum depth to descend into subdirectories. + withdirs (`bool`, *optional*): + Include directory paths in the output. Defaults to False. + detail (`bool`, *optional*): + If True, returns a dict mapping paths to file information. Defaults to False. + refresh (`bool`, *optional*): + If True, bypass the cache and fetch the latest data. Defaults to False. + revision (`str`, *optional*): + The git revision to list from. + + Returns: + `Union[list[str], dict[str, dict[str, Any]]]`: List of paths or dict of file information. + """ + if maxdepth is not None and maxdepth < 1: + raise ValueError("maxdepth must be at least 1") + resolved_path = self.resolve_path(path, revision=revision) + path = resolved_path.unresolve() + try: + out = self._ls_tree(path, recursive=True, refresh=refresh, maxdepth=maxdepth, **kwargs) + except EntryNotFoundError: + # Path could be a file + try: + if self.info(path, revision=revision, **kwargs)["type"] == "file": + out = {path: {}} + else: + out = {} + except FileNotFoundError: + out = {} + else: + if not withdirs: + out = [o for o in out if o["type"] != "directory"] + else: + # If `withdirs=True`, include the directory itself to be consistent with the spec + path_info = self.info(path, **kwargs) + out = [path_info] + out if path_info["type"] == "directory" else out + out = {o["name"]: o for o in out} + names = sorted(out) + if not detail: + return names + else: + return {name: out[name] for name in names} + + def cp_file(self, path1: str, path2: str, revision: str | None = None, **kwargs) -> None: + """ + Copy a file within or between repositories. + + > [!WARNING] + > Note: When possible, use `HfApi.upload_file()` for better performance. + + Args: + path1 (`str`): + Source path to copy from. + path2 (`str`): + Destination path to copy to. + revision (`str`, *optional*): + The git revision to copy from. + + """ + resolved_path1 = self.resolve_path(path1, revision=revision) + resolved_path2 = self.resolve_path(path2, revision=revision) + if isinstance(resolved_path1, HfFileSystemResolvedBucketPath) or isinstance( + resolved_path2, HfFileSystemResolvedBucketPath + ): + raise NotImplementedError("Copy from/to buckets is not available yet") + + same_repo = ( + resolved_path1.repo_type == resolved_path2.repo_type and resolved_path1.repo_id == resolved_path2.repo_id + ) + + if same_repo: + commit_message = f"Copy {path1} to {path2}" + self._api.create_commit( + repo_id=resolved_path1.repo_id, + repo_type=resolved_path1.repo_type, + revision=resolved_path2.revision, + commit_message=kwargs.get("commit_message", commit_message), + commit_description=kwargs.get("commit_description", ""), + operations=[ + CommitOperationCopy( + src_path_in_repo=resolved_path1.path_in_repo, + path_in_repo=resolved_path2.path_in_repo, + src_revision=resolved_path1.revision, + ) + ], + ) + else: + with self.open(path1, "rb", revision=resolved_path1.revision) as f: + content = f.read() + commit_message = f"Copy {path1} to {path2}" + self._api.upload_file( + path_or_fileobj=content, + path_in_repo=resolved_path2.path_in_repo, + repo_id=resolved_path2.repo_id, + token=self.token, + repo_type=resolved_path2.repo_type, + revision=resolved_path2.revision, + commit_message=kwargs.get("commit_message", commit_message), + commit_description=kwargs.get("commit_description"), + ) + self.invalidate_cache(path=resolved_path1.unresolve()) + self.invalidate_cache(path=resolved_path2.unresolve()) + + def modified(self, path: str, **kwargs) -> datetime: + """ + Get the last modified time of a file. + + For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.modified). + + Args: + path (`str`): + Path to the file. + + Returns: + `datetime`: Last modified time of the file. + """ + info = self.info(path, **{**kwargs, "expand_info": True}) # type: ignore + if "last_commit" in info: + if info["last_commit"] is None: + raise NotImplementedError(f"'modified' is not implemented for repository paths like '{path}'") + return info["last_commit"].date + elif "mtime" in info and info["mtime"]: + return info["mtime"] + elif "uploaded_at" in info and info["uploaded_at"]: + return info["uploaded_at"] + else: + raise NotImplementedError(f"Cannot determined 'modified' for path '{path}' (info: {info})") + + def info(self, path: str, refresh: bool = False, revision: str | None = None, **kwargs) -> dict[str, Any]: + """ + Get information about a file or directory. + + For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.info). + + > [!WARNING] + > Note: When possible, use `HfApi.get_paths_info()` or `HfApi.repo_info()` for better performance + > (or `HfApi.get_bucket_paths_info()` or `HfApi.bucket_info()` for buckets) + + Args: + path (`str`): + Path to get info for. + refresh (`bool`, *optional*): + If True, bypass the cache and fetch the latest data. Defaults to False. + revision (`str`, *optional*): + The git revision to get info from. + + Returns: + `dict[str, Any]`: Dictionary containing file information (type, size, commit info, etc.). + + """ + resolved_path = self.resolve_path(path, revision=revision) + path = resolved_path.unresolve() + expand_info = kwargs.get( + "expand_info", self.expand_info if self.expand_info is not None else False + ) # don't expose it as a parameter in the public API to follow the spec + out: dict[str, Any] | None + if not resolved_path.path: + # Path is the root directory + out = { + "name": path, + "size": 0, + "type": "directory", + } + if isinstance(resolved_path, HfFileSystemResolvedRepositoryPath): + out["last_commit"] = None + if isinstance(resolved_path, HfFileSystemResolvedRepositoryPath) and expand_info: + last_commit = self._api.list_repo_commits( + resolved_path.repo_id, repo_type=resolved_path.repo_type, revision=resolved_path.revision + )[-1] + out = { + **out, + "tree_id": None, # TODO: tree_id of the root directory? + "last_commit": LastCommitInfo( + oid=last_commit.commit_id, title=last_commit.title, date=last_commit.created_at + ), + } + elif isinstance(resolved_path, HfFileSystemResolvedBucketPath): + parent_path = self._parent(path) + # Fill the cache with cheap call + self.ls(parent_path, refresh=refresh) + out1 = [o for o in self.dircache[parent_path] if o["name"] == path] + if not out1: + _raise_file_not_found(path, None) + out = out1[0] + else: + out = None + parent_path = self._parent(path) + if not expand_info and parent_path not in self.dircache: + # Fill the cache with cheap call + self.ls(parent_path) + if parent_path in self.dircache: + # Check if the path is in the cache + out1 = [o for o in self.dircache[parent_path] if o["name"] == path] + if not out1: + _raise_file_not_found(path, None) + out = out1[0] + if refresh or out is None or (expand_info and out and out["last_commit"] is None): + paths_info = self._api.get_paths_info( + resolved_path.repo_id, + resolved_path.path_in_repo, + expand=expand_info, + revision=resolved_path.revision, + repo_type=resolved_path.repo_type, + ) + if not paths_info: + _raise_file_not_found(path, None) + path_info = paths_info[0] + root_path = HfFileSystemResolvedRepositoryPath( + resolved_path.repo_type, + resolved_path.repo_id, + resolved_path.revision, + path_in_repo="", + _raw_revision=resolved_path._raw_revision, + ).unresolve() + if isinstance(path_info, RepoFile): + out = { + "name": root_path + "/" + path_info.path, + "size": path_info.size, + "type": "file", + "blob_id": path_info.blob_id, + "lfs": path_info.lfs, + "xet_hash": path_info.xet_hash, + "last_commit": path_info.last_commit, + "security": path_info.security, + } + else: + out = { + "name": root_path + "/" + path_info.path, + "size": 0, + "type": "directory", + "tree_id": path_info.tree_id, + "last_commit": path_info.last_commit, + } + if not expand_info: + out = {k: out[k] for k in ["name", "size", "type"]} + assert out is not None + return out + + def exists(self, path, **kwargs): + """ + Check if a file exists. + + For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.exists). + + > [!WARNING] + > Note: When possible, use `HfApi.file_exists()` for better performance. + + Args: + path (`str`): + Path to check. + + Returns: + `bool`: True if file exists, False otherwise. + """ + try: + if kwargs.get("refresh", False): + self.invalidate_cache(path) + + self.info(path, **kwargs) + return True + except OSError: + return False + + def isdir(self, path): + """ + Check if a path is a directory. + + For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isdir). + + Args: + path (`str`): + Path to check. + + Returns: + `bool`: True if path is a directory, False otherwise. + """ + try: + return self.info(path)["type"] == "directory" + except OSError: + return False + + def isfile(self, path): + """ + Check if a path is a file. + + For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isfile). + + Args: + path (`str`): + Path to check. + + Returns: + `bool`: True if path is a file, False otherwise. + """ + try: + return self.info(path)["type"] == "file" + except OSError: + return False + + def url(self, path: str) -> str: + """ + Get the HTTP URL of the given path. + + Args: + path (`str`): + Path to get URL for. + + Returns: + `str`: HTTP URL to access the file or directory on the Hub. + """ + resolved_path = self.resolve_path(path) + if isinstance(resolved_path, HfFileSystemResolvedBucketPath): + url = f"{self.endpoint}/buckets/{resolved_path.bucket_id}/resolve/{quote(resolved_path.path)}" + else: + url = hf_hub_url( + resolved_path.repo_id, + resolved_path.path_in_repo, + repo_type=resolved_path.repo_type, + revision=resolved_path.revision, + endpoint=self.endpoint, + ) + if self.isdir(path): + url = url.replace("/resolve/", "/tree/", 1) + return url + + def get_file(self, rpath, lpath, callback=_DEFAULT_CALLBACK, outfile=None, **kwargs) -> None: + """ + Copy single remote file to local. + + > [!WARNING] + > Note: When possible, use `HfApi.hf_hub_download()` or `HfApi.download_bucket_files` for better performance. + + Args: + rpath (`str`): + Remote path to download from. + lpath (`str`): + Local path to download to. + callback (`Callback`, *optional*): + Optional callback to track download progress. Defaults to no callback. + outfile (`IO`, *optional*): + Optional file-like object to write to. If provided, `lpath` is ignored. + + """ + revision = kwargs.get("revision") + unhandled_kwargs = set(kwargs.keys()) - {"revision"} + if not isinstance(callback, (NoOpCallback, TqdmCallback)) or len(unhandled_kwargs) > 0: + # for now, let's not handle custom callbacks + # and let's not handle custom kwargs + return super().get_file(rpath, lpath, callback=callback, outfile=outfile, **kwargs) + + # Taken from https://github.com/fsspec/filesystem_spec/blob/47b445ae4c284a82dd15e0287b1ffc410e8fc470/fsspec/spec.py#L883 + if isfilelike(lpath): + outfile = lpath + elif self.isdir(rpath): + os.makedirs(lpath, exist_ok=True) + return None + + if isinstance(lpath, (str, Path)): # otherwise, let's assume it's a file-like object + os.makedirs(os.path.dirname(lpath), exist_ok=True) + + # Open file if not already open + close_file = False + if outfile is None: + outfile = open(lpath, "wb") + close_file = True + initial_pos = outfile.tell() + + # Custom implementation of `get_file` to use `http_get`. + resolve_remote_path = self.resolve_path(rpath, revision=revision) + expected_size = self.info(rpath, revision=revision)["size"] + callback.set_size(expected_size) + try: + http_get( + url=self.url(resolve_remote_path.unresolve()), + temp_file=outfile, # type: ignore + displayed_filename=rpath, + expected_size=expected_size, + resume_size=0, + headers=self._api._build_hf_headers(), + _tqdm_bar=callback.tqdm if isinstance(callback, TqdmCallback) else None, + ) + outfile.seek(initial_pos) + finally: + # Close file only if we opened it ourselves + if close_file: + outfile.close() + + @property + def transaction(self): + """A context within which files are committed together upon exit + + Requires the file class to implement `.commit()` and `.discard()` + for the normal and exception cases. + """ + # Taken from https://github.com/fsspec/filesystem_spec/blob/3fbb6fee33b46cccb015607630843dea049d3243/fsspec/spec.py#L231 + # See https://github.com/huggingface/huggingface_hub/issues/1733 + raise NotImplementedError("Transactional commits are not supported.") + + def start_transaction(self): + """Begin write transaction for deferring files, non-context version""" + # Taken from https://github.com/fsspec/filesystem_spec/blob/3fbb6fee33b46cccb015607630843dea049d3243/fsspec/spec.py#L241 + # See https://github.com/huggingface/huggingface_hub/issues/1733 + raise NotImplementedError("Transactional commits are not supported.") + + def __reduce__(self): + # re-populate the instance cache at HfFileSystem._cache and re-populate the state of every instance + return make_instance, ( + type(self), + self.storage_args, + self.storage_options, + self._get_instance_state(), + ) + + def _get_instance_state(self): + return { + "dircache": deepcopy(self.dircache), + "_repo_and_revision_exists_cache": deepcopy(self._repo_and_revision_exists_cache), + "_bucket_exists_cache": deepcopy(self._bucket_exists_cache), + } + + +class HfFileSystemFile(fsspec.spec.AbstractBufferedFile): + def __init__(self, fs: HfFileSystem, path: str, revision: str | None = None, **kwargs): + try: + self.resolved_path = fs.resolve_path(path, revision=revision) + except FileNotFoundError as e: + if "w" in kwargs.get("mode", ""): + raise FileNotFoundError( + f"{e}.\nMake sure the repository and revision exist before writing data." + ) from e + raise + super().__init__(fs, self.resolved_path.unresolve(), **kwargs) + self.fs: HfFileSystem + + def __del__(self): + if not hasattr(self, "resolved_path"): + # Means that the constructor failed. Nothing to do. + return + return super().__del__() + + def _fetch_range(self, start: int, end: int) -> bytes: + headers = { + "range": f"bytes={start}-{end - 1}", + **self.fs._api._build_hf_headers(), + } + url = self.url() + r = http_backoff("GET", url, headers=headers, timeout=constants.HF_HUB_DOWNLOAD_TIMEOUT) + hf_raise_for_status(r) + return r.content + + def _initiate_upload(self) -> None: + self.temp_file = tempfile.NamedTemporaryFile(prefix="hffs-", delete=False) + + def _upload_chunk(self, final: bool = False) -> None: + self.buffer.seek(0) + block = self.buffer.read() + self.temp_file.write(block) + if final: + self.temp_file.close() + if isinstance(self.resolved_path, HfFileSystemResolvedBucketPath): + self.fs._api.batch_bucket_files( + self.resolved_path.bucket_id, add=[(self.temp_file.name, self.resolved_path.path)] + ) + else: + self.fs._api.upload_file( + path_or_fileobj=self.temp_file.name, + path_in_repo=self.resolved_path.path_in_repo, + repo_id=self.resolved_path.repo_id, + token=self.fs.token, + repo_type=self.resolved_path.repo_type, + revision=self.resolved_path.revision, + commit_message=self.kwargs.get("commit_message"), + commit_description=self.kwargs.get("commit_description"), + ) + os.remove(self.temp_file.name) + self.fs.invalidate_cache( + path=self.resolved_path.unresolve(), + ) + + def read(self, length=-1): + """Read remote file. + + If `length` is not provided or is -1, the entire file is downloaded and read. On POSIX systems the file is + loaded in memory directly. Otherwise, the file is downloaded to a temporary file and read from there. + """ + if self.mode == "rb" and (length is None or length == -1) and self.loc == 0: + with self.fs.open(self.path, "rb", block_size=0) as f: # block_size=0 enables fast streaming + out = f.read() + self.loc += len(out) + return out + return super().read(length) + + def url(self) -> str: + return self.fs.url(self.path) + + +class HfFileSystemStreamFile(fsspec.spec.AbstractBufferedFile): + def __init__( + self, + fs: HfFileSystem, + path: str, + mode: str = "rb", + revision: str | None = None, + block_size: int = 0, + cache_type: str = "none", + **kwargs, + ): + if block_size != 0: + raise ValueError(f"HfFileSystemStreamFile only supports block_size=0 but got {block_size}") + if cache_type != "none": + raise ValueError(f"HfFileSystemStreamFile only supports cache_type='none' but got {cache_type}") + if "w" in mode: + raise ValueError(f"HfFileSystemStreamFile only supports reading but got mode='{mode}'") + try: + self.resolved_path = fs.resolve_path(path, revision=revision) + except FileNotFoundError as e: + if "w" in kwargs.get("mode", ""): + raise FileNotFoundError( + f"{e}.\nMake sure the repository and revision exist before writing data." + ) from e + # avoid an unnecessary .info() call to instantiate .details + self.details = {"name": self.resolved_path.unresolve(), "size": None} + super().__init__( + fs, self.resolved_path.unresolve(), mode=mode, block_size=block_size, cache_type=cache_type, **kwargs + ) + self.response: httpx.Response | None = None + self.fs: HfFileSystem + self._exit_stack = ExitStack() + # streaming state + self._stream_iterator: Iterator[bytes] | None = None + self._stream_buffer = bytearray() + + def seek(self, loc: int, whence: int = 0): + if loc == 0 and whence == 1: + return + if loc == self.loc and whence == 0: + return + raise ValueError("Cannot seek streaming HF file") + + def read(self, length: int = -1): + """Read the remote file. + + If the file is already open, we reuse the connection. + Otherwise, open a new connection and read from it. + + If reading the stream fails, we retry with a new connection. + """ + if self.response is None: + self._open_connection() + + retried_once = False + while True: + try: + if self.response is None or self._stream_iterator is None: + return b"" # Already read the entire file + out = self._read_from_stream(self._stream_iterator, length) + self.loc += len(out) + return out + except Exception: + if self.response is not None: + self.response.close() + if retried_once: # Already retried once, give up + raise + # First failure, retry with range header + self._open_connection() + retried_once = True + + def _read_from_stream(self, iterator: Iterator[bytes], length: int = -1) -> bytes: + """Read up to `length` bytes from stream buffer and stream. + + If length < 0, read until EOF. + + If EOF is reached before length, fewer bytes may be returned. + """ + if length == 0: + return b"" + + if length < 0: + buf = bytearray(self._stream_buffer) + self._stream_buffer.clear() + for chunk in iterator: + buf.extend(chunk) + return bytes(buf) + + if length <= len(self._stream_buffer): + result = bytes(self._stream_buffer[:length]) + del self._stream_buffer[:length] + return result + + buf = bytearray(self._stream_buffer) + self._stream_buffer.clear() + for chunk in iterator: + need = length - len(buf) + if need > len(chunk): + buf.extend(chunk) + else: + buf.extend(chunk[:need]) + self._stream_buffer.extend(chunk[need:]) + break + return bytes(buf) + + def url(self) -> str: + return self.fs.url(self.path) + + def __del__(self): + if not hasattr(self, "resolved_path"): + # Means that the constructor failed. Nothing to do. + return + self._exit_stack.close() + return super().__del__() + + def __reduce__(self): + return reopen, (self.fs, self.path, self.mode, self.blocksize, self.cache.name) + + def _open_connection(self): + """Open a connection to the remote file.""" + # reset streaming state + self._stream_buffer.clear() + self._stream_iterator = None + + url = self.url() + headers = self.fs._api._build_hf_headers() + if self.loc > 0: + headers["Range"] = f"bytes={self.loc}-" + self.response = self._exit_stack.enter_context( + http_stream_backoff( + "GET", + url, + headers=headers, + timeout=constants.HF_HUB_DOWNLOAD_TIMEOUT, + ) + ) + + try: + hf_raise_for_status(self.response) + except HfHubHTTPError as e: + if e.response.status_code == 416: + # Range not satisfiable => means that we have already read the entire file + self.response = None + return + raise + + self._stream_iterator = self.response.iter_bytes() + + +def safe_revision(revision: str) -> str: + return revision if SPECIAL_REFS_REVISION_REGEX.match(revision) else safe_quote(revision) + + +def safe_quote(s: str) -> str: + return quote(s, safe="") + + +def _raise_file_not_found(path: str, err: Exception | None) -> NoReturn: + msg = path + if isinstance(err, RepositoryNotFoundError): + msg = f"{path} (repository not found)" + elif isinstance(err, RevisionNotFoundError): + msg = f"{path} (revision not found)" + elif isinstance(err, HFValidationError): + msg = f"{path} (invalid repository id)" + raise FileNotFoundError(msg) from err + + +def reopen(fs: HfFileSystem, path: str, mode: str, block_size: int, cache_type: str): + return fs.open(path, mode=mode, block_size=block_size, cache_type=cache_type) + + +def make_instance(cls, args, kwargs, instance_state): + fs = cls(*args, **kwargs) + for attr, state_value in instance_state.items(): + setattr(fs, attr, state_value) + return fs + + +hffs = HfFileSystem() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/hub_mixin.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/hub_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..937cfe1851538aa8389222885015212c80514871 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/hub_mixin.py @@ -0,0 +1,834 @@ +import inspect +import json +import os +from collections.abc import Callable +from dataclasses import Field, asdict, dataclass, is_dataclass +from pathlib import Path +from typing import Any, ClassVar, Protocol, TypeVar + +import packaging.version + +from . import constants +from .errors import EntryNotFoundError, HfHubHTTPError +from .file_download import hf_hub_download +from .hf_api import HfApi +from .repocard import ModelCard, ModelCardData +from .utils import ( + SoftTemporaryDirectory, + is_jsonable, + is_safetensors_available, + is_simple_optional_type, + is_torch_available, + logging, + unwrap_simple_optional_type, + validate_hf_hub_args, +) + + +if is_torch_available(): + import torch # type: ignore + +if is_safetensors_available(): + import safetensors + from safetensors.torch import load_model as load_model_as_safetensor + from safetensors.torch import save_model as save_model_as_safetensor + + +logger = logging.get_logger(__name__) + + +# Type alias for dataclass instances, copied from https://github.com/python/typeshed/blob/9f28171658b9ca6c32a7cb93fbb99fc92b17858b/stdlib/_typeshed/__init__.pyi#L349 +class DataclassInstance(Protocol): + __dataclass_fields__: ClassVar[dict[str, Field]] + + +# Generic variable that is either ModelHubMixin or a subclass thereof +T = TypeVar("T", bound="ModelHubMixin") +# Generic variable to represent an args type +ARGS_T = TypeVar("ARGS_T") +ENCODER_T = Callable[[ARGS_T], Any] +DECODER_T = Callable[[Any], ARGS_T] +CODER_T = tuple[ENCODER_T, DECODER_T] + + +DEFAULT_MODEL_CARD = """ +--- +# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1 +# Doc / guide: https://huggingface.co/docs/hub/model-cards +{{ card_data }} +--- + +This model has been pushed to the Hub using the [PytorchModelHubMixin](https://huggingface.co/docs/huggingface_hub/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin) integration: +- Code: {{ repo_url | default("[More Information Needed]", true) }} +- Paper: {{ paper_url | default("[More Information Needed]", true) }} +- Docs: {{ docs_url | default("[More Information Needed]", true) }} +""" + + +@dataclass +class MixinInfo: + model_card_template: str + model_card_data: ModelCardData + docs_url: str | None = None + paper_url: str | None = None + repo_url: str | None = None + + +class ModelHubMixin: + """ + A generic mixin to integrate ANY machine learning framework with the Hub. + + To integrate your framework, your model class must inherit from this class. Custom logic for saving/loading models + have to be overwritten in [`_from_pretrained`] and [`_save_pretrained`]. [`PyTorchModelHubMixin`] is a good example + of mixin integration with the Hub. Check out our [integration guide](../guides/integrations) for more instructions. + + When inheriting from [`ModelHubMixin`], you can define class-level attributes. These attributes are not passed to + `__init__` but to the class definition itself. This is useful to define metadata about the library integrating + [`ModelHubMixin`]. + + For more details on how to integrate the mixin with your library, checkout the [integration guide](../guides/integrations). + + Args: + repo_url (`str`, *optional*): + URL of the library repository. Used to generate model card. + paper_url (`str`, *optional*): + URL of the library paper. Used to generate model card. + docs_url (`str`, *optional*): + URL of the library documentation. Used to generate model card. + model_card_template (`str`, *optional*): + Template of the model card. Used to generate model card. Defaults to a generic template. + language (`str` or `list[str]`, *optional*): + Language supported by the library. Used to generate model card. + library_name (`str`, *optional*): + Name of the library integrating ModelHubMixin. Used to generate model card. + license (`str`, *optional*): + License of the library integrating ModelHubMixin. Used to generate model card. + E.g: "apache-2.0" + license_name (`str`, *optional*): + Name of the library integrating ModelHubMixin. Used to generate model card. + Only used if `license` is set to `other`. + E.g: "coqui-public-model-license". + license_link (`str`, *optional*): + URL to the license of the library integrating ModelHubMixin. Used to generate model card. + Only used if `license` is set to `other` and `license_name` is set. + E.g: "https://coqui.ai/cpml". + pipeline_tag (`str`, *optional*): + Tag of the pipeline. Used to generate model card. E.g. "text-classification". + tags (`list[str]`, *optional*): + Tags to be added to the model card. Used to generate model card. E.g. ["computer-vision"] + coders (`dict[Type, tuple[Callable, Callable]]`, *optional*): + Dictionary of custom types and their encoders/decoders. Used to encode/decode arguments that are not + jsonable by default. E.g. dataclasses, argparse.Namespace, OmegaConf, etc. + + Example: + + ```python + >>> from huggingface_hub import ModelHubMixin + + # Inherit from ModelHubMixin + >>> class MyCustomModel( + ... ModelHubMixin, + ... library_name="my-library", + ... tags=["computer-vision"], + ... repo_url="https://github.com/huggingface/my-cool-library", + ... paper_url="https://arxiv.org/abs/2304.12244", + ... docs_url="https://huggingface.co/docs/my-cool-library", + ... # ^ optional metadata to generate model card + ... ): + ... def __init__(self, size: int = 512, device: str = "cpu"): + ... # define how to initialize your model + ... super().__init__() + ... ... + ... + ... def _save_pretrained(self, save_directory: Path) -> None: + ... # define how to serialize your model + ... ... + ... + ... @classmethod + ... def from_pretrained( + ... cls: type[T], + ... pretrained_model_name_or_path: Union[str, Path], + ... *, + ... force_download: bool = False, + ... token: Optional[Union[str, bool]] = None, + ... cache_dir: Optional[Union[str, Path]] = None, + ... local_files_only: bool = False, + ... revision: Optional[str] = None, + ... **model_kwargs, + ... ) -> T: + ... # define how to deserialize your model + ... ... + + >>> model = MyCustomModel(size=256, device="gpu") + + # Save model weights to local directory + >>> model.save_pretrained("my-awesome-model") + + # Push model weights to the Hub + >>> model.push_to_hub("my-awesome-model") + + # Download and initialize weights from the Hub + >>> reloaded_model = MyCustomModel.from_pretrained("username/my-awesome-model") + >>> reloaded_model.size + 256 + + # Model card has been correctly populated + >>> from huggingface_hub import ModelCard + >>> card = ModelCard.load("username/my-awesome-model") + >>> card.data.tags + ["x-custom-tag", "pytorch_model_hub_mixin", "model_hub_mixin"] + >>> card.data.library_name + "my-library" + ``` + """ + + _hub_mixin_config: dict | DataclassInstance | None = None + # ^ optional config attribute automatically set in `from_pretrained` + _hub_mixin_info: MixinInfo + # ^ information about the library integrating ModelHubMixin (used to generate model card) + _hub_mixin_inject_config: bool # whether `_from_pretrained` expects `config` or not + _hub_mixin_init_parameters: dict[str, inspect.Parameter] # __init__ parameters + _hub_mixin_jsonable_default_values: dict[str, Any] # default values for __init__ parameters + _hub_mixin_jsonable_custom_types: tuple[type, ...] # custom types that can be encoded/decoded + _hub_mixin_coders: dict[type, CODER_T] # encoders/decoders for custom types + # ^ internal values to handle config + + def __init_subclass__( + cls, + *, + # Generic info for model card + repo_url: str | None = None, + paper_url: str | None = None, + docs_url: str | None = None, + # Model card template + model_card_template: str = DEFAULT_MODEL_CARD, + # Model card metadata + language: list[str] | None = None, + library_name: str | None = None, + license: str | None = None, + license_name: str | None = None, + license_link: str | None = None, + pipeline_tag: str | None = None, + tags: list[str] | None = None, + # How to encode/decode arguments with custom type into a JSON config? + coders: None + | ( + dict[type, CODER_T] + # Key is a type. + # Value is a tuple (encoder, decoder). + # Example: {MyCustomType: (lambda x: x.value, lambda data: MyCustomType(data))} + ) = None, + ) -> None: + """Inspect __init__ signature only once when subclassing + handle modelcard.""" + super().__init_subclass__() + + # Will be reused when creating modelcard + tags = tags or [] + tags.append("model_hub_mixin") + + # Initialize MixinInfo if not existent + info = MixinInfo(model_card_template=model_card_template, model_card_data=ModelCardData()) + + # If parent class has a MixinInfo, inherit from it as a copy + if hasattr(cls, "_hub_mixin_info"): + # Inherit model card template from parent class if not explicitly set + if model_card_template == DEFAULT_MODEL_CARD: + info.model_card_template = cls._hub_mixin_info.model_card_template + + # Inherit from parent model card data + info.model_card_data = ModelCardData(**cls._hub_mixin_info.model_card_data.to_dict()) + + # Inherit other info + info.docs_url = cls._hub_mixin_info.docs_url + info.paper_url = cls._hub_mixin_info.paper_url + info.repo_url = cls._hub_mixin_info.repo_url + cls._hub_mixin_info = info + + # Update MixinInfo with metadata + if model_card_template is not None and model_card_template != DEFAULT_MODEL_CARD: + info.model_card_template = model_card_template + if repo_url is not None: + info.repo_url = repo_url + if paper_url is not None: + info.paper_url = paper_url + if docs_url is not None: + info.docs_url = docs_url + if language is not None: + info.model_card_data.language = language + if library_name is not None: + info.model_card_data.library_name = library_name + if license is not None: + info.model_card_data.license = license + if license_name is not None: + info.model_card_data.license_name = license_name + if license_link is not None: + info.model_card_data.license_link = license_link + if pipeline_tag is not None: + info.model_card_data.pipeline_tag = pipeline_tag + if tags is not None: + normalized_tags = list(tags) + if info.model_card_data.tags is not None: + info.model_card_data.tags.extend(normalized_tags) + else: + info.model_card_data.tags = normalized_tags + + if info.model_card_data.tags is not None: + info.model_card_data.tags = sorted(set(info.model_card_data.tags)) + + # Handle encoders/decoders for args + cls._hub_mixin_coders = coders or {} + cls._hub_mixin_jsonable_custom_types = tuple(cls._hub_mixin_coders.keys()) + + # Inspect __init__ signature to handle config + cls._hub_mixin_init_parameters = dict(inspect.signature(cls.__init__).parameters) + cls._hub_mixin_jsonable_default_values = { + param.name: cls._encode_arg(param.default) + for param in cls._hub_mixin_init_parameters.values() + if param.default is not inspect.Parameter.empty and cls._is_jsonable(param.default) + } + cls._hub_mixin_inject_config = "config" in inspect.signature(cls._from_pretrained).parameters + + def __new__(cls: type[T], *args, **kwargs) -> T: + """Create a new instance of the class and handle config. + + 3 cases: + - If `self._hub_mixin_config` is already set, do nothing. + - If `config` is passed as a dataclass, set it as `self._hub_mixin_config`. + - Otherwise, build `self._hub_mixin_config` from default values and passed values. + """ + instance = super().__new__(cls) + + # If `config` is already set, return early + if instance._hub_mixin_config is not None: + return instance + + # Infer passed values + passed_values = { + **{ + key: value + for key, value in zip( + # [1:] to skip `self` parameter + list(cls._hub_mixin_init_parameters)[1:], + args, + ) + }, + **kwargs, + } + + # If config passed as dataclass => set it and return early + if is_dataclass(passed_values.get("config")): + instance._hub_mixin_config = passed_values["config"] + return instance + + # Otherwise, build config from default + passed values + init_config = { + # default values + **cls._hub_mixin_jsonable_default_values, + # passed values + **{ + key: cls._encode_arg(value) # Encode custom types as jsonable value + for key, value in passed_values.items() + if instance._is_jsonable(value) # Only if jsonable or we have a custom encoder + }, + } + passed_config = init_config.pop("config", {}) + + # Populate `init_config` with provided config + if isinstance(passed_config, dict): + init_config.update(passed_config) + + # Set `config` attribute and return + if init_config != {}: + instance._hub_mixin_config = init_config + return instance + + @classmethod + def _is_jsonable(cls, value: Any) -> bool: + """Check if a value is JSON serializable.""" + if is_dataclass(value): + return True + if isinstance(value, cls._hub_mixin_jsonable_custom_types): + return True + return is_jsonable(value) + + @classmethod + def _encode_arg(cls, arg: Any) -> Any: + """Encode an argument into a JSON serializable format.""" + if is_dataclass(arg): + return asdict(arg) # type: ignore[arg-type] + for type_, (encoder, _) in cls._hub_mixin_coders.items(): + if isinstance(arg, type_): + if arg is None: + return None + return encoder(arg) + return arg + + @classmethod + def _decode_arg(cls, expected_type: type[ARGS_T], value: Any) -> ARGS_T | None: + """Decode a JSON serializable value into an argument.""" + if is_simple_optional_type(expected_type): + if value is None: + return None + expected_type = unwrap_simple_optional_type(expected_type) # type: ignore + # Dataclass => handle it + if is_dataclass(expected_type): + return _load_dataclass(expected_type, value) # type: ignore + # Otherwise => check custom decoders + for type_, (_, decoder) in cls._hub_mixin_coders.items(): + if inspect.isclass(expected_type) and issubclass(expected_type, type_): + return decoder(value) + # Otherwise => don't decode + return value + + def save_pretrained( + self, + save_directory: str | Path, + *, + config: dict | DataclassInstance | None = None, + repo_id: str | None = None, + push_to_hub: bool = False, + model_card_kwargs: dict[str, Any] | None = None, + **push_to_hub_kwargs, + ) -> str | None: + """ + Save weights in local directory. + + Args: + save_directory (`str` or `Path`): + Path to directory in which the model weights and configuration will be saved. + config (`dict` or `DataclassInstance`, *optional*): + Model configuration specified as a key/value dictionary or a dataclass instance. + push_to_hub (`bool`, *optional*, defaults to `False`): + Whether or not to push your model to the Huggingface Hub after saving it. + repo_id (`str`, *optional*): + ID of your repository on the Hub. Used only if `push_to_hub=True`. Will default to the folder name if + not provided. + model_card_kwargs (`dict[str, Any]`, *optional*): + Additional arguments passed to the model card template to customize the model card. + push_to_hub_kwargs: + Additional key word arguments passed along to the [`~ModelHubMixin.push_to_hub`] method. + Returns: + `str` or `None`: url of the commit on the Hub if `push_to_hub=True`, `None` otherwise. + """ + save_directory = Path(save_directory) + save_directory.mkdir(parents=True, exist_ok=True) + + # Remove config.json if already exists. After `_save_pretrained` we don't want to overwrite config.json + # as it might have been saved by the custom `_save_pretrained` already. However we do want to overwrite + # an existing config.json if it was not saved by `_save_pretrained`. + config_path = save_directory / constants.CONFIG_NAME + config_path.unlink(missing_ok=True) + + # save model weights/files (framework-specific) + self._save_pretrained(save_directory) + + # save config (if provided and if not serialized yet in `_save_pretrained`) + if config is None: + config = self._hub_mixin_config + if config is not None: + if is_dataclass(config): + config = asdict(config) # type: ignore[arg-type] + if not config_path.exists(): + config_str = json.dumps(config, sort_keys=True, indent=2) + config_path.write_text(config_str) + + # save model card + model_card_path = save_directory / "README.md" + model_card_kwargs = model_card_kwargs if model_card_kwargs is not None else {} + if not model_card_path.exists(): # do not overwrite if already exists + self.generate_model_card(**model_card_kwargs).save(save_directory / "README.md") + + # push to the Hub if required + if push_to_hub: + kwargs = push_to_hub_kwargs.copy() # soft-copy to avoid mutating input + if config is not None: # kwarg for `push_to_hub` + kwargs["config"] = config + if repo_id is None: + repo_id = save_directory.name # Defaults to `save_directory` name + return self.push_to_hub(repo_id=repo_id, model_card_kwargs=model_card_kwargs, **kwargs) + return None + + def _save_pretrained(self, save_directory: Path) -> None: + """ + Overwrite this method in subclass to define how to save your model. + Check out our [integration guide](../guides/integrations) for instructions. + + Args: + save_directory (`str` or `Path`): + Path to directory in which the model weights and configuration will be saved. + """ + raise NotImplementedError + + @classmethod + @validate_hf_hub_args + def from_pretrained( + cls: type[T], + pretrained_model_name_or_path: str | Path, + *, + force_download: bool = False, + token: str | bool | None = None, + cache_dir: str | Path | None = None, + local_files_only: bool = False, + revision: str | None = None, + **model_kwargs, + ) -> T: + """ + Download a model from the Huggingface Hub and instantiate it. + + Args: + pretrained_model_name_or_path (`str`, `Path`): + - Either the `model_id` (string) of a model hosted on the Hub, e.g. `bigscience/bloom`. + - Or a path to a `directory` containing model weights saved using + [`~transformers.PreTrainedModel.save_pretrained`], e.g., `../path/to/my_model_directory/`. + revision (`str`, *optional*): + Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. + Defaults to the latest commit on `main` branch. + force_download (`bool`, *optional*, defaults to `False`): + Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding + the existing cache. + token (`str` or `bool`, *optional*): + The token to use as HTTP bearer authorization for remote files. By default, it will use the token + cached when running `hf auth login`. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the local cached file if it exists. + model_kwargs (`dict`, *optional*): + Additional kwargs to pass to the model during initialization. + """ + model_id = str(pretrained_model_name_or_path) + config_file: str | None = None + if os.path.isdir(model_id): + if constants.CONFIG_NAME in os.listdir(model_id): + config_file = os.path.join(model_id, constants.CONFIG_NAME) + else: + logger.warning(f"{constants.CONFIG_NAME} not found in {Path(model_id).resolve()}") + else: + try: + config_file = hf_hub_download( + repo_id=model_id, + filename=constants.CONFIG_NAME, + revision=revision, + cache_dir=cache_dir, + force_download=force_download, + token=token, + local_files_only=local_files_only, + ) + except HfHubHTTPError as e: + logger.info(f"{constants.CONFIG_NAME} not found on the HuggingFace Hub: {str(e)}") + + # Read config + config = None + if config_file is not None: + with open(config_file, encoding="utf-8") as f: + config = json.load(f) + + # Decode custom types in config + for key, value in config.items(): + if key in cls._hub_mixin_init_parameters: + expected_type = cls._hub_mixin_init_parameters[key].annotation + if expected_type is not inspect.Parameter.empty: + config[key] = cls._decode_arg(expected_type, value) + + # Populate model_kwargs from config + for param in cls._hub_mixin_init_parameters.values(): + if param.name not in model_kwargs and param.name in config: + model_kwargs[param.name] = config[param.name] + + # Check if `config` argument was passed at init + if "config" in cls._hub_mixin_init_parameters and "config" not in model_kwargs: + # Decode `config` argument if it was passed + config_annotation = cls._hub_mixin_init_parameters["config"].annotation + config = cls._decode_arg(config_annotation, config) + + # Forward config to model initialization + model_kwargs["config"] = config + + # Inject config if `**kwargs` are expected + if is_dataclass(cls): + for key in cls.__dataclass_fields__: + if key not in model_kwargs and key in config: + model_kwargs[key] = config[key] + elif any(param.kind == inspect.Parameter.VAR_KEYWORD for param in cls._hub_mixin_init_parameters.values()): + for key, value in config.items(): # type: ignore[union-attr] + if key not in model_kwargs: + model_kwargs[key] = value + + # Finally, also inject if `_from_pretrained` expects it + if cls._hub_mixin_inject_config and "config" not in model_kwargs: + model_kwargs["config"] = config + + instance = cls._from_pretrained( + model_id=str(model_id), + revision=revision, + cache_dir=cache_dir, + force_download=force_download, + local_files_only=local_files_only, + token=token, + **model_kwargs, + ) + + # Implicitly set the config as instance attribute if not already set by the class + # This way `config` will be available when calling `save_pretrained` or `push_to_hub`. + if config is not None and (getattr(instance, "_hub_mixin_config", None) in (None, {})): + instance._hub_mixin_config = config + + return instance + + @classmethod + def _from_pretrained( + cls: type[T], + *, + model_id: str, + revision: str | None, + cache_dir: str | Path | None, + force_download: bool, + local_files_only: bool, + token: str | bool | None, + **model_kwargs, + ) -> T: + """Overwrite this method in subclass to define how to load your model from pretrained. + + Use [`hf_hub_download`] or [`snapshot_download`] to download files from the Hub before loading them. Most + args taken as input can be directly passed to those 2 methods. If needed, you can add more arguments to this + method using "model_kwargs". For example [`PyTorchModelHubMixin._from_pretrained`] takes as input a `map_location` + parameter to set on which device the model should be loaded. + + Check out our [integration guide](../guides/integrations) for more instructions. + + Args: + model_id (`str`): + ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`). + revision (`str`, *optional*): + Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the + latest commit on `main` branch. + force_download (`bool`, *optional*, defaults to `False`): + Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding + the existing cache. + token (`str` or `bool`, *optional*): + The token to use as HTTP bearer authorization for remote files. By default, it will use the token + cached when running `hf auth login`. + cache_dir (`str`, `Path`, *optional*): + Path to the folder where cached files are stored. + local_files_only (`bool`, *optional*, defaults to `False`): + If `True`, avoid downloading the file and return the path to the local cached file if it exists. + model_kwargs: + Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method. + """ + raise NotImplementedError + + @validate_hf_hub_args + def push_to_hub( + self, + repo_id: str, + *, + config: dict | DataclassInstance | None = None, + commit_message: str = "Push model using huggingface_hub.", + private: bool | None = None, + token: str | None = None, + branch: str | None = None, + create_pr: bool | None = None, + allow_patterns: list[str] | str | None = None, + ignore_patterns: list[str] | str | None = None, + delete_patterns: list[str] | str | None = None, + model_card_kwargs: dict[str, Any] | None = None, + ) -> str: + """ + Upload model checkpoint to the Hub. + + Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use + `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more + details. + + Args: + repo_id (`str`): + ID of the repository to push to (example: `"username/my-model"`). + config (`dict` or `DataclassInstance`, *optional*): + Model configuration specified as a key/value dictionary or a dataclass instance. + commit_message (`str`, *optional*): + Message to commit while pushing. + private (`bool`, *optional*): + Whether the repository created should be private. + If `None` (default), the repo will be public unless the organization's default is private. + token (`str`, *optional*): + The token to use as HTTP bearer authorization for remote files. By default, it will use the token + cached when running `hf auth login`. + branch (`str`, *optional*): + The git branch on which to push the model. This defaults to `"main"`. + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request from `branch` with that commit. Defaults to `False`. + allow_patterns (`list[str]` or `str`, *optional*): + If provided, only files matching at least one pattern are pushed. + ignore_patterns (`list[str]` or `str`, *optional*): + If provided, files matching any of the patterns are not pushed. + delete_patterns (`list[str]` or `str`, *optional*): + If provided, remote files matching any of the patterns will be deleted from the repo. + model_card_kwargs (`dict[str, Any]`, *optional*): + Additional arguments passed to the model card template to customize the model card. + + Returns: + The url of the commit of your model in the given repository. + """ + api = HfApi(token=token) + repo_id = api.create_repo(repo_id=repo_id, private=private, exist_ok=True).repo_id + + # Push the files to the repo in a single commit + with SoftTemporaryDirectory() as tmp: + saved_path = Path(tmp) / repo_id + self.save_pretrained(saved_path, config=config, model_card_kwargs=model_card_kwargs) + return api.upload_folder( + repo_id=repo_id, + repo_type="model", + folder_path=saved_path, + commit_message=commit_message, + revision=branch, + create_pr=create_pr, + allow_patterns=allow_patterns, + ignore_patterns=ignore_patterns, + delete_patterns=delete_patterns, + ) + + def generate_model_card(self, *args, **kwargs) -> ModelCard: + card = ModelCard.from_template( + card_data=self._hub_mixin_info.model_card_data, + template_str=self._hub_mixin_info.model_card_template, + repo_url=self._hub_mixin_info.repo_url, + paper_url=self._hub_mixin_info.paper_url, + docs_url=self._hub_mixin_info.docs_url, + **kwargs, + ) + return card + + +class PyTorchModelHubMixin(ModelHubMixin): + """ + Implementation of [`ModelHubMixin`] to provide model Hub upload/download capabilities to PyTorch models. The model + is set in evaluation mode by default using `model.eval()` (dropout modules are deactivated). To train the model, + you should first set it back in training mode with `model.train()`. + + See [`ModelHubMixin`] for more details on how to use the mixin. + + Example: + + ```python + >>> import torch + >>> import torch.nn as nn + >>> from huggingface_hub import PyTorchModelHubMixin + + >>> class MyModel( + ... nn.Module, + ... PyTorchModelHubMixin, + ... library_name="keras-nlp", + ... repo_url="https://github.com/keras-team/keras-nlp", + ... paper_url="https://arxiv.org/abs/2304.12244", + ... docs_url="https://keras.io/keras_nlp/", + ... # ^ optional metadata to generate model card + ... ): + ... def __init__(self, hidden_size: int = 512, vocab_size: int = 30000, output_size: int = 4): + ... super().__init__() + ... self.param = nn.Parameter(torch.rand(hidden_size, vocab_size)) + ... self.linear = nn.Linear(output_size, vocab_size) + + ... def forward(self, x): + ... return self.linear(x + self.param) + >>> model = MyModel(hidden_size=256) + + # Save model weights to local directory + >>> model.save_pretrained("my-awesome-model") + + # Push model weights to the Hub + >>> model.push_to_hub("my-awesome-model") + + # Download and initialize weights from the Hub + >>> model = MyModel.from_pretrained("username/my-awesome-model") + >>> model.hidden_size + 256 + ``` + """ + + def __init_subclass__(cls, *args, tags: list[str] | None = None, **kwargs) -> None: + tags = tags or [] + tags.append("pytorch_model_hub_mixin") + kwargs["tags"] = tags + return super().__init_subclass__(*args, **kwargs) + + def _save_pretrained(self, save_directory: Path) -> None: + """Save weights from a Pytorch model to a local directory.""" + model_to_save = self.module if hasattr(self, "module") else self # type: ignore + save_model_as_safetensor(model_to_save, str(save_directory / constants.SAFETENSORS_SINGLE_FILE)) # type: ignore [arg-type] + + @classmethod + def _from_pretrained( + cls, + *, + model_id: str, + revision: str | None, + cache_dir: str | Path | None, + force_download: bool, + local_files_only: bool, + token: str | bool | None, + map_location: str = "cpu", + strict: bool = False, + **model_kwargs, + ): + """Load Pytorch pretrained weights and return the loaded model.""" + model = cls(**model_kwargs) + if os.path.isdir(model_id): + print("Loading weights from local directory") + model_file = os.path.join(model_id, constants.SAFETENSORS_SINGLE_FILE) + return cls._load_as_safetensor(model, model_file, map_location, strict) + else: + try: + model_file = hf_hub_download( + repo_id=model_id, + filename=constants.SAFETENSORS_SINGLE_FILE, + revision=revision, + cache_dir=cache_dir, + force_download=force_download, + token=token, + local_files_only=local_files_only, + ) + return cls._load_as_safetensor(model, model_file, map_location, strict) + except EntryNotFoundError: + model_file = hf_hub_download( + repo_id=model_id, + filename=constants.PYTORCH_WEIGHTS_NAME, + revision=revision, + cache_dir=cache_dir, + force_download=force_download, + token=token, + local_files_only=local_files_only, + ) + return cls._load_as_pickle(model, model_file, map_location, strict) + + @classmethod + def _load_as_pickle(cls, model: T, model_file: str, map_location: str, strict: bool) -> T: + state_dict = torch.load(model_file, map_location=torch.device(map_location), weights_only=True) + model.load_state_dict(state_dict, strict=strict) # type: ignore + model.eval() # type: ignore + return model + + @classmethod + def _load_as_safetensor(cls, model: T, model_file: str, map_location: str, strict: bool) -> T: + if packaging.version.parse(safetensors.__version__) < packaging.version.parse("0.4.3"): # type: ignore [attr-defined] + load_model_as_safetensor(model, model_file, strict=strict) # type: ignore [arg-type] + if map_location != "cpu": + logger.warning( + "Loading model weights on other devices than 'cpu' is not supported natively in your version of safetensors." + " This means that the model is loaded on 'cpu' first and then copied to the device." + " This leads to a slower loading time." + " Please update safetensors to version 0.4.3 or above for improved performance." + ) + model.to(map_location) # type: ignore [attr-defined] + else: + safetensors.torch.load_model(model, model_file, strict=strict, device=map_location) # type: ignore [arg-type] + model.eval() # type: ignore + return model + + +def _load_dataclass(datacls: type[DataclassInstance], data: dict) -> DataclassInstance: + """Load a dataclass instance from a dictionary. + + Fields not expected by the dataclass are ignored. + """ + return datacls(**{k: v for k, v in data.items() if k in datacls.__dataclass_fields__}) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/lfs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/lfs.py new file mode 100644 index 0000000000000000000000000000000000000000..3dd18e717c307f16429d891a20c6c4b7bed27c3b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/lfs.py @@ -0,0 +1,395 @@ +# Copyright 2019-present, the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Git LFS related type definitions and utilities""" + +import io +import re +from collections.abc import Iterable +from dataclasses import dataclass +from math import ceil +from os.path import getsize +from typing import TYPE_CHECKING, BinaryIO, TypedDict +from urllib.parse import unquote + +from huggingface_hub import constants + +from .utils import ( + build_hf_headers, + fix_hf_endpoint_in_url, + hf_raise_for_status, + http_backoff, + logging, + validate_hf_hub_args, +) +from .utils._lfs import SliceFileObj +from .utils.sha import sha256, sha_fileobj + + +if TYPE_CHECKING: + from ._commit_api import CommitOperationAdd + +logger = logging.get_logger(__name__) + +OID_REGEX = re.compile(r"^[0-9a-f]{40}$") + +LFS_MULTIPART_UPLOAD_COMMAND = "lfs-multipart-upload" + +LFS_HEADERS = { + "Accept": "application/vnd.git-lfs+json", + "Content-Type": "application/vnd.git-lfs+json", +} + + +@dataclass +class UploadInfo: + """ + Dataclass holding required information to determine whether a blob + should be uploaded to the hub using the LFS protocol or the regular protocol + + Args: + sha256 (`bytes`): + SHA256 hash of the blob + size (`int`): + Size in bytes of the blob + sample (`bytes`): + First 512 bytes of the blob + """ + + sha256: bytes + size: int + sample: bytes + + @classmethod + def from_path(cls, path: str): + size = getsize(path) + with open(path, "rb") as file: + sample = file.peek(512)[:512] + sha = sha_fileobj(file) + return cls(size=size, sha256=sha, sample=sample) + + @classmethod + def from_bytes(cls, data: bytes): + sha = sha256(data).digest() + return cls(size=len(data), sample=data[:512], sha256=sha) + + @classmethod + def from_fileobj(cls, fileobj: BinaryIO): + sample = fileobj.read(512) + fileobj.seek(0, io.SEEK_SET) + sha = sha_fileobj(fileobj) + size = fileobj.tell() + fileobj.seek(0, io.SEEK_SET) + return cls(size=size, sha256=sha, sample=sample) + + +@validate_hf_hub_args +def post_lfs_batch_info( + upload_infos: Iterable[UploadInfo], + token: str | None, + repo_type: str, + repo_id: str, + revision: str | None = None, + endpoint: str | None = None, + headers: dict[str, str] | None = None, + transfers: list[str] | None = None, +) -> tuple[list[dict], list[dict], str | None]: + """ + Requests the LFS batch endpoint to retrieve upload instructions + + Learn more: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md + + Args: + upload_infos (`Iterable` of `UploadInfo`): + `UploadInfo` for the files that are being uploaded, typically obtained + from `CommitOperationAdd.upload_info` + repo_type (`str`): + Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`. + repo_id (`str`): + A namespace (user or an organization) and a repo name separated + by a `/`. + revision (`str`, *optional*): + The git revision to upload to. + headers (`dict`, *optional*): + Additional headers to include in the request + transfers (`list`, *optional*): + List of transfer methods to use. Defaults to ["basic", "multipart"]. + + Returns: + `LfsBatchInfo`: 3-tuple: + - First element is the list of upload instructions from the server + - Second element is a list of errors, if any + - Third element is the chosen transfer adapter if provided by the server (e.g. "basic", "multipart", "xet") + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If an argument is invalid or the server response is malformed. + [`HfHubHTTPError`] + If the server returned an error. + """ + endpoint = endpoint if endpoint is not None else constants.ENDPOINT + url_prefix = "" + if repo_type in constants.REPO_TYPES_URL_PREFIXES: + url_prefix = constants.REPO_TYPES_URL_PREFIXES[repo_type] + batch_url = f"{endpoint}/{url_prefix}{repo_id}.git/info/lfs/objects/batch" + payload: dict = { + "operation": "upload", + "transfers": transfers if transfers is not None else ["basic", "multipart"], + "objects": [ + { + "oid": upload.sha256.hex(), + "size": upload.size, + } + for upload in upload_infos + ], + "hash_algo": "sha256", + } + if revision is not None: + payload["ref"] = {"name": unquote(revision)} # revision has been previously 'quoted' + + headers = { + **LFS_HEADERS, + **build_hf_headers(token=token), + **(headers or {}), + } + resp = http_backoff("POST", batch_url, headers=headers, json=payload) + hf_raise_for_status(resp) + batch_info = resp.json() + + objects = batch_info.get("objects", None) + if not isinstance(objects, list): + raise ValueError("Malformed response from server") + + chosen_transfer = batch_info.get("transfer") + chosen_transfer = chosen_transfer if isinstance(chosen_transfer, str) else None + + return ( + [_validate_batch_actions(obj) for obj in objects if "error" not in obj], + [_validate_batch_error(obj) for obj in objects if "error" in obj], + chosen_transfer, + ) + + +class PayloadPartT(TypedDict): + partNumber: int + etag: str + + +class CompletionPayloadT(TypedDict): + """Payload that will be sent to the Hub when uploading multi-part.""" + + oid: str + parts: list[PayloadPartT] + + +def lfs_upload( + operation: "CommitOperationAdd", + lfs_batch_action: dict, + token: str | None = None, + headers: dict[str, str] | None = None, + endpoint: str | None = None, +) -> None: + """ + Handles uploading a given object to the Hub with the LFS protocol. + + Can be a No-op if the content of the file is already present on the hub large file storage. + + Args: + operation (`CommitOperationAdd`): + The add operation triggering this upload. + lfs_batch_action (`dict`): + Upload instructions from the LFS batch endpoint for this object. See [`~utils.lfs.post_lfs_batch_info`] for + more details. + headers (`dict`, *optional*): + Headers to include in the request, including authentication and user agent headers. + + Raises: + [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + If `lfs_batch_action` is improperly formatted + [`HfHubHTTPError`] + If the upload resulted in an error + """ + # 0. If LFS file is already present, skip upload + _validate_batch_actions(lfs_batch_action) + actions = lfs_batch_action.get("actions") + if actions is None: + # The file was already uploaded + logger.debug(f"Content of file {operation.path_in_repo} is already present upstream - skipping upload") + return + + # 1. Validate server response (check required keys in dict) + upload_action = lfs_batch_action["actions"]["upload"] + _validate_lfs_action(upload_action) + verify_action = lfs_batch_action["actions"].get("verify") + if verify_action is not None: + _validate_lfs_action(verify_action) + + # 2. Upload file (either single part or multi-part) + header = upload_action.get("header", {}) + chunk_size = header.get("chunk_size") + upload_url = fix_hf_endpoint_in_url(upload_action["href"], endpoint=endpoint) + if chunk_size is not None: + try: + chunk_size = int(chunk_size) + except (ValueError, TypeError): + raise ValueError( + f"Malformed response from LFS batch endpoint: `chunk_size` should be an integer. Got '{chunk_size}'." + ) + _upload_multi_part(operation=operation, header=header, chunk_size=chunk_size, upload_url=upload_url) + else: + _upload_single_part(operation=operation, upload_url=upload_url) + + # 3. Verify upload went well + if verify_action is not None: + _validate_lfs_action(verify_action) + verify_url = fix_hf_endpoint_in_url(verify_action["href"], endpoint) + verify_resp = http_backoff( + "POST", + verify_url, + headers=build_hf_headers(token=token, headers=headers), + json={"oid": operation.upload_info.sha256.hex(), "size": operation.upload_info.size}, + ) + hf_raise_for_status(verify_resp) + logger.debug(f"{operation.path_in_repo}: Upload successful") + + +def _validate_lfs_action(lfs_action: dict): + """validates response from the LFS batch endpoint""" + if not ( + isinstance(lfs_action.get("href"), str) + and (lfs_action.get("header") is None or isinstance(lfs_action.get("header"), dict)) + ): + raise ValueError("lfs_action is improperly formatted") + return lfs_action + + +def _validate_batch_actions(lfs_batch_actions: dict): + """validates response from the LFS batch endpoint""" + if not (isinstance(lfs_batch_actions.get("oid"), str) and isinstance(lfs_batch_actions.get("size"), int)): + raise ValueError("lfs_batch_actions is improperly formatted") + + upload_action = lfs_batch_actions.get("actions", {}).get("upload") + verify_action = lfs_batch_actions.get("actions", {}).get("verify") + if upload_action is not None: + _validate_lfs_action(upload_action) + if verify_action is not None: + _validate_lfs_action(verify_action) + return lfs_batch_actions + + +def _validate_batch_error(lfs_batch_error: dict): + """validates response from the LFS batch endpoint""" + if not (isinstance(lfs_batch_error.get("oid"), str) and isinstance(lfs_batch_error.get("size"), int)): + raise ValueError("lfs_batch_error is improperly formatted") + error_info = lfs_batch_error.get("error") + if not ( + isinstance(error_info, dict) + and isinstance(error_info.get("message"), str) + and isinstance(error_info.get("code"), int) + ): + raise ValueError("lfs_batch_error is improperly formatted") + return lfs_batch_error + + +def _upload_single_part(operation: "CommitOperationAdd", upload_url: str) -> None: + """ + Uploads `fileobj` as a single PUT HTTP request (basic LFS transfer protocol) + + Args: + upload_url (`str`): + The URL to PUT the file to. + fileobj: + The file-like object holding the data to upload. + + Raises: + [`HfHubHTTPError`] + If the upload resulted in an error. + """ + with operation.as_file(with_tqdm=True) as fileobj: + # S3 might raise a transient 500 error -> let's retry if that happens + response = http_backoff("PUT", upload_url, data=fileobj) + hf_raise_for_status(response) + + +def _upload_multi_part(operation: "CommitOperationAdd", header: dict, chunk_size: int, upload_url: str) -> None: + """ + Uploads file using HF multipart LFS transfer protocol. + """ + # 1. Get upload URLs for each part + sorted_parts_urls = _get_sorted_parts_urls(header=header, upload_info=operation.upload_info, chunk_size=chunk_size) + + # 2. Upload parts (pure Python) + response_headers = _upload_parts_iteratively( + operation=operation, sorted_parts_urls=sorted_parts_urls, chunk_size=chunk_size + ) + + # 3. Send completion request + # NOTE: `upload_url` is the Hub completion endpoint (not the S3 upload URLs). + completion_res = http_backoff( + "POST", + upload_url, + json=_get_completion_payload(response_headers, operation.upload_info.sha256.hex()), + headers=LFS_HEADERS, + ) + hf_raise_for_status(completion_res) + + +def _get_sorted_parts_urls(header: dict, upload_info: UploadInfo, chunk_size: int) -> list[str]: + sorted_part_upload_urls = [ + upload_url + for _, upload_url in sorted( + [ + (int(part_num, 10), upload_url) + for part_num, upload_url in header.items() + if part_num.isdigit() and len(part_num) > 0 + ], + key=lambda t: t[0], + ) + ] + num_parts = len(sorted_part_upload_urls) + if num_parts != ceil(upload_info.size / chunk_size): + raise ValueError("Invalid server response to upload large LFS file") + return sorted_part_upload_urls + + +def _get_completion_payload(response_headers: list[dict], oid: str) -> CompletionPayloadT: + parts: list[PayloadPartT] = [] + for part_number, header in enumerate(response_headers): + etag = header.get("etag") + if etag is None or etag == "": + raise ValueError(f"Invalid etag (`{etag}`) returned for part {part_number + 1}") + parts.append( + { + "partNumber": part_number + 1, + "etag": etag, + } + ) + return {"oid": oid, "parts": parts} + + +def _upload_parts_iteratively( + operation: "CommitOperationAdd", sorted_parts_urls: list[str], chunk_size: int +) -> list[dict]: + headers = [] + with operation.as_file(with_tqdm=True) as fileobj: + for part_idx, part_upload_url in enumerate(sorted_parts_urls): + with SliceFileObj( + fileobj, + seek_from=chunk_size * part_idx, + read_limit=chunk_size, + ) as fileobj_slice: + # S3 might raise a transient 500 error -> let's retry if that happens + part_upload_res = http_backoff("PUT", part_upload_url, data=fileobj_slice) + hf_raise_for_status(part_upload_res) + headers.append(part_upload_res.headers) + return headers # type: ignore diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/repocard.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/repocard.py new file mode 100644 index 0000000000000000000000000000000000000000..f479b83c351cc7cffbcf75060eceee5cad2510be --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/repocard.py @@ -0,0 +1,826 @@ +import os +import re +from pathlib import Path +from typing import Any, Literal + +import yaml + +from huggingface_hub.file_download import hf_hub_download +from huggingface_hub.hf_api import upload_file +from huggingface_hub.repocard_data import ( + CardData, + DatasetCardData, + EvalResult, + ModelCardData, + SpaceCardData, + eval_results_to_model_index, + model_index_to_eval_results, +) +from huggingface_hub.utils import HfHubHTTPError, get_session, hf_raise_for_status, is_jinja_available, yaml_dump + +from . import constants +from .errors import EntryNotFoundError +from .utils import SoftTemporaryDirectory, logging, validate_hf_hub_args + + +logger = logging.get_logger(__name__) + + +TEMPLATE_MODELCARD_PATH = Path(__file__).parent / "templates" / "modelcard_template.md" +TEMPLATE_DATASETCARD_PATH = Path(__file__).parent / "templates" / "datasetcard_template.md" + +# exact same regex as in the Hub server. Please keep in sync. +# See https://github.com/huggingface/moon-landing/blob/main/server/lib/ViewMarkdown.ts#L18 +REGEX_YAML_BLOCK = re.compile(r"^(\s*---[\r\n]+)([\S\s]*?)([\r\n]+---(\r\n|\n|$))") + + +class RepoCard: + card_data_class = CardData + default_template_path = TEMPLATE_MODELCARD_PATH + repo_type = "model" + + def __init__(self, content: str, ignore_metadata_errors: bool = False): + """Initialize a RepoCard from string content. The content should be a + Markdown file with a YAML block at the beginning and a Markdown body. + + Args: + content (`str`): The content of the Markdown file. + + Example: + ```python + >>> from huggingface_hub.repocard import RepoCard + >>> text = ''' + ... --- + ... language: en + ... license: mit + ... --- + ... + ... # My repo + ... ''' + >>> card = RepoCard(text) + >>> card.data.to_dict() + {'language': 'en', 'license': 'mit'} + >>> card.text + '\\n# My repo\\n' + + ``` + > [!TIP] + > Raises the following error: + > + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > when the content of the repo card metadata is not a dictionary. + """ + + # Set the content of the RepoCard, as well as underlying .data and .text attributes. + # See the `content` property setter for more details. + self.ignore_metadata_errors = ignore_metadata_errors + self.content = content + + @property + def content(self): + """The content of the RepoCard, including the YAML block and the Markdown body.""" + line_break = _detect_line_ending(self._content) or "\n" + return f"---{line_break}{self.data.to_yaml(line_break=line_break, original_order=self._original_order)}{line_break}---{line_break}{self.text}" + + @content.setter + def content(self, content: str): + """Set the content of the RepoCard.""" + self._content = content + + match = REGEX_YAML_BLOCK.search(content) + if match: + # Metadata found in the YAML block + yaml_block = match.group(2) + self.text = content[match.end() :] + data_dict = yaml.safe_load(yaml_block) + + if data_dict is None: + data_dict = {} + + # The YAML block's data should be a dictionary + if not isinstance(data_dict, dict): + raise ValueError("repo card metadata block should be a dict") + else: + # Model card without metadata... create empty metadata + logger.warning("Repo card metadata block was not found. Setting CardData to empty.") + data_dict = {} + self.text = content + + self.data = self.card_data_class(**data_dict, ignore_metadata_errors=self.ignore_metadata_errors) + self._original_order = list(data_dict.keys()) + + def __str__(self): + return self.content + + def save(self, filepath: Path | str): + r"""Save a RepoCard to a file. + + Args: + filepath (`Union[Path, str]`): Filepath to the markdown file to save. + + Example: + ```python + >>> from huggingface_hub.repocard import RepoCard + >>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card") + >>> card.save("/tmp/test.md") + + ``` + """ + filepath = Path(filepath) + filepath.parent.mkdir(parents=True, exist_ok=True) + # Preserve newlines as in the existing file. + with open(filepath, mode="w", newline="", encoding="utf-8") as f: + f.write(str(self)) + + @classmethod + def load( + cls, + repo_id_or_path: str | Path, + repo_type: str | None = None, + token: str | None = None, + ignore_metadata_errors: bool = False, + ): + """Initialize a RepoCard from a Hugging Face Hub repo's README.md or a local filepath. + + Args: + repo_id_or_path (`Union[str, Path]`): + The repo ID associated with a Hugging Face Hub repo or a local filepath. + repo_type (`str`, *optional*): + The type of Hugging Face repo to push to. Defaults to None, which will use "model". Other options + are "dataset" and "space". Not used when loading from a local filepath. If this is called from a child + class, the default value will be the child class's `repo_type`. + token (`str`, *optional*): + Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token. + ignore_metadata_errors (`str`): + If True, errors while parsing the metadata section will be ignored. Some information might be lost during + the process. Use it at your own risk. + + Returns: + [`huggingface_hub.repocard.RepoCard`]: The RepoCard (or subclass) initialized from the repo's + README.md file or filepath. + + Example: + ```python + >>> from huggingface_hub.repocard import RepoCard + >>> card = RepoCard.load("nateraw/food") + >>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"] + + ``` + """ + + if Path(repo_id_or_path).is_file(): + card_path = Path(repo_id_or_path) + elif isinstance(repo_id_or_path, str): + card_path = Path( + hf_hub_download( + repo_id_or_path, + constants.REPOCARD_NAME, + repo_type=repo_type or cls.repo_type, + token=token, + ) + ) + else: + raise ValueError(f"Cannot load RepoCard: path not found on disk ({repo_id_or_path}).") + + # Preserve newlines in the existing file. + with card_path.open(mode="r", newline="", encoding="utf-8") as f: + return cls(f.read(), ignore_metadata_errors=ignore_metadata_errors) + + def validate(self, repo_type: str | None = None): + """Validates card against Hugging Face Hub's card validation logic. + Using this function requires access to the internet, so it is only called + internally by [`huggingface_hub.repocard.RepoCard.push_to_hub`]. + + Args: + repo_type (`str`, *optional*, defaults to "model"): + The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". + If this function is called from a child class, the default will be the child class's `repo_type`. + + > [!TIP] + > Raises the following errors: + > + > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) + > if the card fails validation checks. + > - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError) + > if the request to the Hub API fails for any other reason. + """ + + # If repo type is provided, otherwise, use the repo type of the card. + repo_type = repo_type or self.repo_type + + body = { + "repoType": repo_type, + "content": str(self), + } + headers = {"Accept": "text/plain"} + + try: + response = get_session().post("https://huggingface.co/api/validate-yaml", json=body, headers=headers) + hf_raise_for_status(response) + except HfHubHTTPError as exc: + if response.status_code == 400: + raise ValueError(response.text) + else: + raise exc + + def push_to_hub( + self, + repo_id: str, + token: str | None = None, + repo_type: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + revision: str | None = None, + create_pr: bool | None = None, + parent_commit: str | None = None, + ): + """Push a RepoCard to a Hugging Face Hub repo. + + Args: + repo_id (`str`): + The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food". + token (`str`, *optional*): + Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to + the stored token. + repo_type (`str`, *optional*, defaults to "model"): + The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". If this + function is called by a child class, it will default to the child class's `repo_type`. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. + commit_description (`str`, *optional*) + The description of the generated commit. + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the `"main"` branch. + create_pr (`bool`, *optional*): + Whether or not to create a Pull Request with this commit. Defaults to `False`. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed too concurrently. + Returns: + `str`: URL of the commit which updated the card metadata. + """ + + # If repo type is provided, otherwise, use the repo type of the card. + repo_type = repo_type or self.repo_type + + # Validate card before pushing to hub + self.validate(repo_type=repo_type) + + with SoftTemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) / constants.REPOCARD_NAME + tmp_path.write_text(str(self), encoding="utf-8") + url = upload_file( + path_or_fileobj=str(tmp_path), + path_in_repo=constants.REPOCARD_NAME, + repo_id=repo_id, + token=token, + repo_type=repo_type, + commit_message=commit_message, + commit_description=commit_description, + create_pr=create_pr, + revision=revision, + parent_commit=parent_commit, + ) + return url + + @classmethod + def from_template( + cls, + card_data: CardData, + template_path: str | None = None, + template_str: str | None = None, + **template_kwargs, + ): + """Initialize a RepoCard from a template. By default, it uses the default template. + + Templates are Jinja2 templates that can be customized by passing keyword arguments. + + Args: + card_data (`huggingface_hub.CardData`): + A huggingface_hub.CardData instance containing the metadata you want to include in the YAML + header of the repo card on the Hugging Face Hub. + template_path (`str`, *optional*): + A path to a markdown file with optional Jinja template variables that can be filled + in with `template_kwargs`. Defaults to the default template. + + Returns: + [`huggingface_hub.repocard.RepoCard`]: A RepoCard instance with the specified card data and content from the + template. + """ + if is_jinja_available(): + import jinja2 + else: + raise ImportError( + "Using RepoCard.from_template requires Jinja2 to be installed. Please" + " install it with `pip install Jinja2`." + ) + + kwargs = card_data.to_dict().copy() + kwargs.update(template_kwargs) # Template_kwargs have priority + + if template_path is not None: + template_str = Path(template_path).read_text() + if template_str is None: + template_str = Path(cls.default_template_path).read_text() + template = jinja2.Template(template_str) + content = template.render(card_data=card_data.to_yaml(), **kwargs) + return cls(content) + + +class ModelCard(RepoCard): + card_data_class = ModelCardData # type: ignore[assignment] + default_template_path = TEMPLATE_MODELCARD_PATH + repo_type = "model" + + @classmethod + def from_template( # type: ignore # violates Liskov property but easier to use + cls, + card_data: ModelCardData, + template_path: str | None = None, + template_str: str | None = None, + **template_kwargs, + ): + """Initialize a ModelCard from a template. By default, it uses the default template, which can be found here: + https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/modelcard_template.md + + Templates are Jinja2 templates that can be customized by passing keyword arguments. + + Args: + card_data (`huggingface_hub.ModelCardData`): + A huggingface_hub.ModelCardData instance containing the metadata you want to include in the YAML + header of the model card on the Hugging Face Hub. + template_path (`str`, *optional*): + A path to a markdown file with optional Jinja template variables that can be filled + in with `template_kwargs`. Defaults to the default template. + + Returns: + [`huggingface_hub.ModelCard`]: A ModelCard instance with the specified card data and content from the + template. + + Example: + ```python + >>> from huggingface_hub import ModelCard, ModelCardData, EvalResult + + >>> # Using the Default Template + >>> card_data = ModelCardData( + ... language='en', + ... license='mit', + ... library_name='timm', + ... tags=['image-classification', 'resnet'], + ... datasets=['beans'], + ... metrics=['accuracy'], + ... ) + >>> card = ModelCard.from_template( + ... card_data, + ... model_description='This model does x + y...' + ... ) + + >>> # Including Evaluation Results + >>> card_data = ModelCardData( + ... language='en', + ... tags=['image-classification', 'resnet'], + ... eval_results=[ + ... EvalResult( + ... task_type='image-classification', + ... dataset_type='beans', + ... dataset_name='Beans', + ... metric_type='accuracy', + ... metric_value=0.9, + ... ), + ... ], + ... model_name='my-cool-model', + ... ) + >>> card = ModelCard.from_template(card_data) + + >>> # Using a Custom Template + >>> card_data = ModelCardData( + ... language='en', + ... tags=['image-classification', 'resnet'] + ... ) + >>> card = ModelCard.from_template( + ... card_data=card_data, + ... template_path='./src/huggingface_hub/templates/modelcard_template.md', + ... custom_template_var='custom value', # will be replaced in template if it exists + ... ) + + ``` + """ + return super().from_template(card_data, template_path, template_str, **template_kwargs) + + +class DatasetCard(RepoCard): + card_data_class = DatasetCardData # type: ignore[assignment] + default_template_path = TEMPLATE_DATASETCARD_PATH + repo_type = "dataset" + + @classmethod + def from_template( # type: ignore # violates Liskov property but easier to use + cls, + card_data: DatasetCardData, + template_path: str | None = None, + template_str: str | None = None, + **template_kwargs, + ): + """Initialize a DatasetCard from a template. By default, it uses the default template, which can be found here: + https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/datasetcard_template.md + + Templates are Jinja2 templates that can be customized by passing keyword arguments. + + Args: + card_data (`huggingface_hub.DatasetCardData`): + A huggingface_hub.DatasetCardData instance containing the metadata you want to include in the YAML + header of the dataset card on the Hugging Face Hub. + template_path (`str`, *optional*): + A path to a markdown file with optional Jinja template variables that can be filled + in with `template_kwargs`. Defaults to the default template. + + Returns: + [`huggingface_hub.DatasetCard`]: A DatasetCard instance with the specified card data and content from the + template. + + Example: + ```python + >>> from huggingface_hub import DatasetCard, DatasetCardData + + >>> # Using the Default Template + >>> card_data = DatasetCardData( + ... language='en', + ... license='mit', + ... annotations_creators='crowdsourced', + ... task_categories=['text-classification'], + ... task_ids=['sentiment-classification', 'text-scoring'], + ... multilinguality='monolingual', + ... pretty_name='My Text Classification Dataset', + ... ) + >>> card = DatasetCard.from_template( + ... card_data, + ... pretty_name=card_data.pretty_name, + ... ) + + >>> # Using a Custom Template + >>> card_data = DatasetCardData( + ... language='en', + ... license='mit', + ... ) + >>> card = DatasetCard.from_template( + ... card_data=card_data, + ... template_path='./src/huggingface_hub/templates/datasetcard_template.md', + ... custom_template_var='custom value', # will be replaced in template if it exists + ... ) + + ``` + """ + return super().from_template(card_data, template_path, template_str, **template_kwargs) + + +class SpaceCard(RepoCard): + card_data_class = SpaceCardData # type: ignore[assignment] + default_template_path = TEMPLATE_MODELCARD_PATH + repo_type = "space" + + +def _detect_line_ending(content: str) -> Literal["\r", "\n", "\r\n", None]: # noqa: F722 + """Detect the line ending of a string. Used by RepoCard to avoid making huge diff on newlines. + + Uses same implementation as in Hub server, keep it in sync. + + Returns: + str: The detected line ending of the string. + """ + cr = content.count("\r") + lf = content.count("\n") + crlf = content.count("\r\n") + if cr + lf == 0: + return None + if crlf == cr and crlf == lf: + return "\r\n" + if cr > lf: + return "\r" + else: + return "\n" + + +def metadata_load(local_path: str | Path) -> dict | None: + content = Path(local_path).read_text() + match = REGEX_YAML_BLOCK.search(content) + if match: + yaml_block = match.group(2) + data = yaml.safe_load(yaml_block) + if data is None or isinstance(data, dict): + return data + raise ValueError("repo card metadata block should be a dict") + else: + return None + + +def metadata_save(local_path: str | Path, data: dict) -> None: + """ + Save the metadata dict in the upper YAML part Trying to preserve newlines as + in the existing file. Docs about open() with newline="" parameter: + https://docs.python.org/3/library/functions.html?highlight=open#open Does + not work with "^M" linebreaks, which are replaced by \n + """ + line_break = "\n" + content = "" + # try to detect existing newline character + if os.path.exists(local_path): + with open(local_path, newline="", encoding="utf8") as readme: + content = readme.read() + if isinstance(readme.newlines, tuple): + line_break = readme.newlines[0] + elif isinstance(readme.newlines, str): + line_break = readme.newlines + + # creates a new file if it not + with open(local_path, "w", newline="", encoding="utf8") as readme: + data_yaml = yaml_dump(data, sort_keys=False, line_break=line_break) + # sort_keys: keep dict order + match = REGEX_YAML_BLOCK.search(content) + if match: + output = content[: match.start()] + f"---{line_break}{data_yaml}---{line_break}" + content[match.end() :] + else: + output = f"---{line_break}{data_yaml}---{line_break}{content}" + + readme.write(output) + readme.close() + + +def metadata_eval_result( + *, + model_pretty_name: str, + task_pretty_name: str, + task_id: str, + metrics_pretty_name: str, + metrics_id: str, + metrics_value: Any, + dataset_pretty_name: str, + dataset_id: str, + metrics_config: str | None = None, + metrics_verified: bool = False, + dataset_config: str | None = None, + dataset_split: str | None = None, + dataset_revision: str | None = None, + metrics_verification_token: str | None = None, +) -> dict: + """ + Creates a metadata dict with the result from a model evaluated on a dataset. + + Args: + model_pretty_name (`str`): + The name of the model in natural language. + task_pretty_name (`str`): + The name of a task in natural language. + task_id (`str`): + Example: automatic-speech-recognition. A task id. + metrics_pretty_name (`str`): + A name for the metric in natural language. Example: Test WER. + metrics_id (`str`): + Example: wer. A metric id from https://hf.co/metrics. + metrics_value (`Any`): + The value from the metric. Example: 20.0 or "20.0 ± 1.2". + dataset_pretty_name (`str`): + The name of the dataset in natural language. + dataset_id (`str`): + Example: common_voice. A dataset id from https://hf.co/datasets. + metrics_config (`str`, *optional*): + The name of the metric configuration used in `load_metric()`. + Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`. + metrics_verified (`bool`, *optional*, defaults to `False`): + Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set. + dataset_config (`str`, *optional*): + Example: fr. The name of the dataset configuration used in `load_dataset()`. + dataset_split (`str`, *optional*): + Example: test. The name of the dataset split used in `load_dataset()`. + dataset_revision (`str`, *optional*): + Example: 5503434ddd753f426f4b38109466949a1217c2bb. The name of the dataset dataset revision + used in `load_dataset()`. + metrics_verification_token (`bool`, *optional*): + A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. + + Returns: + `dict`: a metadata dict with the result from a model evaluated on a dataset. + + Example: + ```python + >>> from huggingface_hub import metadata_eval_result + >>> results = metadata_eval_result( + ... model_pretty_name="RoBERTa fine-tuned on ReactionGIF", + ... task_pretty_name="Text Classification", + ... task_id="text-classification", + ... metrics_pretty_name="Accuracy", + ... metrics_id="accuracy", + ... metrics_value=0.2662102282047272, + ... dataset_pretty_name="ReactionJPEG", + ... dataset_id="julien-c/reactionjpeg", + ... dataset_config="default", + ... dataset_split="test", + ... ) + >>> results == { + ... 'model-index': [ + ... { + ... 'name': 'RoBERTa fine-tuned on ReactionGIF', + ... 'results': [ + ... { + ... 'task': { + ... 'type': 'text-classification', + ... 'name': 'Text Classification' + ... }, + ... 'dataset': { + ... 'name': 'ReactionJPEG', + ... 'type': 'julien-c/reactionjpeg', + ... 'config': 'default', + ... 'split': 'test' + ... }, + ... 'metrics': [ + ... { + ... 'type': 'accuracy', + ... 'value': 0.2662102282047272, + ... 'name': 'Accuracy', + ... 'verified': False + ... } + ... ] + ... } + ... ] + ... } + ... ] + ... } + True + + ``` + """ + + return { + "model-index": eval_results_to_model_index( + model_name=model_pretty_name, + eval_results=[ + EvalResult( + task_name=task_pretty_name, + task_type=task_id, + metric_name=metrics_pretty_name, + metric_type=metrics_id, + metric_value=metrics_value, + dataset_name=dataset_pretty_name, + dataset_type=dataset_id, + metric_config=metrics_config, + verified=metrics_verified, + verify_token=metrics_verification_token, + dataset_config=dataset_config, + dataset_split=dataset_split, + dataset_revision=dataset_revision, + ) + ], + ) + } + + +@validate_hf_hub_args +def metadata_update( + repo_id: str, + metadata: dict, + *, + repo_type: str | None = None, + overwrite: bool = False, + token: str | None = None, + commit_message: str | None = None, + commit_description: str | None = None, + revision: str | None = None, + create_pr: bool = False, + parent_commit: str | None = None, +) -> str: + """ + Updates the metadata in the README.md of a repository on the Hugging Face Hub. + If the README.md file doesn't exist yet, a new one is created with metadata and + the default ModelCard or DatasetCard template. For `space` repo, an error is thrown + as a Space cannot exist without a `README.md` file. + + Args: + repo_id (`str`): + The name of the repository. + metadata (`dict`): + A dictionary containing the metadata to be updated. + repo_type (`str`, *optional*): + Set to `"dataset"` or `"space"` if updating to a dataset or space, + `None` or `"model"` if updating to a model. Default is `None`. + overwrite (`bool`, *optional*, defaults to `False`): + If set to `True` an existing field can be overwritten, otherwise + attempting to overwrite an existing field will cause an error. + token (`str`, *optional*): + The Hugging Face authentication token. + commit_message (`str`, *optional*): + The summary / title / first line of the generated commit. Defaults to + `f"Update metadata with huggingface_hub"` + commit_description (`str` *optional*) + The description of the generated commit + revision (`str`, *optional*): + The git revision to commit from. Defaults to the head of the + `"main"` branch. + create_pr (`boolean`, *optional*): + Whether or not to create a Pull Request from `revision` with that commit. + Defaults to `False`. + parent_commit (`str`, *optional*): + The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported. + If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`. + If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`. + Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be + especially useful if the repo is updated / committed too concurrently. + Returns: + `str`: URL of the commit which updated the card metadata. + + Example: + ```python + >>> from huggingface_hub import metadata_update + >>> metadata = {'model-index': [{'name': 'RoBERTa fine-tuned on ReactionGIF', + ... 'results': [{'dataset': {'name': 'ReactionGIF', + ... 'type': 'julien-c/reactiongif'}, + ... 'metrics': [{'name': 'Recall', + ... 'type': 'recall', + ... 'value': 0.7762102282047272}], + ... 'task': {'name': 'Text Classification', + ... 'type': 'text-classification'}}]}]} + >>> url = metadata_update("hf-internal-testing/reactiongif-roberta-card", metadata) + + ``` + """ + commit_message = commit_message if commit_message is not None else "Update metadata with huggingface_hub" + + # Card class given repo_type + card_class: type[RepoCard] + if repo_type is None or repo_type == "model": + card_class = ModelCard + elif repo_type == "dataset": + card_class = DatasetCard + elif repo_type == "space": + card_class = RepoCard + else: + raise ValueError(f"Unknown repo_type: {repo_type}") + + # Either load repo_card from the Hub or create an empty one. + # NOTE: Will not create the repo if it doesn't exist. + try: + card = card_class.load(repo_id, token=token, repo_type=repo_type) + except EntryNotFoundError: + if repo_type == "space": + raise ValueError("Cannot update metadata on a Space that doesn't contain a `README.md` file.") + + # Initialize a ModelCard or DatasetCard from default template and no data. + # Cast to the concrete expected card type to satisfy type checkers. + card = card_class.from_template(CardData()) # type: ignore + + for key, value in metadata.items(): + if key == "model-index": + # if the new metadata doesn't include a name, either use existing one or repo name + if "name" not in value[0]: + value[0]["name"] = getattr(card, "model_name", repo_id) + model_name, new_results = model_index_to_eval_results(value) + if card.data.eval_results is None: + card.data.eval_results = new_results + card.data.model_name = model_name + else: + existing_results = card.data.eval_results + + # Iterate over new results + # Iterate over existing results + # If both results describe the same metric but value is different: + # If overwrite=True: overwrite the metric value + # Else: raise ValueError + # Else: append new result to existing ones. + for new_result in new_results: + result_found = False + for existing_result in existing_results: + if new_result.is_equal_except_value(existing_result): + if new_result != existing_result and not overwrite: + raise ValueError( + "You passed a new value for the existing metric" + f" 'name: {new_result.metric_name}, type: " + f"{new_result.metric_type}'. Set `overwrite=True`" + " to overwrite existing metrics." + ) + result_found = True + existing_result.metric_value = new_result.metric_value + if existing_result.verified is True: + existing_result.verify_token = new_result.verify_token + if not result_found: + card.data.eval_results.append(new_result) + else: + # Any metadata that is not a result metric + if card.data.get(key) is not None and not overwrite and card.data.get(key) != value: + raise ValueError( + f"You passed a new value for the existing meta data field '{key}'." + " Set `overwrite=True` to overwrite existing metadata." + ) + else: + card.data[key] = value + + return card.push_to_hub( + repo_id, + token=token, + repo_type=repo_type, + commit_message=commit_message, + commit_description=commit_description, + create_pr=create_pr, + revision=revision, + parent_commit=parent_commit, + ) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/repocard_data.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/repocard_data.py new file mode 100644 index 0000000000000000000000000000000000000000..ea123906f3755e6b54168fd63d267103acb318a7 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/huggingface_hub/repocard_data.py @@ -0,0 +1,770 @@ +import copy +from collections import defaultdict +from dataclasses import dataclass +from typing import Any + +from huggingface_hub.utils import logging, yaml_dump + + +logger = logging.get_logger(__name__) + + +@dataclass +class EvalResult: + """ + Flattened representation of individual evaluation results found in model-index of Model Cards. + + For more information on the model-index spec, see https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1. + + Args: + task_type (`str`): + The task identifier. Example: "image-classification". + dataset_type (`str`): + The dataset identifier. Example: "common_voice". Use dataset id from https://hf.co/datasets. + dataset_name (`str`): + A pretty name for the dataset. Example: "Common Voice (French)". + metric_type (`str`): + The metric identifier. Example: "wer". Use metric id from https://hf.co/metrics. + metric_value (`Any`): + The metric value. Example: 0.9 or "20.0 ± 1.2". + task_name (`str`, *optional*): + A pretty name for the task. Example: "Speech Recognition". + dataset_config (`str`, *optional*): + The name of the dataset configuration used in `load_dataset()`. + Example: fr in `load_dataset("common_voice", "fr")`. See the `datasets` docs for more info: + https://hf.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name + dataset_split (`str`, *optional*): + The split used in `load_dataset()`. Example: "test". + dataset_revision (`str`, *optional*): + The revision (AKA Git Sha) of the dataset used in `load_dataset()`. + Example: 5503434ddd753f426f4b38109466949a1217c2bb + dataset_args (`dict[str, Any]`, *optional*): + The arguments passed during `Metric.compute()`. Example for `bleu`: `{"max_order": 4}` + metric_name (`str`, *optional*): + A pretty name for the metric. Example: "Test WER". + metric_config (`str`, *optional*): + The name of the metric configuration used in `load_metric()`. + Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`. + See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations + metric_args (`dict[str, Any]`, *optional*): + The arguments passed during `Metric.compute()`. Example for `bleu`: max_order: 4 + verified (`bool`, *optional*): + Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set. + verify_token (`str`, *optional*): + A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. + source_name (`str`, *optional*): + The name of the source of the evaluation result. Example: "Open LLM Leaderboard". + source_url (`str`, *optional*): + The URL of the source of the evaluation result. Example: "https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard". + """ + + # Required + + # The task identifier + # Example: automatic-speech-recognition + task_type: str + + # The dataset identifier + # Example: common_voice. Use dataset id from https://hf.co/datasets + dataset_type: str + + # A pretty name for the dataset. + # Example: Common Voice (French) + dataset_name: str + + # The metric identifier + # Example: wer. Use metric id from https://hf.co/metrics + metric_type: str + + # Value of the metric. + # Example: 20.0 or "20.0 ± 1.2" + metric_value: Any + + # Optional + + # A pretty name for the task. + # Example: Speech Recognition + task_name: str | None = None + + # The name of the dataset configuration used in `load_dataset()`. + # Example: fr in `load_dataset("common_voice", "fr")`. + # See the `datasets` docs for more info: + # https://huggingface.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name + dataset_config: str | None = None + + # The split used in `load_dataset()`. + # Example: test + dataset_split: str | None = None + + # The revision (AKA Git Sha) of the dataset used in `load_dataset()`. + # Example: 5503434ddd753f426f4b38109466949a1217c2bb + dataset_revision: str | None = None + + # The arguments passed during `Metric.compute()`. + # Example for `bleu`: max_order: 4 + dataset_args: dict[str, Any] | None = None + + # A pretty name for the metric. + # Example: Test WER + metric_name: str | None = None + + # The name of the metric configuration used in `load_metric()`. + # Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`. + # See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations + metric_config: str | None = None + + # The arguments passed during `Metric.compute()`. + # Example for `bleu`: max_order: 4 + metric_args: dict[str, Any] | None = None + + # Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set. + verified: bool | None = None + + # A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. + verify_token: str | None = None + + # The name of the source of the evaluation result. + # Example: Open LLM Leaderboard + source_name: str | None = None + + # The URL of the source of the evaluation result. + # Example: https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard + source_url: str | None = None + + @property + def unique_identifier(self) -> tuple: + """Returns a tuple that uniquely identifies this evaluation.""" + return ( + self.task_type, + self.dataset_type, + self.dataset_config, + self.dataset_split, + self.dataset_revision, + ) + + def is_equal_except_value(self, other: "EvalResult") -> bool: + """ + Return True if `self` and `other` describe exactly the same metric but with a + different value. + """ + for key, _ in self.__dict__.items(): + if key == "metric_value": + continue + # For metrics computed by Hugging Face's evaluation service, `verify_token` is derived from `metric_value`, + # so we exclude it here in the comparison. + if key != "verify_token" and getattr(self, key) != getattr(other, key): + return False + return True + + def __post_init__(self) -> None: + if self.source_name is not None and self.source_url is None: + raise ValueError("If `source_name` is provided, `source_url` must also be provided.") + + +@dataclass +class CardData: + """Structure containing metadata from a RepoCard. + + [`CardData`] is the parent class of [`ModelCardData`] and [`DatasetCardData`]. + + Metadata can be exported as a dictionary or YAML. Export can be customized to alter the representation of the data + (example: flatten evaluation results). `CardData` behaves as a dictionary (can get, pop, set values) but do not + inherit from `dict` to allow this export step. + """ + + def __init__(self, ignore_metadata_errors: bool = False, **kwargs): + self.__dict__.update(kwargs) + + def to_dict(self): + """Converts CardData to a dict. + + Returns: + `dict`: CardData represented as a dictionary ready to be dumped to a YAML + block for inclusion in a README.md file. + """ + + data_dict = copy.deepcopy(self.__dict__) + self._to_dict(data_dict) + return {key: value for key, value in data_dict.items() if value is not None} + + def _to_dict(self, data_dict): + """Use this method in child classes to alter the dict representation of the data. Alter the dict in-place. + + Args: + data_dict (`dict`): The raw dict representation of the card data. + """ + pass + + def to_yaml(self, line_break=None, original_order: list[str] | None = None) -> str: + """Dumps CardData to a YAML block for inclusion in a README.md file. + + Args: + line_break (str, *optional*): + The line break to use when dumping to yaml. + + Returns: + `str`: CardData represented as a YAML block. + """ + if original_order: + self.__dict__ = { + k: self.__dict__[k] + for k in original_order + list(set(self.__dict__.keys()) - set(original_order)) + if k in self.__dict__ + } + return yaml_dump(self.to_dict(), sort_keys=False, line_break=line_break).strip() + + def __repr__(self): + return repr(self.__dict__) + + def __str__(self): + return self.to_yaml() + + def get(self, key: str, default: Any = None) -> Any: + """Get value for a given metadata key.""" + value = self.__dict__.get(key) + return default if value is None else value + + def pop(self, key: str, default: Any = None) -> Any: + """Pop value for a given metadata key.""" + return self.__dict__.pop(key, default) + + def __getitem__(self, key: str) -> Any: + """Get value for a given metadata key.""" + return self.__dict__[key] + + def __setitem__(self, key: str, value: Any) -> None: + """Set value for a given metadata key.""" + self.__dict__[key] = value + + def __contains__(self, key: str) -> bool: + """Check if a given metadata key is set.""" + return key in self.__dict__ + + def __len__(self) -> int: + """Return the number of metadata keys set.""" + return len(self.__dict__) + + +def _validate_eval_results( + eval_results: EvalResult | list[EvalResult] | None, + model_name: str | None, +) -> list[EvalResult]: + if eval_results is None: + return [] + if isinstance(eval_results, EvalResult): + eval_results = [eval_results] + if not isinstance(eval_results, list) or not all(isinstance(r, EvalResult) for r in eval_results): + raise ValueError( + f"`eval_results` should be of type `EvalResult` or a list of `EvalResult`, got {type(eval_results)}." + ) + if model_name is None: + raise ValueError("Passing `eval_results` requires `model_name` to be set.") + return eval_results + + +class ModelCardData(CardData): + """Model Card Metadata that is used by Hugging Face Hub when included at the top of your README.md + + Args: + base_model (`str` or `list[str]`, *optional*): + The identifier of the base model from which the model derives. This is applicable for example if your model is a + fine-tune or adapter of an existing model. The value must be the ID of a model on the Hub (or a list of IDs + if your model derives from multiple models). Defaults to None. + datasets (`Union[str, list[str]]`, *optional*): + Dataset or list of datasets that were used to train this model. Should be a dataset ID + found on https://hf.co/datasets. Defaults to None. + eval_results (`Union[list[EvalResult], EvalResult]`, *optional*): + List of `huggingface_hub.EvalResult` that define evaluation results of the model. If provided, + `model_name` is used to as a name on PapersWithCode's leaderboards. Defaults to `None`. + language (`Union[str, list[str]]`, *optional*): + Language of model's training data or metadata. It must be an ISO 639-1, 639-2 or + 639-3 code (two/three letters), or a special value like "code", "multilingual". Defaults to `None`. + library_name (`str`, *optional*): + Name of library used by this model. Example: keras or any library from + https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/model-libraries.ts. + Defaults to None. + license (`str`, *optional*): + License of this model. Example: apache-2.0 or any license from + https://huggingface.co/docs/hub/repositories-licenses. Defaults to None. + license_name (`str`, *optional*): + Name of the license of this model. Defaults to None. To be used in conjunction with `license_link`. + Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a name. In that case, use `license` instead. + license_link (`str`, *optional*): + Link to the license of this model. Defaults to None. To be used in conjunction with `license_name`. + Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a link. In that case, use `license` instead. + metrics (`list[str]`, *optional*): + List of metrics used to evaluate this model. Should be a metric name that can be found + at https://hf.co/metrics. Example: 'accuracy'. Defaults to None. + model_name (`str`, *optional*): + A name for this model. It is used along with + `eval_results` to construct the `model-index` within the card's metadata. The name + you supply here is what will be used on PapersWithCode's leaderboards. If None is provided + then the repo name is used as a default. Defaults to None. + pipeline_tag (`str`, *optional*): + The pipeline tag associated with the model. Example: "text-classification". + tags (`list[str]`, *optional*): + List of tags to add to your model that can be used when filtering on the Hugging + Face Hub. Defaults to None. + ignore_metadata_errors (`str`): + If True, errors while parsing the metadata section will be ignored. Some information might be lost during + the process. Use it at your own risk. + kwargs (`dict`, *optional*): + Additional metadata that will be added to the model card. Defaults to None. + + Example: + ```python + >>> from huggingface_hub import ModelCardData + >>> card_data = ModelCardData( + ... language="en", + ... license="mit", + ... library_name="timm", + ... tags=['image-classification', 'resnet'], + ... ) + >>> card_data.to_dict() + {'language': 'en', 'license': 'mit', 'library_name': 'timm', 'tags': ['image-classification', 'resnet']} + + ``` + """ + + def __init__( + self, + *, + base_model: str | list[str] | None = None, + datasets: str | list[str] | None = None, + eval_results: list[EvalResult] | None = None, + language: str | list[str] | None = None, + library_name: str | None = None, + license: str | None = None, + license_name: str | None = None, + license_link: str | None = None, + metrics: list[str] | None = None, + model_name: str | None = None, + pipeline_tag: str | None = None, + tags: list[str] | None = None, + ignore_metadata_errors: bool = False, + **kwargs, + ): + self.base_model = base_model + self.datasets = datasets + self.eval_results = eval_results + self.language = language + self.library_name = library_name + self.license = license + self.license_name = license_name + self.license_link = license_link + self.metrics = metrics + self.model_name = model_name + self.pipeline_tag = pipeline_tag + self.tags = _to_unique_list(tags) + + model_index = kwargs.pop("model-index", None) + if model_index: + try: + model_name, eval_results = model_index_to_eval_results(model_index) + self.model_name = model_name + self.eval_results = eval_results + except (KeyError, TypeError) as error: + if ignore_metadata_errors: + logger.warning("Invalid model-index. Not loading eval results into CardData.") + else: + raise ValueError( + f"Invalid `model_index` in metadata cannot be parsed: {error.__class__} {error}. Pass" + " `ignore_metadata_errors=True` to ignore this error while loading a Model Card. Warning:" + " some information will be lost. Use it at your own risk." + ) + + super().__init__(**kwargs) + + if self.eval_results: + try: + self.eval_results = _validate_eval_results(self.eval_results, self.model_name) + except Exception as e: + if ignore_metadata_errors: + logger.warning(f"Failed to validate eval_results: {e}. Not loading eval results into CardData.") + else: + raise ValueError(f"Failed to validate eval_results: {e}") from e + + def _to_dict(self, data_dict): + """Format the internal data dict. In this case, we convert eval results to a valid model index""" + if self.eval_results is not None: + data_dict["model-index"] = eval_results_to_model_index(self.model_name, self.eval_results) # type: ignore + del data_dict["eval_results"], data_dict["model_name"] + + +class DatasetCardData(CardData): + """Dataset Card Metadata that is used by Hugging Face Hub when included at the top of your README.md + + Args: + language (`list[str]`, *optional*): + Language of dataset's data or metadata. It must be an ISO 639-1, 639-2 or + 639-3 code (two/three letters), or a special value like "code", "multilingual". + license (`Union[str, list[str]]`, *optional*): + License(s) of this dataset. Example: apache-2.0 or any license from + https://huggingface.co/docs/hub/repositories-licenses. + annotations_creators (`Union[str, list[str]]`, *optional*): + How the annotations for the dataset were created. + Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'no-annotation', 'other'. + language_creators (`Union[str, list[str]]`, *optional*): + How the text-based data in the dataset was created. + Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'other' + multilinguality (`Union[str, list[str]]`, *optional*): + Whether the dataset is multilingual. + Options are: 'monolingual', 'multilingual', 'translation', 'other'. + size_categories (`Union[str, list[str]]`, *optional*): + The number of examples in the dataset. Options are: 'n<1K', '1K1T', and 'other'. + source_datasets (`list[str]]`, *optional*): + Indicates whether the dataset is an original dataset or extended from another existing dataset. + Options are: 'original' and 'extended'. + task_categories (`Union[str, list[str]]`, *optional*): + What categories of task does the dataset support? + task_ids (`Union[str, list[str]]`, *optional*): + What specific tasks does the dataset support? + paperswithcode_id (`str`, *optional*): + ID of the dataset on PapersWithCode. + pretty_name (`str`, *optional*): + A more human-readable name for the dataset. (ex. "Cats vs. Dogs") + train_eval_index (`dict`, *optional*): + A dictionary that describes the necessary spec for doing evaluation on the Hub. + If not provided, it will be gathered from the 'train-eval-index' key of the kwargs. + config_names (`Union[str, list[str]]`, *optional*): + A list of the available dataset configs for the dataset. + """ + + def __init__( + self, + *, + language: str | list[str] | None = None, + license: str | list[str] | None = None, + annotations_creators: str | list[str] | None = None, + language_creators: str | list[str] | None = None, + multilinguality: str | list[str] | None = None, + size_categories: str | list[str] | None = None, + source_datasets: list[str] | None = None, + task_categories: str | list[str] | None = None, + task_ids: str | list[str] | None = None, + paperswithcode_id: str | None = None, + pretty_name: str | None = None, + train_eval_index: dict | None = None, + config_names: str | list[str] | None = None, + ignore_metadata_errors: bool = False, + **kwargs, + ): + self.annotations_creators = annotations_creators + self.language_creators = language_creators + self.language = language + self.license = license + self.multilinguality = multilinguality + self.size_categories = size_categories + self.source_datasets = source_datasets + self.task_categories = task_categories + self.task_ids = task_ids + self.paperswithcode_id = paperswithcode_id + self.pretty_name = pretty_name + self.config_names = config_names + + # TODO - maybe handle this similarly to EvalResult? + self.train_eval_index = train_eval_index or kwargs.pop("train-eval-index", None) + super().__init__(**kwargs) + + def _to_dict(self, data_dict): + data_dict["train-eval-index"] = data_dict.pop("train_eval_index") + + +class SpaceCardData(CardData): + """Space Card Metadata that is used by Hugging Face Hub when included at the top of your README.md + + To get an exhaustive reference of Spaces configuration, please visit https://huggingface.co/docs/hub/spaces-config-reference#spaces-configuration-reference. + + Args: + title (`str`, *optional*) + Title of the Space. + sdk (`str`, *optional*) + SDK of the Space (one of `gradio`, `streamlit`, `docker`, or `static`). + sdk_version (`str`, *optional*) + Version of the used SDK (if Gradio/Streamlit sdk). + python_version (`str`, *optional*) + Python version used in the Space (if Gradio/Streamlit sdk). + app_file (`str`, *optional*) + Path to your main application file (which contains either gradio or streamlit Python code, or static html code). + Path is relative to the root of the repository. + app_port (`str`, *optional*) + Port on which your application is running. Used only if sdk is `docker`. + license (`str`, *optional*) + License of this model. Example: apache-2.0 or any license from + https://huggingface.co/docs/hub/repositories-licenses. + duplicated_from (`str`, *optional*) + ID of the original Space if this is a duplicated Space. + models (list[`str`], *optional*) + List of models related to this Space. Should be a dataset ID found on https://hf.co/models. + datasets (`list[str]`, *optional*) + List of datasets related to this Space. Should be a dataset ID found on https://hf.co/datasets. + tags (`list[str]`, *optional*) + List of tags to add to your Space that can be used when filtering on the Hub. + ignore_metadata_errors (`str`): + If True, errors while parsing the metadata section will be ignored. Some information might be lost during + the process. Use it at your own risk. + kwargs (`dict`, *optional*): + Additional metadata that will be added to the space card. + + Example: + ```python + >>> from huggingface_hub import SpaceCardData + >>> card_data = SpaceCardData( + ... title="Dreambooth Training", + ... license="mit", + ... sdk="gradio", + ... duplicated_from="multimodalart/dreambooth-training" + ... ) + >>> card_data.to_dict() + {'title': 'Dreambooth Training', 'sdk': 'gradio', 'license': 'mit', 'duplicated_from': 'multimodalart/dreambooth-training'} + ``` + """ + + def __init__( + self, + *, + title: str | None = None, + sdk: str | None = None, + sdk_version: str | None = None, + python_version: str | None = None, + app_file: str | None = None, + app_port: int | None = None, + license: str | None = None, + duplicated_from: str | None = None, + models: list[str] | None = None, + datasets: list[str] | None = None, + tags: list[str] | None = None, + ignore_metadata_errors: bool = False, + **kwargs, + ): + self.title = title + self.sdk = sdk + self.sdk_version = sdk_version + self.python_version = python_version + self.app_file = app_file + self.app_port = app_port + self.license = license + self.duplicated_from = duplicated_from + self.models = models + self.datasets = datasets + self.tags = _to_unique_list(tags) + super().__init__(**kwargs) + + +def model_index_to_eval_results(model_index: list[dict[str, Any]]) -> tuple[str, list[EvalResult]]: + """Takes in a model index and returns the model name and a list of `huggingface_hub.EvalResult` objects. + + A detailed spec of the model index can be found here: + https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1 + + Args: + model_index (`list[dict[str, Any]]`): + A model index data structure, likely coming from a README.md file on the + Hugging Face Hub. + + Returns: + model_name (`str`): + The name of the model as found in the model index. This is used as the + identifier for the model on leaderboards like PapersWithCode. + eval_results (`list[EvalResult]`): + A list of `huggingface_hub.EvalResult` objects containing the metrics + reported in the provided model_index. + + Example: + ```python + >>> from huggingface_hub.repocard_data import model_index_to_eval_results + >>> # Define a minimal model index + >>> model_index = [ + ... { + ... "name": "my-cool-model", + ... "results": [ + ... { + ... "task": { + ... "type": "image-classification" + ... }, + ... "dataset": { + ... "type": "beans", + ... "name": "Beans" + ... }, + ... "metrics": [ + ... { + ... "type": "accuracy", + ... "value": 0.9 + ... } + ... ] + ... } + ... ] + ... } + ... ] + >>> model_name, eval_results = model_index_to_eval_results(model_index) + >>> model_name + 'my-cool-model' + >>> eval_results[0].task_type + 'image-classification' + >>> eval_results[0].metric_type + 'accuracy' + + ``` + """ + + eval_results = [] + for elem in model_index: + name = elem["name"] + results = elem["results"] + for result in results: + task_type = result["task"]["type"] + task_name = result["task"].get("name") + dataset_type = result["dataset"]["type"] + dataset_name = result["dataset"]["name"] + dataset_config = result["dataset"].get("config") + dataset_split = result["dataset"].get("split") + dataset_revision = result["dataset"].get("revision") + dataset_args = result["dataset"].get("args") + source_name = result.get("source", {}).get("name") + source_url = result.get("source", {}).get("url") + + for metric in result["metrics"]: + metric_type = metric["type"] + metric_value = metric["value"] + metric_name = metric.get("name") + metric_args = metric.get("args") + metric_config = metric.get("config") + verified = metric.get("verified") + verify_token = metric.get("verifyToken") + + eval_result = EvalResult( + task_type=task_type, # Required + dataset_type=dataset_type, # Required + dataset_name=dataset_name, # Required + metric_type=metric_type, # Required + metric_value=metric_value, # Required + task_name=task_name, + dataset_config=dataset_config, + dataset_split=dataset_split, + dataset_revision=dataset_revision, + dataset_args=dataset_args, + metric_name=metric_name, + metric_args=metric_args, + metric_config=metric_config, + verified=verified, + verify_token=verify_token, + source_name=source_name, + source_url=source_url, + ) + eval_results.append(eval_result) + return name, eval_results + + +def _remove_none(obj): + """ + Recursively remove `None` values from a dict. Borrowed from: https://stackoverflow.com/a/20558778 + """ + if isinstance(obj, (list, tuple, set)): + return type(obj)(_remove_none(x) for x in obj if x is not None) + elif isinstance(obj, dict): + return type(obj)((_remove_none(k), _remove_none(v)) for k, v in obj.items() if k is not None and v is not None) + else: + return obj + + +def eval_results_to_model_index(model_name: str, eval_results: list[EvalResult]) -> list[dict[str, Any]]: + """Takes in given model name and list of `huggingface_hub.EvalResult` and returns a + valid model-index that will be compatible with the format expected by the + Hugging Face Hub. + + Args: + model_name (`str`): + Name of the model (ex. "my-cool-model"). This is used as the identifier + for the model on leaderboards like PapersWithCode. + eval_results (`list[EvalResult]`): + List of `huggingface_hub.EvalResult` objects containing the metrics to be + reported in the model-index. + + Returns: + model_index (`list[dict[str, Any]]`): The eval_results converted to a model-index. + + Example: + ```python + >>> from huggingface_hub.repocard_data import eval_results_to_model_index, EvalResult + >>> # Define minimal eval_results + >>> eval_results = [ + ... EvalResult( + ... task_type="image-classification", # Required + ... dataset_type="beans", # Required + ... dataset_name="Beans", # Required + ... metric_type="accuracy", # Required + ... metric_value=0.9, # Required + ... ) + ... ] + >>> eval_results_to_model_index("my-cool-model", eval_results) + [{'name': 'my-cool-model', 'results': [{'task': {'type': 'image-classification'}, 'dataset': {'name': 'Beans', 'type': 'beans'}, 'metrics': [{'type': 'accuracy', 'value': 0.9}]}]}] + + ``` + """ + + # Metrics are reported on a unique task-and-dataset basis. + # Here, we make a map of those pairs and the associated EvalResults. + task_and_ds_types_map: dict[Any, list[EvalResult]] = defaultdict(list) + for eval_result in eval_results: + task_and_ds_types_map[eval_result.unique_identifier].append(eval_result) + + # Use the map from above to generate the model index data. + model_index_data: list[dict[str, Any]] = [] + for results in task_and_ds_types_map.values(): + # All items from `results` share same metadata + sample_result = results[0] + data: dict[str, Any] = { + "task": { + "type": sample_result.task_type, + "name": sample_result.task_name, + }, + "dataset": { + "name": sample_result.dataset_name, + "type": sample_result.dataset_type, + "config": sample_result.dataset_config, + "split": sample_result.dataset_split, + "revision": sample_result.dataset_revision, + "args": sample_result.dataset_args, + }, + "metrics": [ + { + "type": result.metric_type, + "value": result.metric_value, + "name": result.metric_name, + "config": result.metric_config, + "args": result.metric_args, + "verified": result.verified, + "verifyToken": result.verify_token, + } + for result in results + ], + } + if sample_result.source_url is not None: + source: dict[str, str] = { + "url": sample_result.source_url, + } + if sample_result.source_name is not None: + source["name"] = sample_result.source_name + data["source"] = source + model_index_data.append(data) + + # TODO - Check if there cases where this list is longer than one? + # Finally, the model index itself is list of dicts. + model_index = [ + { + "name": model_name, + "results": model_index_data, + } + ] + return _remove_none(model_index) + + +def _to_unique_list(tags: list[str] | None) -> list[str] | None: + if tags is None: + return tags + unique_tags = [] # make tags unique + keep order explicitly + for tag in tags: + if tag not in unique_tags: + unique_tags.append(tag) + return unique_tags diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna-3.15.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna-3.15.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna-3.15.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna-3.15.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna-3.15.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3dd388cb837ee9937f0ba8ec25248b0fc5b9472f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna-3.15.dist-info/METADATA @@ -0,0 +1,194 @@ +Metadata-Version: 2.4 +Name: idna +Version: 3.15 +Summary: Internationalized Domain Names in Applications (IDNA) +Author-email: Kim Davies +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +License-Expression: BSD-3-Clause +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: System Administrators +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Internet :: Name Service (DNS) +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Utilities +License-File: LICENSE.md +Requires-Dist: ruff >= 0.6.2 ; extra == "all" +Requires-Dist: mypy >= 1.11.2 ; extra == "all" +Requires-Dist: pytest >= 8.3.2 ; extra == "all" +Project-URL: Changelog, https://github.com/kjd/idna/blob/master/HISTORY.md +Project-URL: Issue tracker, https://github.com/kjd/idna/issues +Project-URL: Source, https://github.com/kjd/idna +Provides-Extra: all + +# Internationalized Domain Names in Applications (IDNA) + +Support for [Internationalized Domain Names in +Applications (IDNA)](https://tools.ietf.org/html/rfc5891) +and [Unicode IDNA Compatibility Processing](https://unicode.org/reports/tr46/). + +The latest versions of these standards supplied here provide +more comprehensive language coverage and reduce the potential of +allowing domains with known security vulnerabilities. This library +is a suitable replacement for the "encodings.idna" +module that comes with the Python standard library, but which +only supports an older superseded IDNA specification from 2003. + +Basic functions are simply executed: + +```pycon +>>> import idna +>>> idna.encode('ドメイン.テスト') +b'xn--eckwd4c7c.xn--zckzah' +>>> print(idna.decode('xn--eckwd4c7c.xn--zckzah')) +ドメイン.テスト +``` + + +## Installation + +This package is available for installation from PyPI via the +typical mechanisms, such as: + +```bash +$ python3 -m pip install idna +``` + + +## Usage + +For typical usage, the `encode` and `decode` functions will take a +domain name argument and perform a conversion to ASCII-compatible encoding +(known as A-labels), or to Unicode strings (known as U-labels) +respectively. + +```pycon +>>> import idna +>>> idna.encode('ドメイン.テスト') +b'xn--eckwd4c7c.xn--zckzah' +>>> print(idna.decode('xn--eckwd4c7c.xn--zckzah')) +ドメイン.テスト +``` + +Conversions can be applied at a per-label basis using the `ulabel` or +`alabel` functions if necessary: + +```pycon +>>> idna.alabel('测试') +b'xn--0zwm56d' +``` + + +### Compatibility Mapping (UTS #46) + +This library provides support for [Unicode IDNA Compatibility +Processing](https://unicode.org/reports/tr46/) which normalizes input from +different potential ways a user may input a domain prior to performing the IDNA +conversion operations. This functionality, known as a +[mapping](https://tools.ietf.org/html/rfc5895), is considered by the +specification to be a local user-interface issue distinct from IDNA +conversion functionality. + +For example, "Königsgäßchen" is not a permissible label as *LATIN +CAPITAL LETTER K* is not allowed (nor are capital letters in general). +UTS 46 will convert this into lower case prior to applying the IDNA +conversion. + +```pycon +>>> import idna +>>> idna.encode('Königsgäßchen') +... +idna.core.InvalidCodepoint: Codepoint U+004B at position 1 of 'Königsgäßchen' not allowed +>>> idna.encode('Königsgäßchen', uts46=True) +b'xn--knigsgchen-b4a3dun' +>>> print(idna.decode('xn--knigsgchen-b4a3dun')) +königsgäßchen +``` + + +## Exceptions + +All errors raised during the conversion following the specification +should raise an exception derived from the `idna.IDNAError` base +class. + +More specific exceptions that may be generated as `idna.IDNABidiError` +when the error reflects an illegal combination of left-to-right and +right-to-left characters in a label; `idna.InvalidCodepoint` when +a specific codepoint is an illegal character in an IDN label (i.e. +INVALID); and `idna.InvalidCodepointContext` when the codepoint is +illegal based on its position in the string (i.e. it is CONTEXTO or CONTEXTJ +but the contextual requirements are not satisfied.) + +## Building and Diagnostics + +The IDNA and UTS 46 functionality relies upon pre-calculated lookup +tables for performance. These tables are derived from computing against +eligibility criteria in the respective standards using the command-line +script `tools/idna-data`. + +This tool will fetch relevant codepoint data from the Unicode repository +and perform the required calculations to identify eligibility. There are +three main modes: + +* `idna-data make-libdata`. Generates `idnadata.py` and + `uts46data.py`, the pre-calculated lookup tables used for IDNA and + UTS 46 conversions. Implementers who wish to track this library against + a different Unicode version may use this tool to manually generate a + different version of the `idnadata.py` and `uts46data.py` files. + +* `idna-data make-table`. Generate a table of the IDNA disposition + (e.g. PVALID, CONTEXTJ, CONTEXTO) in the format found in Appendix + B.1 of RFC 5892 and the pre-computed tables published by [IANA](https://www.iana.org/). + +* `idna-data U+0061`. Prints debugging output on the various + properties associated with an individual Unicode codepoint (in this + case, U+0061), that are used to assess the IDNA and UTS 46 status of a + codepoint. This is helpful in debugging or analysis. + +The tool accepts a number of arguments, described using `idna-data -h`. +Most notably, the `--version` argument allows the specification +of the version of Unicode to be used in computing the table data. For +example, `idna-data --version 9.0.0 make-libdata` will generate +library data against Unicode 9.0.0. + + +## Additional Notes + +* **Packages**. The latest tagged release version is published in the + [Python Package Index](https://pypi.org/project/idna/). + +* **Version support**. This library supports Python 3.8 and higher. + As this library serves as a low-level toolkit for a variety of + applications, many of which strive for broad compatibility with older + Python versions, there is no rush to remove older interpreter support. + Support for older versions are likely to be removed from new releases + as automated tests can no longer easily be run, i.e. once the Python + version is officially end-of-life. + +* **Testing**. The library has a test suite based on each rule of the + IDNA specification, as well as tests that are provided as part of the + Unicode Technical Standard 46, [Unicode IDNA Compatibility Processing](https://unicode.org/reports/tr46/). + +* **Emoji**. It is an occasional request to support emoji domains in + this library. Encoding of symbols like emoji is expressly prohibited by + the IDNA technical standard, and emoji domains are broadly phased + out across the domain industry due to associated security risks. + +* **Transitional processing**. Unicode 16.0.0 removed transitional + processing so the `transitional` argument for the encode() method + no longer has any effect and will be removed at a later date. + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna-3.15.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna-3.15.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..7cd67edef918710b7e5a139dd5d058341d8af3d1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna-3.15.dist-info/RECORD @@ -0,0 +1,22 @@ +idna-3.15.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +idna-3.15.dist-info/METADATA,sha256=y4rCRb8knJ4jRkJ7xUu_eZcclre_a0aGLkM1-nYAGCc,7699 +idna-3.15.dist-info/RECORD,, +idna-3.15.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +idna-3.15.dist-info/licenses/LICENSE.md,sha256=GppPDj1HmickDd1ZqRN6ZqtKD539yMphiMwL_YUYfwQ,1541 +idna/__init__.py,sha256=MPqNDLZbXqGaNdXxAFhiqFPKEQXju2jNQhCey6-5eJM,868 +idna/__pycache__/__init__.cpython-311.pyc,, +idna/__pycache__/codec.cpython-311.pyc,, +idna/__pycache__/compat.cpython-311.pyc,, +idna/__pycache__/core.cpython-311.pyc,, +idna/__pycache__/idnadata.cpython-311.pyc,, +idna/__pycache__/intranges.cpython-311.pyc,, +idna/__pycache__/package_data.cpython-311.pyc,, +idna/__pycache__/uts46data.cpython-311.pyc,, +idna/codec.py,sha256=wtyXiDNWK2PtIs8LAhTHR7FFCNC4EcMwwASksHJqBxs,5047 +idna/compat.py,sha256=AepA39ceRHxkfHP41-FvKW5Ki-f4PfUZ90RUMlCNdmo,1353 +idna/core.py,sha256=7rMnUtssWtnkkXrR7lRAXvEZe2xKtLcc49dZDN2ATxU,23119 +idna/idnadata.py,sha256=EYkhqhOze0Whw1pIMum_-qEHM-8utUwc_IBoIUWW8Go,92613 +idna/intranges.py,sha256=egpSEXYDJ6BE0Ejo8djRdhsb4JJUtyoAQ_e49GP-7VE,1882 +idna/package_data.py,sha256=adrXxBOTH4qXst7KXV_z8WJwP5OKbQfG8SOHBfFK42s,21 +idna/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +idna/uts46data.py,sha256=8Vqa3jakE4ZWYYMkt-cTkp7IzpwJEmorYDyAaAZOPI4,202681 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna-3.15.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna-3.15.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna-3.15.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cfdc030a751b089fc7e38fc88093b791605d501d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/__init__.py @@ -0,0 +1,45 @@ +from .core import ( + IDNABidiError, + IDNAError, + InvalidCodepoint, + InvalidCodepointContext, + alabel, + check_bidi, + check_hyphen_ok, + check_initial_combiner, + check_label, + check_nfc, + decode, + encode, + ulabel, + uts46_remap, + valid_contextj, + valid_contexto, + valid_label_length, + valid_string_length, +) +from .intranges import intranges_contain +from .package_data import __version__ + +__all__ = [ + "__version__", + "IDNABidiError", + "IDNAError", + "InvalidCodepoint", + "InvalidCodepointContext", + "alabel", + "check_bidi", + "check_hyphen_ok", + "check_initial_combiner", + "check_label", + "check_nfc", + "decode", + "encode", + "intranges_contain", + "ulabel", + "uts46_remap", + "valid_contextj", + "valid_contexto", + "valid_label_length", + "valid_string_length", +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/codec.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/codec.py new file mode 100644 index 0000000000000000000000000000000000000000..280dc3972cb74bd29603fa612d22ffd05bdb77cc --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/codec.py @@ -0,0 +1,159 @@ +import codecs +from typing import Any, Optional, Tuple + +from .core import IDNAError, _unicode_dots_re, alabel, decode, encode, ulabel + + +class Codec(codecs.Codec): + """Stateless IDNA 2008 codec. + + Implements the :class:`codecs.Codec` protocol so that the whole-domain + encoder (:func:`idna.encode`) and decoder (:func:`idna.decode`) are + accessible through the standard codec machinery as ``"idna2008"``. + + Only the ``"strict"`` error handler is supported; any other handler + raises :exc:`~idna.IDNAError`. + """ + + def encode(self, data: str, errors: str = "strict") -> Tuple[bytes, int]: # ty: ignore[invalid-method-override] + if errors != "strict": + raise IDNAError(f'Unsupported error handling "{errors}"') + + if not data: + return b"", 0 + + return encode(data), len(data) + + def decode(self, data: bytes, errors: str = "strict") -> Tuple[str, int]: # ty: ignore[invalid-method-override] + if errors != "strict": + raise IDNAError(f'Unsupported error handling "{errors}"') + + if not data: + return "", 0 + + return decode(data), len(data) + + +class IncrementalEncoder(codecs.BufferedIncrementalEncoder): + """Incremental IDNA 2008 encoder. + + Buffers a partial trailing label across calls until either the next + label separator is seen or ``final=True``, so that streamed input is + encoded one whole label at a time. Any of the four Unicode label + separators (``U+002E``, ``U+3002``, ``U+FF0E``, ``U+FF61``) ends a + label; the result always uses ``U+002E`` as the separator. + + Only the ``"strict"`` error handler is supported. + """ + + def _buffer_encode(self, data: str, errors: str, final: bool) -> Tuple[bytes, int]: # ty: ignore[invalid-method-override] + if errors != "strict": + raise IDNAError(f'Unsupported error handling "{errors}"') + + if not data: + return b"", 0 + + labels = _unicode_dots_re.split(data) + trailing_dot = b"" + if labels: + if not labels[-1]: + trailing_dot = b"." + del labels[-1] + elif not final: + # Keep potentially unfinished label until the next call + del labels[-1] + if labels: + trailing_dot = b"." + + result = [] + size = 0 + for label in labels: + result.append(alabel(label)) + if size: + size += 1 + size += len(label) + + # Join with U+002E + result_bytes = b".".join(result) + trailing_dot + size += len(trailing_dot) + return result_bytes, size + + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + """Incremental IDNA 2008 decoder. + + Buffers a partial trailing label across calls until either the next + label separator is seen or ``final=True``, so that streamed input is + decoded one whole label at a time. + + Only the ``"strict"`` error handler is supported. + """ + + def _buffer_decode(self, data: Any, errors: str, final: bool) -> Tuple[str, int]: # ty: ignore[invalid-method-override] + if errors != "strict": + raise IDNAError(f'Unsupported error handling "{errors}"') + + if not data: + return ("", 0) + + if not isinstance(data, str): + data = str(data, "ascii") + + labels = _unicode_dots_re.split(data) + trailing_dot = "" + if labels: + if not labels[-1]: + trailing_dot = "." + del labels[-1] + elif not final: + # Keep potentially unfinished label until the next call + del labels[-1] + if labels: + trailing_dot = "." + + result = [] + size = 0 + for label in labels: + result.append(ulabel(label)) + if size: + size += 1 + size += len(label) + + result_str = ".".join(result) + trailing_dot + size += len(trailing_dot) + return (result_str, size) + + +class StreamWriter(Codec, codecs.StreamWriter): + pass + + +class StreamReader(Codec, codecs.StreamReader): + pass + + +def search_function(name: str) -> Optional[codecs.CodecInfo]: + """Codec search function registered with :mod:`codecs`. + + Returns a :class:`codecs.CodecInfo` for the ``"idna2008"`` codec name + so that ``str.encode("idna2008")`` and ``bytes.decode("idna2008")`` + invoke the IDNA 2008 codec defined in this module. + + :param name: The codec name being looked up. + :returns: A :class:`codecs.CodecInfo` instance if ``name`` is + ``"idna2008"``, otherwise ``None``. + """ + if name != "idna2008": + return None + return codecs.CodecInfo( + name=name, + encode=Codec().encode, + decode=Codec().decode, # type: ignore + incrementalencoder=IncrementalEncoder, + incrementaldecoder=IncrementalDecoder, + streamwriter=StreamWriter, + streamreader=StreamReader, + ) + + +codecs.register(search_function) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/compat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..1d01e3d9750860e6ec87fb7c0955cee6bcd9fcc1 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/compat.py @@ -0,0 +1,41 @@ +from typing import Any, Union + +from .core import decode, encode + + +def ToASCII(label: str) -> bytes: + """Compatibility shim for :rfc:`3490` ``ToASCII``. + + Delegates to :func:`idna.encode` (IDNA 2008). Provided to ease porting + of code written against the legacy :mod:`encodings.idna` API; new code + should call :func:`idna.encode` directly. + + :param label: The label or domain to encode. + :returns: The encoded form as ASCII :class:`bytes`. + """ + return encode(label) + + +def ToUnicode(label: Union[bytes, bytearray]) -> str: + """Compatibility shim for :rfc:`3490` ``ToUnicode``. + + Delegates to :func:`idna.decode` (IDNA 2008). Provided to ease porting + of code written against the legacy :mod:`encodings.idna` API; new code + should call :func:`idna.decode` directly. + + :param label: The label or domain to decode. + :returns: The decoded Unicode form. + """ + return decode(label) + + +def nameprep(s: Any) -> None: + """Stub for :rfc:`3491` Nameprep, which is not used by IDNA 2008. + + IDNA 2008 (:rfc:`5891`) replaces Nameprep with the per-codepoint + validity classes from :rfc:`5892`; this function exists only to + return a clear error if legacy code attempts to call it. + + :raises NotImplementedError: Always. + """ + raise NotImplementedError("IDNA 2008 does not utilise nameprep protocol") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/core.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/core.py new file mode 100644 index 0000000000000000000000000000000000000000..b6f9442deb35f1389e3e6184ac4dec7637ac545e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/core.py @@ -0,0 +1,620 @@ +import bisect +import re +import unicodedata +import warnings +from typing import Optional, Union + +from . import idnadata +from .intranges import intranges_contain + +_virama_combining_class = 9 +_alabel_prefix = b"xn--" +_unicode_dots_re = re.compile("[\u002e\u3002\uff0e\uff61]") + + +# Bidi category sets from RFC 5893, hoisted out of the per-codepoint loop +_bidi_rtl_first = frozenset({"R", "AL"}) +_bidi_rtl_categories = frozenset({"R", "AL", "AN"}) +_bidi_rtl_allowed = frozenset({"R", "AL", "AN", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"}) +_bidi_rtl_valid_ending = frozenset({"R", "AL", "EN", "AN"}) +_bidi_rtl_numeric = frozenset({"AN", "EN"}) +_bidi_ltr_allowed = frozenset({"L", "EN", "ES", "CS", "ET", "ON", "BN", "NSM"}) +_bidi_ltr_valid_ending = frozenset({"L", "EN"}) +_bidi_joiner_l_or_d = frozenset({ord("L"), ord("D")}) +_bidi_joiner_r_or_d = frozenset({ord("R"), ord("D")}) + + +class IDNAError(UnicodeError): + """Base exception for all IDNA-encoding related problems""" + + pass + + +class IDNABidiError(IDNAError): + """Exception when bidirectional requirements are not satisfied""" + + pass + + +class InvalidCodepoint(IDNAError): + """Exception when a disallowed or unallocated codepoint is used""" + + pass + + +class InvalidCodepointContext(IDNAError): + """Exception when the codepoint is not valid in the context it is used""" + + pass + + +def _combining_class(cp: int) -> int: + v = unicodedata.combining(chr(cp)) + if v == 0 and not unicodedata.name(chr(cp)): + raise ValueError("Unknown character in unicodedata") + return v + + +def _is_script(cp: str, script: str) -> bool: + return intranges_contain(ord(cp), idnadata.scripts[script]) + + +def _punycode(s: str) -> bytes: + return s.encode("punycode") + + +def _unot(s: int) -> str: + return f"U+{s:04X}" + + +def valid_label_length(label: Union[bytes, str]) -> bool: + """Check that a label does not exceed the maximum permitted length. + + Per :rfc:`1035` (and :rfc:`5891` §4.2.4) a DNS label must not exceed + 63 octets. The argument may be either a :class:`str` (a U-label, where + length is measured in characters) or :class:`bytes` (an A-label, where + length is measured in octets). + + :param label: The label to check. + :returns: ``True`` if the label is within the length limit, otherwise + ``False``. + """ + return len(label) <= 63 + + +def valid_string_length(domain: Union[bytes, str], trailing_dot: bool) -> bool: + """Check that a full domain name does not exceed the maximum length. + + Per :rfc:`1035`, a domain name is limited to 253 octets when no trailing + dot is present, or 254 octets when one is included. + + :param domain: The full (possibly multi-label) domain name. + :param trailing_dot: ``True`` if ``domain`` includes a trailing ``.``. + :returns: ``True`` if the domain is within the length limit, otherwise + ``False``. + """ + return len(domain) <= (254 if trailing_dot else 253) + + +def check_bidi(label: str, check_ltr: bool = False) -> bool: + """Validate the Bidi Rule from :rfc:`5893` for a single label. + + The Bidi Rule constrains how bidirectional characters (Hebrew, Arabic, + etc.) may appear within a label. By default the check is only applied + when the label contains at least one right-to-left character (Unicode + bidirectional categories ``R``, ``AL``, or ``AN``); set ``check_ltr`` + to ``True`` to apply it to LTR-only labels as well. + + :param label: The label to validate, as a Unicode string. + :param check_ltr: If ``True``, apply the rules even when the label + contains no RTL characters. + :returns: ``True`` if the label satisfies the Bidi Rule. + :raises IDNABidiError: If any of Bidi Rule conditions 1-6 are violated, + or if the directional category of a codepoint cannot be determined. + """ + # Bidi rules should only be applied if string contains RTL characters + bidi_label = False + for idx, cp in enumerate(label, 1): + direction = unicodedata.bidirectional(cp) + if direction == "": + # String likely comes from a newer version of Unicode + raise IDNABidiError(f"Unknown directionality in label {repr(label)} at position {idx}") + if direction in _bidi_rtl_categories: + bidi_label = True + if not bidi_label and not check_ltr: + return True + + # Bidi rule 1 + direction = unicodedata.bidirectional(label[0]) + if direction in _bidi_rtl_first: + rtl = True + elif direction == "L": + rtl = False + else: + raise IDNABidiError(f"First codepoint in label {repr(label)} must be directionality L, R or AL") + + valid_ending = False + number_type: Optional[str] = None + for idx, cp in enumerate(label, 1): + direction = unicodedata.bidirectional(cp) + + if rtl: + # Bidi rule 2 + if direction not in _bidi_rtl_allowed: + raise IDNABidiError(f"Invalid direction for codepoint at position {idx} in a right-to-left label") + # Bidi rule 3 + if direction in _bidi_rtl_valid_ending: + valid_ending = True + elif direction != "NSM": + valid_ending = False + # Bidi rule 4 + if direction in _bidi_rtl_numeric: + if not number_type: + number_type = direction + else: + if number_type != direction: + raise IDNABidiError("Can not mix numeral types in a right-to-left label") + else: + # Bidi rule 5 + if direction not in _bidi_ltr_allowed: + raise IDNABidiError(f"Invalid direction for codepoint at position {idx} in a left-to-right label") + # Bidi rule 6 + if direction in _bidi_ltr_valid_ending: + valid_ending = True + elif direction != "NSM": + valid_ending = False + + if not valid_ending: + raise IDNABidiError("Label ends with illegal codepoint directionality") + + return True + + +def check_initial_combiner(label: str) -> bool: + """Reject labels that begin with a combining mark. + + Per :rfc:`5891` §4.2.3.2 a label must not start with a character of + Unicode general category ``M`` (Mark). + + :param label: The label to check. + :returns: ``True`` if the first character is not a combining mark. + :raises IDNAError: If the label begins with a combining character. + """ + if unicodedata.category(label[0])[0] == "M": + raise IDNAError("Label begins with an illegal combining character") + return True + + +def check_hyphen_ok(label: str) -> bool: + """Validate the hyphen restrictions for a label. + + Per :rfc:`5891` §4.2.3.1 a label must not start or end with a hyphen + (``U+002D``), and must not have hyphens in both the third and fourth + positions (the prefix reserved for A-labels). + + :param label: The label to check. + :returns: ``True`` if the hyphen restrictions are satisfied. + :raises IDNAError: If any of the hyphen restrictions are violated. + """ + if label[2:4] == "--": + raise IDNAError("Label has disallowed hyphens in 3rd and 4th position") + if label[0] == "-" or label[-1] == "-": + raise IDNAError("Label must not start or end with a hyphen") + return True + + +def check_nfc(label: str) -> None: + """Require that a label is in Unicode Normalization Form C. + + :param label: The label to check. + :raises IDNAError: If ``label`` differs from its NFC normalisation. + """ + if unicodedata.normalize("NFC", label) != label: + raise IDNAError("Label must be in Normalization Form C") + + +def valid_contextj(label: str, pos: int) -> bool: + """Validate the CONTEXTJ rules from :rfc:`5892` Appendix A. + + These rules govern the contextual use of the joiner codepoints + ``U+200C`` (ZERO WIDTH NON-JOINER, Appendix A.1) and ``U+200D`` + (ZERO WIDTH JOINER, Appendix A.2) within a label. + + :param label: The label containing the codepoint. + :param pos: Index of the joiner codepoint within ``label``. + :returns: ``True`` if the codepoint at ``pos`` satisfies its CONTEXTJ + rule, ``False`` otherwise (including when the codepoint at + ``pos`` is not a recognised joiner). + :raises ValueError: If an adjacent codepoint has no Unicode name when + determining its combining class. + """ + cp_value = ord(label[pos]) + + if cp_value == 0x200C: + if pos > 0 and _combining_class(ord(label[pos - 1])) == _virama_combining_class: + return True + + ok = False + for i in range(pos - 1, -1, -1): + joining_type = idnadata.joining_types().get(ord(label[i])) + if joining_type == ord("T"): + continue + elif joining_type in _bidi_joiner_l_or_d: + ok = True + break + else: + break + + if not ok: + return False + + ok = False + for i in range(pos + 1, len(label)): + joining_type = idnadata.joining_types().get(ord(label[i])) + if joining_type == ord("T"): + continue + elif joining_type in _bidi_joiner_r_or_d: + ok = True + break + else: + break + return ok + + if cp_value == 0x200D: + return pos > 0 and _combining_class(ord(label[pos - 1])) == _virama_combining_class + + else: + return False + + +def valid_contexto(label: str, pos: int, exception: bool = False) -> bool: + """Validate the CONTEXTO rules from :rfc:`5892` Appendix A. + + Covers the contextual rules for codepoints such as MIDDLE DOT + (``U+00B7``), Greek lower numeral sign, Hebrew punctuation, Katakana + middle dot, and the Arabic-Indic / Extended Arabic-Indic digit ranges. + + :param label: The label containing the codepoint. + :param pos: Index of the codepoint within ``label``. + :param exception: Reserved for forward compatibility; currently unused. + :returns: ``True`` if the codepoint at ``pos`` satisfies its CONTEXTO + rule, ``False`` otherwise (including when the codepoint is not a + recognised CONTEXTO codepoint). + """ + cp_value = ord(label[pos]) + + if cp_value == 0x00B7: + return 0 < pos < len(label) - 1 and ord(label[pos - 1]) == 0x006C and ord(label[pos + 1]) == 0x006C + + elif cp_value == 0x0375: + if pos < len(label) - 1 and len(label) > 1: + return _is_script(label[pos + 1], "Greek") + return False + + elif cp_value == 0x05F3 or cp_value == 0x05F4: + if pos > 0: + return _is_script(label[pos - 1], "Hebrew") + return False + + elif cp_value == 0x30FB: + for cp in label: + if cp == "\u30fb": + continue + if _is_script(cp, "Hiragana") or _is_script(cp, "Katakana") or _is_script(cp, "Han"): + return True + return False + + elif 0x660 <= cp_value <= 0x669: + return not any(0x6F0 <= ord(cp) <= 0x06F9 for cp in label) + + elif 0x6F0 <= cp_value <= 0x6F9: + return not any(0x660 <= ord(cp) <= 0x0669 for cp in label) + + return False + + +def check_label(label: Union[str, bytes, bytearray]) -> None: + """Run the full set of IDNA 2008 validity checks on a single label. + + Applies, in order: NFC normalisation (:func:`check_nfc`), hyphen + restrictions (:func:`check_hyphen_ok`), the no-leading-combiner rule + (:func:`check_initial_combiner`), per-codepoint validity (PVALID, + CONTEXTJ, CONTEXTO classes from :rfc:`5892`), and the Bidi Rule + (:func:`check_bidi`). + + :param label: The label to validate. ``bytes`` or ``bytearray`` input + is decoded as UTF-8 first. + :raises IDNAError: If the label is empty or fails a structural rule. + :raises InvalidCodepoint: If the label contains a DISALLOWED or + UNASSIGNED codepoint. + :raises InvalidCodepointContext: If a CONTEXTJ or CONTEXTO codepoint + is not valid in its context. + :raises IDNABidiError: If the Bidi Rule is violated. + """ + if isinstance(label, (bytes, bytearray)): + label = label.decode("utf-8") + if len(label) == 0: + raise IDNAError("Empty Label") + + # Reject on domain length rather than label length so support some UTS 46 + # use cases, still reducing processing of label contextual rules + if not valid_string_length(label, trailing_dot=True): + raise IDNAError("Label too long") + + check_nfc(label) + check_hyphen_ok(label) + check_initial_combiner(label) + + for pos, cp in enumerate(label): + cp_value = ord(cp) + if intranges_contain(cp_value, idnadata.codepoint_classes["PVALID"]): + continue + elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTJ"]): + try: + if not valid_contextj(label, pos): + raise InvalidCodepointContext( + f"Joiner {_unot(cp_value)} not allowed at position {pos + 1} in {repr(label)}" + ) + except ValueError as err: + raise IDNAError( + f"Unknown codepoint adjacent to joiner {_unot(cp_value)} at position {pos + 1} in {repr(label)}" + ) from err + elif intranges_contain(cp_value, idnadata.codepoint_classes["CONTEXTO"]): + if not valid_contexto(label, pos): + raise InvalidCodepointContext( + f"Codepoint {_unot(cp_value)} not allowed at position {pos + 1} in {repr(label)}" + ) + else: + raise InvalidCodepoint(f"Codepoint {_unot(cp_value)} at position {pos + 1} of {repr(label)} not allowed") + + check_bidi(label) + + +def alabel(label: str) -> bytes: + """Convert a single U-label into its A-label form. + + The result is the ASCII-Compatible Encoding (ACE) form per :rfc:`5891` + §4: the label is validated, Punycode-encoded, and prefixed with + ``xn--``. Pure ASCII labels that are already valid IDNA labels are + returned unchanged (as :class:`bytes`). + + :param label: The label to convert, as a Unicode string. + :returns: The A-label as ASCII-encoded :class:`bytes`. + :raises IDNAError: If the label is invalid or the resulting A-label + exceeds 63 octets. + """ + try: + label_bytes = label.encode("ascii") + ulabel(label_bytes) + if not valid_label_length(label_bytes): + raise IDNAError("Label too long") + return label_bytes + except UnicodeEncodeError: + pass + + check_label(label) + label_bytes = _alabel_prefix + _punycode(label) + + if not valid_label_length(label_bytes): + raise IDNAError("Label too long") + + return label_bytes + + +def ulabel(label: Union[str, bytes, bytearray]) -> str: + """Convert a single A-label into its U-label form. + + Performs the inverse of :func:`alabel`: an ``xn--``-prefixed label is + Punycode-decoded and validated. Labels that are already Unicode (or + plain ASCII without the ACE prefix) are validated and returned as a + Unicode string. + + :param label: The label to convert. ``bytes`` or ``bytearray`` input + is treated as ASCII. + :returns: The U-label as a Unicode string. + :raises IDNAError: If the label is malformed or fails validation. + """ + if not isinstance(label, (bytes, bytearray)): + try: + label_bytes = label.encode("ascii") + except UnicodeEncodeError: + check_label(label) + return label + else: + label_bytes = bytes(label) + + label_bytes = label_bytes.lower() + if label_bytes.startswith(_alabel_prefix): + label_bytes = label_bytes[len(_alabel_prefix) :] + if not label_bytes: + raise IDNAError("Malformed A-label, no Punycode eligible content found") + if label_bytes.endswith(b"-"): + raise IDNAError("A-label must not end with a hyphen") + else: + check_label(label_bytes) + return label_bytes.decode("ascii") + + try: + label = label_bytes.decode("punycode") + except UnicodeError as err: + raise IDNAError("Invalid A-label") from err + check_label(label) + return label + + +def uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str: + """Apply the UTS #46 character mapping to a domain string. + + Implements the mapping table from `UTS #46 §4 + `_: each character is kept, + replaced, or rejected based on its status (``V``, ``M``, ``D``, ``3``, + ``I``). The result is returned in Normalisation Form C. + + :param domain: The full domain name to remap. + :param std3_rules: If ``True``, apply the stricter STD3 ASCII rules + (status ``3`` codepoints raise instead of being kept or mapped). + :param transitional: If ``True``, use transitional processing (status + ``D`` codepoints are mapped instead of kept). Transitional + processing has been removed from UTS #46 and this option is + retained only for backwards compatibility. + :returns: The remapped domain, in Normalisation Form C. + :raises InvalidCodepoint: If the domain contains a disallowed + codepoint under the chosen rules. + """ + from .uts46data import uts46data + + output = "" + + for pos, char in enumerate(domain): + code_point = ord(char) + uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (code_point, "Z")) - 1] + status = uts46row[1] + replacement: Optional[str] = None + if len(uts46row) == 3: + replacement = uts46row[2] # ty: ignore[index-out-of-bounds] + + # UTS #46 §4: V is always valid, D is deviation (kept unless transitional), + # 3 is disallowed-STD3 (kept unmapped if std3_rules is off and no mapping). + keep_as_is = ( + status == "V" or (status == "D" and not transitional) or (status == "3" and not std3_rules and replacement is None) + ) + # M is mapped, 3-with-replacement and transitional D fall through to the + # same replacement output path. + use_replacement = replacement is not None and ( + status == "M" or (status == "3" and not std3_rules) or (status == "D" and transitional) + ) + + if keep_as_is: + output += char + elif use_replacement: + assert replacement is not None # narrowed by use_replacement + output += replacement + elif status == "I": + continue + else: + raise InvalidCodepoint(f"Codepoint {_unot(code_point)} not allowed at position {pos + 1} in {repr(domain)}") + + return unicodedata.normalize("NFC", output) + + +def encode( + s: Union[str, bytes, bytearray], + strict: bool = False, + uts46: bool = False, + std3_rules: bool = False, + transitional: bool = False, +) -> bytes: + """Encode a Unicode domain name into its ASCII (A-label) form. + + Splits the input on label separators (only ``U+002E`` if ``strict`` is + set; otherwise also IDEOGRAPHIC FULL STOP ``U+3002``, FULLWIDTH FULL + STOP ``U+FF0E``, and HALFWIDTH IDEOGRAPHIC FULL STOP ``U+FF61``), + encodes each label with :func:`alabel`, and rejoins them with ``.``. + Optionally pre-processes the input through :func:`uts46_remap`. + + :param s: The domain name to encode. + :param strict: If ``True``, only ``U+002E`` is recognised as a label + separator. + :param uts46: If ``True``, apply UTS #46 mapping before encoding. + :param std3_rules: Forwarded to :func:`uts46_remap` when ``uts46`` is + ``True``. + :param transitional: Forwarded to :func:`uts46_remap` when ``uts46`` + is ``True``. Deprecated: emits a :class:`DeprecationWarning` and + will be removed in a future version. + :returns: The encoded domain as ASCII :class:`bytes`. + :raises IDNAError: If the domain is empty, contains an invalid label, + or exceeds the maximum domain length. + """ + if transitional: + warnings.warn( + "Transitional processing has been removed from UTS #46. " + "The transitional argument will be removed in a future version.", + DeprecationWarning, + stacklevel=2, + ) + if not isinstance(s, str): + try: + s = str(s, "ascii") + except (UnicodeDecodeError, TypeError) as err: + raise IDNAError("should pass a unicode string to the function rather than a byte string.") from err + if uts46: + s = uts46_remap(s, std3_rules, transitional) + + # Reject inputs that exceed the maximum DNS domain length up-front + # to avoid expensive computation on long inputs. + if not valid_string_length(s, trailing_dot=True): + raise IDNAError("Domain too long") + + trailing_dot = False + result = [] + labels = s.split(".") if strict else _unicode_dots_re.split(s) + if not labels or labels == [""]: + raise IDNAError("Empty domain") + if labels[-1] == "": + del labels[-1] + trailing_dot = True + for label in labels: + s = alabel(label) + if s: + result.append(s) + else: + raise IDNAError("Empty label") + if trailing_dot: + result.append(b"") + s = b".".join(result) + if not valid_string_length(s, trailing_dot): + raise IDNAError("Domain too long") + return s + + +def decode( + s: Union[str, bytes, bytearray], + strict: bool = False, + uts46: bool = False, + std3_rules: bool = False, +) -> str: + """Decode an A-label-encoded domain name back to Unicode. + + Splits the input on label separators (see :func:`encode` for the + rules), decodes each label with :func:`ulabel`, and rejoins them + with ``.``. Optionally pre-processes the input through + :func:`uts46_remap`. + + :param s: The domain name to decode. + :param strict: If ``True``, only ``U+002E`` is recognised as a label + separator. + :param uts46: If ``True``, apply UTS #46 mapping before decoding. + :param std3_rules: Forwarded to :func:`uts46_remap` when ``uts46`` is + ``True``. + :returns: The decoded domain as a Unicode string. + :raises IDNAError: If the input is not valid ASCII, contains an + invalid label, or is empty. + """ + if not isinstance(s, str): + try: + s = str(s, "ascii") + except (UnicodeDecodeError, TypeError) as err: + raise IDNAError("Invalid ASCII in A-label") from err + if uts46: + s = uts46_remap(s, std3_rules, False) + # Reject inputs that exceed the maximum DNS domain length up-front + # to avoid expensive computation on long inputs. + if not valid_string_length(s, trailing_dot=True): + raise IDNAError("Domain too long") + trailing_dot = False + result = [] + labels = s.split(".") if strict else _unicode_dots_re.split(s) + if not labels or labels == [""]: + raise IDNAError("Empty domain") + if not labels[-1]: + del labels[-1] + trailing_dot = True + for label in labels: + s = ulabel(label) + if s: + result.append(s) + else: + raise IDNAError("Empty label") + if trailing_dot: + result.append("") + return ".".join(result) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/idnadata.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/idnadata.py new file mode 100644 index 0000000000000000000000000000000000000000..8335f26059c8bb932cca0b15a085ec91701b743a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/idnadata.py @@ -0,0 +1,4367 @@ +# This file is automatically generated by tools/idna-data + +from functools import lru_cache +from typing import Dict + +__version__ = "17.0.0" + +scripts = { + "Greek": ( + 0x37000000374, + 0x37500000378, + 0x37A0000037E, + 0x37F00000380, + 0x38400000385, + 0x38600000387, + 0x3880000038B, + 0x38C0000038D, + 0x38E000003A2, + 0x3A3000003E2, + 0x3F000000400, + 0x1D2600001D2B, + 0x1D5D00001D62, + 0x1D6600001D6B, + 0x1DBF00001DC0, + 0x1F0000001F16, + 0x1F1800001F1E, + 0x1F2000001F46, + 0x1F4800001F4E, + 0x1F5000001F58, + 0x1F5900001F5A, + 0x1F5B00001F5C, + 0x1F5D00001F5E, + 0x1F5F00001F7E, + 0x1F8000001FB5, + 0x1FB600001FC5, + 0x1FC600001FD4, + 0x1FD600001FDC, + 0x1FDD00001FF0, + 0x1FF200001FF5, + 0x1FF600001FFF, + 0x212600002127, + 0xAB650000AB66, + 0x101400001018F, + 0x101A0000101A1, + 0x1D2000001D246, + ), + "Han": ( + 0x2E8000002E9A, + 0x2E9B00002EF4, + 0x2F0000002FD6, + 0x300500003006, + 0x300700003008, + 0x30210000302A, + 0x30380000303C, + 0x340000004DC0, + 0x4E000000A000, + 0xF9000000FA6E, + 0xFA700000FADA, + 0x16FE200016FE4, + 0x16FF000016FF7, + 0x200000002A6E0, + 0x2A7000002B81E, + 0x2B8200002CEAE, + 0x2CEB00002EBE1, + 0x2EBF00002EE5E, + 0x2F8000002FA1E, + 0x300000003134B, + 0x313500003347A, + ), + "Hebrew": ( + 0x591000005C8, + 0x5D0000005EB, + 0x5EF000005F5, + 0xFB1D0000FB37, + 0xFB380000FB3D, + 0xFB3E0000FB3F, + 0xFB400000FB42, + 0xFB430000FB45, + 0xFB460000FB50, + ), + "Hiragana": ( + 0x304100003097, + 0x309D000030A0, + 0x1B0010001B120, + 0x1B1320001B133, + 0x1B1500001B153, + 0x1F2000001F201, + ), + "Katakana": ( + 0x30A1000030FB, + 0x30FD00003100, + 0x31F000003200, + 0x32D0000032FF, + 0x330000003358, + 0xFF660000FF70, + 0xFF710000FF9E, + 0x1AFF00001AFF4, + 0x1AFF50001AFFC, + 0x1AFFD0001AFFF, + 0x1B0000001B001, + 0x1B1200001B123, + 0x1B1550001B156, + 0x1B1640001B168, + ), +} + + +@lru_cache(None) +def joining_types() -> Dict[int, int]: + return { + 0xAD: 84, + 0x300: 84, + 0x301: 84, + 0x302: 84, + 0x303: 84, + 0x304: 84, + 0x305: 84, + 0x306: 84, + 0x307: 84, + 0x308: 84, + 0x309: 84, + 0x30A: 84, + 0x30B: 84, + 0x30C: 84, + 0x30D: 84, + 0x30E: 84, + 0x30F: 84, + 0x310: 84, + 0x311: 84, + 0x312: 84, + 0x313: 84, + 0x314: 84, + 0x315: 84, + 0x316: 84, + 0x317: 84, + 0x318: 84, + 0x319: 84, + 0x31A: 84, + 0x31B: 84, + 0x31C: 84, + 0x31D: 84, + 0x31E: 84, + 0x31F: 84, + 0x320: 84, + 0x321: 84, + 0x322: 84, + 0x323: 84, + 0x324: 84, + 0x325: 84, + 0x326: 84, + 0x327: 84, + 0x328: 84, + 0x329: 84, + 0x32A: 84, + 0x32B: 84, + 0x32C: 84, + 0x32D: 84, + 0x32E: 84, + 0x32F: 84, + 0x330: 84, + 0x331: 84, + 0x332: 84, + 0x333: 84, + 0x334: 84, + 0x335: 84, + 0x336: 84, + 0x337: 84, + 0x338: 84, + 0x339: 84, + 0x33A: 84, + 0x33B: 84, + 0x33C: 84, + 0x33D: 84, + 0x33E: 84, + 0x33F: 84, + 0x340: 84, + 0x341: 84, + 0x342: 84, + 0x343: 84, + 0x344: 84, + 0x345: 84, + 0x346: 84, + 0x347: 84, + 0x348: 84, + 0x349: 84, + 0x34A: 84, + 0x34B: 84, + 0x34C: 84, + 0x34D: 84, + 0x34E: 84, + 0x34F: 84, + 0x350: 84, + 0x351: 84, + 0x352: 84, + 0x353: 84, + 0x354: 84, + 0x355: 84, + 0x356: 84, + 0x357: 84, + 0x358: 84, + 0x359: 84, + 0x35A: 84, + 0x35B: 84, + 0x35C: 84, + 0x35D: 84, + 0x35E: 84, + 0x35F: 84, + 0x360: 84, + 0x361: 84, + 0x362: 84, + 0x363: 84, + 0x364: 84, + 0x365: 84, + 0x366: 84, + 0x367: 84, + 0x368: 84, + 0x369: 84, + 0x36A: 84, + 0x36B: 84, + 0x36C: 84, + 0x36D: 84, + 0x36E: 84, + 0x36F: 84, + 0x483: 84, + 0x484: 84, + 0x485: 84, + 0x486: 84, + 0x487: 84, + 0x488: 84, + 0x489: 84, + 0x591: 84, + 0x592: 84, + 0x593: 84, + 0x594: 84, + 0x595: 84, + 0x596: 84, + 0x597: 84, + 0x598: 84, + 0x599: 84, + 0x59A: 84, + 0x59B: 84, + 0x59C: 84, + 0x59D: 84, + 0x59E: 84, + 0x59F: 84, + 0x5A0: 84, + 0x5A1: 84, + 0x5A2: 84, + 0x5A3: 84, + 0x5A4: 84, + 0x5A5: 84, + 0x5A6: 84, + 0x5A7: 84, + 0x5A8: 84, + 0x5A9: 84, + 0x5AA: 84, + 0x5AB: 84, + 0x5AC: 84, + 0x5AD: 84, + 0x5AE: 84, + 0x5AF: 84, + 0x5B0: 84, + 0x5B1: 84, + 0x5B2: 84, + 0x5B3: 84, + 0x5B4: 84, + 0x5B5: 84, + 0x5B6: 84, + 0x5B7: 84, + 0x5B8: 84, + 0x5B9: 84, + 0x5BA: 84, + 0x5BB: 84, + 0x5BC: 84, + 0x5BD: 84, + 0x5BF: 84, + 0x5C1: 84, + 0x5C2: 84, + 0x5C4: 84, + 0x5C5: 84, + 0x5C7: 84, + 0x610: 84, + 0x611: 84, + 0x612: 84, + 0x613: 84, + 0x614: 84, + 0x615: 84, + 0x616: 84, + 0x617: 84, + 0x618: 84, + 0x619: 84, + 0x61A: 84, + 0x61C: 84, + 0x620: 68, + 0x622: 82, + 0x623: 82, + 0x624: 82, + 0x625: 82, + 0x626: 68, + 0x627: 82, + 0x628: 68, + 0x629: 82, + 0x62A: 68, + 0x62B: 68, + 0x62C: 68, + 0x62D: 68, + 0x62E: 68, + 0x62F: 82, + 0x630: 82, + 0x631: 82, + 0x632: 82, + 0x633: 68, + 0x634: 68, + 0x635: 68, + 0x636: 68, + 0x637: 68, + 0x638: 68, + 0x639: 68, + 0x63A: 68, + 0x63B: 68, + 0x63C: 68, + 0x63D: 68, + 0x63E: 68, + 0x63F: 68, + 0x640: 67, + 0x641: 68, + 0x642: 68, + 0x643: 68, + 0x644: 68, + 0x645: 68, + 0x646: 68, + 0x647: 68, + 0x648: 82, + 0x649: 68, + 0x64A: 68, + 0x64B: 84, + 0x64C: 84, + 0x64D: 84, + 0x64E: 84, + 0x64F: 84, + 0x650: 84, + 0x651: 84, + 0x652: 84, + 0x653: 84, + 0x654: 84, + 0x655: 84, + 0x656: 84, + 0x657: 84, + 0x658: 84, + 0x659: 84, + 0x65A: 84, + 0x65B: 84, + 0x65C: 84, + 0x65D: 84, + 0x65E: 84, + 0x65F: 84, + 0x66E: 68, + 0x66F: 68, + 0x670: 84, + 0x671: 82, + 0x672: 82, + 0x673: 82, + 0x675: 82, + 0x676: 82, + 0x677: 82, + 0x678: 68, + 0x679: 68, + 0x67A: 68, + 0x67B: 68, + 0x67C: 68, + 0x67D: 68, + 0x67E: 68, + 0x67F: 68, + 0x680: 68, + 0x681: 68, + 0x682: 68, + 0x683: 68, + 0x684: 68, + 0x685: 68, + 0x686: 68, + 0x687: 68, + 0x688: 82, + 0x689: 82, + 0x68A: 82, + 0x68B: 82, + 0x68C: 82, + 0x68D: 82, + 0x68E: 82, + 0x68F: 82, + 0x690: 82, + 0x691: 82, + 0x692: 82, + 0x693: 82, + 0x694: 82, + 0x695: 82, + 0x696: 82, + 0x697: 82, + 0x698: 82, + 0x699: 82, + 0x69A: 68, + 0x69B: 68, + 0x69C: 68, + 0x69D: 68, + 0x69E: 68, + 0x69F: 68, + 0x6A0: 68, + 0x6A1: 68, + 0x6A2: 68, + 0x6A3: 68, + 0x6A4: 68, + 0x6A5: 68, + 0x6A6: 68, + 0x6A7: 68, + 0x6A8: 68, + 0x6A9: 68, + 0x6AA: 68, + 0x6AB: 68, + 0x6AC: 68, + 0x6AD: 68, + 0x6AE: 68, + 0x6AF: 68, + 0x6B0: 68, + 0x6B1: 68, + 0x6B2: 68, + 0x6B3: 68, + 0x6B4: 68, + 0x6B5: 68, + 0x6B6: 68, + 0x6B7: 68, + 0x6B8: 68, + 0x6B9: 68, + 0x6BA: 68, + 0x6BB: 68, + 0x6BC: 68, + 0x6BD: 68, + 0x6BE: 68, + 0x6BF: 68, + 0x6C0: 82, + 0x6C1: 68, + 0x6C2: 68, + 0x6C3: 82, + 0x6C4: 82, + 0x6C5: 82, + 0x6C6: 82, + 0x6C7: 82, + 0x6C8: 82, + 0x6C9: 82, + 0x6CA: 82, + 0x6CB: 82, + 0x6CC: 68, + 0x6CD: 82, + 0x6CE: 68, + 0x6CF: 82, + 0x6D0: 68, + 0x6D1: 68, + 0x6D2: 82, + 0x6D3: 82, + 0x6D5: 82, + 0x6D6: 84, + 0x6D7: 84, + 0x6D8: 84, + 0x6D9: 84, + 0x6DA: 84, + 0x6DB: 84, + 0x6DC: 84, + 0x6DF: 84, + 0x6E0: 84, + 0x6E1: 84, + 0x6E2: 84, + 0x6E3: 84, + 0x6E4: 84, + 0x6E7: 84, + 0x6E8: 84, + 0x6EA: 84, + 0x6EB: 84, + 0x6EC: 84, + 0x6ED: 84, + 0x6EE: 82, + 0x6EF: 82, + 0x6FA: 68, + 0x6FB: 68, + 0x6FC: 68, + 0x6FF: 68, + 0x70F: 84, + 0x710: 82, + 0x711: 84, + 0x712: 68, + 0x713: 68, + 0x714: 68, + 0x715: 82, + 0x716: 82, + 0x717: 82, + 0x718: 82, + 0x719: 82, + 0x71A: 68, + 0x71B: 68, + 0x71C: 68, + 0x71D: 68, + 0x71E: 82, + 0x71F: 68, + 0x720: 68, + 0x721: 68, + 0x722: 68, + 0x723: 68, + 0x724: 68, + 0x725: 68, + 0x726: 68, + 0x727: 68, + 0x728: 82, + 0x729: 68, + 0x72A: 82, + 0x72B: 68, + 0x72C: 82, + 0x72D: 68, + 0x72E: 68, + 0x72F: 82, + 0x730: 84, + 0x731: 84, + 0x732: 84, + 0x733: 84, + 0x734: 84, + 0x735: 84, + 0x736: 84, + 0x737: 84, + 0x738: 84, + 0x739: 84, + 0x73A: 84, + 0x73B: 84, + 0x73C: 84, + 0x73D: 84, + 0x73E: 84, + 0x73F: 84, + 0x740: 84, + 0x741: 84, + 0x742: 84, + 0x743: 84, + 0x744: 84, + 0x745: 84, + 0x746: 84, + 0x747: 84, + 0x748: 84, + 0x749: 84, + 0x74A: 84, + 0x74D: 82, + 0x74E: 68, + 0x74F: 68, + 0x750: 68, + 0x751: 68, + 0x752: 68, + 0x753: 68, + 0x754: 68, + 0x755: 68, + 0x756: 68, + 0x757: 68, + 0x758: 68, + 0x759: 82, + 0x75A: 82, + 0x75B: 82, + 0x75C: 68, + 0x75D: 68, + 0x75E: 68, + 0x75F: 68, + 0x760: 68, + 0x761: 68, + 0x762: 68, + 0x763: 68, + 0x764: 68, + 0x765: 68, + 0x766: 68, + 0x767: 68, + 0x768: 68, + 0x769: 68, + 0x76A: 68, + 0x76B: 82, + 0x76C: 82, + 0x76D: 68, + 0x76E: 68, + 0x76F: 68, + 0x770: 68, + 0x771: 82, + 0x772: 68, + 0x773: 82, + 0x774: 82, + 0x775: 68, + 0x776: 68, + 0x777: 68, + 0x778: 82, + 0x779: 82, + 0x77A: 68, + 0x77B: 68, + 0x77C: 68, + 0x77D: 68, + 0x77E: 68, + 0x77F: 68, + 0x7A6: 84, + 0x7A7: 84, + 0x7A8: 84, + 0x7A9: 84, + 0x7AA: 84, + 0x7AB: 84, + 0x7AC: 84, + 0x7AD: 84, + 0x7AE: 84, + 0x7AF: 84, + 0x7B0: 84, + 0x7CA: 68, + 0x7CB: 68, + 0x7CC: 68, + 0x7CD: 68, + 0x7CE: 68, + 0x7CF: 68, + 0x7D0: 68, + 0x7D1: 68, + 0x7D2: 68, + 0x7D3: 68, + 0x7D4: 68, + 0x7D5: 68, + 0x7D6: 68, + 0x7D7: 68, + 0x7D8: 68, + 0x7D9: 68, + 0x7DA: 68, + 0x7DB: 68, + 0x7DC: 68, + 0x7DD: 68, + 0x7DE: 68, + 0x7DF: 68, + 0x7E0: 68, + 0x7E1: 68, + 0x7E2: 68, + 0x7E3: 68, + 0x7E4: 68, + 0x7E5: 68, + 0x7E6: 68, + 0x7E7: 68, + 0x7E8: 68, + 0x7E9: 68, + 0x7EA: 68, + 0x7EB: 84, + 0x7EC: 84, + 0x7ED: 84, + 0x7EE: 84, + 0x7EF: 84, + 0x7F0: 84, + 0x7F1: 84, + 0x7F2: 84, + 0x7F3: 84, + 0x7FA: 67, + 0x7FD: 84, + 0x816: 84, + 0x817: 84, + 0x818: 84, + 0x819: 84, + 0x81B: 84, + 0x81C: 84, + 0x81D: 84, + 0x81E: 84, + 0x81F: 84, + 0x820: 84, + 0x821: 84, + 0x822: 84, + 0x823: 84, + 0x825: 84, + 0x826: 84, + 0x827: 84, + 0x829: 84, + 0x82A: 84, + 0x82B: 84, + 0x82C: 84, + 0x82D: 84, + 0x840: 82, + 0x841: 68, + 0x842: 68, + 0x843: 68, + 0x844: 68, + 0x845: 68, + 0x846: 82, + 0x847: 82, + 0x848: 68, + 0x849: 82, + 0x84A: 68, + 0x84B: 68, + 0x84C: 68, + 0x84D: 68, + 0x84E: 68, + 0x84F: 68, + 0x850: 68, + 0x851: 68, + 0x852: 68, + 0x853: 68, + 0x854: 82, + 0x855: 68, + 0x856: 82, + 0x857: 82, + 0x858: 82, + 0x859: 84, + 0x85A: 84, + 0x85B: 84, + 0x860: 68, + 0x862: 68, + 0x863: 68, + 0x864: 68, + 0x865: 68, + 0x867: 82, + 0x868: 68, + 0x869: 82, + 0x86A: 82, + 0x870: 82, + 0x871: 82, + 0x872: 82, + 0x873: 82, + 0x874: 82, + 0x875: 82, + 0x876: 82, + 0x877: 82, + 0x878: 82, + 0x879: 82, + 0x87A: 82, + 0x87B: 82, + 0x87C: 82, + 0x87D: 82, + 0x87E: 82, + 0x87F: 82, + 0x880: 82, + 0x881: 82, + 0x882: 82, + 0x883: 67, + 0x884: 67, + 0x885: 67, + 0x886: 68, + 0x889: 68, + 0x88A: 68, + 0x88B: 68, + 0x88C: 68, + 0x88D: 68, + 0x88E: 82, + 0x88F: 68, + 0x897: 84, + 0x898: 84, + 0x899: 84, + 0x89A: 84, + 0x89B: 84, + 0x89C: 84, + 0x89D: 84, + 0x89E: 84, + 0x89F: 84, + 0x8A0: 68, + 0x8A1: 68, + 0x8A2: 68, + 0x8A3: 68, + 0x8A4: 68, + 0x8A5: 68, + 0x8A6: 68, + 0x8A7: 68, + 0x8A8: 68, + 0x8A9: 68, + 0x8AA: 82, + 0x8AB: 82, + 0x8AC: 82, + 0x8AE: 82, + 0x8AF: 68, + 0x8B0: 68, + 0x8B1: 82, + 0x8B2: 82, + 0x8B3: 68, + 0x8B4: 68, + 0x8B5: 68, + 0x8B6: 68, + 0x8B7: 68, + 0x8B8: 68, + 0x8B9: 82, + 0x8BA: 68, + 0x8BB: 68, + 0x8BC: 68, + 0x8BD: 68, + 0x8BE: 68, + 0x8BF: 68, + 0x8C0: 68, + 0x8C1: 68, + 0x8C2: 68, + 0x8C3: 68, + 0x8C4: 68, + 0x8C5: 68, + 0x8C6: 68, + 0x8C7: 68, + 0x8C8: 68, + 0x8CA: 84, + 0x8CB: 84, + 0x8CC: 84, + 0x8CD: 84, + 0x8CE: 84, + 0x8CF: 84, + 0x8D0: 84, + 0x8D1: 84, + 0x8D2: 84, + 0x8D3: 84, + 0x8D4: 84, + 0x8D5: 84, + 0x8D6: 84, + 0x8D7: 84, + 0x8D8: 84, + 0x8D9: 84, + 0x8DA: 84, + 0x8DB: 84, + 0x8DC: 84, + 0x8DD: 84, + 0x8DE: 84, + 0x8DF: 84, + 0x8E0: 84, + 0x8E1: 84, + 0x8E3: 84, + 0x8E4: 84, + 0x8E5: 84, + 0x8E6: 84, + 0x8E7: 84, + 0x8E8: 84, + 0x8E9: 84, + 0x8EA: 84, + 0x8EB: 84, + 0x8EC: 84, + 0x8ED: 84, + 0x8EE: 84, + 0x8EF: 84, + 0x8F0: 84, + 0x8F1: 84, + 0x8F2: 84, + 0x8F3: 84, + 0x8F4: 84, + 0x8F5: 84, + 0x8F6: 84, + 0x8F7: 84, + 0x8F8: 84, + 0x8F9: 84, + 0x8FA: 84, + 0x8FB: 84, + 0x8FC: 84, + 0x8FD: 84, + 0x8FE: 84, + 0x8FF: 84, + 0x900: 84, + 0x901: 84, + 0x902: 84, + 0x93A: 84, + 0x93C: 84, + 0x941: 84, + 0x942: 84, + 0x943: 84, + 0x944: 84, + 0x945: 84, + 0x946: 84, + 0x947: 84, + 0x948: 84, + 0x94D: 84, + 0x951: 84, + 0x952: 84, + 0x953: 84, + 0x954: 84, + 0x955: 84, + 0x956: 84, + 0x957: 84, + 0x962: 84, + 0x963: 84, + 0x981: 84, + 0x9BC: 84, + 0x9C1: 84, + 0x9C2: 84, + 0x9C3: 84, + 0x9C4: 84, + 0x9CD: 84, + 0x9E2: 84, + 0x9E3: 84, + 0x9FE: 84, + 0xA01: 84, + 0xA02: 84, + 0xA3C: 84, + 0xA41: 84, + 0xA42: 84, + 0xA47: 84, + 0xA48: 84, + 0xA4B: 84, + 0xA4C: 84, + 0xA4D: 84, + 0xA51: 84, + 0xA70: 84, + 0xA71: 84, + 0xA75: 84, + 0xA81: 84, + 0xA82: 84, + 0xABC: 84, + 0xAC1: 84, + 0xAC2: 84, + 0xAC3: 84, + 0xAC4: 84, + 0xAC5: 84, + 0xAC7: 84, + 0xAC8: 84, + 0xACD: 84, + 0xAE2: 84, + 0xAE3: 84, + 0xAFA: 84, + 0xAFB: 84, + 0xAFC: 84, + 0xAFD: 84, + 0xAFE: 84, + 0xAFF: 84, + 0xB01: 84, + 0xB3C: 84, + 0xB3F: 84, + 0xB41: 84, + 0xB42: 84, + 0xB43: 84, + 0xB44: 84, + 0xB4D: 84, + 0xB55: 84, + 0xB56: 84, + 0xB62: 84, + 0xB63: 84, + 0xB82: 84, + 0xBC0: 84, + 0xBCD: 84, + 0xC00: 84, + 0xC04: 84, + 0xC3C: 84, + 0xC3E: 84, + 0xC3F: 84, + 0xC40: 84, + 0xC46: 84, + 0xC47: 84, + 0xC48: 84, + 0xC4A: 84, + 0xC4B: 84, + 0xC4C: 84, + 0xC4D: 84, + 0xC55: 84, + 0xC56: 84, + 0xC62: 84, + 0xC63: 84, + 0xC81: 84, + 0xCBC: 84, + 0xCBF: 84, + 0xCC6: 84, + 0xCCC: 84, + 0xCCD: 84, + 0xCE2: 84, + 0xCE3: 84, + 0xD00: 84, + 0xD01: 84, + 0xD3B: 84, + 0xD3C: 84, + 0xD41: 84, + 0xD42: 84, + 0xD43: 84, + 0xD44: 84, + 0xD4D: 84, + 0xD62: 84, + 0xD63: 84, + 0xD81: 84, + 0xDCA: 84, + 0xDD2: 84, + 0xDD3: 84, + 0xDD4: 84, + 0xDD6: 84, + 0xE31: 84, + 0xE34: 84, + 0xE35: 84, + 0xE36: 84, + 0xE37: 84, + 0xE38: 84, + 0xE39: 84, + 0xE3A: 84, + 0xE47: 84, + 0xE48: 84, + 0xE49: 84, + 0xE4A: 84, + 0xE4B: 84, + 0xE4C: 84, + 0xE4D: 84, + 0xE4E: 84, + 0xEB1: 84, + 0xEB4: 84, + 0xEB5: 84, + 0xEB6: 84, + 0xEB7: 84, + 0xEB8: 84, + 0xEB9: 84, + 0xEBA: 84, + 0xEBB: 84, + 0xEBC: 84, + 0xEC8: 84, + 0xEC9: 84, + 0xECA: 84, + 0xECB: 84, + 0xECC: 84, + 0xECD: 84, + 0xECE: 84, + 0xF18: 84, + 0xF19: 84, + 0xF35: 84, + 0xF37: 84, + 0xF39: 84, + 0xF71: 84, + 0xF72: 84, + 0xF73: 84, + 0xF74: 84, + 0xF75: 84, + 0xF76: 84, + 0xF77: 84, + 0xF78: 84, + 0xF79: 84, + 0xF7A: 84, + 0xF7B: 84, + 0xF7C: 84, + 0xF7D: 84, + 0xF7E: 84, + 0xF80: 84, + 0xF81: 84, + 0xF82: 84, + 0xF83: 84, + 0xF84: 84, + 0xF86: 84, + 0xF87: 84, + 0xF8D: 84, + 0xF8E: 84, + 0xF8F: 84, + 0xF90: 84, + 0xF91: 84, + 0xF92: 84, + 0xF93: 84, + 0xF94: 84, + 0xF95: 84, + 0xF96: 84, + 0xF97: 84, + 0xF99: 84, + 0xF9A: 84, + 0xF9B: 84, + 0xF9C: 84, + 0xF9D: 84, + 0xF9E: 84, + 0xF9F: 84, + 0xFA0: 84, + 0xFA1: 84, + 0xFA2: 84, + 0xFA3: 84, + 0xFA4: 84, + 0xFA5: 84, + 0xFA6: 84, + 0xFA7: 84, + 0xFA8: 84, + 0xFA9: 84, + 0xFAA: 84, + 0xFAB: 84, + 0xFAC: 84, + 0xFAD: 84, + 0xFAE: 84, + 0xFAF: 84, + 0xFB0: 84, + 0xFB1: 84, + 0xFB2: 84, + 0xFB3: 84, + 0xFB4: 84, + 0xFB5: 84, + 0xFB6: 84, + 0xFB7: 84, + 0xFB8: 84, + 0xFB9: 84, + 0xFBA: 84, + 0xFBB: 84, + 0xFBC: 84, + 0xFC6: 84, + 0x102D: 84, + 0x102E: 84, + 0x102F: 84, + 0x1030: 84, + 0x1032: 84, + 0x1033: 84, + 0x1034: 84, + 0x1035: 84, + 0x1036: 84, + 0x1037: 84, + 0x1039: 84, + 0x103A: 84, + 0x103D: 84, + 0x103E: 84, + 0x1058: 84, + 0x1059: 84, + 0x105E: 84, + 0x105F: 84, + 0x1060: 84, + 0x1071: 84, + 0x1072: 84, + 0x1073: 84, + 0x1074: 84, + 0x1082: 84, + 0x1085: 84, + 0x1086: 84, + 0x108D: 84, + 0x109D: 84, + 0x135D: 84, + 0x135E: 84, + 0x135F: 84, + 0x1712: 84, + 0x1713: 84, + 0x1714: 84, + 0x1732: 84, + 0x1733: 84, + 0x1752: 84, + 0x1753: 84, + 0x1772: 84, + 0x1773: 84, + 0x17B4: 84, + 0x17B5: 84, + 0x17B7: 84, + 0x17B8: 84, + 0x17B9: 84, + 0x17BA: 84, + 0x17BB: 84, + 0x17BC: 84, + 0x17BD: 84, + 0x17C6: 84, + 0x17C9: 84, + 0x17CA: 84, + 0x17CB: 84, + 0x17CC: 84, + 0x17CD: 84, + 0x17CE: 84, + 0x17CF: 84, + 0x17D0: 84, + 0x17D1: 84, + 0x17D2: 84, + 0x17D3: 84, + 0x17DD: 84, + 0x1807: 68, + 0x180A: 67, + 0x180B: 84, + 0x180C: 84, + 0x180D: 84, + 0x180F: 84, + 0x1820: 68, + 0x1821: 68, + 0x1822: 68, + 0x1823: 68, + 0x1824: 68, + 0x1825: 68, + 0x1826: 68, + 0x1827: 68, + 0x1828: 68, + 0x1829: 68, + 0x182A: 68, + 0x182B: 68, + 0x182C: 68, + 0x182D: 68, + 0x182E: 68, + 0x182F: 68, + 0x1830: 68, + 0x1831: 68, + 0x1832: 68, + 0x1833: 68, + 0x1834: 68, + 0x1835: 68, + 0x1836: 68, + 0x1837: 68, + 0x1838: 68, + 0x1839: 68, + 0x183A: 68, + 0x183B: 68, + 0x183C: 68, + 0x183D: 68, + 0x183E: 68, + 0x183F: 68, + 0x1840: 68, + 0x1841: 68, + 0x1842: 68, + 0x1843: 68, + 0x1844: 68, + 0x1845: 68, + 0x1846: 68, + 0x1847: 68, + 0x1848: 68, + 0x1849: 68, + 0x184A: 68, + 0x184B: 68, + 0x184C: 68, + 0x184D: 68, + 0x184E: 68, + 0x184F: 68, + 0x1850: 68, + 0x1851: 68, + 0x1852: 68, + 0x1853: 68, + 0x1854: 68, + 0x1855: 68, + 0x1856: 68, + 0x1857: 68, + 0x1858: 68, + 0x1859: 68, + 0x185A: 68, + 0x185B: 68, + 0x185C: 68, + 0x185D: 68, + 0x185E: 68, + 0x185F: 68, + 0x1860: 68, + 0x1861: 68, + 0x1862: 68, + 0x1863: 68, + 0x1864: 68, + 0x1865: 68, + 0x1866: 68, + 0x1867: 68, + 0x1868: 68, + 0x1869: 68, + 0x186A: 68, + 0x186B: 68, + 0x186C: 68, + 0x186D: 68, + 0x186E: 68, + 0x186F: 68, + 0x1870: 68, + 0x1871: 68, + 0x1872: 68, + 0x1873: 68, + 0x1874: 68, + 0x1875: 68, + 0x1876: 68, + 0x1877: 68, + 0x1878: 68, + 0x1885: 84, + 0x1886: 84, + 0x1887: 68, + 0x1888: 68, + 0x1889: 68, + 0x188A: 68, + 0x188B: 68, + 0x188C: 68, + 0x188D: 68, + 0x188E: 68, + 0x188F: 68, + 0x1890: 68, + 0x1891: 68, + 0x1892: 68, + 0x1893: 68, + 0x1894: 68, + 0x1895: 68, + 0x1896: 68, + 0x1897: 68, + 0x1898: 68, + 0x1899: 68, + 0x189A: 68, + 0x189B: 68, + 0x189C: 68, + 0x189D: 68, + 0x189E: 68, + 0x189F: 68, + 0x18A0: 68, + 0x18A1: 68, + 0x18A2: 68, + 0x18A3: 68, + 0x18A4: 68, + 0x18A5: 68, + 0x18A6: 68, + 0x18A7: 68, + 0x18A8: 68, + 0x18A9: 84, + 0x18AA: 68, + 0x1920: 84, + 0x1921: 84, + 0x1922: 84, + 0x1927: 84, + 0x1928: 84, + 0x1932: 84, + 0x1939: 84, + 0x193A: 84, + 0x193B: 84, + 0x1A17: 84, + 0x1A18: 84, + 0x1A1B: 84, + 0x1A56: 84, + 0x1A58: 84, + 0x1A59: 84, + 0x1A5A: 84, + 0x1A5B: 84, + 0x1A5C: 84, + 0x1A5D: 84, + 0x1A5E: 84, + 0x1A60: 84, + 0x1A62: 84, + 0x1A65: 84, + 0x1A66: 84, + 0x1A67: 84, + 0x1A68: 84, + 0x1A69: 84, + 0x1A6A: 84, + 0x1A6B: 84, + 0x1A6C: 84, + 0x1A73: 84, + 0x1A74: 84, + 0x1A75: 84, + 0x1A76: 84, + 0x1A77: 84, + 0x1A78: 84, + 0x1A79: 84, + 0x1A7A: 84, + 0x1A7B: 84, + 0x1A7C: 84, + 0x1A7F: 84, + 0x1AB0: 84, + 0x1AB1: 84, + 0x1AB2: 84, + 0x1AB3: 84, + 0x1AB4: 84, + 0x1AB5: 84, + 0x1AB6: 84, + 0x1AB7: 84, + 0x1AB8: 84, + 0x1AB9: 84, + 0x1ABA: 84, + 0x1ABB: 84, + 0x1ABC: 84, + 0x1ABD: 84, + 0x1ABE: 84, + 0x1ABF: 84, + 0x1AC0: 84, + 0x1AC1: 84, + 0x1AC2: 84, + 0x1AC3: 84, + 0x1AC4: 84, + 0x1AC5: 84, + 0x1AC6: 84, + 0x1AC7: 84, + 0x1AC8: 84, + 0x1AC9: 84, + 0x1ACA: 84, + 0x1ACB: 84, + 0x1ACC: 84, + 0x1ACD: 84, + 0x1ACE: 84, + 0x1ACF: 84, + 0x1AD0: 84, + 0x1AD1: 84, + 0x1AD2: 84, + 0x1AD3: 84, + 0x1AD4: 84, + 0x1AD5: 84, + 0x1AD6: 84, + 0x1AD7: 84, + 0x1AD8: 84, + 0x1AD9: 84, + 0x1ADA: 84, + 0x1ADB: 84, + 0x1ADC: 84, + 0x1ADD: 84, + 0x1AE0: 84, + 0x1AE1: 84, + 0x1AE2: 84, + 0x1AE3: 84, + 0x1AE4: 84, + 0x1AE5: 84, + 0x1AE6: 84, + 0x1AE7: 84, + 0x1AE8: 84, + 0x1AE9: 84, + 0x1AEA: 84, + 0x1AEB: 84, + 0x1B00: 84, + 0x1B01: 84, + 0x1B02: 84, + 0x1B03: 84, + 0x1B34: 84, + 0x1B36: 84, + 0x1B37: 84, + 0x1B38: 84, + 0x1B39: 84, + 0x1B3A: 84, + 0x1B3C: 84, + 0x1B42: 84, + 0x1B6B: 84, + 0x1B6C: 84, + 0x1B6D: 84, + 0x1B6E: 84, + 0x1B6F: 84, + 0x1B70: 84, + 0x1B71: 84, + 0x1B72: 84, + 0x1B73: 84, + 0x1B80: 84, + 0x1B81: 84, + 0x1BA2: 84, + 0x1BA3: 84, + 0x1BA4: 84, + 0x1BA5: 84, + 0x1BA8: 84, + 0x1BA9: 84, + 0x1BAB: 84, + 0x1BAC: 84, + 0x1BAD: 84, + 0x1BE6: 84, + 0x1BE8: 84, + 0x1BE9: 84, + 0x1BED: 84, + 0x1BEF: 84, + 0x1BF0: 84, + 0x1BF1: 84, + 0x1C2C: 84, + 0x1C2D: 84, + 0x1C2E: 84, + 0x1C2F: 84, + 0x1C30: 84, + 0x1C31: 84, + 0x1C32: 84, + 0x1C33: 84, + 0x1C36: 84, + 0x1C37: 84, + 0x1CD0: 84, + 0x1CD1: 84, + 0x1CD2: 84, + 0x1CD4: 84, + 0x1CD5: 84, + 0x1CD6: 84, + 0x1CD7: 84, + 0x1CD8: 84, + 0x1CD9: 84, + 0x1CDA: 84, + 0x1CDB: 84, + 0x1CDC: 84, + 0x1CDD: 84, + 0x1CDE: 84, + 0x1CDF: 84, + 0x1CE0: 84, + 0x1CE2: 84, + 0x1CE3: 84, + 0x1CE4: 84, + 0x1CE5: 84, + 0x1CE6: 84, + 0x1CE7: 84, + 0x1CE8: 84, + 0x1CED: 84, + 0x1CF4: 84, + 0x1CF8: 84, + 0x1CF9: 84, + 0x1DC0: 84, + 0x1DC1: 84, + 0x1DC2: 84, + 0x1DC3: 84, + 0x1DC4: 84, + 0x1DC5: 84, + 0x1DC6: 84, + 0x1DC7: 84, + 0x1DC8: 84, + 0x1DC9: 84, + 0x1DCA: 84, + 0x1DCB: 84, + 0x1DCC: 84, + 0x1DCD: 84, + 0x1DCE: 84, + 0x1DCF: 84, + 0x1DD0: 84, + 0x1DD1: 84, + 0x1DD2: 84, + 0x1DD3: 84, + 0x1DD4: 84, + 0x1DD5: 84, + 0x1DD6: 84, + 0x1DD7: 84, + 0x1DD8: 84, + 0x1DD9: 84, + 0x1DDA: 84, + 0x1DDB: 84, + 0x1DDC: 84, + 0x1DDD: 84, + 0x1DDE: 84, + 0x1DDF: 84, + 0x1DE0: 84, + 0x1DE1: 84, + 0x1DE2: 84, + 0x1DE3: 84, + 0x1DE4: 84, + 0x1DE5: 84, + 0x1DE6: 84, + 0x1DE7: 84, + 0x1DE8: 84, + 0x1DE9: 84, + 0x1DEA: 84, + 0x1DEB: 84, + 0x1DEC: 84, + 0x1DED: 84, + 0x1DEE: 84, + 0x1DEF: 84, + 0x1DF0: 84, + 0x1DF1: 84, + 0x1DF2: 84, + 0x1DF3: 84, + 0x1DF4: 84, + 0x1DF5: 84, + 0x1DF6: 84, + 0x1DF7: 84, + 0x1DF8: 84, + 0x1DF9: 84, + 0x1DFA: 84, + 0x1DFB: 84, + 0x1DFC: 84, + 0x1DFD: 84, + 0x1DFE: 84, + 0x1DFF: 84, + 0x200B: 84, + 0x200D: 67, + 0x200E: 84, + 0x200F: 84, + 0x202A: 84, + 0x202B: 84, + 0x202C: 84, + 0x202D: 84, + 0x202E: 84, + 0x2060: 84, + 0x2061: 84, + 0x2062: 84, + 0x2063: 84, + 0x2064: 84, + 0x206A: 84, + 0x206B: 84, + 0x206C: 84, + 0x206D: 84, + 0x206E: 84, + 0x206F: 84, + 0x20D0: 84, + 0x20D1: 84, + 0x20D2: 84, + 0x20D3: 84, + 0x20D4: 84, + 0x20D5: 84, + 0x20D6: 84, + 0x20D7: 84, + 0x20D8: 84, + 0x20D9: 84, + 0x20DA: 84, + 0x20DB: 84, + 0x20DC: 84, + 0x20DD: 84, + 0x20DE: 84, + 0x20DF: 84, + 0x20E0: 84, + 0x20E1: 84, + 0x20E2: 84, + 0x20E3: 84, + 0x20E4: 84, + 0x20E5: 84, + 0x20E6: 84, + 0x20E7: 84, + 0x20E8: 84, + 0x20E9: 84, + 0x20EA: 84, + 0x20EB: 84, + 0x20EC: 84, + 0x20ED: 84, + 0x20EE: 84, + 0x20EF: 84, + 0x20F0: 84, + 0x2CEF: 84, + 0x2CF0: 84, + 0x2CF1: 84, + 0x2D7F: 84, + 0x2DE0: 84, + 0x2DE1: 84, + 0x2DE2: 84, + 0x2DE3: 84, + 0x2DE4: 84, + 0x2DE5: 84, + 0x2DE6: 84, + 0x2DE7: 84, + 0x2DE8: 84, + 0x2DE9: 84, + 0x2DEA: 84, + 0x2DEB: 84, + 0x2DEC: 84, + 0x2DED: 84, + 0x2DEE: 84, + 0x2DEF: 84, + 0x2DF0: 84, + 0x2DF1: 84, + 0x2DF2: 84, + 0x2DF3: 84, + 0x2DF4: 84, + 0x2DF5: 84, + 0x2DF6: 84, + 0x2DF7: 84, + 0x2DF8: 84, + 0x2DF9: 84, + 0x2DFA: 84, + 0x2DFB: 84, + 0x2DFC: 84, + 0x2DFD: 84, + 0x2DFE: 84, + 0x2DFF: 84, + 0x302A: 84, + 0x302B: 84, + 0x302C: 84, + 0x302D: 84, + 0x3099: 84, + 0x309A: 84, + 0xA66F: 84, + 0xA670: 84, + 0xA671: 84, + 0xA672: 84, + 0xA674: 84, + 0xA675: 84, + 0xA676: 84, + 0xA677: 84, + 0xA678: 84, + 0xA679: 84, + 0xA67A: 84, + 0xA67B: 84, + 0xA67C: 84, + 0xA67D: 84, + 0xA69E: 84, + 0xA69F: 84, + 0xA6F0: 84, + 0xA6F1: 84, + 0xA802: 84, + 0xA806: 84, + 0xA80B: 84, + 0xA825: 84, + 0xA826: 84, + 0xA82C: 84, + 0xA840: 68, + 0xA841: 68, + 0xA842: 68, + 0xA843: 68, + 0xA844: 68, + 0xA845: 68, + 0xA846: 68, + 0xA847: 68, + 0xA848: 68, + 0xA849: 68, + 0xA84A: 68, + 0xA84B: 68, + 0xA84C: 68, + 0xA84D: 68, + 0xA84E: 68, + 0xA84F: 68, + 0xA850: 68, + 0xA851: 68, + 0xA852: 68, + 0xA853: 68, + 0xA854: 68, + 0xA855: 68, + 0xA856: 68, + 0xA857: 68, + 0xA858: 68, + 0xA859: 68, + 0xA85A: 68, + 0xA85B: 68, + 0xA85C: 68, + 0xA85D: 68, + 0xA85E: 68, + 0xA85F: 68, + 0xA860: 68, + 0xA861: 68, + 0xA862: 68, + 0xA863: 68, + 0xA864: 68, + 0xA865: 68, + 0xA866: 68, + 0xA867: 68, + 0xA868: 68, + 0xA869: 68, + 0xA86A: 68, + 0xA86B: 68, + 0xA86C: 68, + 0xA86D: 68, + 0xA86E: 68, + 0xA86F: 68, + 0xA870: 68, + 0xA871: 68, + 0xA872: 76, + 0xA8C4: 84, + 0xA8C5: 84, + 0xA8E0: 84, + 0xA8E1: 84, + 0xA8E2: 84, + 0xA8E3: 84, + 0xA8E4: 84, + 0xA8E5: 84, + 0xA8E6: 84, + 0xA8E7: 84, + 0xA8E8: 84, + 0xA8E9: 84, + 0xA8EA: 84, + 0xA8EB: 84, + 0xA8EC: 84, + 0xA8ED: 84, + 0xA8EE: 84, + 0xA8EF: 84, + 0xA8F0: 84, + 0xA8F1: 84, + 0xA8FF: 84, + 0xA926: 84, + 0xA927: 84, + 0xA928: 84, + 0xA929: 84, + 0xA92A: 84, + 0xA92B: 84, + 0xA92C: 84, + 0xA92D: 84, + 0xA947: 84, + 0xA948: 84, + 0xA949: 84, + 0xA94A: 84, + 0xA94B: 84, + 0xA94C: 84, + 0xA94D: 84, + 0xA94E: 84, + 0xA94F: 84, + 0xA950: 84, + 0xA951: 84, + 0xA980: 84, + 0xA981: 84, + 0xA982: 84, + 0xA9B3: 84, + 0xA9B6: 84, + 0xA9B7: 84, + 0xA9B8: 84, + 0xA9B9: 84, + 0xA9BC: 84, + 0xA9BD: 84, + 0xA9E5: 84, + 0xAA29: 84, + 0xAA2A: 84, + 0xAA2B: 84, + 0xAA2C: 84, + 0xAA2D: 84, + 0xAA2E: 84, + 0xAA31: 84, + 0xAA32: 84, + 0xAA35: 84, + 0xAA36: 84, + 0xAA43: 84, + 0xAA4C: 84, + 0xAA7C: 84, + 0xAAB0: 84, + 0xAAB2: 84, + 0xAAB3: 84, + 0xAAB4: 84, + 0xAAB7: 84, + 0xAAB8: 84, + 0xAABE: 84, + 0xAABF: 84, + 0xAAC1: 84, + 0xAAEC: 84, + 0xAAED: 84, + 0xAAF6: 84, + 0xABE5: 84, + 0xABE8: 84, + 0xABED: 84, + 0xFB1E: 84, + 0xFE00: 84, + 0xFE01: 84, + 0xFE02: 84, + 0xFE03: 84, + 0xFE04: 84, + 0xFE05: 84, + 0xFE06: 84, + 0xFE07: 84, + 0xFE08: 84, + 0xFE09: 84, + 0xFE0A: 84, + 0xFE0B: 84, + 0xFE0C: 84, + 0xFE0D: 84, + 0xFE0E: 84, + 0xFE0F: 84, + 0xFE20: 84, + 0xFE21: 84, + 0xFE22: 84, + 0xFE23: 84, + 0xFE24: 84, + 0xFE25: 84, + 0xFE26: 84, + 0xFE27: 84, + 0xFE28: 84, + 0xFE29: 84, + 0xFE2A: 84, + 0xFE2B: 84, + 0xFE2C: 84, + 0xFE2D: 84, + 0xFE2E: 84, + 0xFE2F: 84, + 0xFEFF: 84, + 0xFFF9: 84, + 0xFFFA: 84, + 0xFFFB: 84, + 0x101FD: 84, + 0x102E0: 84, + 0x10376: 84, + 0x10377: 84, + 0x10378: 84, + 0x10379: 84, + 0x1037A: 84, + 0x10A01: 84, + 0x10A02: 84, + 0x10A03: 84, + 0x10A05: 84, + 0x10A06: 84, + 0x10A0C: 84, + 0x10A0D: 84, + 0x10A0E: 84, + 0x10A0F: 84, + 0x10A38: 84, + 0x10A39: 84, + 0x10A3A: 84, + 0x10A3F: 84, + 0x10AC0: 68, + 0x10AC1: 68, + 0x10AC2: 68, + 0x10AC3: 68, + 0x10AC4: 68, + 0x10AC5: 82, + 0x10AC7: 82, + 0x10AC9: 82, + 0x10ACA: 82, + 0x10ACD: 76, + 0x10ACE: 82, + 0x10ACF: 82, + 0x10AD0: 82, + 0x10AD1: 82, + 0x10AD2: 82, + 0x10AD3: 68, + 0x10AD4: 68, + 0x10AD5: 68, + 0x10AD6: 68, + 0x10AD7: 76, + 0x10AD8: 68, + 0x10AD9: 68, + 0x10ADA: 68, + 0x10ADB: 68, + 0x10ADC: 68, + 0x10ADD: 82, + 0x10ADE: 68, + 0x10ADF: 68, + 0x10AE0: 68, + 0x10AE1: 82, + 0x10AE4: 82, + 0x10AE5: 84, + 0x10AE6: 84, + 0x10AEB: 68, + 0x10AEC: 68, + 0x10AED: 68, + 0x10AEE: 68, + 0x10AEF: 82, + 0x10B80: 68, + 0x10B81: 82, + 0x10B82: 68, + 0x10B83: 82, + 0x10B84: 82, + 0x10B85: 82, + 0x10B86: 68, + 0x10B87: 68, + 0x10B88: 68, + 0x10B89: 82, + 0x10B8A: 68, + 0x10B8B: 68, + 0x10B8C: 82, + 0x10B8D: 68, + 0x10B8E: 82, + 0x10B8F: 82, + 0x10B90: 68, + 0x10B91: 82, + 0x10BA9: 82, + 0x10BAA: 82, + 0x10BAB: 82, + 0x10BAC: 82, + 0x10BAD: 68, + 0x10BAE: 68, + 0x10D00: 76, + 0x10D01: 68, + 0x10D02: 68, + 0x10D03: 68, + 0x10D04: 68, + 0x10D05: 68, + 0x10D06: 68, + 0x10D07: 68, + 0x10D08: 68, + 0x10D09: 68, + 0x10D0A: 68, + 0x10D0B: 68, + 0x10D0C: 68, + 0x10D0D: 68, + 0x10D0E: 68, + 0x10D0F: 68, + 0x10D10: 68, + 0x10D11: 68, + 0x10D12: 68, + 0x10D13: 68, + 0x10D14: 68, + 0x10D15: 68, + 0x10D16: 68, + 0x10D17: 68, + 0x10D18: 68, + 0x10D19: 68, + 0x10D1A: 68, + 0x10D1B: 68, + 0x10D1C: 68, + 0x10D1D: 68, + 0x10D1E: 68, + 0x10D1F: 68, + 0x10D20: 68, + 0x10D21: 68, + 0x10D22: 82, + 0x10D23: 68, + 0x10D24: 84, + 0x10D25: 84, + 0x10D26: 84, + 0x10D27: 84, + 0x10D69: 84, + 0x10D6A: 84, + 0x10D6B: 84, + 0x10D6C: 84, + 0x10D6D: 84, + 0x10EAB: 84, + 0x10EAC: 84, + 0x10EC2: 82, + 0x10EC3: 68, + 0x10EC4: 68, + 0x10EC6: 68, + 0x10EC7: 68, + 0x10EFA: 84, + 0x10EFB: 84, + 0x10EFC: 84, + 0x10EFD: 84, + 0x10EFE: 84, + 0x10EFF: 84, + 0x10F30: 68, + 0x10F31: 68, + 0x10F32: 68, + 0x10F33: 82, + 0x10F34: 68, + 0x10F35: 68, + 0x10F36: 68, + 0x10F37: 68, + 0x10F38: 68, + 0x10F39: 68, + 0x10F3A: 68, + 0x10F3B: 68, + 0x10F3C: 68, + 0x10F3D: 68, + 0x10F3E: 68, + 0x10F3F: 68, + 0x10F40: 68, + 0x10F41: 68, + 0x10F42: 68, + 0x10F43: 68, + 0x10F44: 68, + 0x10F46: 84, + 0x10F47: 84, + 0x10F48: 84, + 0x10F49: 84, + 0x10F4A: 84, + 0x10F4B: 84, + 0x10F4C: 84, + 0x10F4D: 84, + 0x10F4E: 84, + 0x10F4F: 84, + 0x10F50: 84, + 0x10F51: 68, + 0x10F52: 68, + 0x10F53: 68, + 0x10F54: 82, + 0x10F70: 68, + 0x10F71: 68, + 0x10F72: 68, + 0x10F73: 68, + 0x10F74: 82, + 0x10F75: 82, + 0x10F76: 68, + 0x10F77: 68, + 0x10F78: 68, + 0x10F79: 68, + 0x10F7A: 68, + 0x10F7B: 68, + 0x10F7C: 68, + 0x10F7D: 68, + 0x10F7E: 68, + 0x10F7F: 68, + 0x10F80: 68, + 0x10F81: 68, + 0x10F82: 84, + 0x10F83: 84, + 0x10F84: 84, + 0x10F85: 84, + 0x10FB0: 68, + 0x10FB2: 68, + 0x10FB3: 68, + 0x10FB4: 82, + 0x10FB5: 82, + 0x10FB6: 82, + 0x10FB8: 68, + 0x10FB9: 82, + 0x10FBA: 82, + 0x10FBB: 68, + 0x10FBC: 68, + 0x10FBD: 82, + 0x10FBE: 68, + 0x10FBF: 68, + 0x10FC1: 68, + 0x10FC2: 82, + 0x10FC3: 82, + 0x10FC4: 68, + 0x10FC9: 82, + 0x10FCA: 68, + 0x10FCB: 76, + 0x11001: 84, + 0x11038: 84, + 0x11039: 84, + 0x1103A: 84, + 0x1103B: 84, + 0x1103C: 84, + 0x1103D: 84, + 0x1103E: 84, + 0x1103F: 84, + 0x11040: 84, + 0x11041: 84, + 0x11042: 84, + 0x11043: 84, + 0x11044: 84, + 0x11045: 84, + 0x11046: 84, + 0x11070: 84, + 0x11073: 84, + 0x11074: 84, + 0x1107F: 84, + 0x11080: 84, + 0x11081: 84, + 0x110B3: 84, + 0x110B4: 84, + 0x110B5: 84, + 0x110B6: 84, + 0x110B9: 84, + 0x110BA: 84, + 0x110C2: 84, + 0x11100: 84, + 0x11101: 84, + 0x11102: 84, + 0x11127: 84, + 0x11128: 84, + 0x11129: 84, + 0x1112A: 84, + 0x1112B: 84, + 0x1112D: 84, + 0x1112E: 84, + 0x1112F: 84, + 0x11130: 84, + 0x11131: 84, + 0x11132: 84, + 0x11133: 84, + 0x11134: 84, + 0x11173: 84, + 0x11180: 84, + 0x11181: 84, + 0x111B6: 84, + 0x111B7: 84, + 0x111B8: 84, + 0x111B9: 84, + 0x111BA: 84, + 0x111BB: 84, + 0x111BC: 84, + 0x111BD: 84, + 0x111BE: 84, + 0x111C9: 84, + 0x111CA: 84, + 0x111CB: 84, + 0x111CC: 84, + 0x111CF: 84, + 0x1122F: 84, + 0x11230: 84, + 0x11231: 84, + 0x11234: 84, + 0x11236: 84, + 0x11237: 84, + 0x1123E: 84, + 0x11241: 84, + 0x112DF: 84, + 0x112E3: 84, + 0x112E4: 84, + 0x112E5: 84, + 0x112E6: 84, + 0x112E7: 84, + 0x112E8: 84, + 0x112E9: 84, + 0x112EA: 84, + 0x11300: 84, + 0x11301: 84, + 0x1133B: 84, + 0x1133C: 84, + 0x11340: 84, + 0x11366: 84, + 0x11367: 84, + 0x11368: 84, + 0x11369: 84, + 0x1136A: 84, + 0x1136B: 84, + 0x1136C: 84, + 0x11370: 84, + 0x11371: 84, + 0x11372: 84, + 0x11373: 84, + 0x11374: 84, + 0x113BB: 84, + 0x113BC: 84, + 0x113BD: 84, + 0x113BE: 84, + 0x113BF: 84, + 0x113C0: 84, + 0x113CE: 84, + 0x113D0: 84, + 0x113D2: 84, + 0x113E1: 84, + 0x113E2: 84, + 0x11438: 84, + 0x11439: 84, + 0x1143A: 84, + 0x1143B: 84, + 0x1143C: 84, + 0x1143D: 84, + 0x1143E: 84, + 0x1143F: 84, + 0x11442: 84, + 0x11443: 84, + 0x11444: 84, + 0x11446: 84, + 0x1145E: 84, + 0x114B3: 84, + 0x114B4: 84, + 0x114B5: 84, + 0x114B6: 84, + 0x114B7: 84, + 0x114B8: 84, + 0x114BA: 84, + 0x114BF: 84, + 0x114C0: 84, + 0x114C2: 84, + 0x114C3: 84, + 0x115B2: 84, + 0x115B3: 84, + 0x115B4: 84, + 0x115B5: 84, + 0x115BC: 84, + 0x115BD: 84, + 0x115BF: 84, + 0x115C0: 84, + 0x115DC: 84, + 0x115DD: 84, + 0x11633: 84, + 0x11634: 84, + 0x11635: 84, + 0x11636: 84, + 0x11637: 84, + 0x11638: 84, + 0x11639: 84, + 0x1163A: 84, + 0x1163D: 84, + 0x1163F: 84, + 0x11640: 84, + 0x116AB: 84, + 0x116AD: 84, + 0x116B0: 84, + 0x116B1: 84, + 0x116B2: 84, + 0x116B3: 84, + 0x116B4: 84, + 0x116B5: 84, + 0x116B7: 84, + 0x1171D: 84, + 0x1171F: 84, + 0x11722: 84, + 0x11723: 84, + 0x11724: 84, + 0x11725: 84, + 0x11727: 84, + 0x11728: 84, + 0x11729: 84, + 0x1172A: 84, + 0x1172B: 84, + 0x1182F: 84, + 0x11830: 84, + 0x11831: 84, + 0x11832: 84, + 0x11833: 84, + 0x11834: 84, + 0x11835: 84, + 0x11836: 84, + 0x11837: 84, + 0x11839: 84, + 0x1183A: 84, + 0x1193B: 84, + 0x1193C: 84, + 0x1193E: 84, + 0x11943: 84, + 0x119D4: 84, + 0x119D5: 84, + 0x119D6: 84, + 0x119D7: 84, + 0x119DA: 84, + 0x119DB: 84, + 0x119E0: 84, + 0x11A01: 84, + 0x11A02: 84, + 0x11A03: 84, + 0x11A04: 84, + 0x11A05: 84, + 0x11A06: 84, + 0x11A07: 84, + 0x11A08: 84, + 0x11A09: 84, + 0x11A0A: 84, + 0x11A33: 84, + 0x11A34: 84, + 0x11A35: 84, + 0x11A36: 84, + 0x11A37: 84, + 0x11A38: 84, + 0x11A3B: 84, + 0x11A3C: 84, + 0x11A3D: 84, + 0x11A3E: 84, + 0x11A47: 84, + 0x11A51: 84, + 0x11A52: 84, + 0x11A53: 84, + 0x11A54: 84, + 0x11A55: 84, + 0x11A56: 84, + 0x11A59: 84, + 0x11A5A: 84, + 0x11A5B: 84, + 0x11A8A: 84, + 0x11A8B: 84, + 0x11A8C: 84, + 0x11A8D: 84, + 0x11A8E: 84, + 0x11A8F: 84, + 0x11A90: 84, + 0x11A91: 84, + 0x11A92: 84, + 0x11A93: 84, + 0x11A94: 84, + 0x11A95: 84, + 0x11A96: 84, + 0x11A98: 84, + 0x11A99: 84, + 0x11B60: 84, + 0x11B62: 84, + 0x11B63: 84, + 0x11B64: 84, + 0x11B66: 84, + 0x11C30: 84, + 0x11C31: 84, + 0x11C32: 84, + 0x11C33: 84, + 0x11C34: 84, + 0x11C35: 84, + 0x11C36: 84, + 0x11C38: 84, + 0x11C39: 84, + 0x11C3A: 84, + 0x11C3B: 84, + 0x11C3C: 84, + 0x11C3D: 84, + 0x11C3F: 84, + 0x11C92: 84, + 0x11C93: 84, + 0x11C94: 84, + 0x11C95: 84, + 0x11C96: 84, + 0x11C97: 84, + 0x11C98: 84, + 0x11C99: 84, + 0x11C9A: 84, + 0x11C9B: 84, + 0x11C9C: 84, + 0x11C9D: 84, + 0x11C9E: 84, + 0x11C9F: 84, + 0x11CA0: 84, + 0x11CA1: 84, + 0x11CA2: 84, + 0x11CA3: 84, + 0x11CA4: 84, + 0x11CA5: 84, + 0x11CA6: 84, + 0x11CA7: 84, + 0x11CAA: 84, + 0x11CAB: 84, + 0x11CAC: 84, + 0x11CAD: 84, + 0x11CAE: 84, + 0x11CAF: 84, + 0x11CB0: 84, + 0x11CB2: 84, + 0x11CB3: 84, + 0x11CB5: 84, + 0x11CB6: 84, + 0x11D31: 84, + 0x11D32: 84, + 0x11D33: 84, + 0x11D34: 84, + 0x11D35: 84, + 0x11D36: 84, + 0x11D3A: 84, + 0x11D3C: 84, + 0x11D3D: 84, + 0x11D3F: 84, + 0x11D40: 84, + 0x11D41: 84, + 0x11D42: 84, + 0x11D43: 84, + 0x11D44: 84, + 0x11D45: 84, + 0x11D47: 84, + 0x11D90: 84, + 0x11D91: 84, + 0x11D95: 84, + 0x11D97: 84, + 0x11EF3: 84, + 0x11EF4: 84, + 0x11F00: 84, + 0x11F01: 84, + 0x11F36: 84, + 0x11F37: 84, + 0x11F38: 84, + 0x11F39: 84, + 0x11F3A: 84, + 0x11F40: 84, + 0x11F42: 84, + 0x11F5A: 84, + 0x13430: 84, + 0x13431: 84, + 0x13432: 84, + 0x13433: 84, + 0x13434: 84, + 0x13435: 84, + 0x13436: 84, + 0x13437: 84, + 0x13438: 84, + 0x13439: 84, + 0x1343A: 84, + 0x1343B: 84, + 0x1343C: 84, + 0x1343D: 84, + 0x1343E: 84, + 0x1343F: 84, + 0x13440: 84, + 0x13447: 84, + 0x13448: 84, + 0x13449: 84, + 0x1344A: 84, + 0x1344B: 84, + 0x1344C: 84, + 0x1344D: 84, + 0x1344E: 84, + 0x1344F: 84, + 0x13450: 84, + 0x13451: 84, + 0x13452: 84, + 0x13453: 84, + 0x13454: 84, + 0x13455: 84, + 0x1611E: 84, + 0x1611F: 84, + 0x16120: 84, + 0x16121: 84, + 0x16122: 84, + 0x16123: 84, + 0x16124: 84, + 0x16125: 84, + 0x16126: 84, + 0x16127: 84, + 0x16128: 84, + 0x16129: 84, + 0x1612D: 84, + 0x1612E: 84, + 0x1612F: 84, + 0x16AF0: 84, + 0x16AF1: 84, + 0x16AF2: 84, + 0x16AF3: 84, + 0x16AF4: 84, + 0x16B30: 84, + 0x16B31: 84, + 0x16B32: 84, + 0x16B33: 84, + 0x16B34: 84, + 0x16B35: 84, + 0x16B36: 84, + 0x16F4F: 84, + 0x16F8F: 84, + 0x16F90: 84, + 0x16F91: 84, + 0x16F92: 84, + 0x16FE4: 84, + 0x1BC9D: 84, + 0x1BC9E: 84, + 0x1BCA0: 84, + 0x1BCA1: 84, + 0x1BCA2: 84, + 0x1BCA3: 84, + 0x1CF00: 84, + 0x1CF01: 84, + 0x1CF02: 84, + 0x1CF03: 84, + 0x1CF04: 84, + 0x1CF05: 84, + 0x1CF06: 84, + 0x1CF07: 84, + 0x1CF08: 84, + 0x1CF09: 84, + 0x1CF0A: 84, + 0x1CF0B: 84, + 0x1CF0C: 84, + 0x1CF0D: 84, + 0x1CF0E: 84, + 0x1CF0F: 84, + 0x1CF10: 84, + 0x1CF11: 84, + 0x1CF12: 84, + 0x1CF13: 84, + 0x1CF14: 84, + 0x1CF15: 84, + 0x1CF16: 84, + 0x1CF17: 84, + 0x1CF18: 84, + 0x1CF19: 84, + 0x1CF1A: 84, + 0x1CF1B: 84, + 0x1CF1C: 84, + 0x1CF1D: 84, + 0x1CF1E: 84, + 0x1CF1F: 84, + 0x1CF20: 84, + 0x1CF21: 84, + 0x1CF22: 84, + 0x1CF23: 84, + 0x1CF24: 84, + 0x1CF25: 84, + 0x1CF26: 84, + 0x1CF27: 84, + 0x1CF28: 84, + 0x1CF29: 84, + 0x1CF2A: 84, + 0x1CF2B: 84, + 0x1CF2C: 84, + 0x1CF2D: 84, + 0x1CF30: 84, + 0x1CF31: 84, + 0x1CF32: 84, + 0x1CF33: 84, + 0x1CF34: 84, + 0x1CF35: 84, + 0x1CF36: 84, + 0x1CF37: 84, + 0x1CF38: 84, + 0x1CF39: 84, + 0x1CF3A: 84, + 0x1CF3B: 84, + 0x1CF3C: 84, + 0x1CF3D: 84, + 0x1CF3E: 84, + 0x1CF3F: 84, + 0x1CF40: 84, + 0x1CF41: 84, + 0x1CF42: 84, + 0x1CF43: 84, + 0x1CF44: 84, + 0x1CF45: 84, + 0x1CF46: 84, + 0x1D167: 84, + 0x1D168: 84, + 0x1D169: 84, + 0x1D173: 84, + 0x1D174: 84, + 0x1D175: 84, + 0x1D176: 84, + 0x1D177: 84, + 0x1D178: 84, + 0x1D179: 84, + 0x1D17A: 84, + 0x1D17B: 84, + 0x1D17C: 84, + 0x1D17D: 84, + 0x1D17E: 84, + 0x1D17F: 84, + 0x1D180: 84, + 0x1D181: 84, + 0x1D182: 84, + 0x1D185: 84, + 0x1D186: 84, + 0x1D187: 84, + 0x1D188: 84, + 0x1D189: 84, + 0x1D18A: 84, + 0x1D18B: 84, + 0x1D1AA: 84, + 0x1D1AB: 84, + 0x1D1AC: 84, + 0x1D1AD: 84, + 0x1D242: 84, + 0x1D243: 84, + 0x1D244: 84, + 0x1DA00: 84, + 0x1DA01: 84, + 0x1DA02: 84, + 0x1DA03: 84, + 0x1DA04: 84, + 0x1DA05: 84, + 0x1DA06: 84, + 0x1DA07: 84, + 0x1DA08: 84, + 0x1DA09: 84, + 0x1DA0A: 84, + 0x1DA0B: 84, + 0x1DA0C: 84, + 0x1DA0D: 84, + 0x1DA0E: 84, + 0x1DA0F: 84, + 0x1DA10: 84, + 0x1DA11: 84, + 0x1DA12: 84, + 0x1DA13: 84, + 0x1DA14: 84, + 0x1DA15: 84, + 0x1DA16: 84, + 0x1DA17: 84, + 0x1DA18: 84, + 0x1DA19: 84, + 0x1DA1A: 84, + 0x1DA1B: 84, + 0x1DA1C: 84, + 0x1DA1D: 84, + 0x1DA1E: 84, + 0x1DA1F: 84, + 0x1DA20: 84, + 0x1DA21: 84, + 0x1DA22: 84, + 0x1DA23: 84, + 0x1DA24: 84, + 0x1DA25: 84, + 0x1DA26: 84, + 0x1DA27: 84, + 0x1DA28: 84, + 0x1DA29: 84, + 0x1DA2A: 84, + 0x1DA2B: 84, + 0x1DA2C: 84, + 0x1DA2D: 84, + 0x1DA2E: 84, + 0x1DA2F: 84, + 0x1DA30: 84, + 0x1DA31: 84, + 0x1DA32: 84, + 0x1DA33: 84, + 0x1DA34: 84, + 0x1DA35: 84, + 0x1DA36: 84, + 0x1DA3B: 84, + 0x1DA3C: 84, + 0x1DA3D: 84, + 0x1DA3E: 84, + 0x1DA3F: 84, + 0x1DA40: 84, + 0x1DA41: 84, + 0x1DA42: 84, + 0x1DA43: 84, + 0x1DA44: 84, + 0x1DA45: 84, + 0x1DA46: 84, + 0x1DA47: 84, + 0x1DA48: 84, + 0x1DA49: 84, + 0x1DA4A: 84, + 0x1DA4B: 84, + 0x1DA4C: 84, + 0x1DA4D: 84, + 0x1DA4E: 84, + 0x1DA4F: 84, + 0x1DA50: 84, + 0x1DA51: 84, + 0x1DA52: 84, + 0x1DA53: 84, + 0x1DA54: 84, + 0x1DA55: 84, + 0x1DA56: 84, + 0x1DA57: 84, + 0x1DA58: 84, + 0x1DA59: 84, + 0x1DA5A: 84, + 0x1DA5B: 84, + 0x1DA5C: 84, + 0x1DA5D: 84, + 0x1DA5E: 84, + 0x1DA5F: 84, + 0x1DA60: 84, + 0x1DA61: 84, + 0x1DA62: 84, + 0x1DA63: 84, + 0x1DA64: 84, + 0x1DA65: 84, + 0x1DA66: 84, + 0x1DA67: 84, + 0x1DA68: 84, + 0x1DA69: 84, + 0x1DA6A: 84, + 0x1DA6B: 84, + 0x1DA6C: 84, + 0x1DA75: 84, + 0x1DA84: 84, + 0x1DA9B: 84, + 0x1DA9C: 84, + 0x1DA9D: 84, + 0x1DA9E: 84, + 0x1DA9F: 84, + 0x1DAA1: 84, + 0x1DAA2: 84, + 0x1DAA3: 84, + 0x1DAA4: 84, + 0x1DAA5: 84, + 0x1DAA6: 84, + 0x1DAA7: 84, + 0x1DAA8: 84, + 0x1DAA9: 84, + 0x1DAAA: 84, + 0x1DAAB: 84, + 0x1DAAC: 84, + 0x1DAAD: 84, + 0x1DAAE: 84, + 0x1DAAF: 84, + 0x1E000: 84, + 0x1E001: 84, + 0x1E002: 84, + 0x1E003: 84, + 0x1E004: 84, + 0x1E005: 84, + 0x1E006: 84, + 0x1E008: 84, + 0x1E009: 84, + 0x1E00A: 84, + 0x1E00B: 84, + 0x1E00C: 84, + 0x1E00D: 84, + 0x1E00E: 84, + 0x1E00F: 84, + 0x1E010: 84, + 0x1E011: 84, + 0x1E012: 84, + 0x1E013: 84, + 0x1E014: 84, + 0x1E015: 84, + 0x1E016: 84, + 0x1E017: 84, + 0x1E018: 84, + 0x1E01B: 84, + 0x1E01C: 84, + 0x1E01D: 84, + 0x1E01E: 84, + 0x1E01F: 84, + 0x1E020: 84, + 0x1E021: 84, + 0x1E023: 84, + 0x1E024: 84, + 0x1E026: 84, + 0x1E027: 84, + 0x1E028: 84, + 0x1E029: 84, + 0x1E02A: 84, + 0x1E08F: 84, + 0x1E130: 84, + 0x1E131: 84, + 0x1E132: 84, + 0x1E133: 84, + 0x1E134: 84, + 0x1E135: 84, + 0x1E136: 84, + 0x1E2AE: 84, + 0x1E2EC: 84, + 0x1E2ED: 84, + 0x1E2EE: 84, + 0x1E2EF: 84, + 0x1E4EC: 84, + 0x1E4ED: 84, + 0x1E4EE: 84, + 0x1E4EF: 84, + 0x1E5EE: 84, + 0x1E5EF: 84, + 0x1E6E3: 84, + 0x1E6E6: 84, + 0x1E6EE: 84, + 0x1E6EF: 84, + 0x1E6F5: 84, + 0x1E8D0: 84, + 0x1E8D1: 84, + 0x1E8D2: 84, + 0x1E8D3: 84, + 0x1E8D4: 84, + 0x1E8D5: 84, + 0x1E8D6: 84, + 0x1E900: 68, + 0x1E901: 68, + 0x1E902: 68, + 0x1E903: 68, + 0x1E904: 68, + 0x1E905: 68, + 0x1E906: 68, + 0x1E907: 68, + 0x1E908: 68, + 0x1E909: 68, + 0x1E90A: 68, + 0x1E90B: 68, + 0x1E90C: 68, + 0x1E90D: 68, + 0x1E90E: 68, + 0x1E90F: 68, + 0x1E910: 68, + 0x1E911: 68, + 0x1E912: 68, + 0x1E913: 68, + 0x1E914: 68, + 0x1E915: 68, + 0x1E916: 68, + 0x1E917: 68, + 0x1E918: 68, + 0x1E919: 68, + 0x1E91A: 68, + 0x1E91B: 68, + 0x1E91C: 68, + 0x1E91D: 68, + 0x1E91E: 68, + 0x1E91F: 68, + 0x1E920: 68, + 0x1E921: 68, + 0x1E922: 68, + 0x1E923: 68, + 0x1E924: 68, + 0x1E925: 68, + 0x1E926: 68, + 0x1E927: 68, + 0x1E928: 68, + 0x1E929: 68, + 0x1E92A: 68, + 0x1E92B: 68, + 0x1E92C: 68, + 0x1E92D: 68, + 0x1E92E: 68, + 0x1E92F: 68, + 0x1E930: 68, + 0x1E931: 68, + 0x1E932: 68, + 0x1E933: 68, + 0x1E934: 68, + 0x1E935: 68, + 0x1E936: 68, + 0x1E937: 68, + 0x1E938: 68, + 0x1E939: 68, + 0x1E93A: 68, + 0x1E93B: 68, + 0x1E93C: 68, + 0x1E93D: 68, + 0x1E93E: 68, + 0x1E93F: 68, + 0x1E940: 68, + 0x1E941: 68, + 0x1E942: 68, + 0x1E943: 68, + 0x1E944: 84, + 0x1E945: 84, + 0x1E946: 84, + 0x1E947: 84, + 0x1E948: 84, + 0x1E949: 84, + 0x1E94A: 84, + 0x1E94B: 84, + 0xE0001: 84, + 0xE0020: 84, + 0xE0021: 84, + 0xE0022: 84, + 0xE0023: 84, + 0xE0024: 84, + 0xE0025: 84, + 0xE0026: 84, + 0xE0027: 84, + 0xE0028: 84, + 0xE0029: 84, + 0xE002A: 84, + 0xE002B: 84, + 0xE002C: 84, + 0xE002D: 84, + 0xE002E: 84, + 0xE002F: 84, + 0xE0030: 84, + 0xE0031: 84, + 0xE0032: 84, + 0xE0033: 84, + 0xE0034: 84, + 0xE0035: 84, + 0xE0036: 84, + 0xE0037: 84, + 0xE0038: 84, + 0xE0039: 84, + 0xE003A: 84, + 0xE003B: 84, + 0xE003C: 84, + 0xE003D: 84, + 0xE003E: 84, + 0xE003F: 84, + 0xE0040: 84, + 0xE0041: 84, + 0xE0042: 84, + 0xE0043: 84, + 0xE0044: 84, + 0xE0045: 84, + 0xE0046: 84, + 0xE0047: 84, + 0xE0048: 84, + 0xE0049: 84, + 0xE004A: 84, + 0xE004B: 84, + 0xE004C: 84, + 0xE004D: 84, + 0xE004E: 84, + 0xE004F: 84, + 0xE0050: 84, + 0xE0051: 84, + 0xE0052: 84, + 0xE0053: 84, + 0xE0054: 84, + 0xE0055: 84, + 0xE0056: 84, + 0xE0057: 84, + 0xE0058: 84, + 0xE0059: 84, + 0xE005A: 84, + 0xE005B: 84, + 0xE005C: 84, + 0xE005D: 84, + 0xE005E: 84, + 0xE005F: 84, + 0xE0060: 84, + 0xE0061: 84, + 0xE0062: 84, + 0xE0063: 84, + 0xE0064: 84, + 0xE0065: 84, + 0xE0066: 84, + 0xE0067: 84, + 0xE0068: 84, + 0xE0069: 84, + 0xE006A: 84, + 0xE006B: 84, + 0xE006C: 84, + 0xE006D: 84, + 0xE006E: 84, + 0xE006F: 84, + 0xE0070: 84, + 0xE0071: 84, + 0xE0072: 84, + 0xE0073: 84, + 0xE0074: 84, + 0xE0075: 84, + 0xE0076: 84, + 0xE0077: 84, + 0xE0078: 84, + 0xE0079: 84, + 0xE007A: 84, + 0xE007B: 84, + 0xE007C: 84, + 0xE007D: 84, + 0xE007E: 84, + 0xE007F: 84, + 0xE0100: 84, + 0xE0101: 84, + 0xE0102: 84, + 0xE0103: 84, + 0xE0104: 84, + 0xE0105: 84, + 0xE0106: 84, + 0xE0107: 84, + 0xE0108: 84, + 0xE0109: 84, + 0xE010A: 84, + 0xE010B: 84, + 0xE010C: 84, + 0xE010D: 84, + 0xE010E: 84, + 0xE010F: 84, + 0xE0110: 84, + 0xE0111: 84, + 0xE0112: 84, + 0xE0113: 84, + 0xE0114: 84, + 0xE0115: 84, + 0xE0116: 84, + 0xE0117: 84, + 0xE0118: 84, + 0xE0119: 84, + 0xE011A: 84, + 0xE011B: 84, + 0xE011C: 84, + 0xE011D: 84, + 0xE011E: 84, + 0xE011F: 84, + 0xE0120: 84, + 0xE0121: 84, + 0xE0122: 84, + 0xE0123: 84, + 0xE0124: 84, + 0xE0125: 84, + 0xE0126: 84, + 0xE0127: 84, + 0xE0128: 84, + 0xE0129: 84, + 0xE012A: 84, + 0xE012B: 84, + 0xE012C: 84, + 0xE012D: 84, + 0xE012E: 84, + 0xE012F: 84, + 0xE0130: 84, + 0xE0131: 84, + 0xE0132: 84, + 0xE0133: 84, + 0xE0134: 84, + 0xE0135: 84, + 0xE0136: 84, + 0xE0137: 84, + 0xE0138: 84, + 0xE0139: 84, + 0xE013A: 84, + 0xE013B: 84, + 0xE013C: 84, + 0xE013D: 84, + 0xE013E: 84, + 0xE013F: 84, + 0xE0140: 84, + 0xE0141: 84, + 0xE0142: 84, + 0xE0143: 84, + 0xE0144: 84, + 0xE0145: 84, + 0xE0146: 84, + 0xE0147: 84, + 0xE0148: 84, + 0xE0149: 84, + 0xE014A: 84, + 0xE014B: 84, + 0xE014C: 84, + 0xE014D: 84, + 0xE014E: 84, + 0xE014F: 84, + 0xE0150: 84, + 0xE0151: 84, + 0xE0152: 84, + 0xE0153: 84, + 0xE0154: 84, + 0xE0155: 84, + 0xE0156: 84, + 0xE0157: 84, + 0xE0158: 84, + 0xE0159: 84, + 0xE015A: 84, + 0xE015B: 84, + 0xE015C: 84, + 0xE015D: 84, + 0xE015E: 84, + 0xE015F: 84, + 0xE0160: 84, + 0xE0161: 84, + 0xE0162: 84, + 0xE0163: 84, + 0xE0164: 84, + 0xE0165: 84, + 0xE0166: 84, + 0xE0167: 84, + 0xE0168: 84, + 0xE0169: 84, + 0xE016A: 84, + 0xE016B: 84, + 0xE016C: 84, + 0xE016D: 84, + 0xE016E: 84, + 0xE016F: 84, + 0xE0170: 84, + 0xE0171: 84, + 0xE0172: 84, + 0xE0173: 84, + 0xE0174: 84, + 0xE0175: 84, + 0xE0176: 84, + 0xE0177: 84, + 0xE0178: 84, + 0xE0179: 84, + 0xE017A: 84, + 0xE017B: 84, + 0xE017C: 84, + 0xE017D: 84, + 0xE017E: 84, + 0xE017F: 84, + 0xE0180: 84, + 0xE0181: 84, + 0xE0182: 84, + 0xE0183: 84, + 0xE0184: 84, + 0xE0185: 84, + 0xE0186: 84, + 0xE0187: 84, + 0xE0188: 84, + 0xE0189: 84, + 0xE018A: 84, + 0xE018B: 84, + 0xE018C: 84, + 0xE018D: 84, + 0xE018E: 84, + 0xE018F: 84, + 0xE0190: 84, + 0xE0191: 84, + 0xE0192: 84, + 0xE0193: 84, + 0xE0194: 84, + 0xE0195: 84, + 0xE0196: 84, + 0xE0197: 84, + 0xE0198: 84, + 0xE0199: 84, + 0xE019A: 84, + 0xE019B: 84, + 0xE019C: 84, + 0xE019D: 84, + 0xE019E: 84, + 0xE019F: 84, + 0xE01A0: 84, + 0xE01A1: 84, + 0xE01A2: 84, + 0xE01A3: 84, + 0xE01A4: 84, + 0xE01A5: 84, + 0xE01A6: 84, + 0xE01A7: 84, + 0xE01A8: 84, + 0xE01A9: 84, + 0xE01AA: 84, + 0xE01AB: 84, + 0xE01AC: 84, + 0xE01AD: 84, + 0xE01AE: 84, + 0xE01AF: 84, + 0xE01B0: 84, + 0xE01B1: 84, + 0xE01B2: 84, + 0xE01B3: 84, + 0xE01B4: 84, + 0xE01B5: 84, + 0xE01B6: 84, + 0xE01B7: 84, + 0xE01B8: 84, + 0xE01B9: 84, + 0xE01BA: 84, + 0xE01BB: 84, + 0xE01BC: 84, + 0xE01BD: 84, + 0xE01BE: 84, + 0xE01BF: 84, + 0xE01C0: 84, + 0xE01C1: 84, + 0xE01C2: 84, + 0xE01C3: 84, + 0xE01C4: 84, + 0xE01C5: 84, + 0xE01C6: 84, + 0xE01C7: 84, + 0xE01C8: 84, + 0xE01C9: 84, + 0xE01CA: 84, + 0xE01CB: 84, + 0xE01CC: 84, + 0xE01CD: 84, + 0xE01CE: 84, + 0xE01CF: 84, + 0xE01D0: 84, + 0xE01D1: 84, + 0xE01D2: 84, + 0xE01D3: 84, + 0xE01D4: 84, + 0xE01D5: 84, + 0xE01D6: 84, + 0xE01D7: 84, + 0xE01D8: 84, + 0xE01D9: 84, + 0xE01DA: 84, + 0xE01DB: 84, + 0xE01DC: 84, + 0xE01DD: 84, + 0xE01DE: 84, + 0xE01DF: 84, + 0xE01E0: 84, + 0xE01E1: 84, + 0xE01E2: 84, + 0xE01E3: 84, + 0xE01E4: 84, + 0xE01E5: 84, + 0xE01E6: 84, + 0xE01E7: 84, + 0xE01E8: 84, + 0xE01E9: 84, + 0xE01EA: 84, + 0xE01EB: 84, + 0xE01EC: 84, + 0xE01ED: 84, + 0xE01EE: 84, + 0xE01EF: 84, + } + + +codepoint_classes = { + "PVALID": ( + 0x2D0000002E, + 0x300000003A, + 0x610000007B, + 0xDF000000F7, + 0xF800000100, + 0x10100000102, + 0x10300000104, + 0x10500000106, + 0x10700000108, + 0x1090000010A, + 0x10B0000010C, + 0x10D0000010E, + 0x10F00000110, + 0x11100000112, + 0x11300000114, + 0x11500000116, + 0x11700000118, + 0x1190000011A, + 0x11B0000011C, + 0x11D0000011E, + 0x11F00000120, + 0x12100000122, + 0x12300000124, + 0x12500000126, + 0x12700000128, + 0x1290000012A, + 0x12B0000012C, + 0x12D0000012E, + 0x12F00000130, + 0x13100000132, + 0x13500000136, + 0x13700000139, + 0x13A0000013B, + 0x13C0000013D, + 0x13E0000013F, + 0x14200000143, + 0x14400000145, + 0x14600000147, + 0x14800000149, + 0x14B0000014C, + 0x14D0000014E, + 0x14F00000150, + 0x15100000152, + 0x15300000154, + 0x15500000156, + 0x15700000158, + 0x1590000015A, + 0x15B0000015C, + 0x15D0000015E, + 0x15F00000160, + 0x16100000162, + 0x16300000164, + 0x16500000166, + 0x16700000168, + 0x1690000016A, + 0x16B0000016C, + 0x16D0000016E, + 0x16F00000170, + 0x17100000172, + 0x17300000174, + 0x17500000176, + 0x17700000178, + 0x17A0000017B, + 0x17C0000017D, + 0x17E0000017F, + 0x18000000181, + 0x18300000184, + 0x18500000186, + 0x18800000189, + 0x18C0000018E, + 0x19200000193, + 0x19500000196, + 0x1990000019C, + 0x19E0000019F, + 0x1A1000001A2, + 0x1A3000001A4, + 0x1A5000001A6, + 0x1A8000001A9, + 0x1AA000001AC, + 0x1AD000001AE, + 0x1B0000001B1, + 0x1B4000001B5, + 0x1B6000001B7, + 0x1B9000001BC, + 0x1BD000001C4, + 0x1CE000001CF, + 0x1D0000001D1, + 0x1D2000001D3, + 0x1D4000001D5, + 0x1D6000001D7, + 0x1D8000001D9, + 0x1DA000001DB, + 0x1DC000001DE, + 0x1DF000001E0, + 0x1E1000001E2, + 0x1E3000001E4, + 0x1E5000001E6, + 0x1E7000001E8, + 0x1E9000001EA, + 0x1EB000001EC, + 0x1ED000001EE, + 0x1EF000001F1, + 0x1F5000001F6, + 0x1F9000001FA, + 0x1FB000001FC, + 0x1FD000001FE, + 0x1FF00000200, + 0x20100000202, + 0x20300000204, + 0x20500000206, + 0x20700000208, + 0x2090000020A, + 0x20B0000020C, + 0x20D0000020E, + 0x20F00000210, + 0x21100000212, + 0x21300000214, + 0x21500000216, + 0x21700000218, + 0x2190000021A, + 0x21B0000021C, + 0x21D0000021E, + 0x21F00000220, + 0x22100000222, + 0x22300000224, + 0x22500000226, + 0x22700000228, + 0x2290000022A, + 0x22B0000022C, + 0x22D0000022E, + 0x22F00000230, + 0x23100000232, + 0x2330000023A, + 0x23C0000023D, + 0x23F00000241, + 0x24200000243, + 0x24700000248, + 0x2490000024A, + 0x24B0000024C, + 0x24D0000024E, + 0x24F000002B0, + 0x2B9000002C2, + 0x2C6000002D2, + 0x2EC000002ED, + 0x2EE000002EF, + 0x30000000340, + 0x34200000343, + 0x3460000034F, + 0x35000000370, + 0x37100000372, + 0x37300000374, + 0x37700000378, + 0x37B0000037E, + 0x39000000391, + 0x3AC000003CF, + 0x3D7000003D8, + 0x3D9000003DA, + 0x3DB000003DC, + 0x3DD000003DE, + 0x3DF000003E0, + 0x3E1000003E2, + 0x3E3000003E4, + 0x3E5000003E6, + 0x3E7000003E8, + 0x3E9000003EA, + 0x3EB000003EC, + 0x3ED000003EE, + 0x3EF000003F0, + 0x3F3000003F4, + 0x3F8000003F9, + 0x3FB000003FD, + 0x43000000460, + 0x46100000462, + 0x46300000464, + 0x46500000466, + 0x46700000468, + 0x4690000046A, + 0x46B0000046C, + 0x46D0000046E, + 0x46F00000470, + 0x47100000472, + 0x47300000474, + 0x47500000476, + 0x47700000478, + 0x4790000047A, + 0x47B0000047C, + 0x47D0000047E, + 0x47F00000480, + 0x48100000482, + 0x48300000488, + 0x48B0000048C, + 0x48D0000048E, + 0x48F00000490, + 0x49100000492, + 0x49300000494, + 0x49500000496, + 0x49700000498, + 0x4990000049A, + 0x49B0000049C, + 0x49D0000049E, + 0x49F000004A0, + 0x4A1000004A2, + 0x4A3000004A4, + 0x4A5000004A6, + 0x4A7000004A8, + 0x4A9000004AA, + 0x4AB000004AC, + 0x4AD000004AE, + 0x4AF000004B0, + 0x4B1000004B2, + 0x4B3000004B4, + 0x4B5000004B6, + 0x4B7000004B8, + 0x4B9000004BA, + 0x4BB000004BC, + 0x4BD000004BE, + 0x4BF000004C0, + 0x4C2000004C3, + 0x4C4000004C5, + 0x4C6000004C7, + 0x4C8000004C9, + 0x4CA000004CB, + 0x4CC000004CD, + 0x4CE000004D0, + 0x4D1000004D2, + 0x4D3000004D4, + 0x4D5000004D6, + 0x4D7000004D8, + 0x4D9000004DA, + 0x4DB000004DC, + 0x4DD000004DE, + 0x4DF000004E0, + 0x4E1000004E2, + 0x4E3000004E4, + 0x4E5000004E6, + 0x4E7000004E8, + 0x4E9000004EA, + 0x4EB000004EC, + 0x4ED000004EE, + 0x4EF000004F0, + 0x4F1000004F2, + 0x4F3000004F4, + 0x4F5000004F6, + 0x4F7000004F8, + 0x4F9000004FA, + 0x4FB000004FC, + 0x4FD000004FE, + 0x4FF00000500, + 0x50100000502, + 0x50300000504, + 0x50500000506, + 0x50700000508, + 0x5090000050A, + 0x50B0000050C, + 0x50D0000050E, + 0x50F00000510, + 0x51100000512, + 0x51300000514, + 0x51500000516, + 0x51700000518, + 0x5190000051A, + 0x51B0000051C, + 0x51D0000051E, + 0x51F00000520, + 0x52100000522, + 0x52300000524, + 0x52500000526, + 0x52700000528, + 0x5290000052A, + 0x52B0000052C, + 0x52D0000052E, + 0x52F00000530, + 0x5590000055A, + 0x56000000587, + 0x58800000589, + 0x591000005BE, + 0x5BF000005C0, + 0x5C1000005C3, + 0x5C4000005C6, + 0x5C7000005C8, + 0x5D0000005EB, + 0x5EF000005F3, + 0x6100000061B, + 0x62000000640, + 0x64100000660, + 0x66E00000675, + 0x679000006D4, + 0x6D5000006DD, + 0x6DF000006E9, + 0x6EA000006F0, + 0x6FA00000700, + 0x7100000074B, + 0x74D000007B2, + 0x7C0000007F6, + 0x7FD000007FE, + 0x8000000082E, + 0x8400000085C, + 0x8600000086B, + 0x87000000888, + 0x88900000890, + 0x897000008E2, + 0x8E300000958, + 0x96000000964, + 0x96600000970, + 0x97100000984, + 0x9850000098D, + 0x98F00000991, + 0x993000009A9, + 0x9AA000009B1, + 0x9B2000009B3, + 0x9B6000009BA, + 0x9BC000009C5, + 0x9C7000009C9, + 0x9CB000009CF, + 0x9D7000009D8, + 0x9E0000009E4, + 0x9E6000009F2, + 0x9FC000009FD, + 0x9FE000009FF, + 0xA0100000A04, + 0xA0500000A0B, + 0xA0F00000A11, + 0xA1300000A29, + 0xA2A00000A31, + 0xA3200000A33, + 0xA3500000A36, + 0xA3800000A3A, + 0xA3C00000A3D, + 0xA3E00000A43, + 0xA4700000A49, + 0xA4B00000A4E, + 0xA5100000A52, + 0xA5C00000A5D, + 0xA6600000A76, + 0xA8100000A84, + 0xA8500000A8E, + 0xA8F00000A92, + 0xA9300000AA9, + 0xAAA00000AB1, + 0xAB200000AB4, + 0xAB500000ABA, + 0xABC00000AC6, + 0xAC700000ACA, + 0xACB00000ACE, + 0xAD000000AD1, + 0xAE000000AE4, + 0xAE600000AF0, + 0xAF900000B00, + 0xB0100000B04, + 0xB0500000B0D, + 0xB0F00000B11, + 0xB1300000B29, + 0xB2A00000B31, + 0xB3200000B34, + 0xB3500000B3A, + 0xB3C00000B45, + 0xB4700000B49, + 0xB4B00000B4E, + 0xB5500000B58, + 0xB5F00000B64, + 0xB6600000B70, + 0xB7100000B72, + 0xB8200000B84, + 0xB8500000B8B, + 0xB8E00000B91, + 0xB9200000B96, + 0xB9900000B9B, + 0xB9C00000B9D, + 0xB9E00000BA0, + 0xBA300000BA5, + 0xBA800000BAB, + 0xBAE00000BBA, + 0xBBE00000BC3, + 0xBC600000BC9, + 0xBCA00000BCE, + 0xBD000000BD1, + 0xBD700000BD8, + 0xBE600000BF0, + 0xC0000000C0D, + 0xC0E00000C11, + 0xC1200000C29, + 0xC2A00000C3A, + 0xC3C00000C45, + 0xC4600000C49, + 0xC4A00000C4E, + 0xC5500000C57, + 0xC5800000C5B, + 0xC5C00000C5E, + 0xC6000000C64, + 0xC6600000C70, + 0xC8000000C84, + 0xC8500000C8D, + 0xC8E00000C91, + 0xC9200000CA9, + 0xCAA00000CB4, + 0xCB500000CBA, + 0xCBC00000CC5, + 0xCC600000CC9, + 0xCCA00000CCE, + 0xCD500000CD7, + 0xCDC00000CDF, + 0xCE000000CE4, + 0xCE600000CF0, + 0xCF100000CF4, + 0xD0000000D0D, + 0xD0E00000D11, + 0xD1200000D45, + 0xD4600000D49, + 0xD4A00000D4F, + 0xD5400000D58, + 0xD5F00000D64, + 0xD6600000D70, + 0xD7A00000D80, + 0xD8100000D84, + 0xD8500000D97, + 0xD9A00000DB2, + 0xDB300000DBC, + 0xDBD00000DBE, + 0xDC000000DC7, + 0xDCA00000DCB, + 0xDCF00000DD5, + 0xDD600000DD7, + 0xDD800000DE0, + 0xDE600000DF0, + 0xDF200000DF4, + 0xE0100000E33, + 0xE3400000E3B, + 0xE4000000E4F, + 0xE5000000E5A, + 0xE8100000E83, + 0xE8400000E85, + 0xE8600000E8B, + 0xE8C00000EA4, + 0xEA500000EA6, + 0xEA700000EB3, + 0xEB400000EBE, + 0xEC000000EC5, + 0xEC600000EC7, + 0xEC800000ECF, + 0xED000000EDA, + 0xEDE00000EE0, + 0xF0000000F01, + 0xF0B00000F0C, + 0xF1800000F1A, + 0xF2000000F2A, + 0xF3500000F36, + 0xF3700000F38, + 0xF3900000F3A, + 0xF3E00000F43, + 0xF4400000F48, + 0xF4900000F4D, + 0xF4E00000F52, + 0xF5300000F57, + 0xF5800000F5C, + 0xF5D00000F69, + 0xF6A00000F6D, + 0xF7100000F73, + 0xF7400000F75, + 0xF7A00000F81, + 0xF8200000F85, + 0xF8600000F93, + 0xF9400000F98, + 0xF9900000F9D, + 0xF9E00000FA2, + 0xFA300000FA7, + 0xFA800000FAC, + 0xFAD00000FB9, + 0xFBA00000FBD, + 0xFC600000FC7, + 0x10000000104A, + 0x10500000109E, + 0x10D0000010FB, + 0x10FD00001100, + 0x120000001249, + 0x124A0000124E, + 0x125000001257, + 0x125800001259, + 0x125A0000125E, + 0x126000001289, + 0x128A0000128E, + 0x1290000012B1, + 0x12B2000012B6, + 0x12B8000012BF, + 0x12C0000012C1, + 0x12C2000012C6, + 0x12C8000012D7, + 0x12D800001311, + 0x131200001316, + 0x13180000135B, + 0x135D00001360, + 0x138000001390, + 0x13A0000013F6, + 0x14010000166D, + 0x166F00001680, + 0x16810000169B, + 0x16A0000016EB, + 0x16F1000016F9, + 0x170000001716, + 0x171F00001735, + 0x174000001754, + 0x17600000176D, + 0x176E00001771, + 0x177200001774, + 0x1780000017B4, + 0x17B6000017D4, + 0x17D7000017D8, + 0x17DC000017DE, + 0x17E0000017EA, + 0x18100000181A, + 0x182000001879, + 0x1880000018AB, + 0x18B0000018F6, + 0x19000000191F, + 0x19200000192C, + 0x19300000193C, + 0x19460000196E, + 0x197000001975, + 0x1980000019AC, + 0x19B0000019CA, + 0x19D0000019DA, + 0x1A0000001A1C, + 0x1A2000001A5F, + 0x1A6000001A7D, + 0x1A7F00001A8A, + 0x1A9000001A9A, + 0x1AA700001AA8, + 0x1AB000001ABE, + 0x1ABF00001ADE, + 0x1AE000001AEC, + 0x1B0000001B4D, + 0x1B5000001B5A, + 0x1B6B00001B74, + 0x1B8000001BF4, + 0x1C0000001C38, + 0x1C4000001C4A, + 0x1C4D00001C7E, + 0x1C8A00001C8B, + 0x1CD000001CD3, + 0x1CD400001CFB, + 0x1D0000001D2C, + 0x1D2F00001D30, + 0x1D3B00001D3C, + 0x1D4E00001D4F, + 0x1D6B00001D78, + 0x1D7900001D9B, + 0x1DC000001E00, + 0x1E0100001E02, + 0x1E0300001E04, + 0x1E0500001E06, + 0x1E0700001E08, + 0x1E0900001E0A, + 0x1E0B00001E0C, + 0x1E0D00001E0E, + 0x1E0F00001E10, + 0x1E1100001E12, + 0x1E1300001E14, + 0x1E1500001E16, + 0x1E1700001E18, + 0x1E1900001E1A, + 0x1E1B00001E1C, + 0x1E1D00001E1E, + 0x1E1F00001E20, + 0x1E2100001E22, + 0x1E2300001E24, + 0x1E2500001E26, + 0x1E2700001E28, + 0x1E2900001E2A, + 0x1E2B00001E2C, + 0x1E2D00001E2E, + 0x1E2F00001E30, + 0x1E3100001E32, + 0x1E3300001E34, + 0x1E3500001E36, + 0x1E3700001E38, + 0x1E3900001E3A, + 0x1E3B00001E3C, + 0x1E3D00001E3E, + 0x1E3F00001E40, + 0x1E4100001E42, + 0x1E4300001E44, + 0x1E4500001E46, + 0x1E4700001E48, + 0x1E4900001E4A, + 0x1E4B00001E4C, + 0x1E4D00001E4E, + 0x1E4F00001E50, + 0x1E5100001E52, + 0x1E5300001E54, + 0x1E5500001E56, + 0x1E5700001E58, + 0x1E5900001E5A, + 0x1E5B00001E5C, + 0x1E5D00001E5E, + 0x1E5F00001E60, + 0x1E6100001E62, + 0x1E6300001E64, + 0x1E6500001E66, + 0x1E6700001E68, + 0x1E6900001E6A, + 0x1E6B00001E6C, + 0x1E6D00001E6E, + 0x1E6F00001E70, + 0x1E7100001E72, + 0x1E7300001E74, + 0x1E7500001E76, + 0x1E7700001E78, + 0x1E7900001E7A, + 0x1E7B00001E7C, + 0x1E7D00001E7E, + 0x1E7F00001E80, + 0x1E8100001E82, + 0x1E8300001E84, + 0x1E8500001E86, + 0x1E8700001E88, + 0x1E8900001E8A, + 0x1E8B00001E8C, + 0x1E8D00001E8E, + 0x1E8F00001E90, + 0x1E9100001E92, + 0x1E9300001E94, + 0x1E9500001E9A, + 0x1E9C00001E9E, + 0x1E9F00001EA0, + 0x1EA100001EA2, + 0x1EA300001EA4, + 0x1EA500001EA6, + 0x1EA700001EA8, + 0x1EA900001EAA, + 0x1EAB00001EAC, + 0x1EAD00001EAE, + 0x1EAF00001EB0, + 0x1EB100001EB2, + 0x1EB300001EB4, + 0x1EB500001EB6, + 0x1EB700001EB8, + 0x1EB900001EBA, + 0x1EBB00001EBC, + 0x1EBD00001EBE, + 0x1EBF00001EC0, + 0x1EC100001EC2, + 0x1EC300001EC4, + 0x1EC500001EC6, + 0x1EC700001EC8, + 0x1EC900001ECA, + 0x1ECB00001ECC, + 0x1ECD00001ECE, + 0x1ECF00001ED0, + 0x1ED100001ED2, + 0x1ED300001ED4, + 0x1ED500001ED6, + 0x1ED700001ED8, + 0x1ED900001EDA, + 0x1EDB00001EDC, + 0x1EDD00001EDE, + 0x1EDF00001EE0, + 0x1EE100001EE2, + 0x1EE300001EE4, + 0x1EE500001EE6, + 0x1EE700001EE8, + 0x1EE900001EEA, + 0x1EEB00001EEC, + 0x1EED00001EEE, + 0x1EEF00001EF0, + 0x1EF100001EF2, + 0x1EF300001EF4, + 0x1EF500001EF6, + 0x1EF700001EF8, + 0x1EF900001EFA, + 0x1EFB00001EFC, + 0x1EFD00001EFE, + 0x1EFF00001F08, + 0x1F1000001F16, + 0x1F2000001F28, + 0x1F3000001F38, + 0x1F4000001F46, + 0x1F5000001F58, + 0x1F6000001F68, + 0x1F7000001F71, + 0x1F7200001F73, + 0x1F7400001F75, + 0x1F7600001F77, + 0x1F7800001F79, + 0x1F7A00001F7B, + 0x1F7C00001F7D, + 0x1FB000001FB2, + 0x1FB600001FB7, + 0x1FC600001FC7, + 0x1FD000001FD3, + 0x1FD600001FD8, + 0x1FE000001FE3, + 0x1FE400001FE8, + 0x1FF600001FF7, + 0x214E0000214F, + 0x218400002185, + 0x2C3000002C60, + 0x2C6100002C62, + 0x2C6500002C67, + 0x2C6800002C69, + 0x2C6A00002C6B, + 0x2C6C00002C6D, + 0x2C7100002C72, + 0x2C7300002C75, + 0x2C7600002C7C, + 0x2C8100002C82, + 0x2C8300002C84, + 0x2C8500002C86, + 0x2C8700002C88, + 0x2C8900002C8A, + 0x2C8B00002C8C, + 0x2C8D00002C8E, + 0x2C8F00002C90, + 0x2C9100002C92, + 0x2C9300002C94, + 0x2C9500002C96, + 0x2C9700002C98, + 0x2C9900002C9A, + 0x2C9B00002C9C, + 0x2C9D00002C9E, + 0x2C9F00002CA0, + 0x2CA100002CA2, + 0x2CA300002CA4, + 0x2CA500002CA6, + 0x2CA700002CA8, + 0x2CA900002CAA, + 0x2CAB00002CAC, + 0x2CAD00002CAE, + 0x2CAF00002CB0, + 0x2CB100002CB2, + 0x2CB300002CB4, + 0x2CB500002CB6, + 0x2CB700002CB8, + 0x2CB900002CBA, + 0x2CBB00002CBC, + 0x2CBD00002CBE, + 0x2CBF00002CC0, + 0x2CC100002CC2, + 0x2CC300002CC4, + 0x2CC500002CC6, + 0x2CC700002CC8, + 0x2CC900002CCA, + 0x2CCB00002CCC, + 0x2CCD00002CCE, + 0x2CCF00002CD0, + 0x2CD100002CD2, + 0x2CD300002CD4, + 0x2CD500002CD6, + 0x2CD700002CD8, + 0x2CD900002CDA, + 0x2CDB00002CDC, + 0x2CDD00002CDE, + 0x2CDF00002CE0, + 0x2CE100002CE2, + 0x2CE300002CE5, + 0x2CEC00002CED, + 0x2CEE00002CF2, + 0x2CF300002CF4, + 0x2D0000002D26, + 0x2D2700002D28, + 0x2D2D00002D2E, + 0x2D3000002D68, + 0x2D7F00002D97, + 0x2DA000002DA7, + 0x2DA800002DAF, + 0x2DB000002DB7, + 0x2DB800002DBF, + 0x2DC000002DC7, + 0x2DC800002DCF, + 0x2DD000002DD7, + 0x2DD800002DDF, + 0x2DE000002E00, + 0x2E2F00002E30, + 0x300500003008, + 0x302A0000302E, + 0x303C0000303D, + 0x304100003097, + 0x30990000309B, + 0x309D0000309F, + 0x30A1000030FB, + 0x30FC000030FF, + 0x310500003130, + 0x31A0000031C0, + 0x31F000003200, + 0x340000004DC0, + 0x4E000000A48D, + 0xA4D00000A4FE, + 0xA5000000A60D, + 0xA6100000A62C, + 0xA6410000A642, + 0xA6430000A644, + 0xA6450000A646, + 0xA6470000A648, + 0xA6490000A64A, + 0xA64B0000A64C, + 0xA64D0000A64E, + 0xA64F0000A650, + 0xA6510000A652, + 0xA6530000A654, + 0xA6550000A656, + 0xA6570000A658, + 0xA6590000A65A, + 0xA65B0000A65C, + 0xA65D0000A65E, + 0xA65F0000A660, + 0xA6610000A662, + 0xA6630000A664, + 0xA6650000A666, + 0xA6670000A668, + 0xA6690000A66A, + 0xA66B0000A66C, + 0xA66D0000A670, + 0xA6740000A67E, + 0xA67F0000A680, + 0xA6810000A682, + 0xA6830000A684, + 0xA6850000A686, + 0xA6870000A688, + 0xA6890000A68A, + 0xA68B0000A68C, + 0xA68D0000A68E, + 0xA68F0000A690, + 0xA6910000A692, + 0xA6930000A694, + 0xA6950000A696, + 0xA6970000A698, + 0xA6990000A69A, + 0xA69B0000A69C, + 0xA69E0000A6E6, + 0xA6F00000A6F2, + 0xA7170000A720, + 0xA7230000A724, + 0xA7250000A726, + 0xA7270000A728, + 0xA7290000A72A, + 0xA72B0000A72C, + 0xA72D0000A72E, + 0xA72F0000A732, + 0xA7330000A734, + 0xA7350000A736, + 0xA7370000A738, + 0xA7390000A73A, + 0xA73B0000A73C, + 0xA73D0000A73E, + 0xA73F0000A740, + 0xA7410000A742, + 0xA7430000A744, + 0xA7450000A746, + 0xA7470000A748, + 0xA7490000A74A, + 0xA74B0000A74C, + 0xA74D0000A74E, + 0xA74F0000A750, + 0xA7510000A752, + 0xA7530000A754, + 0xA7550000A756, + 0xA7570000A758, + 0xA7590000A75A, + 0xA75B0000A75C, + 0xA75D0000A75E, + 0xA75F0000A760, + 0xA7610000A762, + 0xA7630000A764, + 0xA7650000A766, + 0xA7670000A768, + 0xA7690000A76A, + 0xA76B0000A76C, + 0xA76D0000A76E, + 0xA76F0000A770, + 0xA7710000A779, + 0xA77A0000A77B, + 0xA77C0000A77D, + 0xA77F0000A780, + 0xA7810000A782, + 0xA7830000A784, + 0xA7850000A786, + 0xA7870000A789, + 0xA78C0000A78D, + 0xA78E0000A790, + 0xA7910000A792, + 0xA7930000A796, + 0xA7970000A798, + 0xA7990000A79A, + 0xA79B0000A79C, + 0xA79D0000A79E, + 0xA79F0000A7A0, + 0xA7A10000A7A2, + 0xA7A30000A7A4, + 0xA7A50000A7A6, + 0xA7A70000A7A8, + 0xA7A90000A7AA, + 0xA7AF0000A7B0, + 0xA7B50000A7B6, + 0xA7B70000A7B8, + 0xA7B90000A7BA, + 0xA7BB0000A7BC, + 0xA7BD0000A7BE, + 0xA7BF0000A7C0, + 0xA7C10000A7C2, + 0xA7C30000A7C4, + 0xA7C80000A7C9, + 0xA7CA0000A7CB, + 0xA7CD0000A7CE, + 0xA7CF0000A7D0, + 0xA7D10000A7D2, + 0xA7D30000A7D4, + 0xA7D50000A7D6, + 0xA7D70000A7D8, + 0xA7D90000A7DA, + 0xA7DB0000A7DC, + 0xA7F60000A7F8, + 0xA7FA0000A828, + 0xA82C0000A82D, + 0xA8400000A874, + 0xA8800000A8C6, + 0xA8D00000A8DA, + 0xA8E00000A8F8, + 0xA8FB0000A8FC, + 0xA8FD0000A92E, + 0xA9300000A954, + 0xA9800000A9C1, + 0xA9CF0000A9DA, + 0xA9E00000A9FF, + 0xAA000000AA37, + 0xAA400000AA4E, + 0xAA500000AA5A, + 0xAA600000AA77, + 0xAA7A0000AAC3, + 0xAADB0000AADE, + 0xAAE00000AAF0, + 0xAAF20000AAF7, + 0xAB010000AB07, + 0xAB090000AB0F, + 0xAB110000AB17, + 0xAB200000AB27, + 0xAB280000AB2F, + 0xAB300000AB5B, + 0xAB600000AB69, + 0xABC00000ABEB, + 0xABEC0000ABEE, + 0xABF00000ABFA, + 0xAC000000D7A4, + 0xFA0E0000FA10, + 0xFA110000FA12, + 0xFA130000FA15, + 0xFA1F0000FA20, + 0xFA210000FA22, + 0xFA230000FA25, + 0xFA270000FA2A, + 0xFB1E0000FB1F, + 0xFE200000FE30, + 0xFE730000FE74, + 0x100000001000C, + 0x1000D00010027, + 0x100280001003B, + 0x1003C0001003E, + 0x1003F0001004E, + 0x100500001005E, + 0x10080000100FB, + 0x101FD000101FE, + 0x102800001029D, + 0x102A0000102D1, + 0x102E0000102E1, + 0x1030000010320, + 0x1032D00010341, + 0x103420001034A, + 0x103500001037B, + 0x103800001039E, + 0x103A0000103C4, + 0x103C8000103D0, + 0x104280001049E, + 0x104A0000104AA, + 0x104D8000104FC, + 0x1050000010528, + 0x1053000010564, + 0x10597000105A2, + 0x105A3000105B2, + 0x105B3000105BA, + 0x105BB000105BD, + 0x105C0000105F4, + 0x1060000010737, + 0x1074000010756, + 0x1076000010768, + 0x1078000010781, + 0x1080000010806, + 0x1080800010809, + 0x1080A00010836, + 0x1083700010839, + 0x1083C0001083D, + 0x1083F00010856, + 0x1086000010877, + 0x108800001089F, + 0x108E0000108F3, + 0x108F4000108F6, + 0x1090000010916, + 0x109200001093A, + 0x109400001095A, + 0x10980000109B8, + 0x109BE000109C0, + 0x10A0000010A04, + 0x10A0500010A07, + 0x10A0C00010A14, + 0x10A1500010A18, + 0x10A1900010A36, + 0x10A3800010A3B, + 0x10A3F00010A40, + 0x10A6000010A7D, + 0x10A8000010A9D, + 0x10AC000010AC8, + 0x10AC900010AE7, + 0x10B0000010B36, + 0x10B4000010B56, + 0x10B6000010B73, + 0x10B8000010B92, + 0x10C0000010C49, + 0x10CC000010CF3, + 0x10D0000010D28, + 0x10D3000010D3A, + 0x10D4000010D50, + 0x10D6900010D6E, + 0x10D6F00010D86, + 0x10E8000010EAA, + 0x10EAB00010EAD, + 0x10EB000010EB2, + 0x10EC200010EC8, + 0x10EFA00010F1D, + 0x10F2700010F28, + 0x10F3000010F51, + 0x10F7000010F86, + 0x10FB000010FC5, + 0x10FE000010FF7, + 0x1100000011047, + 0x1106600011076, + 0x1107F000110BB, + 0x110C2000110C3, + 0x110D0000110E9, + 0x110F0000110FA, + 0x1110000011135, + 0x1113600011140, + 0x1114400011148, + 0x1115000011174, + 0x1117600011177, + 0x11180000111C5, + 0x111C9000111CD, + 0x111CE000111DB, + 0x111DC000111DD, + 0x1120000011212, + 0x1121300011238, + 0x1123E00011242, + 0x1128000011287, + 0x1128800011289, + 0x1128A0001128E, + 0x1128F0001129E, + 0x1129F000112A9, + 0x112B0000112EB, + 0x112F0000112FA, + 0x1130000011304, + 0x113050001130D, + 0x1130F00011311, + 0x1131300011329, + 0x1132A00011331, + 0x1133200011334, + 0x113350001133A, + 0x1133B00011345, + 0x1134700011349, + 0x1134B0001134E, + 0x1135000011351, + 0x1135700011358, + 0x1135D00011364, + 0x113660001136D, + 0x1137000011375, + 0x113800001138A, + 0x1138B0001138C, + 0x1138E0001138F, + 0x11390000113B6, + 0x113B7000113C1, + 0x113C2000113C3, + 0x113C5000113C6, + 0x113C7000113CB, + 0x113CC000113D4, + 0x113E1000113E3, + 0x114000001144B, + 0x114500001145A, + 0x1145E00011462, + 0x11480000114C6, + 0x114C7000114C8, + 0x114D0000114DA, + 0x11580000115B6, + 0x115B8000115C1, + 0x115D8000115DE, + 0x1160000011641, + 0x1164400011645, + 0x116500001165A, + 0x11680000116B9, + 0x116C0000116CA, + 0x116D0000116E4, + 0x117000001171B, + 0x1171D0001172C, + 0x117300001173A, + 0x1174000011747, + 0x118000001183B, + 0x118C0000118EA, + 0x118FF00011907, + 0x119090001190A, + 0x1190C00011914, + 0x1191500011917, + 0x1191800011936, + 0x1193700011939, + 0x1193B00011944, + 0x119500001195A, + 0x119A0000119A8, + 0x119AA000119D8, + 0x119DA000119E2, + 0x119E3000119E5, + 0x11A0000011A3F, + 0x11A4700011A48, + 0x11A5000011A9A, + 0x11A9D00011A9E, + 0x11AB000011AF9, + 0x11B6000011B68, + 0x11BC000011BE1, + 0x11BF000011BFA, + 0x11C0000011C09, + 0x11C0A00011C37, + 0x11C3800011C41, + 0x11C5000011C5A, + 0x11C7200011C90, + 0x11C9200011CA8, + 0x11CA900011CB7, + 0x11D0000011D07, + 0x11D0800011D0A, + 0x11D0B00011D37, + 0x11D3A00011D3B, + 0x11D3C00011D3E, + 0x11D3F00011D48, + 0x11D5000011D5A, + 0x11D6000011D66, + 0x11D6700011D69, + 0x11D6A00011D8F, + 0x11D9000011D92, + 0x11D9300011D99, + 0x11DA000011DAA, + 0x11DB000011DDC, + 0x11DE000011DEA, + 0x11EE000011EF7, + 0x11F0000011F11, + 0x11F1200011F3B, + 0x11F3E00011F43, + 0x11F5000011F5B, + 0x11FB000011FB1, + 0x120000001239A, + 0x1248000012544, + 0x12F9000012FF1, + 0x1300000013430, + 0x1344000013456, + 0x13460000143FB, + 0x1440000014647, + 0x161000001613A, + 0x1680000016A39, + 0x16A4000016A5F, + 0x16A6000016A6A, + 0x16A7000016ABF, + 0x16AC000016ACA, + 0x16AD000016AEE, + 0x16AF000016AF5, + 0x16B0000016B37, + 0x16B4000016B44, + 0x16B5000016B5A, + 0x16B6300016B78, + 0x16B7D00016B90, + 0x16D4000016D6D, + 0x16D7000016D7A, + 0x16E6000016E80, + 0x16EBB00016ED4, + 0x16F0000016F4B, + 0x16F4F00016F88, + 0x16F8F00016FA0, + 0x16FE000016FE2, + 0x16FE300016FE5, + 0x16FF000016FF4, + 0x1700000018CD6, + 0x18CFF00018D1F, + 0x18D8000018DF3, + 0x1AFF00001AFF4, + 0x1AFF50001AFFC, + 0x1AFFD0001AFFF, + 0x1B0000001B123, + 0x1B1320001B133, + 0x1B1500001B153, + 0x1B1550001B156, + 0x1B1640001B168, + 0x1B1700001B2FC, + 0x1BC000001BC6B, + 0x1BC700001BC7D, + 0x1BC800001BC89, + 0x1BC900001BC9A, + 0x1BC9D0001BC9F, + 0x1CF000001CF2E, + 0x1CF300001CF47, + 0x1DA000001DA37, + 0x1DA3B0001DA6D, + 0x1DA750001DA76, + 0x1DA840001DA85, + 0x1DA9B0001DAA0, + 0x1DAA10001DAB0, + 0x1DF000001DF1F, + 0x1DF250001DF2B, + 0x1E0000001E007, + 0x1E0080001E019, + 0x1E01B0001E022, + 0x1E0230001E025, + 0x1E0260001E02B, + 0x1E08F0001E090, + 0x1E1000001E12D, + 0x1E1300001E13E, + 0x1E1400001E14A, + 0x1E14E0001E14F, + 0x1E2900001E2AF, + 0x1E2C00001E2FA, + 0x1E4D00001E4FA, + 0x1E5D00001E5FB, + 0x1E6C00001E6DF, + 0x1E6E00001E6F6, + 0x1E6FE0001E700, + 0x1E7E00001E7E7, + 0x1E7E80001E7EC, + 0x1E7ED0001E7EF, + 0x1E7F00001E7FF, + 0x1E8000001E8C5, + 0x1E8D00001E8D7, + 0x1E9220001E94C, + 0x1E9500001E95A, + 0x200000002A6E0, + 0x2A7000002B81E, + 0x2B8200002CEAE, + 0x2CEB00002EBE1, + 0x2EBF00002EE5E, + 0x300000003134B, + 0x313500003347A, + ), + "CONTEXTJ": (0x200C0000200E,), + "CONTEXTO": ( + 0xB7000000B8, + 0x37500000376, + 0x5F3000005F5, + 0x6600000066A, + 0x6F0000006FA, + 0x30FB000030FC, + ), +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/intranges.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/intranges.py new file mode 100644 index 0000000000000000000000000000000000000000..ea3455bb8da7d5e882de3fd8d6de443f0e19c611 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/intranges.py @@ -0,0 +1,56 @@ +""" +Given a list of integers, made up of (hopefully) a small number of long runs +of consecutive integers, compute a representation of the form +((start1, end1), (start2, end2) ...). Then answer the question "was x present +in the original list?" in time O(log(# runs)). +""" + +import bisect +from typing import List, Tuple + + +def intranges_from_list(list_: List[int]) -> Tuple[int, ...]: + """Represent a list of integers as a sequence of ranges: + ((start_0, end_0), (start_1, end_1), ...), such that the original + integers are exactly those x such that start_i <= x < end_i for some i. + + Ranges are encoded as single integers (start << 32 | end), not as tuples. + """ + + sorted_list = sorted(list_) + ranges = [] + last_write = -1 + for i in range(len(sorted_list)): + if i + 1 < len(sorted_list) and sorted_list[i] == sorted_list[i + 1] - 1: + continue + current_range = sorted_list[last_write + 1 : i + 1] + ranges.append(_encode_range(current_range[0], current_range[-1] + 1)) + last_write = i + + return tuple(ranges) + + +def _encode_range(start: int, end: int) -> int: + return (start << 32) | end + + +def _decode_range(r: int) -> Tuple[int, int]: + return (r >> 32), (r & ((1 << 32) - 1)) + + +def intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool: + """Determine if `int_` falls into one of the ranges in `ranges`.""" + tuple_ = _encode_range(int_, 0) + pos = bisect.bisect_left(ranges, tuple_) + # we could be immediately ahead of a tuple (start, end) + # with start < int_ <= end + if pos > 0: + left, right = _decode_range(ranges[pos - 1]) + if left <= int_ < right: + return True + # or we could be immediately behind a tuple (int_, end) + if pos < len(ranges): + left, _ = _decode_range(ranges[pos]) + if left == int_: + return True + return False diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/package_data.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/package_data.py new file mode 100644 index 0000000000000000000000000000000000000000..75debb75d6fee4c1933b4d94af3e116f132ae7f3 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/package_data.py @@ -0,0 +1 @@ +__version__ = "3.15" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/uts46data.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/uts46data.py new file mode 100644 index 0000000000000000000000000000000000000000..e13aa90fb86998b1c0e54beaf00a9acf3f6a3320 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/idna/uts46data.py @@ -0,0 +1,8383 @@ +# This file is automatically generated by tools/idna-data + +from typing import Tuple, Union + +"""IDNA Mapping Table from UTS46.""" + + +__version__ = "17.0.0" + +uts46data: Tuple[Union[Tuple[int, str], Tuple[int, str, str]], ...] = ( + (0x0, "V"), + (0x1, "V"), + (0x2, "V"), + (0x3, "V"), + (0x4, "V"), + (0x5, "V"), + (0x6, "V"), + (0x7, "V"), + (0x8, "V"), + (0x9, "V"), + (0xA, "V"), + (0xB, "V"), + (0xC, "V"), + (0xD, "V"), + (0xE, "V"), + (0xF, "V"), + (0x10, "V"), + (0x11, "V"), + (0x12, "V"), + (0x13, "V"), + (0x14, "V"), + (0x15, "V"), + (0x16, "V"), + (0x17, "V"), + (0x18, "V"), + (0x19, "V"), + (0x1A, "V"), + (0x1B, "V"), + (0x1C, "V"), + (0x1D, "V"), + (0x1E, "V"), + (0x1F, "V"), + (0x20, "V"), + (0x21, "V"), + (0x22, "V"), + (0x23, "V"), + (0x24, "V"), + (0x25, "V"), + (0x26, "V"), + (0x27, "V"), + (0x28, "V"), + (0x29, "V"), + (0x2A, "V"), + (0x2B, "V"), + (0x2C, "V"), + (0x2D, "V"), + (0x2E, "V"), + (0x2F, "V"), + (0x30, "V"), + (0x31, "V"), + (0x32, "V"), + (0x33, "V"), + (0x34, "V"), + (0x35, "V"), + (0x36, "V"), + (0x37, "V"), + (0x38, "V"), + (0x39, "V"), + (0x3A, "V"), + (0x3B, "V"), + (0x3C, "V"), + (0x3D, "V"), + (0x3E, "V"), + (0x3F, "V"), + (0x40, "V"), + (0x41, "M", "a"), + (0x42, "M", "b"), + (0x43, "M", "c"), + (0x44, "M", "d"), + (0x45, "M", "e"), + (0x46, "M", "f"), + (0x47, "M", "g"), + (0x48, "M", "h"), + (0x49, "M", "i"), + (0x4A, "M", "j"), + (0x4B, "M", "k"), + (0x4C, "M", "l"), + (0x4D, "M", "m"), + (0x4E, "M", "n"), + (0x4F, "M", "o"), + (0x50, "M", "p"), + (0x51, "M", "q"), + (0x52, "M", "r"), + (0x53, "M", "s"), + (0x54, "M", "t"), + (0x55, "M", "u"), + (0x56, "M", "v"), + (0x57, "M", "w"), + (0x58, "M", "x"), + (0x59, "M", "y"), + (0x5A, "M", "z"), + (0x5B, "V"), + (0x5C, "V"), + (0x5D, "V"), + (0x5E, "V"), + (0x5F, "V"), + (0x60, "V"), + (0x61, "V"), + (0x62, "V"), + (0x63, "V"), + (0x64, "V"), + (0x65, "V"), + (0x66, "V"), + (0x67, "V"), + (0x68, "V"), + (0x69, "V"), + (0x6A, "V"), + (0x6B, "V"), + (0x6C, "V"), + (0x6D, "V"), + (0x6E, "V"), + (0x6F, "V"), + (0x70, "V"), + (0x71, "V"), + (0x72, "V"), + (0x73, "V"), + (0x74, "V"), + (0x75, "V"), + (0x76, "V"), + (0x77, "V"), + (0x78, "V"), + (0x79, "V"), + (0x7A, "V"), + (0x7B, "V"), + (0x7C, "V"), + (0x7D, "V"), + (0x7E, "V"), + (0x7F, "V"), + (0x80, "X"), + (0x81, "X"), + (0x82, "X"), + (0x83, "X"), + (0x84, "X"), + (0x85, "X"), + (0x86, "X"), + (0x87, "X"), + (0x88, "X"), + (0x89, "X"), + (0x8A, "X"), + (0x8B, "X"), + (0x8C, "X"), + (0x8D, "X"), + (0x8E, "X"), + (0x8F, "X"), + (0x90, "X"), + (0x91, "X"), + (0x92, "X"), + (0x93, "X"), + (0x94, "X"), + (0x95, "X"), + (0x96, "X"), + (0x97, "X"), + (0x98, "X"), + (0x99, "X"), + (0x9A, "X"), + (0x9B, "X"), + (0x9C, "X"), + (0x9D, "X"), + (0x9E, "X"), + (0x9F, "X"), + (0xA0, "M", " "), + (0xA1, "V"), + (0xA2, "V"), + (0xA3, "V"), + (0xA4, "V"), + (0xA5, "V"), + (0xA6, "V"), + (0xA7, "V"), + (0xA8, "M", " ̈"), + (0xA9, "V"), + (0xAA, "M", "a"), + (0xAB, "V"), + (0xAC, "V"), + (0xAD, "I"), + (0xAE, "V"), + (0xAF, "M", " ̄"), + (0xB0, "V"), + (0xB1, "V"), + (0xB2, "M", "2"), + (0xB3, "M", "3"), + (0xB4, "M", " ́"), + (0xB5, "M", "μ"), + (0xB6, "V"), + (0xB7, "V"), + (0xB8, "M", " ̧"), + (0xB9, "M", "1"), + (0xBA, "M", "o"), + (0xBB, "V"), + (0xBC, "M", "1⁄4"), + (0xBD, "M", "1⁄2"), + (0xBE, "M", "3⁄4"), + (0xBF, "V"), + (0xC0, "M", "à"), + (0xC1, "M", "á"), + (0xC2, "M", "â"), + (0xC3, "M", "ã"), + (0xC4, "M", "ä"), + (0xC5, "M", "å"), + (0xC6, "M", "æ"), + (0xC7, "M", "ç"), + (0xC8, "M", "è"), + (0xC9, "M", "é"), + (0xCA, "M", "ê"), + (0xCB, "M", "ë"), + (0xCC, "M", "ì"), + (0xCD, "M", "í"), + (0xCE, "M", "î"), + (0xCF, "M", "ï"), + (0xD0, "M", "ð"), + (0xD1, "M", "ñ"), + (0xD2, "M", "ò"), + (0xD3, "M", "ó"), + (0xD4, "M", "ô"), + (0xD5, "M", "õ"), + (0xD6, "M", "ö"), + (0xD7, "V"), + (0xD8, "M", "ø"), + (0xD9, "M", "ù"), + (0xDA, "M", "ú"), + (0xDB, "M", "û"), + (0xDC, "M", "ü"), + (0xDD, "M", "ý"), + (0xDE, "M", "þ"), + (0xDF, "D", "ss"), + (0xE0, "V"), + (0xE1, "V"), + (0xE2, "V"), + (0xE3, "V"), + (0xE4, "V"), + (0xE5, "V"), + (0xE6, "V"), + (0xE7, "V"), + (0xE8, "V"), + (0xE9, "V"), + (0xEA, "V"), + (0xEB, "V"), + (0xEC, "V"), + (0xED, "V"), + (0xEE, "V"), + (0xEF, "V"), + (0xF0, "V"), + (0xF1, "V"), + (0xF2, "V"), + (0xF3, "V"), + (0xF4, "V"), + (0xF5, "V"), + (0xF6, "V"), + (0xF7, "V"), + (0xF8, "V"), + (0xF9, "V"), + (0xFA, "V"), + (0xFB, "V"), + (0xFC, "V"), + (0xFD, "V"), + (0xFE, "V"), + (0xFF, "V"), + (0x100, "M", "ā"), + (0x101, "V"), + (0x102, "M", "ă"), + (0x103, "V"), + (0x104, "M", "ą"), + (0x105, "V"), + (0x106, "M", "ć"), + (0x107, "V"), + (0x108, "M", "ĉ"), + (0x109, "V"), + (0x10A, "M", "ċ"), + (0x10B, "V"), + (0x10C, "M", "č"), + (0x10D, "V"), + (0x10E, "M", "ď"), + (0x10F, "V"), + (0x110, "M", "đ"), + (0x111, "V"), + (0x112, "M", "ē"), + (0x113, "V"), + (0x114, "M", "ĕ"), + (0x115, "V"), + (0x116, "M", "ė"), + (0x117, "V"), + (0x118, "M", "ę"), + (0x119, "V"), + (0x11A, "M", "ě"), + (0x11B, "V"), + (0x11C, "M", "ĝ"), + (0x11D, "V"), + (0x11E, "M", "ğ"), + (0x11F, "V"), + (0x120, "M", "ġ"), + (0x121, "V"), + (0x122, "M", "ģ"), + (0x123, "V"), + (0x124, "M", "ĥ"), + (0x125, "V"), + (0x126, "M", "ħ"), + (0x127, "V"), + (0x128, "M", "ĩ"), + (0x129, "V"), + (0x12A, "M", "ī"), + (0x12B, "V"), + (0x12C, "M", "ĭ"), + (0x12D, "V"), + (0x12E, "M", "į"), + (0x12F, "V"), + (0x130, "M", "i̇"), + (0x131, "V"), + (0x132, "M", "ij"), + (0x134, "M", "ĵ"), + (0x135, "V"), + (0x136, "M", "ķ"), + (0x137, "V"), + (0x139, "M", "ĺ"), + (0x13A, "V"), + (0x13B, "M", "ļ"), + (0x13C, "V"), + (0x13D, "M", "ľ"), + (0x13E, "V"), + (0x13F, "M", "l·"), + (0x141, "M", "ł"), + (0x142, "V"), + (0x143, "M", "ń"), + (0x144, "V"), + (0x145, "M", "ņ"), + (0x146, "V"), + (0x147, "M", "ň"), + (0x148, "V"), + (0x149, "M", "ʼn"), + (0x14A, "M", "ŋ"), + (0x14B, "V"), + (0x14C, "M", "ō"), + (0x14D, "V"), + (0x14E, "M", "ŏ"), + (0x14F, "V"), + (0x150, "M", "ő"), + (0x151, "V"), + (0x152, "M", "œ"), + (0x153, "V"), + (0x154, "M", "ŕ"), + (0x155, "V"), + (0x156, "M", "ŗ"), + (0x157, "V"), + (0x158, "M", "ř"), + (0x159, "V"), + (0x15A, "M", "ś"), + (0x15B, "V"), + (0x15C, "M", "ŝ"), + (0x15D, "V"), + (0x15E, "M", "ş"), + (0x15F, "V"), + (0x160, "M", "š"), + (0x161, "V"), + (0x162, "M", "ţ"), + (0x163, "V"), + (0x164, "M", "ť"), + (0x165, "V"), + (0x166, "M", "ŧ"), + (0x167, "V"), + (0x168, "M", "ũ"), + (0x169, "V"), + (0x16A, "M", "ū"), + (0x16B, "V"), + (0x16C, "M", "ŭ"), + (0x16D, "V"), + (0x16E, "M", "ů"), + (0x16F, "V"), + (0x170, "M", "ű"), + (0x171, "V"), + (0x172, "M", "ų"), + (0x173, "V"), + (0x174, "M", "ŵ"), + (0x175, "V"), + (0x176, "M", "ŷ"), + (0x177, "V"), + (0x178, "M", "ÿ"), + (0x179, "M", "ź"), + (0x17A, "V"), + (0x17B, "M", "ż"), + (0x17C, "V"), + (0x17D, "M", "ž"), + (0x17E, "V"), + (0x17F, "M", "s"), + (0x180, "V"), + (0x181, "M", "ɓ"), + (0x182, "M", "ƃ"), + (0x183, "V"), + (0x184, "M", "ƅ"), + (0x185, "V"), + (0x186, "M", "ɔ"), + (0x187, "M", "ƈ"), + (0x188, "V"), + (0x189, "M", "ɖ"), + (0x18A, "M", "ɗ"), + (0x18B, "M", "ƌ"), + (0x18C, "V"), + (0x18E, "M", "ǝ"), + (0x18F, "M", "ə"), + (0x190, "M", "ɛ"), + (0x191, "M", "ƒ"), + (0x192, "V"), + (0x193, "M", "ɠ"), + (0x194, "M", "ɣ"), + (0x195, "V"), + (0x196, "M", "ɩ"), + (0x197, "M", "ɨ"), + (0x198, "M", "ƙ"), + (0x199, "V"), + (0x19C, "M", "ɯ"), + (0x19D, "M", "ɲ"), + (0x19E, "V"), + (0x19F, "M", "ɵ"), + (0x1A0, "M", "ơ"), + (0x1A1, "V"), + (0x1A2, "M", "ƣ"), + (0x1A3, "V"), + (0x1A4, "M", "ƥ"), + (0x1A5, "V"), + (0x1A6, "M", "ʀ"), + (0x1A7, "M", "ƨ"), + (0x1A8, "V"), + (0x1A9, "M", "ʃ"), + (0x1AA, "V"), + (0x1AC, "M", "ƭ"), + (0x1AD, "V"), + (0x1AE, "M", "ʈ"), + (0x1AF, "M", "ư"), + (0x1B0, "V"), + (0x1B1, "M", "ʊ"), + (0x1B2, "M", "ʋ"), + (0x1B3, "M", "ƴ"), + (0x1B4, "V"), + (0x1B5, "M", "ƶ"), + (0x1B6, "V"), + (0x1B7, "M", "ʒ"), + (0x1B8, "M", "ƹ"), + (0x1B9, "V"), + (0x1BC, "M", "ƽ"), + (0x1BD, "V"), + (0x1C4, "M", "dž"), + (0x1C7, "M", "lj"), + (0x1CA, "M", "nj"), + (0x1CD, "M", "ǎ"), + (0x1CE, "V"), + (0x1CF, "M", "ǐ"), + (0x1D0, "V"), + (0x1D1, "M", "ǒ"), + (0x1D2, "V"), + (0x1D3, "M", "ǔ"), + (0x1D4, "V"), + (0x1D5, "M", "ǖ"), + (0x1D6, "V"), + (0x1D7, "M", "ǘ"), + (0x1D8, "V"), + (0x1D9, "M", "ǚ"), + (0x1DA, "V"), + (0x1DB, "M", "ǜ"), + (0x1DC, "V"), + (0x1DE, "M", "ǟ"), + (0x1DF, "V"), + (0x1E0, "M", "ǡ"), + (0x1E1, "V"), + (0x1E2, "M", "ǣ"), + (0x1E3, "V"), + (0x1E4, "M", "ǥ"), + (0x1E5, "V"), + (0x1E6, "M", "ǧ"), + (0x1E7, "V"), + (0x1E8, "M", "ǩ"), + (0x1E9, "V"), + (0x1EA, "M", "ǫ"), + (0x1EB, "V"), + (0x1EC, "M", "ǭ"), + (0x1ED, "V"), + (0x1EE, "M", "ǯ"), + (0x1EF, "V"), + (0x1F1, "M", "dz"), + (0x1F4, "M", "ǵ"), + (0x1F5, "V"), + (0x1F6, "M", "ƕ"), + (0x1F7, "M", "ƿ"), + (0x1F8, "M", "ǹ"), + (0x1F9, "V"), + (0x1FA, "M", "ǻ"), + (0x1FB, "V"), + (0x1FC, "M", "ǽ"), + (0x1FD, "V"), + (0x1FE, "M", "ǿ"), + (0x1FF, "V"), + (0x200, "M", "ȁ"), + (0x201, "V"), + (0x202, "M", "ȃ"), + (0x203, "V"), + (0x204, "M", "ȅ"), + (0x205, "V"), + (0x206, "M", "ȇ"), + (0x207, "V"), + (0x208, "M", "ȉ"), + (0x209, "V"), + (0x20A, "M", "ȋ"), + (0x20B, "V"), + (0x20C, "M", "ȍ"), + (0x20D, "V"), + (0x20E, "M", "ȏ"), + (0x20F, "V"), + (0x210, "M", "ȑ"), + (0x211, "V"), + (0x212, "M", "ȓ"), + (0x213, "V"), + (0x214, "M", "ȕ"), + (0x215, "V"), + (0x216, "M", "ȗ"), + (0x217, "V"), + (0x218, "M", "ș"), + (0x219, "V"), + (0x21A, "M", "ț"), + (0x21B, "V"), + (0x21C, "M", "ȝ"), + (0x21D, "V"), + (0x21E, "M", "ȟ"), + (0x21F, "V"), + (0x220, "M", "ƞ"), + (0x221, "V"), + (0x222, "M", "ȣ"), + (0x223, "V"), + (0x224, "M", "ȥ"), + (0x225, "V"), + (0x226, "M", "ȧ"), + (0x227, "V"), + (0x228, "M", "ȩ"), + (0x229, "V"), + (0x22A, "M", "ȫ"), + (0x22B, "V"), + (0x22C, "M", "ȭ"), + (0x22D, "V"), + (0x22E, "M", "ȯ"), + (0x22F, "V"), + (0x230, "M", "ȱ"), + (0x231, "V"), + (0x232, "M", "ȳ"), + (0x233, "V"), + (0x23A, "M", "ⱥ"), + (0x23B, "M", "ȼ"), + (0x23C, "V"), + (0x23D, "M", "ƚ"), + (0x23E, "M", "ⱦ"), + (0x23F, "V"), + (0x241, "M", "ɂ"), + (0x242, "V"), + (0x243, "M", "ƀ"), + (0x244, "M", "ʉ"), + (0x245, "M", "ʌ"), + (0x246, "M", "ɇ"), + (0x247, "V"), + (0x248, "M", "ɉ"), + (0x249, "V"), + (0x24A, "M", "ɋ"), + (0x24B, "V"), + (0x24C, "M", "ɍ"), + (0x24D, "V"), + (0x24E, "M", "ɏ"), + (0x24F, "V"), + (0x2B0, "M", "h"), + (0x2B1, "M", "ɦ"), + (0x2B2, "M", "j"), + (0x2B3, "M", "r"), + (0x2B4, "M", "ɹ"), + (0x2B5, "M", "ɻ"), + (0x2B6, "M", "ʁ"), + (0x2B7, "M", "w"), + (0x2B8, "M", "y"), + (0x2B9, "V"), + (0x2D8, "M", " ̆"), + (0x2D9, "M", " ̇"), + (0x2DA, "M", " ̊"), + (0x2DB, "M", " ̨"), + (0x2DC, "M", " ̃"), + (0x2DD, "M", " ̋"), + (0x2DE, "V"), + (0x2E0, "M", "ɣ"), + (0x2E1, "M", "l"), + (0x2E2, "M", "s"), + (0x2E3, "M", "x"), + (0x2E4, "M", "ʕ"), + (0x2E5, "V"), + (0x340, "M", "̀"), + (0x341, "M", "́"), + (0x342, "V"), + (0x343, "M", "̓"), + (0x344, "M", "̈́"), + (0x345, "M", "ι"), + (0x346, "V"), + (0x34F, "I"), + (0x350, "V"), + (0x370, "M", "ͱ"), + (0x371, "V"), + (0x372, "M", "ͳ"), + (0x373, "V"), + (0x374, "M", "ʹ"), + (0x375, "V"), + (0x376, "M", "ͷ"), + (0x377, "V"), + (0x378, "X"), + (0x37A, "M", " ι"), + (0x37B, "V"), + (0x37E, "M", ";"), + (0x37F, "M", "ϳ"), + (0x380, "X"), + (0x384, "M", " ́"), + (0x385, "M", " ̈́"), + (0x386, "M", "ά"), + (0x387, "M", "·"), + (0x388, "M", "έ"), + (0x389, "M", "ή"), + (0x38A, "M", "ί"), + (0x38B, "X"), + (0x38C, "M", "ό"), + (0x38D, "X"), + (0x38E, "M", "ύ"), + (0x38F, "M", "ώ"), + (0x390, "V"), + (0x391, "M", "α"), + (0x392, "M", "β"), + (0x393, "M", "γ"), + (0x394, "M", "δ"), + (0x395, "M", "ε"), + (0x396, "M", "ζ"), + (0x397, "M", "η"), + (0x398, "M", "θ"), + (0x399, "M", "ι"), + (0x39A, "M", "κ"), + (0x39B, "M", "λ"), + (0x39C, "M", "μ"), + (0x39D, "M", "ν"), + (0x39E, "M", "ξ"), + (0x39F, "M", "ο"), + (0x3A0, "M", "π"), + (0x3A1, "M", "ρ"), + (0x3A2, "X"), + (0x3A3, "M", "σ"), + (0x3A4, "M", "τ"), + (0x3A5, "M", "υ"), + (0x3A6, "M", "φ"), + (0x3A7, "M", "χ"), + (0x3A8, "M", "ψ"), + (0x3A9, "M", "ω"), + (0x3AA, "M", "ϊ"), + (0x3AB, "M", "ϋ"), + (0x3AC, "V"), + (0x3C2, "D", "σ"), + (0x3C3, "V"), + (0x3CF, "M", "ϗ"), + (0x3D0, "M", "β"), + (0x3D1, "M", "θ"), + (0x3D2, "M", "υ"), + (0x3D3, "M", "ύ"), + (0x3D4, "M", "ϋ"), + (0x3D5, "M", "φ"), + (0x3D6, "M", "π"), + (0x3D7, "V"), + (0x3D8, "M", "ϙ"), + (0x3D9, "V"), + (0x3DA, "M", "ϛ"), + (0x3DB, "V"), + (0x3DC, "M", "ϝ"), + (0x3DD, "V"), + (0x3DE, "M", "ϟ"), + (0x3DF, "V"), + (0x3E0, "M", "ϡ"), + (0x3E1, "V"), + (0x3E2, "M", "ϣ"), + (0x3E3, "V"), + (0x3E4, "M", "ϥ"), + (0x3E5, "V"), + (0x3E6, "M", "ϧ"), + (0x3E7, "V"), + (0x3E8, "M", "ϩ"), + (0x3E9, "V"), + (0x3EA, "M", "ϫ"), + (0x3EB, "V"), + (0x3EC, "M", "ϭ"), + (0x3ED, "V"), + (0x3EE, "M", "ϯ"), + (0x3EF, "V"), + (0x3F0, "M", "κ"), + (0x3F1, "M", "ρ"), + (0x3F2, "M", "σ"), + (0x3F3, "V"), + (0x3F4, "M", "θ"), + (0x3F5, "M", "ε"), + (0x3F6, "V"), + (0x3F7, "M", "ϸ"), + (0x3F8, "V"), + (0x3F9, "M", "σ"), + (0x3FA, "M", "ϻ"), + (0x3FB, "V"), + (0x3FD, "M", "ͻ"), + (0x3FE, "M", "ͼ"), + (0x3FF, "M", "ͽ"), + (0x400, "M", "ѐ"), + (0x401, "M", "ё"), + (0x402, "M", "ђ"), + (0x403, "M", "ѓ"), + (0x404, "M", "є"), + (0x405, "M", "ѕ"), + (0x406, "M", "і"), + (0x407, "M", "ї"), + (0x408, "M", "ј"), + (0x409, "M", "љ"), + (0x40A, "M", "њ"), + (0x40B, "M", "ћ"), + (0x40C, "M", "ќ"), + (0x40D, "M", "ѝ"), + (0x40E, "M", "ў"), + (0x40F, "M", "џ"), + (0x410, "M", "а"), + (0x411, "M", "б"), + (0x412, "M", "в"), + (0x413, "M", "г"), + (0x414, "M", "д"), + (0x415, "M", "е"), + (0x416, "M", "ж"), + (0x417, "M", "з"), + (0x418, "M", "и"), + (0x419, "M", "й"), + (0x41A, "M", "к"), + (0x41B, "M", "л"), + (0x41C, "M", "м"), + (0x41D, "M", "н"), + (0x41E, "M", "о"), + (0x41F, "M", "п"), + (0x420, "M", "р"), + (0x421, "M", "с"), + (0x422, "M", "т"), + (0x423, "M", "у"), + (0x424, "M", "ф"), + (0x425, "M", "х"), + (0x426, "M", "ц"), + (0x427, "M", "ч"), + (0x428, "M", "ш"), + (0x429, "M", "щ"), + (0x42A, "M", "ъ"), + (0x42B, "M", "ы"), + (0x42C, "M", "ь"), + (0x42D, "M", "э"), + (0x42E, "M", "ю"), + (0x42F, "M", "я"), + (0x430, "V"), + (0x460, "M", "ѡ"), + (0x461, "V"), + (0x462, "M", "ѣ"), + (0x463, "V"), + (0x464, "M", "ѥ"), + (0x465, "V"), + (0x466, "M", "ѧ"), + (0x467, "V"), + (0x468, "M", "ѩ"), + (0x469, "V"), + (0x46A, "M", "ѫ"), + (0x46B, "V"), + (0x46C, "M", "ѭ"), + (0x46D, "V"), + (0x46E, "M", "ѯ"), + (0x46F, "V"), + (0x470, "M", "ѱ"), + (0x471, "V"), + (0x472, "M", "ѳ"), + (0x473, "V"), + (0x474, "M", "ѵ"), + (0x475, "V"), + (0x476, "M", "ѷ"), + (0x477, "V"), + (0x478, "M", "ѹ"), + (0x479, "V"), + (0x47A, "M", "ѻ"), + (0x47B, "V"), + (0x47C, "M", "ѽ"), + (0x47D, "V"), + (0x47E, "M", "ѿ"), + (0x47F, "V"), + (0x480, "M", "ҁ"), + (0x481, "V"), + (0x48A, "M", "ҋ"), + (0x48B, "V"), + (0x48C, "M", "ҍ"), + (0x48D, "V"), + (0x48E, "M", "ҏ"), + (0x48F, "V"), + (0x490, "M", "ґ"), + (0x491, "V"), + (0x492, "M", "ғ"), + (0x493, "V"), + (0x494, "M", "ҕ"), + (0x495, "V"), + (0x496, "M", "җ"), + (0x497, "V"), + (0x498, "M", "ҙ"), + (0x499, "V"), + (0x49A, "M", "қ"), + (0x49B, "V"), + (0x49C, "M", "ҝ"), + (0x49D, "V"), + (0x49E, "M", "ҟ"), + (0x49F, "V"), + (0x4A0, "M", "ҡ"), + (0x4A1, "V"), + (0x4A2, "M", "ң"), + (0x4A3, "V"), + (0x4A4, "M", "ҥ"), + (0x4A5, "V"), + (0x4A6, "M", "ҧ"), + (0x4A7, "V"), + (0x4A8, "M", "ҩ"), + (0x4A9, "V"), + (0x4AA, "M", "ҫ"), + (0x4AB, "V"), + (0x4AC, "M", "ҭ"), + (0x4AD, "V"), + (0x4AE, "M", "ү"), + (0x4AF, "V"), + (0x4B0, "M", "ұ"), + (0x4B1, "V"), + (0x4B2, "M", "ҳ"), + (0x4B3, "V"), + (0x4B4, "M", "ҵ"), + (0x4B5, "V"), + (0x4B6, "M", "ҷ"), + (0x4B7, "V"), + (0x4B8, "M", "ҹ"), + (0x4B9, "V"), + (0x4BA, "M", "һ"), + (0x4BB, "V"), + (0x4BC, "M", "ҽ"), + (0x4BD, "V"), + (0x4BE, "M", "ҿ"), + (0x4BF, "V"), + (0x4C0, "M", "ӏ"), + (0x4C1, "M", "ӂ"), + (0x4C2, "V"), + (0x4C3, "M", "ӄ"), + (0x4C4, "V"), + (0x4C5, "M", "ӆ"), + (0x4C6, "V"), + (0x4C7, "M", "ӈ"), + (0x4C8, "V"), + (0x4C9, "M", "ӊ"), + (0x4CA, "V"), + (0x4CB, "M", "ӌ"), + (0x4CC, "V"), + (0x4CD, "M", "ӎ"), + (0x4CE, "V"), + (0x4D0, "M", "ӑ"), + (0x4D1, "V"), + (0x4D2, "M", "ӓ"), + (0x4D3, "V"), + (0x4D4, "M", "ӕ"), + (0x4D5, "V"), + (0x4D6, "M", "ӗ"), + (0x4D7, "V"), + (0x4D8, "M", "ә"), + (0x4D9, "V"), + (0x4DA, "M", "ӛ"), + (0x4DB, "V"), + (0x4DC, "M", "ӝ"), + (0x4DD, "V"), + (0x4DE, "M", "ӟ"), + (0x4DF, "V"), + (0x4E0, "M", "ӡ"), + (0x4E1, "V"), + (0x4E2, "M", "ӣ"), + (0x4E3, "V"), + (0x4E4, "M", "ӥ"), + (0x4E5, "V"), + (0x4E6, "M", "ӧ"), + (0x4E7, "V"), + (0x4E8, "M", "ө"), + (0x4E9, "V"), + (0x4EA, "M", "ӫ"), + (0x4EB, "V"), + (0x4EC, "M", "ӭ"), + (0x4ED, "V"), + (0x4EE, "M", "ӯ"), + (0x4EF, "V"), + (0x4F0, "M", "ӱ"), + (0x4F1, "V"), + (0x4F2, "M", "ӳ"), + (0x4F3, "V"), + (0x4F4, "M", "ӵ"), + (0x4F5, "V"), + (0x4F6, "M", "ӷ"), + (0x4F7, "V"), + (0x4F8, "M", "ӹ"), + (0x4F9, "V"), + (0x4FA, "M", "ӻ"), + (0x4FB, "V"), + (0x4FC, "M", "ӽ"), + (0x4FD, "V"), + (0x4FE, "M", "ӿ"), + (0x4FF, "V"), + (0x500, "M", "ԁ"), + (0x501, "V"), + (0x502, "M", "ԃ"), + (0x503, "V"), + (0x504, "M", "ԅ"), + (0x505, "V"), + (0x506, "M", "ԇ"), + (0x507, "V"), + (0x508, "M", "ԉ"), + (0x509, "V"), + (0x50A, "M", "ԋ"), + (0x50B, "V"), + (0x50C, "M", "ԍ"), + (0x50D, "V"), + (0x50E, "M", "ԏ"), + (0x50F, "V"), + (0x510, "M", "ԑ"), + (0x511, "V"), + (0x512, "M", "ԓ"), + (0x513, "V"), + (0x514, "M", "ԕ"), + (0x515, "V"), + (0x516, "M", "ԗ"), + (0x517, "V"), + (0x518, "M", "ԙ"), + (0x519, "V"), + (0x51A, "M", "ԛ"), + (0x51B, "V"), + (0x51C, "M", "ԝ"), + (0x51D, "V"), + (0x51E, "M", "ԟ"), + (0x51F, "V"), + (0x520, "M", "ԡ"), + (0x521, "V"), + (0x522, "M", "ԣ"), + (0x523, "V"), + (0x524, "M", "ԥ"), + (0x525, "V"), + (0x526, "M", "ԧ"), + (0x527, "V"), + (0x528, "M", "ԩ"), + (0x529, "V"), + (0x52A, "M", "ԫ"), + (0x52B, "V"), + (0x52C, "M", "ԭ"), + (0x52D, "V"), + (0x52E, "M", "ԯ"), + (0x52F, "V"), + (0x530, "X"), + (0x531, "M", "ա"), + (0x532, "M", "բ"), + (0x533, "M", "գ"), + (0x534, "M", "դ"), + (0x535, "M", "ե"), + (0x536, "M", "զ"), + (0x537, "M", "է"), + (0x538, "M", "ը"), + (0x539, "M", "թ"), + (0x53A, "M", "ժ"), + (0x53B, "M", "ի"), + (0x53C, "M", "լ"), + (0x53D, "M", "խ"), + (0x53E, "M", "ծ"), + (0x53F, "M", "կ"), + (0x540, "M", "հ"), + (0x541, "M", "ձ"), + (0x542, "M", "ղ"), + (0x543, "M", "ճ"), + (0x544, "M", "մ"), + (0x545, "M", "յ"), + (0x546, "M", "ն"), + (0x547, "M", "շ"), + (0x548, "M", "ո"), + (0x549, "M", "չ"), + (0x54A, "M", "պ"), + (0x54B, "M", "ջ"), + (0x54C, "M", "ռ"), + (0x54D, "M", "ս"), + (0x54E, "M", "վ"), + (0x54F, "M", "տ"), + (0x550, "M", "ր"), + (0x551, "M", "ց"), + (0x552, "M", "ւ"), + (0x553, "M", "փ"), + (0x554, "M", "ք"), + (0x555, "M", "օ"), + (0x556, "M", "ֆ"), + (0x557, "X"), + (0x559, "V"), + (0x587, "M", "եւ"), + (0x588, "V"), + (0x58B, "X"), + (0x58D, "V"), + (0x590, "X"), + (0x591, "V"), + (0x5C8, "X"), + (0x5D0, "V"), + (0x5EB, "X"), + (0x5EF, "V"), + (0x5F5, "X"), + (0x606, "V"), + (0x61C, "X"), + (0x61D, "V"), + (0x675, "M", "اٴ"), + (0x676, "M", "وٴ"), + (0x677, "M", "ۇٴ"), + (0x678, "M", "يٴ"), + (0x679, "V"), + (0x6DD, "X"), + (0x6DE, "V"), + (0x70E, "X"), + (0x710, "V"), + (0x74B, "X"), + (0x74D, "V"), + (0x7B2, "X"), + (0x7C0, "V"), + (0x7FB, "X"), + (0x7FD, "V"), + (0x82E, "X"), + (0x830, "V"), + (0x83F, "X"), + (0x840, "V"), + (0x85C, "X"), + (0x85E, "V"), + (0x85F, "X"), + (0x860, "V"), + (0x86B, "X"), + (0x870, "V"), + (0x890, "X"), + (0x897, "V"), + (0x8E2, "X"), + (0x8E3, "V"), + (0x958, "M", "क़"), + (0x959, "M", "ख़"), + (0x95A, "M", "ग़"), + (0x95B, "M", "ज़"), + (0x95C, "M", "ड़"), + (0x95D, "M", "ढ़"), + (0x95E, "M", "फ़"), + (0x95F, "M", "य़"), + (0x960, "V"), + (0x984, "X"), + (0x985, "V"), + (0x98D, "X"), + (0x98F, "V"), + (0x991, "X"), + (0x993, "V"), + (0x9A9, "X"), + (0x9AA, "V"), + (0x9B1, "X"), + (0x9B2, "V"), + (0x9B3, "X"), + (0x9B6, "V"), + (0x9BA, "X"), + (0x9BC, "V"), + (0x9C5, "X"), + (0x9C7, "V"), + (0x9C9, "X"), + (0x9CB, "V"), + (0x9CF, "X"), + (0x9D7, "V"), + (0x9D8, "X"), + (0x9DC, "M", "ড়"), + (0x9DD, "M", "ঢ়"), + (0x9DE, "X"), + (0x9DF, "M", "য়"), + (0x9E0, "V"), + (0x9E4, "X"), + (0x9E6, "V"), + (0x9FF, "X"), + (0xA01, "V"), + (0xA04, "X"), + (0xA05, "V"), + (0xA0B, "X"), + (0xA0F, "V"), + (0xA11, "X"), + (0xA13, "V"), + (0xA29, "X"), + (0xA2A, "V"), + (0xA31, "X"), + (0xA32, "V"), + (0xA33, "M", "ਲ਼"), + (0xA34, "X"), + (0xA35, "V"), + (0xA36, "M", "ਸ਼"), + (0xA37, "X"), + (0xA38, "V"), + (0xA3A, "X"), + (0xA3C, "V"), + (0xA3D, "X"), + (0xA3E, "V"), + (0xA43, "X"), + (0xA47, "V"), + (0xA49, "X"), + (0xA4B, "V"), + (0xA4E, "X"), + (0xA51, "V"), + (0xA52, "X"), + (0xA59, "M", "ਖ਼"), + (0xA5A, "M", "ਗ਼"), + (0xA5B, "M", "ਜ਼"), + (0xA5C, "V"), + (0xA5D, "X"), + (0xA5E, "M", "ਫ਼"), + (0xA5F, "X"), + (0xA66, "V"), + (0xA77, "X"), + (0xA81, "V"), + (0xA84, "X"), + (0xA85, "V"), + (0xA8E, "X"), + (0xA8F, "V"), + (0xA92, "X"), + (0xA93, "V"), + (0xAA9, "X"), + (0xAAA, "V"), + (0xAB1, "X"), + (0xAB2, "V"), + (0xAB4, "X"), + (0xAB5, "V"), + (0xABA, "X"), + (0xABC, "V"), + (0xAC6, "X"), + (0xAC7, "V"), + (0xACA, "X"), + (0xACB, "V"), + (0xACE, "X"), + (0xAD0, "V"), + (0xAD1, "X"), + (0xAE0, "V"), + (0xAE4, "X"), + (0xAE6, "V"), + (0xAF2, "X"), + (0xAF9, "V"), + (0xB00, "X"), + (0xB01, "V"), + (0xB04, "X"), + (0xB05, "V"), + (0xB0D, "X"), + (0xB0F, "V"), + (0xB11, "X"), + (0xB13, "V"), + (0xB29, "X"), + (0xB2A, "V"), + (0xB31, "X"), + (0xB32, "V"), + (0xB34, "X"), + (0xB35, "V"), + (0xB3A, "X"), + (0xB3C, "V"), + (0xB45, "X"), + (0xB47, "V"), + (0xB49, "X"), + (0xB4B, "V"), + (0xB4E, "X"), + (0xB55, "V"), + (0xB58, "X"), + (0xB5C, "M", "ଡ଼"), + (0xB5D, "M", "ଢ଼"), + (0xB5E, "X"), + (0xB5F, "V"), + (0xB64, "X"), + (0xB66, "V"), + (0xB78, "X"), + (0xB82, "V"), + (0xB84, "X"), + (0xB85, "V"), + (0xB8B, "X"), + (0xB8E, "V"), + (0xB91, "X"), + (0xB92, "V"), + (0xB96, "X"), + (0xB99, "V"), + (0xB9B, "X"), + (0xB9C, "V"), + (0xB9D, "X"), + (0xB9E, "V"), + (0xBA0, "X"), + (0xBA3, "V"), + (0xBA5, "X"), + (0xBA8, "V"), + (0xBAB, "X"), + (0xBAE, "V"), + (0xBBA, "X"), + (0xBBE, "V"), + (0xBC3, "X"), + (0xBC6, "V"), + (0xBC9, "X"), + (0xBCA, "V"), + (0xBCE, "X"), + (0xBD0, "V"), + (0xBD1, "X"), + (0xBD7, "V"), + (0xBD8, "X"), + (0xBE6, "V"), + (0xBFB, "X"), + (0xC00, "V"), + (0xC0D, "X"), + (0xC0E, "V"), + (0xC11, "X"), + (0xC12, "V"), + (0xC29, "X"), + (0xC2A, "V"), + (0xC3A, "X"), + (0xC3C, "V"), + (0xC45, "X"), + (0xC46, "V"), + (0xC49, "X"), + (0xC4A, "V"), + (0xC4E, "X"), + (0xC55, "V"), + (0xC57, "X"), + (0xC58, "V"), + (0xC5B, "X"), + (0xC5C, "V"), + (0xC5E, "X"), + (0xC60, "V"), + (0xC64, "X"), + (0xC66, "V"), + (0xC70, "X"), + (0xC77, "V"), + (0xC8D, "X"), + (0xC8E, "V"), + (0xC91, "X"), + (0xC92, "V"), + (0xCA9, "X"), + (0xCAA, "V"), + (0xCB4, "X"), + (0xCB5, "V"), + (0xCBA, "X"), + (0xCBC, "V"), + (0xCC5, "X"), + (0xCC6, "V"), + (0xCC9, "X"), + (0xCCA, "V"), + (0xCCE, "X"), + (0xCD5, "V"), + (0xCD7, "X"), + (0xCDC, "V"), + (0xCDF, "X"), + (0xCE0, "V"), + (0xCE4, "X"), + (0xCE6, "V"), + (0xCF0, "X"), + (0xCF1, "V"), + (0xCF4, "X"), + (0xD00, "V"), + (0xD0D, "X"), + (0xD0E, "V"), + (0xD11, "X"), + (0xD12, "V"), + (0xD45, "X"), + (0xD46, "V"), + (0xD49, "X"), + (0xD4A, "V"), + (0xD50, "X"), + (0xD54, "V"), + (0xD64, "X"), + (0xD66, "V"), + (0xD80, "X"), + (0xD81, "V"), + (0xD84, "X"), + (0xD85, "V"), + (0xD97, "X"), + (0xD9A, "V"), + (0xDB2, "X"), + (0xDB3, "V"), + (0xDBC, "X"), + (0xDBD, "V"), + (0xDBE, "X"), + (0xDC0, "V"), + (0xDC7, "X"), + (0xDCA, "V"), + (0xDCB, "X"), + (0xDCF, "V"), + (0xDD5, "X"), + (0xDD6, "V"), + (0xDD7, "X"), + (0xDD8, "V"), + (0xDE0, "X"), + (0xDE6, "V"), + (0xDF0, "X"), + (0xDF2, "V"), + (0xDF5, "X"), + (0xE01, "V"), + (0xE33, "M", "ํา"), + (0xE34, "V"), + (0xE3B, "X"), + (0xE3F, "V"), + (0xE5C, "X"), + (0xE81, "V"), + (0xE83, "X"), + (0xE84, "V"), + (0xE85, "X"), + (0xE86, "V"), + (0xE8B, "X"), + (0xE8C, "V"), + (0xEA4, "X"), + (0xEA5, "V"), + (0xEA6, "X"), + (0xEA7, "V"), + (0xEB3, "M", "ໍາ"), + (0xEB4, "V"), + (0xEBE, "X"), + (0xEC0, "V"), + (0xEC5, "X"), + (0xEC6, "V"), + (0xEC7, "X"), + (0xEC8, "V"), + (0xECF, "X"), + (0xED0, "V"), + (0xEDA, "X"), + (0xEDC, "M", "ຫນ"), + (0xEDD, "M", "ຫມ"), + (0xEDE, "V"), + (0xEE0, "X"), + (0xF00, "V"), + (0xF0C, "M", "་"), + (0xF0D, "V"), + (0xF43, "M", "གྷ"), + (0xF44, "V"), + (0xF48, "X"), + (0xF49, "V"), + (0xF4D, "M", "ཌྷ"), + (0xF4E, "V"), + (0xF52, "M", "དྷ"), + (0xF53, "V"), + (0xF57, "M", "བྷ"), + (0xF58, "V"), + (0xF5C, "M", "ཛྷ"), + (0xF5D, "V"), + (0xF69, "M", "ཀྵ"), + (0xF6A, "V"), + (0xF6D, "X"), + (0xF71, "V"), + (0xF73, "M", "ཱི"), + (0xF74, "V"), + (0xF75, "M", "ཱུ"), + (0xF76, "M", "ྲྀ"), + (0xF77, "M", "ྲཱྀ"), + (0xF78, "M", "ླྀ"), + (0xF79, "M", "ླཱྀ"), + (0xF7A, "V"), + (0xF81, "M", "ཱྀ"), + (0xF82, "V"), + (0xF93, "M", "ྒྷ"), + (0xF94, "V"), + (0xF98, "X"), + (0xF99, "V"), + (0xF9D, "M", "ྜྷ"), + (0xF9E, "V"), + (0xFA2, "M", "ྡྷ"), + (0xFA3, "V"), + (0xFA7, "M", "ྦྷ"), + (0xFA8, "V"), + (0xFAC, "M", "ྫྷ"), + (0xFAD, "V"), + (0xFB9, "M", "ྐྵ"), + (0xFBA, "V"), + (0xFBD, "X"), + (0xFBE, "V"), + (0xFCD, "X"), + (0xFCE, "V"), + (0xFDB, "X"), + (0x1000, "V"), + (0x10A0, "M", "ⴀ"), + (0x10A1, "M", "ⴁ"), + (0x10A2, "M", "ⴂ"), + (0x10A3, "M", "ⴃ"), + (0x10A4, "M", "ⴄ"), + (0x10A5, "M", "ⴅ"), + (0x10A6, "M", "ⴆ"), + (0x10A7, "M", "ⴇ"), + (0x10A8, "M", "ⴈ"), + (0x10A9, "M", "ⴉ"), + (0x10AA, "M", "ⴊ"), + (0x10AB, "M", "ⴋ"), + (0x10AC, "M", "ⴌ"), + (0x10AD, "M", "ⴍ"), + (0x10AE, "M", "ⴎ"), + (0x10AF, "M", "ⴏ"), + (0x10B0, "M", "ⴐ"), + (0x10B1, "M", "ⴑ"), + (0x10B2, "M", "ⴒ"), + (0x10B3, "M", "ⴓ"), + (0x10B4, "M", "ⴔ"), + (0x10B5, "M", "ⴕ"), + (0x10B6, "M", "ⴖ"), + (0x10B7, "M", "ⴗ"), + (0x10B8, "M", "ⴘ"), + (0x10B9, "M", "ⴙ"), + (0x10BA, "M", "ⴚ"), + (0x10BB, "M", "ⴛ"), + (0x10BC, "M", "ⴜ"), + (0x10BD, "M", "ⴝ"), + (0x10BE, "M", "ⴞ"), + (0x10BF, "M", "ⴟ"), + (0x10C0, "M", "ⴠ"), + (0x10C1, "M", "ⴡ"), + (0x10C2, "M", "ⴢ"), + (0x10C3, "M", "ⴣ"), + (0x10C4, "M", "ⴤ"), + (0x10C5, "M", "ⴥ"), + (0x10C6, "X"), + (0x10C7, "M", "ⴧ"), + (0x10C8, "X"), + (0x10CD, "M", "ⴭ"), + (0x10CE, "X"), + (0x10D0, "V"), + (0x10FC, "M", "ნ"), + (0x10FD, "V"), + (0x115F, "I"), + (0x1161, "V"), + (0x1249, "X"), + (0x124A, "V"), + (0x124E, "X"), + (0x1250, "V"), + (0x1257, "X"), + (0x1258, "V"), + (0x1259, "X"), + (0x125A, "V"), + (0x125E, "X"), + (0x1260, "V"), + (0x1289, "X"), + (0x128A, "V"), + (0x128E, "X"), + (0x1290, "V"), + (0x12B1, "X"), + (0x12B2, "V"), + (0x12B6, "X"), + (0x12B8, "V"), + (0x12BF, "X"), + (0x12C0, "V"), + (0x12C1, "X"), + (0x12C2, "V"), + (0x12C6, "X"), + (0x12C8, "V"), + (0x12D7, "X"), + (0x12D8, "V"), + (0x1311, "X"), + (0x1312, "V"), + (0x1316, "X"), + (0x1318, "V"), + (0x135B, "X"), + (0x135D, "V"), + (0x137D, "X"), + (0x1380, "V"), + (0x139A, "X"), + (0x13A0, "V"), + (0x13F6, "X"), + (0x13F8, "M", "Ᏸ"), + (0x13F9, "M", "Ᏹ"), + (0x13FA, "M", "Ᏺ"), + (0x13FB, "M", "Ᏻ"), + (0x13FC, "M", "Ᏼ"), + (0x13FD, "M", "Ᏽ"), + (0x13FE, "X"), + (0x1400, "V"), + (0x1680, "X"), + (0x1681, "V"), + (0x169D, "X"), + (0x16A0, "V"), + (0x16F9, "X"), + (0x1700, "V"), + (0x1716, "X"), + (0x171F, "V"), + (0x1737, "X"), + (0x1740, "V"), + (0x1754, "X"), + (0x1760, "V"), + (0x176D, "X"), + (0x176E, "V"), + (0x1771, "X"), + (0x1772, "V"), + (0x1774, "X"), + (0x1780, "V"), + (0x17B4, "I"), + (0x17B6, "V"), + (0x17DE, "X"), + (0x17E0, "V"), + (0x17EA, "X"), + (0x17F0, "V"), + (0x17FA, "X"), + (0x1800, "V"), + (0x180B, "I"), + (0x1810, "V"), + (0x181A, "X"), + (0x1820, "V"), + (0x1879, "X"), + (0x1880, "V"), + (0x18AB, "X"), + (0x18B0, "V"), + (0x18F6, "X"), + (0x1900, "V"), + (0x191F, "X"), + (0x1920, "V"), + (0x192C, "X"), + (0x1930, "V"), + (0x193C, "X"), + (0x1940, "V"), + (0x1941, "X"), + (0x1944, "V"), + (0x196E, "X"), + (0x1970, "V"), + (0x1975, "X"), + (0x1980, "V"), + (0x19AC, "X"), + (0x19B0, "V"), + (0x19CA, "X"), + (0x19D0, "V"), + (0x19DB, "X"), + (0x19DE, "V"), + (0x1A1C, "X"), + (0x1A1E, "V"), + (0x1A5F, "X"), + (0x1A60, "V"), + (0x1A7D, "X"), + (0x1A7F, "V"), + (0x1A8A, "X"), + (0x1A90, "V"), + (0x1A9A, "X"), + (0x1AA0, "V"), + (0x1AAE, "X"), + (0x1AB0, "V"), + (0x1ADE, "X"), + (0x1AE0, "V"), + (0x1AEC, "X"), + (0x1B00, "V"), + (0x1B4D, "X"), + (0x1B4E, "V"), + (0x1BF4, "X"), + (0x1BFC, "V"), + (0x1C38, "X"), + (0x1C3B, "V"), + (0x1C4A, "X"), + (0x1C4D, "V"), + (0x1C80, "M", "в"), + (0x1C81, "M", "д"), + (0x1C82, "M", "о"), + (0x1C83, "M", "с"), + (0x1C84, "M", "т"), + (0x1C86, "M", "ъ"), + (0x1C87, "M", "ѣ"), + (0x1C88, "M", "ꙋ"), + (0x1C89, "M", "ᲊ"), + (0x1C8A, "V"), + (0x1C8B, "X"), + (0x1C90, "M", "ა"), + (0x1C91, "M", "ბ"), + (0x1C92, "M", "გ"), + (0x1C93, "M", "დ"), + (0x1C94, "M", "ე"), + (0x1C95, "M", "ვ"), + (0x1C96, "M", "ზ"), + (0x1C97, "M", "თ"), + (0x1C98, "M", "ი"), + (0x1C99, "M", "კ"), + (0x1C9A, "M", "ლ"), + (0x1C9B, "M", "მ"), + (0x1C9C, "M", "ნ"), + (0x1C9D, "M", "ო"), + (0x1C9E, "M", "პ"), + (0x1C9F, "M", "ჟ"), + (0x1CA0, "M", "რ"), + (0x1CA1, "M", "ს"), + (0x1CA2, "M", "ტ"), + (0x1CA3, "M", "უ"), + (0x1CA4, "M", "ფ"), + (0x1CA5, "M", "ქ"), + (0x1CA6, "M", "ღ"), + (0x1CA7, "M", "ყ"), + (0x1CA8, "M", "შ"), + (0x1CA9, "M", "ჩ"), + (0x1CAA, "M", "ც"), + (0x1CAB, "M", "ძ"), + (0x1CAC, "M", "წ"), + (0x1CAD, "M", "ჭ"), + (0x1CAE, "M", "ხ"), + (0x1CAF, "M", "ჯ"), + (0x1CB0, "M", "ჰ"), + (0x1CB1, "M", "ჱ"), + (0x1CB2, "M", "ჲ"), + (0x1CB3, "M", "ჳ"), + (0x1CB4, "M", "ჴ"), + (0x1CB5, "M", "ჵ"), + (0x1CB6, "M", "ჶ"), + (0x1CB7, "M", "ჷ"), + (0x1CB8, "M", "ჸ"), + (0x1CB9, "M", "ჹ"), + (0x1CBA, "M", "ჺ"), + (0x1CBB, "X"), + (0x1CBD, "M", "ჽ"), + (0x1CBE, "M", "ჾ"), + (0x1CBF, "M", "ჿ"), + (0x1CC0, "V"), + (0x1CC8, "X"), + (0x1CD0, "V"), + (0x1CFB, "X"), + (0x1D00, "V"), + (0x1D2C, "M", "a"), + (0x1D2D, "M", "æ"), + (0x1D2E, "M", "b"), + (0x1D2F, "V"), + (0x1D30, "M", "d"), + (0x1D31, "M", "e"), + (0x1D32, "M", "ǝ"), + (0x1D33, "M", "g"), + (0x1D34, "M", "h"), + (0x1D35, "M", "i"), + (0x1D36, "M", "j"), + (0x1D37, "M", "k"), + (0x1D38, "M", "l"), + (0x1D39, "M", "m"), + (0x1D3A, "M", "n"), + (0x1D3B, "V"), + (0x1D3C, "M", "o"), + (0x1D3D, "M", "ȣ"), + (0x1D3E, "M", "p"), + (0x1D3F, "M", "r"), + (0x1D40, "M", "t"), + (0x1D41, "M", "u"), + (0x1D42, "M", "w"), + (0x1D43, "M", "a"), + (0x1D44, "M", "ɐ"), + (0x1D45, "M", "ɑ"), + (0x1D46, "M", "ᴂ"), + (0x1D47, "M", "b"), + (0x1D48, "M", "d"), + (0x1D49, "M", "e"), + (0x1D4A, "M", "ə"), + (0x1D4B, "M", "ɛ"), + (0x1D4C, "M", "ɜ"), + (0x1D4D, "M", "g"), + (0x1D4E, "V"), + (0x1D4F, "M", "k"), + (0x1D50, "M", "m"), + (0x1D51, "M", "ŋ"), + (0x1D52, "M", "o"), + (0x1D53, "M", "ɔ"), + (0x1D54, "M", "ᴖ"), + (0x1D55, "M", "ᴗ"), + (0x1D56, "M", "p"), + (0x1D57, "M", "t"), + (0x1D58, "M", "u"), + (0x1D59, "M", "ᴝ"), + (0x1D5A, "M", "ɯ"), + (0x1D5B, "M", "v"), + (0x1D5C, "M", "ᴥ"), + (0x1D5D, "M", "β"), + (0x1D5E, "M", "γ"), + (0x1D5F, "M", "δ"), + (0x1D60, "M", "φ"), + (0x1D61, "M", "χ"), + (0x1D62, "M", "i"), + (0x1D63, "M", "r"), + (0x1D64, "M", "u"), + (0x1D65, "M", "v"), + (0x1D66, "M", "β"), + (0x1D67, "M", "γ"), + (0x1D68, "M", "ρ"), + (0x1D69, "M", "φ"), + (0x1D6A, "M", "χ"), + (0x1D6B, "V"), + (0x1D78, "M", "н"), + (0x1D79, "V"), + (0x1D9B, "M", "ɒ"), + (0x1D9C, "M", "c"), + (0x1D9D, "M", "ɕ"), + (0x1D9E, "M", "ð"), + (0x1D9F, "M", "ɜ"), + (0x1DA0, "M", "f"), + (0x1DA1, "M", "ɟ"), + (0x1DA2, "M", "ɡ"), + (0x1DA3, "M", "ɥ"), + (0x1DA4, "M", "ɨ"), + (0x1DA5, "M", "ɩ"), + (0x1DA6, "M", "ɪ"), + (0x1DA7, "M", "ᵻ"), + (0x1DA8, "M", "ʝ"), + (0x1DA9, "M", "ɭ"), + (0x1DAA, "M", "ᶅ"), + (0x1DAB, "M", "ʟ"), + (0x1DAC, "M", "ɱ"), + (0x1DAD, "M", "ɰ"), + (0x1DAE, "M", "ɲ"), + (0x1DAF, "M", "ɳ"), + (0x1DB0, "M", "ɴ"), + (0x1DB1, "M", "ɵ"), + (0x1DB2, "M", "ɸ"), + (0x1DB3, "M", "ʂ"), + (0x1DB4, "M", "ʃ"), + (0x1DB5, "M", "ƫ"), + (0x1DB6, "M", "ʉ"), + (0x1DB7, "M", "ʊ"), + (0x1DB8, "M", "ᴜ"), + (0x1DB9, "M", "ʋ"), + (0x1DBA, "M", "ʌ"), + (0x1DBB, "M", "z"), + (0x1DBC, "M", "ʐ"), + (0x1DBD, "M", "ʑ"), + (0x1DBE, "M", "ʒ"), + (0x1DBF, "M", "θ"), + (0x1DC0, "V"), + (0x1E00, "M", "ḁ"), + (0x1E01, "V"), + (0x1E02, "M", "ḃ"), + (0x1E03, "V"), + (0x1E04, "M", "ḅ"), + (0x1E05, "V"), + (0x1E06, "M", "ḇ"), + (0x1E07, "V"), + (0x1E08, "M", "ḉ"), + (0x1E09, "V"), + (0x1E0A, "M", "ḋ"), + (0x1E0B, "V"), + (0x1E0C, "M", "ḍ"), + (0x1E0D, "V"), + (0x1E0E, "M", "ḏ"), + (0x1E0F, "V"), + (0x1E10, "M", "ḑ"), + (0x1E11, "V"), + (0x1E12, "M", "ḓ"), + (0x1E13, "V"), + (0x1E14, "M", "ḕ"), + (0x1E15, "V"), + (0x1E16, "M", "ḗ"), + (0x1E17, "V"), + (0x1E18, "M", "ḙ"), + (0x1E19, "V"), + (0x1E1A, "M", "ḛ"), + (0x1E1B, "V"), + (0x1E1C, "M", "ḝ"), + (0x1E1D, "V"), + (0x1E1E, "M", "ḟ"), + (0x1E1F, "V"), + (0x1E20, "M", "ḡ"), + (0x1E21, "V"), + (0x1E22, "M", "ḣ"), + (0x1E23, "V"), + (0x1E24, "M", "ḥ"), + (0x1E25, "V"), + (0x1E26, "M", "ḧ"), + (0x1E27, "V"), + (0x1E28, "M", "ḩ"), + (0x1E29, "V"), + (0x1E2A, "M", "ḫ"), + (0x1E2B, "V"), + (0x1E2C, "M", "ḭ"), + (0x1E2D, "V"), + (0x1E2E, "M", "ḯ"), + (0x1E2F, "V"), + (0x1E30, "M", "ḱ"), + (0x1E31, "V"), + (0x1E32, "M", "ḳ"), + (0x1E33, "V"), + (0x1E34, "M", "ḵ"), + (0x1E35, "V"), + (0x1E36, "M", "ḷ"), + (0x1E37, "V"), + (0x1E38, "M", "ḹ"), + (0x1E39, "V"), + (0x1E3A, "M", "ḻ"), + (0x1E3B, "V"), + (0x1E3C, "M", "ḽ"), + (0x1E3D, "V"), + (0x1E3E, "M", "ḿ"), + (0x1E3F, "V"), + (0x1E40, "M", "ṁ"), + (0x1E41, "V"), + (0x1E42, "M", "ṃ"), + (0x1E43, "V"), + (0x1E44, "M", "ṅ"), + (0x1E45, "V"), + (0x1E46, "M", "ṇ"), + (0x1E47, "V"), + (0x1E48, "M", "ṉ"), + (0x1E49, "V"), + (0x1E4A, "M", "ṋ"), + (0x1E4B, "V"), + (0x1E4C, "M", "ṍ"), + (0x1E4D, "V"), + (0x1E4E, "M", "ṏ"), + (0x1E4F, "V"), + (0x1E50, "M", "ṑ"), + (0x1E51, "V"), + (0x1E52, "M", "ṓ"), + (0x1E53, "V"), + (0x1E54, "M", "ṕ"), + (0x1E55, "V"), + (0x1E56, "M", "ṗ"), + (0x1E57, "V"), + (0x1E58, "M", "ṙ"), + (0x1E59, "V"), + (0x1E5A, "M", "ṛ"), + (0x1E5B, "V"), + (0x1E5C, "M", "ṝ"), + (0x1E5D, "V"), + (0x1E5E, "M", "ṟ"), + (0x1E5F, "V"), + (0x1E60, "M", "ṡ"), + (0x1E61, "V"), + (0x1E62, "M", "ṣ"), + (0x1E63, "V"), + (0x1E64, "M", "ṥ"), + (0x1E65, "V"), + (0x1E66, "M", "ṧ"), + (0x1E67, "V"), + (0x1E68, "M", "ṩ"), + (0x1E69, "V"), + (0x1E6A, "M", "ṫ"), + (0x1E6B, "V"), + (0x1E6C, "M", "ṭ"), + (0x1E6D, "V"), + (0x1E6E, "M", "ṯ"), + (0x1E6F, "V"), + (0x1E70, "M", "ṱ"), + (0x1E71, "V"), + (0x1E72, "M", "ṳ"), + (0x1E73, "V"), + (0x1E74, "M", "ṵ"), + (0x1E75, "V"), + (0x1E76, "M", "ṷ"), + (0x1E77, "V"), + (0x1E78, "M", "ṹ"), + (0x1E79, "V"), + (0x1E7A, "M", "ṻ"), + (0x1E7B, "V"), + (0x1E7C, "M", "ṽ"), + (0x1E7D, "V"), + (0x1E7E, "M", "ṿ"), + (0x1E7F, "V"), + (0x1E80, "M", "ẁ"), + (0x1E81, "V"), + (0x1E82, "M", "ẃ"), + (0x1E83, "V"), + (0x1E84, "M", "ẅ"), + (0x1E85, "V"), + (0x1E86, "M", "ẇ"), + (0x1E87, "V"), + (0x1E88, "M", "ẉ"), + (0x1E89, "V"), + (0x1E8A, "M", "ẋ"), + (0x1E8B, "V"), + (0x1E8C, "M", "ẍ"), + (0x1E8D, "V"), + (0x1E8E, "M", "ẏ"), + (0x1E8F, "V"), + (0x1E90, "M", "ẑ"), + (0x1E91, "V"), + (0x1E92, "M", "ẓ"), + (0x1E93, "V"), + (0x1E94, "M", "ẕ"), + (0x1E95, "V"), + (0x1E9A, "M", "aʾ"), + (0x1E9B, "M", "ṡ"), + (0x1E9C, "V"), + (0x1E9E, "M", "ß"), + (0x1E9F, "V"), + (0x1EA0, "M", "ạ"), + (0x1EA1, "V"), + (0x1EA2, "M", "ả"), + (0x1EA3, "V"), + (0x1EA4, "M", "ấ"), + (0x1EA5, "V"), + (0x1EA6, "M", "ầ"), + (0x1EA7, "V"), + (0x1EA8, "M", "ẩ"), + (0x1EA9, "V"), + (0x1EAA, "M", "ẫ"), + (0x1EAB, "V"), + (0x1EAC, "M", "ậ"), + (0x1EAD, "V"), + (0x1EAE, "M", "ắ"), + (0x1EAF, "V"), + (0x1EB0, "M", "ằ"), + (0x1EB1, "V"), + (0x1EB2, "M", "ẳ"), + (0x1EB3, "V"), + (0x1EB4, "M", "ẵ"), + (0x1EB5, "V"), + (0x1EB6, "M", "ặ"), + (0x1EB7, "V"), + (0x1EB8, "M", "ẹ"), + (0x1EB9, "V"), + (0x1EBA, "M", "ẻ"), + (0x1EBB, "V"), + (0x1EBC, "M", "ẽ"), + (0x1EBD, "V"), + (0x1EBE, "M", "ế"), + (0x1EBF, "V"), + (0x1EC0, "M", "ề"), + (0x1EC1, "V"), + (0x1EC2, "M", "ể"), + (0x1EC3, "V"), + (0x1EC4, "M", "ễ"), + (0x1EC5, "V"), + (0x1EC6, "M", "ệ"), + (0x1EC7, "V"), + (0x1EC8, "M", "ỉ"), + (0x1EC9, "V"), + (0x1ECA, "M", "ị"), + (0x1ECB, "V"), + (0x1ECC, "M", "ọ"), + (0x1ECD, "V"), + (0x1ECE, "M", "ỏ"), + (0x1ECF, "V"), + (0x1ED0, "M", "ố"), + (0x1ED1, "V"), + (0x1ED2, "M", "ồ"), + (0x1ED3, "V"), + (0x1ED4, "M", "ổ"), + (0x1ED5, "V"), + (0x1ED6, "M", "ỗ"), + (0x1ED7, "V"), + (0x1ED8, "M", "ộ"), + (0x1ED9, "V"), + (0x1EDA, "M", "ớ"), + (0x1EDB, "V"), + (0x1EDC, "M", "ờ"), + (0x1EDD, "V"), + (0x1EDE, "M", "ở"), + (0x1EDF, "V"), + (0x1EE0, "M", "ỡ"), + (0x1EE1, "V"), + (0x1EE2, "M", "ợ"), + (0x1EE3, "V"), + (0x1EE4, "M", "ụ"), + (0x1EE5, "V"), + (0x1EE6, "M", "ủ"), + (0x1EE7, "V"), + (0x1EE8, "M", "ứ"), + (0x1EE9, "V"), + (0x1EEA, "M", "ừ"), + (0x1EEB, "V"), + (0x1EEC, "M", "ử"), + (0x1EED, "V"), + (0x1EEE, "M", "ữ"), + (0x1EEF, "V"), + (0x1EF0, "M", "ự"), + (0x1EF1, "V"), + (0x1EF2, "M", "ỳ"), + (0x1EF3, "V"), + (0x1EF4, "M", "ỵ"), + (0x1EF5, "V"), + (0x1EF6, "M", "ỷ"), + (0x1EF7, "V"), + (0x1EF8, "M", "ỹ"), + (0x1EF9, "V"), + (0x1EFA, "M", "ỻ"), + (0x1EFB, "V"), + (0x1EFC, "M", "ỽ"), + (0x1EFD, "V"), + (0x1EFE, "M", "ỿ"), + (0x1EFF, "V"), + (0x1F08, "M", "ἀ"), + (0x1F09, "M", "ἁ"), + (0x1F0A, "M", "ἂ"), + (0x1F0B, "M", "ἃ"), + (0x1F0C, "M", "ἄ"), + (0x1F0D, "M", "ἅ"), + (0x1F0E, "M", "ἆ"), + (0x1F0F, "M", "ἇ"), + (0x1F10, "V"), + (0x1F16, "X"), + (0x1F18, "M", "ἐ"), + (0x1F19, "M", "ἑ"), + (0x1F1A, "M", "ἒ"), + (0x1F1B, "M", "ἓ"), + (0x1F1C, "M", "ἔ"), + (0x1F1D, "M", "ἕ"), + (0x1F1E, "X"), + (0x1F20, "V"), + (0x1F28, "M", "ἠ"), + (0x1F29, "M", "ἡ"), + (0x1F2A, "M", "ἢ"), + (0x1F2B, "M", "ἣ"), + (0x1F2C, "M", "ἤ"), + (0x1F2D, "M", "ἥ"), + (0x1F2E, "M", "ἦ"), + (0x1F2F, "M", "ἧ"), + (0x1F30, "V"), + (0x1F38, "M", "ἰ"), + (0x1F39, "M", "ἱ"), + (0x1F3A, "M", "ἲ"), + (0x1F3B, "M", "ἳ"), + (0x1F3C, "M", "ἴ"), + (0x1F3D, "M", "ἵ"), + (0x1F3E, "M", "ἶ"), + (0x1F3F, "M", "ἷ"), + (0x1F40, "V"), + (0x1F46, "X"), + (0x1F48, "M", "ὀ"), + (0x1F49, "M", "ὁ"), + (0x1F4A, "M", "ὂ"), + (0x1F4B, "M", "ὃ"), + (0x1F4C, "M", "ὄ"), + (0x1F4D, "M", "ὅ"), + (0x1F4E, "X"), + (0x1F50, "V"), + (0x1F58, "X"), + (0x1F59, "M", "ὑ"), + (0x1F5A, "X"), + (0x1F5B, "M", "ὓ"), + (0x1F5C, "X"), + (0x1F5D, "M", "ὕ"), + (0x1F5E, "X"), + (0x1F5F, "M", "ὗ"), + (0x1F60, "V"), + (0x1F68, "M", "ὠ"), + (0x1F69, "M", "ὡ"), + (0x1F6A, "M", "ὢ"), + (0x1F6B, "M", "ὣ"), + (0x1F6C, "M", "ὤ"), + (0x1F6D, "M", "ὥ"), + (0x1F6E, "M", "ὦ"), + (0x1F6F, "M", "ὧ"), + (0x1F70, "V"), + (0x1F71, "M", "ά"), + (0x1F72, "V"), + (0x1F73, "M", "έ"), + (0x1F74, "V"), + (0x1F75, "M", "ή"), + (0x1F76, "V"), + (0x1F77, "M", "ί"), + (0x1F78, "V"), + (0x1F79, "M", "ό"), + (0x1F7A, "V"), + (0x1F7B, "M", "ύ"), + (0x1F7C, "V"), + (0x1F7D, "M", "ώ"), + (0x1F7E, "X"), + (0x1F80, "M", "ἀι"), + (0x1F81, "M", "ἁι"), + (0x1F82, "M", "ἂι"), + (0x1F83, "M", "ἃι"), + (0x1F84, "M", "ἄι"), + (0x1F85, "M", "ἅι"), + (0x1F86, "M", "ἆι"), + (0x1F87, "M", "ἇι"), + (0x1F88, "M", "ἀι"), + (0x1F89, "M", "ἁι"), + (0x1F8A, "M", "ἂι"), + (0x1F8B, "M", "ἃι"), + (0x1F8C, "M", "ἄι"), + (0x1F8D, "M", "ἅι"), + (0x1F8E, "M", "ἆι"), + (0x1F8F, "M", "ἇι"), + (0x1F90, "M", "ἠι"), + (0x1F91, "M", "ἡι"), + (0x1F92, "M", "ἢι"), + (0x1F93, "M", "ἣι"), + (0x1F94, "M", "ἤι"), + (0x1F95, "M", "ἥι"), + (0x1F96, "M", "ἦι"), + (0x1F97, "M", "ἧι"), + (0x1F98, "M", "ἠι"), + (0x1F99, "M", "ἡι"), + (0x1F9A, "M", "ἢι"), + (0x1F9B, "M", "ἣι"), + (0x1F9C, "M", "ἤι"), + (0x1F9D, "M", "ἥι"), + (0x1F9E, "M", "ἦι"), + (0x1F9F, "M", "ἧι"), + (0x1FA0, "M", "ὠι"), + (0x1FA1, "M", "ὡι"), + (0x1FA2, "M", "ὢι"), + (0x1FA3, "M", "ὣι"), + (0x1FA4, "M", "ὤι"), + (0x1FA5, "M", "ὥι"), + (0x1FA6, "M", "ὦι"), + (0x1FA7, "M", "ὧι"), + (0x1FA8, "M", "ὠι"), + (0x1FA9, "M", "ὡι"), + (0x1FAA, "M", "ὢι"), + (0x1FAB, "M", "ὣι"), + (0x1FAC, "M", "ὤι"), + (0x1FAD, "M", "ὥι"), + (0x1FAE, "M", "ὦι"), + (0x1FAF, "M", "ὧι"), + (0x1FB0, "V"), + (0x1FB2, "M", "ὰι"), + (0x1FB3, "M", "αι"), + (0x1FB4, "M", "άι"), + (0x1FB5, "X"), + (0x1FB6, "V"), + (0x1FB7, "M", "ᾶι"), + (0x1FB8, "M", "ᾰ"), + (0x1FB9, "M", "ᾱ"), + (0x1FBA, "M", "ὰ"), + (0x1FBB, "M", "ά"), + (0x1FBC, "M", "αι"), + (0x1FBD, "M", " ̓"), + (0x1FBE, "M", "ι"), + (0x1FBF, "M", " ̓"), + (0x1FC0, "M", " ͂"), + (0x1FC1, "M", " ̈͂"), + (0x1FC2, "M", "ὴι"), + (0x1FC3, "M", "ηι"), + (0x1FC4, "M", "ήι"), + (0x1FC5, "X"), + (0x1FC6, "V"), + (0x1FC7, "M", "ῆι"), + (0x1FC8, "M", "ὲ"), + (0x1FC9, "M", "έ"), + (0x1FCA, "M", "ὴ"), + (0x1FCB, "M", "ή"), + (0x1FCC, "M", "ηι"), + (0x1FCD, "M", " ̓̀"), + (0x1FCE, "M", " ̓́"), + (0x1FCF, "M", " ̓͂"), + (0x1FD0, "V"), + (0x1FD3, "M", "ΐ"), + (0x1FD4, "X"), + (0x1FD6, "V"), + (0x1FD8, "M", "ῐ"), + (0x1FD9, "M", "ῑ"), + (0x1FDA, "M", "ὶ"), + (0x1FDB, "M", "ί"), + (0x1FDC, "X"), + (0x1FDD, "M", " ̔̀"), + (0x1FDE, "M", " ̔́"), + (0x1FDF, "M", " ̔͂"), + (0x1FE0, "V"), + (0x1FE3, "M", "ΰ"), + (0x1FE4, "V"), + (0x1FE8, "M", "ῠ"), + (0x1FE9, "M", "ῡ"), + (0x1FEA, "M", "ὺ"), + (0x1FEB, "M", "ύ"), + (0x1FEC, "M", "ῥ"), + (0x1FED, "M", " ̈̀"), + (0x1FEE, "M", " ̈́"), + (0x1FEF, "M", "`"), + (0x1FF0, "X"), + (0x1FF2, "M", "ὼι"), + (0x1FF3, "M", "ωι"), + (0x1FF4, "M", "ώι"), + (0x1FF5, "X"), + (0x1FF6, "V"), + (0x1FF7, "M", "ῶι"), + (0x1FF8, "M", "ὸ"), + (0x1FF9, "M", "ό"), + (0x1FFA, "M", "ὼ"), + (0x1FFB, "M", "ώ"), + (0x1FFC, "M", "ωι"), + (0x1FFD, "M", " ́"), + (0x1FFE, "M", " ̔"), + (0x1FFF, "X"), + (0x2000, "M", " "), + (0x200B, "I"), + (0x200C, "D", ""), + (0x200E, "X"), + (0x2010, "V"), + (0x2011, "M", "‐"), + (0x2012, "V"), + (0x2017, "M", " ̳"), + (0x2018, "V"), + (0x2024, "X"), + (0x2027, "V"), + (0x2028, "X"), + (0x202F, "M", " "), + (0x2030, "V"), + (0x2033, "M", "′′"), + (0x2034, "M", "′′′"), + (0x2035, "V"), + (0x2036, "M", "‵‵"), + (0x2037, "M", "‵‵‵"), + (0x2038, "V"), + (0x203C, "M", "!!"), + (0x203D, "V"), + (0x203E, "M", " ̅"), + (0x203F, "V"), + (0x2047, "M", "??"), + (0x2048, "M", "?!"), + (0x2049, "M", "!?"), + (0x204A, "V"), + (0x2057, "M", "′′′′"), + (0x2058, "V"), + (0x205F, "M", " "), + (0x2060, "I"), + (0x2065, "X"), + (0x206A, "I"), + (0x2070, "M", "0"), + (0x2071, "M", "i"), + (0x2072, "X"), + (0x2074, "M", "4"), + (0x2075, "M", "5"), + (0x2076, "M", "6"), + (0x2077, "M", "7"), + (0x2078, "M", "8"), + (0x2079, "M", "9"), + (0x207A, "M", "+"), + (0x207B, "M", "−"), + (0x207C, "M", "="), + (0x207D, "M", "("), + (0x207E, "M", ")"), + (0x207F, "M", "n"), + (0x2080, "M", "0"), + (0x2081, "M", "1"), + (0x2082, "M", "2"), + (0x2083, "M", "3"), + (0x2084, "M", "4"), + (0x2085, "M", "5"), + (0x2086, "M", "6"), + (0x2087, "M", "7"), + (0x2088, "M", "8"), + (0x2089, "M", "9"), + (0x208A, "M", "+"), + (0x208B, "M", "−"), + (0x208C, "M", "="), + (0x208D, "M", "("), + (0x208E, "M", ")"), + (0x208F, "X"), + (0x2090, "M", "a"), + (0x2091, "M", "e"), + (0x2092, "M", "o"), + (0x2093, "M", "x"), + (0x2094, "M", "ə"), + (0x2095, "M", "h"), + (0x2096, "M", "k"), + (0x2097, "M", "l"), + (0x2098, "M", "m"), + (0x2099, "M", "n"), + (0x209A, "M", "p"), + (0x209B, "M", "s"), + (0x209C, "M", "t"), + (0x209D, "X"), + (0x20A0, "V"), + (0x20A8, "M", "rs"), + (0x20A9, "V"), + (0x20C2, "X"), + (0x20D0, "V"), + (0x20F1, "X"), + (0x2100, "M", "a/c"), + (0x2101, "M", "a/s"), + (0x2102, "M", "c"), + (0x2103, "M", "°c"), + (0x2104, "V"), + (0x2105, "M", "c/o"), + (0x2106, "M", "c/u"), + (0x2107, "M", "ɛ"), + (0x2108, "V"), + (0x2109, "M", "°f"), + (0x210A, "M", "g"), + (0x210B, "M", "h"), + (0x210F, "M", "ħ"), + (0x2110, "M", "i"), + (0x2112, "M", "l"), + (0x2114, "V"), + (0x2115, "M", "n"), + (0x2116, "M", "no"), + (0x2117, "V"), + (0x2119, "M", "p"), + (0x211A, "M", "q"), + (0x211B, "M", "r"), + (0x211E, "V"), + (0x2120, "M", "sm"), + (0x2121, "M", "tel"), + (0x2122, "M", "tm"), + (0x2123, "V"), + (0x2124, "M", "z"), + (0x2125, "V"), + (0x2126, "M", "ω"), + (0x2127, "V"), + (0x2128, "M", "z"), + (0x2129, "V"), + (0x212A, "M", "k"), + (0x212B, "M", "å"), + (0x212C, "M", "b"), + (0x212D, "M", "c"), + (0x212E, "V"), + (0x212F, "M", "e"), + (0x2131, "M", "f"), + (0x2132, "M", "ⅎ"), + (0x2133, "M", "m"), + (0x2134, "M", "o"), + (0x2135, "M", "א"), + (0x2136, "M", "ב"), + (0x2137, "M", "ג"), + (0x2138, "M", "ד"), + (0x2139, "M", "i"), + (0x213A, "V"), + (0x213B, "M", "fax"), + (0x213C, "M", "π"), + (0x213D, "M", "γ"), + (0x213F, "M", "π"), + (0x2140, "M", "∑"), + (0x2141, "V"), + (0x2145, "M", "d"), + (0x2147, "M", "e"), + (0x2148, "M", "i"), + (0x2149, "M", "j"), + (0x214A, "V"), + (0x2150, "M", "1⁄7"), + (0x2151, "M", "1⁄9"), + (0x2152, "M", "1⁄10"), + (0x2153, "M", "1⁄3"), + (0x2154, "M", "2⁄3"), + (0x2155, "M", "1⁄5"), + (0x2156, "M", "2⁄5"), + (0x2157, "M", "3⁄5"), + (0x2158, "M", "4⁄5"), + (0x2159, "M", "1⁄6"), + (0x215A, "M", "5⁄6"), + (0x215B, "M", "1⁄8"), + (0x215C, "M", "3⁄8"), + (0x215D, "M", "5⁄8"), + (0x215E, "M", "7⁄8"), + (0x215F, "M", "1⁄"), + (0x2160, "M", "i"), + (0x2161, "M", "ii"), + (0x2162, "M", "iii"), + (0x2163, "M", "iv"), + (0x2164, "M", "v"), + (0x2165, "M", "vi"), + (0x2166, "M", "vii"), + (0x2167, "M", "viii"), + (0x2168, "M", "ix"), + (0x2169, "M", "x"), + (0x216A, "M", "xi"), + (0x216B, "M", "xii"), + (0x216C, "M", "l"), + (0x216D, "M", "c"), + (0x216E, "M", "d"), + (0x216F, "M", "m"), + (0x2170, "M", "i"), + (0x2171, "M", "ii"), + (0x2172, "M", "iii"), + (0x2173, "M", "iv"), + (0x2174, "M", "v"), + (0x2175, "M", "vi"), + (0x2176, "M", "vii"), + (0x2177, "M", "viii"), + (0x2178, "M", "ix"), + (0x2179, "M", "x"), + (0x217A, "M", "xi"), + (0x217B, "M", "xii"), + (0x217C, "M", "l"), + (0x217D, "M", "c"), + (0x217E, "M", "d"), + (0x217F, "M", "m"), + (0x2180, "V"), + (0x2183, "M", "ↄ"), + (0x2184, "V"), + (0x2189, "M", "0⁄3"), + (0x218A, "V"), + (0x218C, "X"), + (0x2190, "V"), + (0x222C, "M", "∫∫"), + (0x222D, "M", "∫∫∫"), + (0x222E, "V"), + (0x222F, "M", "∮∮"), + (0x2230, "M", "∮∮∮"), + (0x2231, "V"), + (0x2329, "M", "〈"), + (0x232A, "M", "〉"), + (0x232B, "V"), + (0x242A, "X"), + (0x2440, "V"), + (0x244B, "X"), + (0x2460, "M", "1"), + (0x2461, "M", "2"), + (0x2462, "M", "3"), + (0x2463, "M", "4"), + (0x2464, "M", "5"), + (0x2465, "M", "6"), + (0x2466, "M", "7"), + (0x2467, "M", "8"), + (0x2468, "M", "9"), + (0x2469, "M", "10"), + (0x246A, "M", "11"), + (0x246B, "M", "12"), + (0x246C, "M", "13"), + (0x246D, "M", "14"), + (0x246E, "M", "15"), + (0x246F, "M", "16"), + (0x2470, "M", "17"), + (0x2471, "M", "18"), + (0x2472, "M", "19"), + (0x2473, "M", "20"), + (0x2474, "M", "(1)"), + (0x2475, "M", "(2)"), + (0x2476, "M", "(3)"), + (0x2477, "M", "(4)"), + (0x2478, "M", "(5)"), + (0x2479, "M", "(6)"), + (0x247A, "M", "(7)"), + (0x247B, "M", "(8)"), + (0x247C, "M", "(9)"), + (0x247D, "M", "(10)"), + (0x247E, "M", "(11)"), + (0x247F, "M", "(12)"), + (0x2480, "M", "(13)"), + (0x2481, "M", "(14)"), + (0x2482, "M", "(15)"), + (0x2483, "M", "(16)"), + (0x2484, "M", "(17)"), + (0x2485, "M", "(18)"), + (0x2486, "M", "(19)"), + (0x2487, "M", "(20)"), + (0x2488, "X"), + (0x249C, "M", "(a)"), + (0x249D, "M", "(b)"), + (0x249E, "M", "(c)"), + (0x249F, "M", "(d)"), + (0x24A0, "M", "(e)"), + (0x24A1, "M", "(f)"), + (0x24A2, "M", "(g)"), + (0x24A3, "M", "(h)"), + (0x24A4, "M", "(i)"), + (0x24A5, "M", "(j)"), + (0x24A6, "M", "(k)"), + (0x24A7, "M", "(l)"), + (0x24A8, "M", "(m)"), + (0x24A9, "M", "(n)"), + (0x24AA, "M", "(o)"), + (0x24AB, "M", "(p)"), + (0x24AC, "M", "(q)"), + (0x24AD, "M", "(r)"), + (0x24AE, "M", "(s)"), + (0x24AF, "M", "(t)"), + (0x24B0, "M", "(u)"), + (0x24B1, "M", "(v)"), + (0x24B2, "M", "(w)"), + (0x24B3, "M", "(x)"), + (0x24B4, "M", "(y)"), + (0x24B5, "M", "(z)"), + (0x24B6, "M", "a"), + (0x24B7, "M", "b"), + (0x24B8, "M", "c"), + (0x24B9, "M", "d"), + (0x24BA, "M", "e"), + (0x24BB, "M", "f"), + (0x24BC, "M", "g"), + (0x24BD, "M", "h"), + (0x24BE, "M", "i"), + (0x24BF, "M", "j"), + (0x24C0, "M", "k"), + (0x24C1, "M", "l"), + (0x24C2, "M", "m"), + (0x24C3, "M", "n"), + (0x24C4, "M", "o"), + (0x24C5, "M", "p"), + (0x24C6, "M", "q"), + (0x24C7, "M", "r"), + (0x24C8, "M", "s"), + (0x24C9, "M", "t"), + (0x24CA, "M", "u"), + (0x24CB, "M", "v"), + (0x24CC, "M", "w"), + (0x24CD, "M", "x"), + (0x24CE, "M", "y"), + (0x24CF, "M", "z"), + (0x24D0, "M", "a"), + (0x24D1, "M", "b"), + (0x24D2, "M", "c"), + (0x24D3, "M", "d"), + (0x24D4, "M", "e"), + (0x24D5, "M", "f"), + (0x24D6, "M", "g"), + (0x24D7, "M", "h"), + (0x24D8, "M", "i"), + (0x24D9, "M", "j"), + (0x24DA, "M", "k"), + (0x24DB, "M", "l"), + (0x24DC, "M", "m"), + (0x24DD, "M", "n"), + (0x24DE, "M", "o"), + (0x24DF, "M", "p"), + (0x24E0, "M", "q"), + (0x24E1, "M", "r"), + (0x24E2, "M", "s"), + (0x24E3, "M", "t"), + (0x24E4, "M", "u"), + (0x24E5, "M", "v"), + (0x24E6, "M", "w"), + (0x24E7, "M", "x"), + (0x24E8, "M", "y"), + (0x24E9, "M", "z"), + (0x24EA, "M", "0"), + (0x24EB, "V"), + (0x2A0C, "M", "∫∫∫∫"), + (0x2A0D, "V"), + (0x2A74, "M", "::="), + (0x2A75, "M", "=="), + (0x2A76, "M", "==="), + (0x2A77, "V"), + (0x2ADC, "M", "⫝̸"), + (0x2ADD, "V"), + (0x2B74, "X"), + (0x2B76, "V"), + (0x2C00, "M", "ⰰ"), + (0x2C01, "M", "ⰱ"), + (0x2C02, "M", "ⰲ"), + (0x2C03, "M", "ⰳ"), + (0x2C04, "M", "ⰴ"), + (0x2C05, "M", "ⰵ"), + (0x2C06, "M", "ⰶ"), + (0x2C07, "M", "ⰷ"), + (0x2C08, "M", "ⰸ"), + (0x2C09, "M", "ⰹ"), + (0x2C0A, "M", "ⰺ"), + (0x2C0B, "M", "ⰻ"), + (0x2C0C, "M", "ⰼ"), + (0x2C0D, "M", "ⰽ"), + (0x2C0E, "M", "ⰾ"), + (0x2C0F, "M", "ⰿ"), + (0x2C10, "M", "ⱀ"), + (0x2C11, "M", "ⱁ"), + (0x2C12, "M", "ⱂ"), + (0x2C13, "M", "ⱃ"), + (0x2C14, "M", "ⱄ"), + (0x2C15, "M", "ⱅ"), + (0x2C16, "M", "ⱆ"), + (0x2C17, "M", "ⱇ"), + (0x2C18, "M", "ⱈ"), + (0x2C19, "M", "ⱉ"), + (0x2C1A, "M", "ⱊ"), + (0x2C1B, "M", "ⱋ"), + (0x2C1C, "M", "ⱌ"), + (0x2C1D, "M", "ⱍ"), + (0x2C1E, "M", "ⱎ"), + (0x2C1F, "M", "ⱏ"), + (0x2C20, "M", "ⱐ"), + (0x2C21, "M", "ⱑ"), + (0x2C22, "M", "ⱒ"), + (0x2C23, "M", "ⱓ"), + (0x2C24, "M", "ⱔ"), + (0x2C25, "M", "ⱕ"), + (0x2C26, "M", "ⱖ"), + (0x2C27, "M", "ⱗ"), + (0x2C28, "M", "ⱘ"), + (0x2C29, "M", "ⱙ"), + (0x2C2A, "M", "ⱚ"), + (0x2C2B, "M", "ⱛ"), + (0x2C2C, "M", "ⱜ"), + (0x2C2D, "M", "ⱝ"), + (0x2C2E, "M", "ⱞ"), + (0x2C2F, "M", "ⱟ"), + (0x2C30, "V"), + (0x2C60, "M", "ⱡ"), + (0x2C61, "V"), + (0x2C62, "M", "ɫ"), + (0x2C63, "M", "ᵽ"), + (0x2C64, "M", "ɽ"), + (0x2C65, "V"), + (0x2C67, "M", "ⱨ"), + (0x2C68, "V"), + (0x2C69, "M", "ⱪ"), + (0x2C6A, "V"), + (0x2C6B, "M", "ⱬ"), + (0x2C6C, "V"), + (0x2C6D, "M", "ɑ"), + (0x2C6E, "M", "ɱ"), + (0x2C6F, "M", "ɐ"), + (0x2C70, "M", "ɒ"), + (0x2C71, "V"), + (0x2C72, "M", "ⱳ"), + (0x2C73, "V"), + (0x2C75, "M", "ⱶ"), + (0x2C76, "V"), + (0x2C7C, "M", "j"), + (0x2C7D, "M", "v"), + (0x2C7E, "M", "ȿ"), + (0x2C7F, "M", "ɀ"), + (0x2C80, "M", "ⲁ"), + (0x2C81, "V"), + (0x2C82, "M", "ⲃ"), + (0x2C83, "V"), + (0x2C84, "M", "ⲅ"), + (0x2C85, "V"), + (0x2C86, "M", "ⲇ"), + (0x2C87, "V"), + (0x2C88, "M", "ⲉ"), + (0x2C89, "V"), + (0x2C8A, "M", "ⲋ"), + (0x2C8B, "V"), + (0x2C8C, "M", "ⲍ"), + (0x2C8D, "V"), + (0x2C8E, "M", "ⲏ"), + (0x2C8F, "V"), + (0x2C90, "M", "ⲑ"), + (0x2C91, "V"), + (0x2C92, "M", "ⲓ"), + (0x2C93, "V"), + (0x2C94, "M", "ⲕ"), + (0x2C95, "V"), + (0x2C96, "M", "ⲗ"), + (0x2C97, "V"), + (0x2C98, "M", "ⲙ"), + (0x2C99, "V"), + (0x2C9A, "M", "ⲛ"), + (0x2C9B, "V"), + (0x2C9C, "M", "ⲝ"), + (0x2C9D, "V"), + (0x2C9E, "M", "ⲟ"), + (0x2C9F, "V"), + (0x2CA0, "M", "ⲡ"), + (0x2CA1, "V"), + (0x2CA2, "M", "ⲣ"), + (0x2CA3, "V"), + (0x2CA4, "M", "ⲥ"), + (0x2CA5, "V"), + (0x2CA6, "M", "ⲧ"), + (0x2CA7, "V"), + (0x2CA8, "M", "ⲩ"), + (0x2CA9, "V"), + (0x2CAA, "M", "ⲫ"), + (0x2CAB, "V"), + (0x2CAC, "M", "ⲭ"), + (0x2CAD, "V"), + (0x2CAE, "M", "ⲯ"), + (0x2CAF, "V"), + (0x2CB0, "M", "ⲱ"), + (0x2CB1, "V"), + (0x2CB2, "M", "ⲳ"), + (0x2CB3, "V"), + (0x2CB4, "M", "ⲵ"), + (0x2CB5, "V"), + (0x2CB6, "M", "ⲷ"), + (0x2CB7, "V"), + (0x2CB8, "M", "ⲹ"), + (0x2CB9, "V"), + (0x2CBA, "M", "ⲻ"), + (0x2CBB, "V"), + (0x2CBC, "M", "ⲽ"), + (0x2CBD, "V"), + (0x2CBE, "M", "ⲿ"), + (0x2CBF, "V"), + (0x2CC0, "M", "ⳁ"), + (0x2CC1, "V"), + (0x2CC2, "M", "ⳃ"), + (0x2CC3, "V"), + (0x2CC4, "M", "ⳅ"), + (0x2CC5, "V"), + (0x2CC6, "M", "ⳇ"), + (0x2CC7, "V"), + (0x2CC8, "M", "ⳉ"), + (0x2CC9, "V"), + (0x2CCA, "M", "ⳋ"), + (0x2CCB, "V"), + (0x2CCC, "M", "ⳍ"), + (0x2CCD, "V"), + (0x2CCE, "M", "ⳏ"), + (0x2CCF, "V"), + (0x2CD0, "M", "ⳑ"), + (0x2CD1, "V"), + (0x2CD2, "M", "ⳓ"), + (0x2CD3, "V"), + (0x2CD4, "M", "ⳕ"), + (0x2CD5, "V"), + (0x2CD6, "M", "ⳗ"), + (0x2CD7, "V"), + (0x2CD8, "M", "ⳙ"), + (0x2CD9, "V"), + (0x2CDA, "M", "ⳛ"), + (0x2CDB, "V"), + (0x2CDC, "M", "ⳝ"), + (0x2CDD, "V"), + (0x2CDE, "M", "ⳟ"), + (0x2CDF, "V"), + (0x2CE0, "M", "ⳡ"), + (0x2CE1, "V"), + (0x2CE2, "M", "ⳣ"), + (0x2CE3, "V"), + (0x2CEB, "M", "ⳬ"), + (0x2CEC, "V"), + (0x2CED, "M", "ⳮ"), + (0x2CEE, "V"), + (0x2CF2, "M", "ⳳ"), + (0x2CF3, "V"), + (0x2CF4, "X"), + (0x2CF9, "V"), + (0x2D26, "X"), + (0x2D27, "V"), + (0x2D28, "X"), + (0x2D2D, "V"), + (0x2D2E, "X"), + (0x2D30, "V"), + (0x2D68, "X"), + (0x2D6F, "M", "ⵡ"), + (0x2D70, "V"), + (0x2D71, "X"), + (0x2D7F, "V"), + (0x2D97, "X"), + (0x2DA0, "V"), + (0x2DA7, "X"), + (0x2DA8, "V"), + (0x2DAF, "X"), + (0x2DB0, "V"), + (0x2DB7, "X"), + (0x2DB8, "V"), + (0x2DBF, "X"), + (0x2DC0, "V"), + (0x2DC7, "X"), + (0x2DC8, "V"), + (0x2DCF, "X"), + (0x2DD0, "V"), + (0x2DD7, "X"), + (0x2DD8, "V"), + (0x2DDF, "X"), + (0x2DE0, "V"), + (0x2E5E, "X"), + (0x2E80, "V"), + (0x2E9A, "X"), + (0x2E9B, "V"), + (0x2E9F, "M", "母"), + (0x2EA0, "V"), + (0x2EF3, "M", "龟"), + (0x2EF4, "X"), + (0x2F00, "M", "一"), + (0x2F01, "M", "丨"), + (0x2F02, "M", "丶"), + (0x2F03, "M", "丿"), + (0x2F04, "M", "乙"), + (0x2F05, "M", "亅"), + (0x2F06, "M", "二"), + (0x2F07, "M", "亠"), + (0x2F08, "M", "人"), + (0x2F09, "M", "儿"), + (0x2F0A, "M", "入"), + (0x2F0B, "M", "八"), + (0x2F0C, "M", "冂"), + (0x2F0D, "M", "冖"), + (0x2F0E, "M", "冫"), + (0x2F0F, "M", "几"), + (0x2F10, "M", "凵"), + (0x2F11, "M", "刀"), + (0x2F12, "M", "力"), + (0x2F13, "M", "勹"), + (0x2F14, "M", "匕"), + (0x2F15, "M", "匚"), + (0x2F16, "M", "匸"), + (0x2F17, "M", "十"), + (0x2F18, "M", "卜"), + (0x2F19, "M", "卩"), + (0x2F1A, "M", "厂"), + (0x2F1B, "M", "厶"), + (0x2F1C, "M", "又"), + (0x2F1D, "M", "口"), + (0x2F1E, "M", "囗"), + (0x2F1F, "M", "土"), + (0x2F20, "M", "士"), + (0x2F21, "M", "夂"), + (0x2F22, "M", "夊"), + (0x2F23, "M", "夕"), + (0x2F24, "M", "大"), + (0x2F25, "M", "女"), + (0x2F26, "M", "子"), + (0x2F27, "M", "宀"), + (0x2F28, "M", "寸"), + (0x2F29, "M", "小"), + (0x2F2A, "M", "尢"), + (0x2F2B, "M", "尸"), + (0x2F2C, "M", "屮"), + (0x2F2D, "M", "山"), + (0x2F2E, "M", "巛"), + (0x2F2F, "M", "工"), + (0x2F30, "M", "己"), + (0x2F31, "M", "巾"), + (0x2F32, "M", "干"), + (0x2F33, "M", "幺"), + (0x2F34, "M", "广"), + (0x2F35, "M", "廴"), + (0x2F36, "M", "廾"), + (0x2F37, "M", "弋"), + (0x2F38, "M", "弓"), + (0x2F39, "M", "彐"), + (0x2F3A, "M", "彡"), + (0x2F3B, "M", "彳"), + (0x2F3C, "M", "心"), + (0x2F3D, "M", "戈"), + (0x2F3E, "M", "戶"), + (0x2F3F, "M", "手"), + (0x2F40, "M", "支"), + (0x2F41, "M", "攴"), + (0x2F42, "M", "文"), + (0x2F43, "M", "斗"), + (0x2F44, "M", "斤"), + (0x2F45, "M", "方"), + (0x2F46, "M", "无"), + (0x2F47, "M", "日"), + (0x2F48, "M", "曰"), + (0x2F49, "M", "月"), + (0x2F4A, "M", "木"), + (0x2F4B, "M", "欠"), + (0x2F4C, "M", "止"), + (0x2F4D, "M", "歹"), + (0x2F4E, "M", "殳"), + (0x2F4F, "M", "毋"), + (0x2F50, "M", "比"), + (0x2F51, "M", "毛"), + (0x2F52, "M", "氏"), + (0x2F53, "M", "气"), + (0x2F54, "M", "水"), + (0x2F55, "M", "火"), + (0x2F56, "M", "爪"), + (0x2F57, "M", "父"), + (0x2F58, "M", "爻"), + (0x2F59, "M", "爿"), + (0x2F5A, "M", "片"), + (0x2F5B, "M", "牙"), + (0x2F5C, "M", "牛"), + (0x2F5D, "M", "犬"), + (0x2F5E, "M", "玄"), + (0x2F5F, "M", "玉"), + (0x2F60, "M", "瓜"), + (0x2F61, "M", "瓦"), + (0x2F62, "M", "甘"), + (0x2F63, "M", "生"), + (0x2F64, "M", "用"), + (0x2F65, "M", "田"), + (0x2F66, "M", "疋"), + (0x2F67, "M", "疒"), + (0x2F68, "M", "癶"), + (0x2F69, "M", "白"), + (0x2F6A, "M", "皮"), + (0x2F6B, "M", "皿"), + (0x2F6C, "M", "目"), + (0x2F6D, "M", "矛"), + (0x2F6E, "M", "矢"), + (0x2F6F, "M", "石"), + (0x2F70, "M", "示"), + (0x2F71, "M", "禸"), + (0x2F72, "M", "禾"), + (0x2F73, "M", "穴"), + (0x2F74, "M", "立"), + (0x2F75, "M", "竹"), + (0x2F76, "M", "米"), + (0x2F77, "M", "糸"), + (0x2F78, "M", "缶"), + (0x2F79, "M", "网"), + (0x2F7A, "M", "羊"), + (0x2F7B, "M", "羽"), + (0x2F7C, "M", "老"), + (0x2F7D, "M", "而"), + (0x2F7E, "M", "耒"), + (0x2F7F, "M", "耳"), + (0x2F80, "M", "聿"), + (0x2F81, "M", "肉"), + (0x2F82, "M", "臣"), + (0x2F83, "M", "自"), + (0x2F84, "M", "至"), + (0x2F85, "M", "臼"), + (0x2F86, "M", "舌"), + (0x2F87, "M", "舛"), + (0x2F88, "M", "舟"), + (0x2F89, "M", "艮"), + (0x2F8A, "M", "色"), + (0x2F8B, "M", "艸"), + (0x2F8C, "M", "虍"), + (0x2F8D, "M", "虫"), + (0x2F8E, "M", "血"), + (0x2F8F, "M", "行"), + (0x2F90, "M", "衣"), + (0x2F91, "M", "襾"), + (0x2F92, "M", "見"), + (0x2F93, "M", "角"), + (0x2F94, "M", "言"), + (0x2F95, "M", "谷"), + (0x2F96, "M", "豆"), + (0x2F97, "M", "豕"), + (0x2F98, "M", "豸"), + (0x2F99, "M", "貝"), + (0x2F9A, "M", "赤"), + (0x2F9B, "M", "走"), + (0x2F9C, "M", "足"), + (0x2F9D, "M", "身"), + (0x2F9E, "M", "車"), + (0x2F9F, "M", "辛"), + (0x2FA0, "M", "辰"), + (0x2FA1, "M", "辵"), + (0x2FA2, "M", "邑"), + (0x2FA3, "M", "酉"), + (0x2FA4, "M", "釆"), + (0x2FA5, "M", "里"), + (0x2FA6, "M", "金"), + (0x2FA7, "M", "長"), + (0x2FA8, "M", "門"), + (0x2FA9, "M", "阜"), + (0x2FAA, "M", "隶"), + (0x2FAB, "M", "隹"), + (0x2FAC, "M", "雨"), + (0x2FAD, "M", "靑"), + (0x2FAE, "M", "非"), + (0x2FAF, "M", "面"), + (0x2FB0, "M", "革"), + (0x2FB1, "M", "韋"), + (0x2FB2, "M", "韭"), + (0x2FB3, "M", "音"), + (0x2FB4, "M", "頁"), + (0x2FB5, "M", "風"), + (0x2FB6, "M", "飛"), + (0x2FB7, "M", "食"), + (0x2FB8, "M", "首"), + (0x2FB9, "M", "香"), + (0x2FBA, "M", "馬"), + (0x2FBB, "M", "骨"), + (0x2FBC, "M", "高"), + (0x2FBD, "M", "髟"), + (0x2FBE, "M", "鬥"), + (0x2FBF, "M", "鬯"), + (0x2FC0, "M", "鬲"), + (0x2FC1, "M", "鬼"), + (0x2FC2, "M", "魚"), + (0x2FC3, "M", "鳥"), + (0x2FC4, "M", "鹵"), + (0x2FC5, "M", "鹿"), + (0x2FC6, "M", "麥"), + (0x2FC7, "M", "麻"), + (0x2FC8, "M", "黃"), + (0x2FC9, "M", "黍"), + (0x2FCA, "M", "黑"), + (0x2FCB, "M", "黹"), + (0x2FCC, "M", "黽"), + (0x2FCD, "M", "鼎"), + (0x2FCE, "M", "鼓"), + (0x2FCF, "M", "鼠"), + (0x2FD0, "M", "鼻"), + (0x2FD1, "M", "齊"), + (0x2FD2, "M", "齒"), + (0x2FD3, "M", "龍"), + (0x2FD4, "M", "龜"), + (0x2FD5, "M", "龠"), + (0x2FD6, "X"), + (0x3000, "M", " "), + (0x3001, "V"), + (0x3002, "M", "."), + (0x3003, "V"), + (0x3036, "M", "〒"), + (0x3037, "V"), + (0x3038, "M", "十"), + (0x3039, "M", "卄"), + (0x303A, "M", "卅"), + (0x303B, "V"), + (0x3040, "X"), + (0x3041, "V"), + (0x3097, "X"), + (0x3099, "V"), + (0x309B, "M", " ゙"), + (0x309C, "M", " ゚"), + (0x309D, "V"), + (0x309F, "M", "より"), + (0x30A0, "V"), + (0x30FF, "M", "コト"), + (0x3100, "X"), + (0x3105, "V"), + (0x3130, "X"), + (0x3131, "M", "ᄀ"), + (0x3132, "M", "ᄁ"), + (0x3133, "M", "ᆪ"), + (0x3134, "M", "ᄂ"), + (0x3135, "M", "ᆬ"), + (0x3136, "M", "ᆭ"), + (0x3137, "M", "ᄃ"), + (0x3138, "M", "ᄄ"), + (0x3139, "M", "ᄅ"), + (0x313A, "M", "ᆰ"), + (0x313B, "M", "ᆱ"), + (0x313C, "M", "ᆲ"), + (0x313D, "M", "ᆳ"), + (0x313E, "M", "ᆴ"), + (0x313F, "M", "ᆵ"), + (0x3140, "M", "ᄚ"), + (0x3141, "M", "ᄆ"), + (0x3142, "M", "ᄇ"), + (0x3143, "M", "ᄈ"), + (0x3144, "M", "ᄡ"), + (0x3145, "M", "ᄉ"), + (0x3146, "M", "ᄊ"), + (0x3147, "M", "ᄋ"), + (0x3148, "M", "ᄌ"), + (0x3149, "M", "ᄍ"), + (0x314A, "M", "ᄎ"), + (0x314B, "M", "ᄏ"), + (0x314C, "M", "ᄐ"), + (0x314D, "M", "ᄑ"), + (0x314E, "M", "ᄒ"), + (0x314F, "M", "ᅡ"), + (0x3150, "M", "ᅢ"), + (0x3151, "M", "ᅣ"), + (0x3152, "M", "ᅤ"), + (0x3153, "M", "ᅥ"), + (0x3154, "M", "ᅦ"), + (0x3155, "M", "ᅧ"), + (0x3156, "M", "ᅨ"), + (0x3157, "M", "ᅩ"), + (0x3158, "M", "ᅪ"), + (0x3159, "M", "ᅫ"), + (0x315A, "M", "ᅬ"), + (0x315B, "M", "ᅭ"), + (0x315C, "M", "ᅮ"), + (0x315D, "M", "ᅯ"), + (0x315E, "M", "ᅰ"), + (0x315F, "M", "ᅱ"), + (0x3160, "M", "ᅲ"), + (0x3161, "M", "ᅳ"), + (0x3162, "M", "ᅴ"), + (0x3163, "M", "ᅵ"), + (0x3164, "I"), + (0x3165, "M", "ᄔ"), + (0x3166, "M", "ᄕ"), + (0x3167, "M", "ᇇ"), + (0x3168, "M", "ᇈ"), + (0x3169, "M", "ᇌ"), + (0x316A, "M", "ᇎ"), + (0x316B, "M", "ᇓ"), + (0x316C, "M", "ᇗ"), + (0x316D, "M", "ᇙ"), + (0x316E, "M", "ᄜ"), + (0x316F, "M", "ᇝ"), + (0x3170, "M", "ᇟ"), + (0x3171, "M", "ᄝ"), + (0x3172, "M", "ᄞ"), + (0x3173, "M", "ᄠ"), + (0x3174, "M", "ᄢ"), + (0x3175, "M", "ᄣ"), + (0x3176, "M", "ᄧ"), + (0x3177, "M", "ᄩ"), + (0x3178, "M", "ᄫ"), + (0x3179, "M", "ᄬ"), + (0x317A, "M", "ᄭ"), + (0x317B, "M", "ᄮ"), + (0x317C, "M", "ᄯ"), + (0x317D, "M", "ᄲ"), + (0x317E, "M", "ᄶ"), + (0x317F, "M", "ᅀ"), + (0x3180, "M", "ᅇ"), + (0x3181, "M", "ᅌ"), + (0x3182, "M", "ᇱ"), + (0x3183, "M", "ᇲ"), + (0x3184, "M", "ᅗ"), + (0x3185, "M", "ᅘ"), + (0x3186, "M", "ᅙ"), + (0x3187, "M", "ᆄ"), + (0x3188, "M", "ᆅ"), + (0x3189, "M", "ᆈ"), + (0x318A, "M", "ᆑ"), + (0x318B, "M", "ᆒ"), + (0x318C, "M", "ᆔ"), + (0x318D, "M", "ᆞ"), + (0x318E, "M", "ᆡ"), + (0x318F, "X"), + (0x3190, "V"), + (0x3192, "M", "一"), + (0x3193, "M", "二"), + (0x3194, "M", "三"), + (0x3195, "M", "四"), + (0x3196, "M", "上"), + (0x3197, "M", "中"), + (0x3198, "M", "下"), + (0x3199, "M", "甲"), + (0x319A, "M", "乙"), + (0x319B, "M", "丙"), + (0x319C, "M", "丁"), + (0x319D, "M", "天"), + (0x319E, "M", "地"), + (0x319F, "M", "人"), + (0x31A0, "V"), + (0x31E6, "X"), + (0x31F0, "V"), + (0x3200, "M", "(ᄀ)"), + (0x3201, "M", "(ᄂ)"), + (0x3202, "M", "(ᄃ)"), + (0x3203, "M", "(ᄅ)"), + (0x3204, "M", "(ᄆ)"), + (0x3205, "M", "(ᄇ)"), + (0x3206, "M", "(ᄉ)"), + (0x3207, "M", "(ᄋ)"), + (0x3208, "M", "(ᄌ)"), + (0x3209, "M", "(ᄎ)"), + (0x320A, "M", "(ᄏ)"), + (0x320B, "M", "(ᄐ)"), + (0x320C, "M", "(ᄑ)"), + (0x320D, "M", "(ᄒ)"), + (0x320E, "M", "(가)"), + (0x320F, "M", "(나)"), + (0x3210, "M", "(다)"), + (0x3211, "M", "(라)"), + (0x3212, "M", "(마)"), + (0x3213, "M", "(바)"), + (0x3214, "M", "(사)"), + (0x3215, "M", "(아)"), + (0x3216, "M", "(자)"), + (0x3217, "M", "(차)"), + (0x3218, "M", "(카)"), + (0x3219, "M", "(타)"), + (0x321A, "M", "(파)"), + (0x321B, "M", "(하)"), + (0x321C, "M", "(주)"), + (0x321D, "M", "(오전)"), + (0x321E, "M", "(오후)"), + (0x321F, "X"), + (0x3220, "M", "(一)"), + (0x3221, "M", "(二)"), + (0x3222, "M", "(三)"), + (0x3223, "M", "(四)"), + (0x3224, "M", "(五)"), + (0x3225, "M", "(六)"), + (0x3226, "M", "(七)"), + (0x3227, "M", "(八)"), + (0x3228, "M", "(九)"), + (0x3229, "M", "(十)"), + (0x322A, "M", "(月)"), + (0x322B, "M", "(火)"), + (0x322C, "M", "(水)"), + (0x322D, "M", "(木)"), + (0x322E, "M", "(金)"), + (0x322F, "M", "(土)"), + (0x3230, "M", "(日)"), + (0x3231, "M", "(株)"), + (0x3232, "M", "(有)"), + (0x3233, "M", "(社)"), + (0x3234, "M", "(名)"), + (0x3235, "M", "(特)"), + (0x3236, "M", "(財)"), + (0x3237, "M", "(祝)"), + (0x3238, "M", "(労)"), + (0x3239, "M", "(代)"), + (0x323A, "M", "(呼)"), + (0x323B, "M", "(学)"), + (0x323C, "M", "(監)"), + (0x323D, "M", "(企)"), + (0x323E, "M", "(資)"), + (0x323F, "M", "(協)"), + (0x3240, "M", "(祭)"), + (0x3241, "M", "(休)"), + (0x3242, "M", "(自)"), + (0x3243, "M", "(至)"), + (0x3244, "M", "問"), + (0x3245, "M", "幼"), + (0x3246, "M", "文"), + (0x3247, "M", "箏"), + (0x3248, "V"), + (0x3250, "M", "pte"), + (0x3251, "M", "21"), + (0x3252, "M", "22"), + (0x3253, "M", "23"), + (0x3254, "M", "24"), + (0x3255, "M", "25"), + (0x3256, "M", "26"), + (0x3257, "M", "27"), + (0x3258, "M", "28"), + (0x3259, "M", "29"), + (0x325A, "M", "30"), + (0x325B, "M", "31"), + (0x325C, "M", "32"), + (0x325D, "M", "33"), + (0x325E, "M", "34"), + (0x325F, "M", "35"), + (0x3260, "M", "ᄀ"), + (0x3261, "M", "ᄂ"), + (0x3262, "M", "ᄃ"), + (0x3263, "M", "ᄅ"), + (0x3264, "M", "ᄆ"), + (0x3265, "M", "ᄇ"), + (0x3266, "M", "ᄉ"), + (0x3267, "M", "ᄋ"), + (0x3268, "M", "ᄌ"), + (0x3269, "M", "ᄎ"), + (0x326A, "M", "ᄏ"), + (0x326B, "M", "ᄐ"), + (0x326C, "M", "ᄑ"), + (0x326D, "M", "ᄒ"), + (0x326E, "M", "가"), + (0x326F, "M", "나"), + (0x3270, "M", "다"), + (0x3271, "M", "라"), + (0x3272, "M", "마"), + (0x3273, "M", "바"), + (0x3274, "M", "사"), + (0x3275, "M", "아"), + (0x3276, "M", "자"), + (0x3277, "M", "차"), + (0x3278, "M", "카"), + (0x3279, "M", "타"), + (0x327A, "M", "파"), + (0x327B, "M", "하"), + (0x327C, "M", "참고"), + (0x327D, "M", "주의"), + (0x327E, "M", "우"), + (0x327F, "V"), + (0x3280, "M", "一"), + (0x3281, "M", "二"), + (0x3282, "M", "三"), + (0x3283, "M", "四"), + (0x3284, "M", "五"), + (0x3285, "M", "六"), + (0x3286, "M", "七"), + (0x3287, "M", "八"), + (0x3288, "M", "九"), + (0x3289, "M", "十"), + (0x328A, "M", "月"), + (0x328B, "M", "火"), + (0x328C, "M", "水"), + (0x328D, "M", "木"), + (0x328E, "M", "金"), + (0x328F, "M", "土"), + (0x3290, "M", "日"), + (0x3291, "M", "株"), + (0x3292, "M", "有"), + (0x3293, "M", "社"), + (0x3294, "M", "名"), + (0x3295, "M", "特"), + (0x3296, "M", "財"), + (0x3297, "M", "祝"), + (0x3298, "M", "労"), + (0x3299, "M", "秘"), + (0x329A, "M", "男"), + (0x329B, "M", "女"), + (0x329C, "M", "適"), + (0x329D, "M", "優"), + (0x329E, "M", "印"), + (0x329F, "M", "注"), + (0x32A0, "M", "項"), + (0x32A1, "M", "休"), + (0x32A2, "M", "写"), + (0x32A3, "M", "正"), + (0x32A4, "M", "上"), + (0x32A5, "M", "中"), + (0x32A6, "M", "下"), + (0x32A7, "M", "左"), + (0x32A8, "M", "右"), + (0x32A9, "M", "医"), + (0x32AA, "M", "宗"), + (0x32AB, "M", "学"), + (0x32AC, "M", "監"), + (0x32AD, "M", "企"), + (0x32AE, "M", "資"), + (0x32AF, "M", "協"), + (0x32B0, "M", "夜"), + (0x32B1, "M", "36"), + (0x32B2, "M", "37"), + (0x32B3, "M", "38"), + (0x32B4, "M", "39"), + (0x32B5, "M", "40"), + (0x32B6, "M", "41"), + (0x32B7, "M", "42"), + (0x32B8, "M", "43"), + (0x32B9, "M", "44"), + (0x32BA, "M", "45"), + (0x32BB, "M", "46"), + (0x32BC, "M", "47"), + (0x32BD, "M", "48"), + (0x32BE, "M", "49"), + (0x32BF, "M", "50"), + (0x32C0, "M", "1月"), + (0x32C1, "M", "2月"), + (0x32C2, "M", "3月"), + (0x32C3, "M", "4月"), + (0x32C4, "M", "5月"), + (0x32C5, "M", "6月"), + (0x32C6, "M", "7月"), + (0x32C7, "M", "8月"), + (0x32C8, "M", "9月"), + (0x32C9, "M", "10月"), + (0x32CA, "M", "11月"), + (0x32CB, "M", "12月"), + (0x32CC, "M", "hg"), + (0x32CD, "M", "erg"), + (0x32CE, "M", "ev"), + (0x32CF, "M", "ltd"), + (0x32D0, "M", "ア"), + (0x32D1, "M", "イ"), + (0x32D2, "M", "ウ"), + (0x32D3, "M", "エ"), + (0x32D4, "M", "オ"), + (0x32D5, "M", "カ"), + (0x32D6, "M", "キ"), + (0x32D7, "M", "ク"), + (0x32D8, "M", "ケ"), + (0x32D9, "M", "コ"), + (0x32DA, "M", "サ"), + (0x32DB, "M", "シ"), + (0x32DC, "M", "ス"), + (0x32DD, "M", "セ"), + (0x32DE, "M", "ソ"), + (0x32DF, "M", "タ"), + (0x32E0, "M", "チ"), + (0x32E1, "M", "ツ"), + (0x32E2, "M", "テ"), + (0x32E3, "M", "ト"), + (0x32E4, "M", "ナ"), + (0x32E5, "M", "ニ"), + (0x32E6, "M", "ヌ"), + (0x32E7, "M", "ネ"), + (0x32E8, "M", "ノ"), + (0x32E9, "M", "ハ"), + (0x32EA, "M", "ヒ"), + (0x32EB, "M", "フ"), + (0x32EC, "M", "ヘ"), + (0x32ED, "M", "ホ"), + (0x32EE, "M", "マ"), + (0x32EF, "M", "ミ"), + (0x32F0, "M", "ム"), + (0x32F1, "M", "メ"), + (0x32F2, "M", "モ"), + (0x32F3, "M", "ヤ"), + (0x32F4, "M", "ユ"), + (0x32F5, "M", "ヨ"), + (0x32F6, "M", "ラ"), + (0x32F7, "M", "リ"), + (0x32F8, "M", "ル"), + (0x32F9, "M", "レ"), + (0x32FA, "M", "ロ"), + (0x32FB, "M", "ワ"), + (0x32FC, "M", "ヰ"), + (0x32FD, "M", "ヱ"), + (0x32FE, "M", "ヲ"), + (0x32FF, "M", "令和"), + (0x3300, "M", "アパート"), + (0x3301, "M", "アルファ"), + (0x3302, "M", "アンペア"), + (0x3303, "M", "アール"), + (0x3304, "M", "イニング"), + (0x3305, "M", "インチ"), + (0x3306, "M", "ウォン"), + (0x3307, "M", "エスクード"), + (0x3308, "M", "エーカー"), + (0x3309, "M", "オンス"), + (0x330A, "M", "オーム"), + (0x330B, "M", "カイリ"), + (0x330C, "M", "カラット"), + (0x330D, "M", "カロリー"), + (0x330E, "M", "ガロン"), + (0x330F, "M", "ガンマ"), + (0x3310, "M", "ギガ"), + (0x3311, "M", "ギニー"), + (0x3312, "M", "キュリー"), + (0x3313, "M", "ギルダー"), + (0x3314, "M", "キロ"), + (0x3315, "M", "キログラム"), + (0x3316, "M", "キロメートル"), + (0x3317, "M", "キロワット"), + (0x3318, "M", "グラム"), + (0x3319, "M", "グラムトン"), + (0x331A, "M", "クルゼイロ"), + (0x331B, "M", "クローネ"), + (0x331C, "M", "ケース"), + (0x331D, "M", "コルナ"), + (0x331E, "M", "コーポ"), + (0x331F, "M", "サイクル"), + (0x3320, "M", "サンチーム"), + (0x3321, "M", "シリング"), + (0x3322, "M", "センチ"), + (0x3323, "M", "セント"), + (0x3324, "M", "ダース"), + (0x3325, "M", "デシ"), + (0x3326, "M", "ドル"), + (0x3327, "M", "トン"), + (0x3328, "M", "ナノ"), + (0x3329, "M", "ノット"), + (0x332A, "M", "ハイツ"), + (0x332B, "M", "パーセント"), + (0x332C, "M", "パーツ"), + (0x332D, "M", "バーレル"), + (0x332E, "M", "ピアストル"), + (0x332F, "M", "ピクル"), + (0x3330, "M", "ピコ"), + (0x3331, "M", "ビル"), + (0x3332, "M", "ファラッド"), + (0x3333, "M", "フィート"), + (0x3334, "M", "ブッシェル"), + (0x3335, "M", "フラン"), + (0x3336, "M", "ヘクタール"), + (0x3337, "M", "ペソ"), + (0x3338, "M", "ペニヒ"), + (0x3339, "M", "ヘルツ"), + (0x333A, "M", "ペンス"), + (0x333B, "M", "ページ"), + (0x333C, "M", "ベータ"), + (0x333D, "M", "ポイント"), + (0x333E, "M", "ボルト"), + (0x333F, "M", "ホン"), + (0x3340, "M", "ポンド"), + (0x3341, "M", "ホール"), + (0x3342, "M", "ホーン"), + (0x3343, "M", "マイクロ"), + (0x3344, "M", "マイル"), + (0x3345, "M", "マッハ"), + (0x3346, "M", "マルク"), + (0x3347, "M", "マンション"), + (0x3348, "M", "ミクロン"), + (0x3349, "M", "ミリ"), + (0x334A, "M", "ミリバール"), + (0x334B, "M", "メガ"), + (0x334C, "M", "メガトン"), + (0x334D, "M", "メートル"), + (0x334E, "M", "ヤード"), + (0x334F, "M", "ヤール"), + (0x3350, "M", "ユアン"), + (0x3351, "M", "リットル"), + (0x3352, "M", "リラ"), + (0x3353, "M", "ルピー"), + (0x3354, "M", "ルーブル"), + (0x3355, "M", "レム"), + (0x3356, "M", "レントゲン"), + (0x3357, "M", "ワット"), + (0x3358, "M", "0点"), + (0x3359, "M", "1点"), + (0x335A, "M", "2点"), + (0x335B, "M", "3点"), + (0x335C, "M", "4点"), + (0x335D, "M", "5点"), + (0x335E, "M", "6点"), + (0x335F, "M", "7点"), + (0x3360, "M", "8点"), + (0x3361, "M", "9点"), + (0x3362, "M", "10点"), + (0x3363, "M", "11点"), + (0x3364, "M", "12点"), + (0x3365, "M", "13点"), + (0x3366, "M", "14点"), + (0x3367, "M", "15点"), + (0x3368, "M", "16点"), + (0x3369, "M", "17点"), + (0x336A, "M", "18点"), + (0x336B, "M", "19点"), + (0x336C, "M", "20点"), + (0x336D, "M", "21点"), + (0x336E, "M", "22点"), + (0x336F, "M", "23点"), + (0x3370, "M", "24点"), + (0x3371, "M", "hpa"), + (0x3372, "M", "da"), + (0x3373, "M", "au"), + (0x3374, "M", "bar"), + (0x3375, "M", "ov"), + (0x3376, "M", "pc"), + (0x3377, "M", "dm"), + (0x3378, "M", "dm2"), + (0x3379, "M", "dm3"), + (0x337A, "M", "iu"), + (0x337B, "M", "平成"), + (0x337C, "M", "昭和"), + (0x337D, "M", "大正"), + (0x337E, "M", "明治"), + (0x337F, "M", "株式会社"), + (0x3380, "M", "pa"), + (0x3381, "M", "na"), + (0x3382, "M", "μa"), + (0x3383, "M", "ma"), + (0x3384, "M", "ka"), + (0x3385, "M", "kb"), + (0x3386, "M", "mb"), + (0x3387, "M", "gb"), + (0x3388, "M", "cal"), + (0x3389, "M", "kcal"), + (0x338A, "M", "pf"), + (0x338B, "M", "nf"), + (0x338C, "M", "μf"), + (0x338D, "M", "μg"), + (0x338E, "M", "mg"), + (0x338F, "M", "kg"), + (0x3390, "M", "hz"), + (0x3391, "M", "khz"), + (0x3392, "M", "mhz"), + (0x3393, "M", "ghz"), + (0x3394, "M", "thz"), + (0x3395, "M", "μl"), + (0x3396, "M", "ml"), + (0x3397, "M", "dl"), + (0x3398, "M", "kl"), + (0x3399, "M", "fm"), + (0x339A, "M", "nm"), + (0x339B, "M", "μm"), + (0x339C, "M", "mm"), + (0x339D, "M", "cm"), + (0x339E, "M", "km"), + (0x339F, "M", "mm2"), + (0x33A0, "M", "cm2"), + (0x33A1, "M", "m2"), + (0x33A2, "M", "km2"), + (0x33A3, "M", "mm3"), + (0x33A4, "M", "cm3"), + (0x33A5, "M", "m3"), + (0x33A6, "M", "km3"), + (0x33A7, "M", "m∕s"), + (0x33A8, "M", "m∕s2"), + (0x33A9, "M", "pa"), + (0x33AA, "M", "kpa"), + (0x33AB, "M", "mpa"), + (0x33AC, "M", "gpa"), + (0x33AD, "M", "rad"), + (0x33AE, "M", "rad∕s"), + (0x33AF, "M", "rad∕s2"), + (0x33B0, "M", "ps"), + (0x33B1, "M", "ns"), + (0x33B2, "M", "μs"), + (0x33B3, "M", "ms"), + (0x33B4, "M", "pv"), + (0x33B5, "M", "nv"), + (0x33B6, "M", "μv"), + (0x33B7, "M", "mv"), + (0x33B8, "M", "kv"), + (0x33B9, "M", "mv"), + (0x33BA, "M", "pw"), + (0x33BB, "M", "nw"), + (0x33BC, "M", "μw"), + (0x33BD, "M", "mw"), + (0x33BE, "M", "kw"), + (0x33BF, "M", "mw"), + (0x33C0, "M", "kω"), + (0x33C1, "M", "mω"), + (0x33C2, "X"), + (0x33C3, "M", "bq"), + (0x33C4, "M", "cc"), + (0x33C5, "M", "cd"), + (0x33C6, "M", "c∕kg"), + (0x33C7, "X"), + (0x33C8, "M", "db"), + (0x33C9, "M", "gy"), + (0x33CA, "M", "ha"), + (0x33CB, "M", "hp"), + (0x33CC, "M", "in"), + (0x33CD, "M", "kk"), + (0x33CE, "M", "km"), + (0x33CF, "M", "kt"), + (0x33D0, "M", "lm"), + (0x33D1, "M", "ln"), + (0x33D2, "M", "log"), + (0x33D3, "M", "lx"), + (0x33D4, "M", "mb"), + (0x33D5, "M", "mil"), + (0x33D6, "M", "mol"), + (0x33D7, "M", "ph"), + (0x33D8, "X"), + (0x33D9, "M", "ppm"), + (0x33DA, "M", "pr"), + (0x33DB, "M", "sr"), + (0x33DC, "M", "sv"), + (0x33DD, "M", "wb"), + (0x33DE, "M", "v∕m"), + (0x33DF, "M", "a∕m"), + (0x33E0, "M", "1日"), + (0x33E1, "M", "2日"), + (0x33E2, "M", "3日"), + (0x33E3, "M", "4日"), + (0x33E4, "M", "5日"), + (0x33E5, "M", "6日"), + (0x33E6, "M", "7日"), + (0x33E7, "M", "8日"), + (0x33E8, "M", "9日"), + (0x33E9, "M", "10日"), + (0x33EA, "M", "11日"), + (0x33EB, "M", "12日"), + (0x33EC, "M", "13日"), + (0x33ED, "M", "14日"), + (0x33EE, "M", "15日"), + (0x33EF, "M", "16日"), + (0x33F0, "M", "17日"), + (0x33F1, "M", "18日"), + (0x33F2, "M", "19日"), + (0x33F3, "M", "20日"), + (0x33F4, "M", "21日"), + (0x33F5, "M", "22日"), + (0x33F6, "M", "23日"), + (0x33F7, "M", "24日"), + (0x33F8, "M", "25日"), + (0x33F9, "M", "26日"), + (0x33FA, "M", "27日"), + (0x33FB, "M", "28日"), + (0x33FC, "M", "29日"), + (0x33FD, "M", "30日"), + (0x33FE, "M", "31日"), + (0x33FF, "M", "gal"), + (0x3400, "V"), + (0xA48D, "X"), + (0xA490, "V"), + (0xA4C7, "X"), + (0xA4D0, "V"), + (0xA62C, "X"), + (0xA640, "M", "ꙁ"), + (0xA641, "V"), + (0xA642, "M", "ꙃ"), + (0xA643, "V"), + (0xA644, "M", "ꙅ"), + (0xA645, "V"), + (0xA646, "M", "ꙇ"), + (0xA647, "V"), + (0xA648, "M", "ꙉ"), + (0xA649, "V"), + (0xA64A, "M", "ꙋ"), + (0xA64B, "V"), + (0xA64C, "M", "ꙍ"), + (0xA64D, "V"), + (0xA64E, "M", "ꙏ"), + (0xA64F, "V"), + (0xA650, "M", "ꙑ"), + (0xA651, "V"), + (0xA652, "M", "ꙓ"), + (0xA653, "V"), + (0xA654, "M", "ꙕ"), + (0xA655, "V"), + (0xA656, "M", "ꙗ"), + (0xA657, "V"), + (0xA658, "M", "ꙙ"), + (0xA659, "V"), + (0xA65A, "M", "ꙛ"), + (0xA65B, "V"), + (0xA65C, "M", "ꙝ"), + (0xA65D, "V"), + (0xA65E, "M", "ꙟ"), + (0xA65F, "V"), + (0xA660, "M", "ꙡ"), + (0xA661, "V"), + (0xA662, "M", "ꙣ"), + (0xA663, "V"), + (0xA664, "M", "ꙥ"), + (0xA665, "V"), + (0xA666, "M", "ꙧ"), + (0xA667, "V"), + (0xA668, "M", "ꙩ"), + (0xA669, "V"), + (0xA66A, "M", "ꙫ"), + (0xA66B, "V"), + (0xA66C, "M", "ꙭ"), + (0xA66D, "V"), + (0xA680, "M", "ꚁ"), + (0xA681, "V"), + (0xA682, "M", "ꚃ"), + (0xA683, "V"), + (0xA684, "M", "ꚅ"), + (0xA685, "V"), + (0xA686, "M", "ꚇ"), + (0xA687, "V"), + (0xA688, "M", "ꚉ"), + (0xA689, "V"), + (0xA68A, "M", "ꚋ"), + (0xA68B, "V"), + (0xA68C, "M", "ꚍ"), + (0xA68D, "V"), + (0xA68E, "M", "ꚏ"), + (0xA68F, "V"), + (0xA690, "M", "ꚑ"), + (0xA691, "V"), + (0xA692, "M", "ꚓ"), + (0xA693, "V"), + (0xA694, "M", "ꚕ"), + (0xA695, "V"), + (0xA696, "M", "ꚗ"), + (0xA697, "V"), + (0xA698, "M", "ꚙ"), + (0xA699, "V"), + (0xA69A, "M", "ꚛ"), + (0xA69B, "V"), + (0xA69C, "M", "ъ"), + (0xA69D, "M", "ь"), + (0xA69E, "V"), + (0xA6F8, "X"), + (0xA700, "V"), + (0xA722, "M", "ꜣ"), + (0xA723, "V"), + (0xA724, "M", "ꜥ"), + (0xA725, "V"), + (0xA726, "M", "ꜧ"), + (0xA727, "V"), + (0xA728, "M", "ꜩ"), + (0xA729, "V"), + (0xA72A, "M", "ꜫ"), + (0xA72B, "V"), + (0xA72C, "M", "ꜭ"), + (0xA72D, "V"), + (0xA72E, "M", "ꜯ"), + (0xA72F, "V"), + (0xA732, "M", "ꜳ"), + (0xA733, "V"), + (0xA734, "M", "ꜵ"), + (0xA735, "V"), + (0xA736, "M", "ꜷ"), + (0xA737, "V"), + (0xA738, "M", "ꜹ"), + (0xA739, "V"), + (0xA73A, "M", "ꜻ"), + (0xA73B, "V"), + (0xA73C, "M", "ꜽ"), + (0xA73D, "V"), + (0xA73E, "M", "ꜿ"), + (0xA73F, "V"), + (0xA740, "M", "ꝁ"), + (0xA741, "V"), + (0xA742, "M", "ꝃ"), + (0xA743, "V"), + (0xA744, "M", "ꝅ"), + (0xA745, "V"), + (0xA746, "M", "ꝇ"), + (0xA747, "V"), + (0xA748, "M", "ꝉ"), + (0xA749, "V"), + (0xA74A, "M", "ꝋ"), + (0xA74B, "V"), + (0xA74C, "M", "ꝍ"), + (0xA74D, "V"), + (0xA74E, "M", "ꝏ"), + (0xA74F, "V"), + (0xA750, "M", "ꝑ"), + (0xA751, "V"), + (0xA752, "M", "ꝓ"), + (0xA753, "V"), + (0xA754, "M", "ꝕ"), + (0xA755, "V"), + (0xA756, "M", "ꝗ"), + (0xA757, "V"), + (0xA758, "M", "ꝙ"), + (0xA759, "V"), + (0xA75A, "M", "ꝛ"), + (0xA75B, "V"), + (0xA75C, "M", "ꝝ"), + (0xA75D, "V"), + (0xA75E, "M", "ꝟ"), + (0xA75F, "V"), + (0xA760, "M", "ꝡ"), + (0xA761, "V"), + (0xA762, "M", "ꝣ"), + (0xA763, "V"), + (0xA764, "M", "ꝥ"), + (0xA765, "V"), + (0xA766, "M", "ꝧ"), + (0xA767, "V"), + (0xA768, "M", "ꝩ"), + (0xA769, "V"), + (0xA76A, "M", "ꝫ"), + (0xA76B, "V"), + (0xA76C, "M", "ꝭ"), + (0xA76D, "V"), + (0xA76E, "M", "ꝯ"), + (0xA76F, "V"), + (0xA770, "M", "ꝯ"), + (0xA771, "V"), + (0xA779, "M", "ꝺ"), + (0xA77A, "V"), + (0xA77B, "M", "ꝼ"), + (0xA77C, "V"), + (0xA77D, "M", "ᵹ"), + (0xA77E, "M", "ꝿ"), + (0xA77F, "V"), + (0xA780, "M", "ꞁ"), + (0xA781, "V"), + (0xA782, "M", "ꞃ"), + (0xA783, "V"), + (0xA784, "M", "ꞅ"), + (0xA785, "V"), + (0xA786, "M", "ꞇ"), + (0xA787, "V"), + (0xA78B, "M", "ꞌ"), + (0xA78C, "V"), + (0xA78D, "M", "ɥ"), + (0xA78E, "V"), + (0xA790, "M", "ꞑ"), + (0xA791, "V"), + (0xA792, "M", "ꞓ"), + (0xA793, "V"), + (0xA796, "M", "ꞗ"), + (0xA797, "V"), + (0xA798, "M", "ꞙ"), + (0xA799, "V"), + (0xA79A, "M", "ꞛ"), + (0xA79B, "V"), + (0xA79C, "M", "ꞝ"), + (0xA79D, "V"), + (0xA79E, "M", "ꞟ"), + (0xA79F, "V"), + (0xA7A0, "M", "ꞡ"), + (0xA7A1, "V"), + (0xA7A2, "M", "ꞣ"), + (0xA7A3, "V"), + (0xA7A4, "M", "ꞥ"), + (0xA7A5, "V"), + (0xA7A6, "M", "ꞧ"), + (0xA7A7, "V"), + (0xA7A8, "M", "ꞩ"), + (0xA7A9, "V"), + (0xA7AA, "M", "ɦ"), + (0xA7AB, "M", "ɜ"), + (0xA7AC, "M", "ɡ"), + (0xA7AD, "M", "ɬ"), + (0xA7AE, "M", "ɪ"), + (0xA7AF, "V"), + (0xA7B0, "M", "ʞ"), + (0xA7B1, "M", "ʇ"), + (0xA7B2, "M", "ʝ"), + (0xA7B3, "M", "ꭓ"), + (0xA7B4, "M", "ꞵ"), + (0xA7B5, "V"), + (0xA7B6, "M", "ꞷ"), + (0xA7B7, "V"), + (0xA7B8, "M", "ꞹ"), + (0xA7B9, "V"), + (0xA7BA, "M", "ꞻ"), + (0xA7BB, "V"), + (0xA7BC, "M", "ꞽ"), + (0xA7BD, "V"), + (0xA7BE, "M", "ꞿ"), + (0xA7BF, "V"), + (0xA7C0, "M", "ꟁ"), + (0xA7C1, "V"), + (0xA7C2, "M", "ꟃ"), + (0xA7C3, "V"), + (0xA7C4, "M", "ꞔ"), + (0xA7C5, "M", "ʂ"), + (0xA7C6, "M", "ᶎ"), + (0xA7C7, "M", "ꟈ"), + (0xA7C8, "V"), + (0xA7C9, "M", "ꟊ"), + (0xA7CA, "V"), + (0xA7CB, "M", "ɤ"), + (0xA7CC, "M", "ꟍ"), + (0xA7CD, "V"), + (0xA7CE, "M", "꟏"), + (0xA7CF, "V"), + (0xA7D0, "M", "ꟑ"), + (0xA7D1, "V"), + (0xA7D2, "M", "ꟓ"), + (0xA7D3, "V"), + (0xA7D4, "M", "ꟕ"), + (0xA7D5, "V"), + (0xA7D6, "M", "ꟗ"), + (0xA7D7, "V"), + (0xA7D8, "M", "ꟙ"), + (0xA7D9, "V"), + (0xA7DA, "M", "ꟛ"), + (0xA7DB, "V"), + (0xA7DC, "M", "ƛ"), + (0xA7DD, "X"), + (0xA7F1, "M", "s"), + (0xA7F2, "M", "c"), + (0xA7F3, "M", "f"), + (0xA7F4, "M", "q"), + (0xA7F5, "M", "ꟶ"), + (0xA7F6, "V"), + (0xA7F8, "M", "ħ"), + (0xA7F9, "M", "œ"), + (0xA7FA, "V"), + (0xA82D, "X"), + (0xA830, "V"), + (0xA83A, "X"), + (0xA840, "V"), + (0xA878, "X"), + (0xA880, "V"), + (0xA8C6, "X"), + (0xA8CE, "V"), + (0xA8DA, "X"), + (0xA8E0, "V"), + (0xA954, "X"), + (0xA95F, "V"), + (0xA97D, "X"), + (0xA980, "V"), + (0xA9CE, "X"), + (0xA9CF, "V"), + (0xA9DA, "X"), + (0xA9DE, "V"), + (0xA9FF, "X"), + (0xAA00, "V"), + (0xAA37, "X"), + (0xAA40, "V"), + (0xAA4E, "X"), + (0xAA50, "V"), + (0xAA5A, "X"), + (0xAA5C, "V"), + (0xAAC3, "X"), + (0xAADB, "V"), + (0xAAF7, "X"), + (0xAB01, "V"), + (0xAB07, "X"), + (0xAB09, "V"), + (0xAB0F, "X"), + (0xAB11, "V"), + (0xAB17, "X"), + (0xAB20, "V"), + (0xAB27, "X"), + (0xAB28, "V"), + (0xAB2F, "X"), + (0xAB30, "V"), + (0xAB5C, "M", "ꜧ"), + (0xAB5D, "M", "ꬷ"), + (0xAB5E, "M", "ɫ"), + (0xAB5F, "M", "ꭒ"), + (0xAB60, "V"), + (0xAB69, "M", "ʍ"), + (0xAB6A, "V"), + (0xAB6C, "X"), + (0xAB70, "M", "Ꭰ"), + (0xAB71, "M", "Ꭱ"), + (0xAB72, "M", "Ꭲ"), + (0xAB73, "M", "Ꭳ"), + (0xAB74, "M", "Ꭴ"), + (0xAB75, "M", "Ꭵ"), + (0xAB76, "M", "Ꭶ"), + (0xAB77, "M", "Ꭷ"), + (0xAB78, "M", "Ꭸ"), + (0xAB79, "M", "Ꭹ"), + (0xAB7A, "M", "Ꭺ"), + (0xAB7B, "M", "Ꭻ"), + (0xAB7C, "M", "Ꭼ"), + (0xAB7D, "M", "Ꭽ"), + (0xAB7E, "M", "Ꭾ"), + (0xAB7F, "M", "Ꭿ"), + (0xAB80, "M", "Ꮀ"), + (0xAB81, "M", "Ꮁ"), + (0xAB82, "M", "Ꮂ"), + (0xAB83, "M", "Ꮃ"), + (0xAB84, "M", "Ꮄ"), + (0xAB85, "M", "Ꮅ"), + (0xAB86, "M", "Ꮆ"), + (0xAB87, "M", "Ꮇ"), + (0xAB88, "M", "Ꮈ"), + (0xAB89, "M", "Ꮉ"), + (0xAB8A, "M", "Ꮊ"), + (0xAB8B, "M", "Ꮋ"), + (0xAB8C, "M", "Ꮌ"), + (0xAB8D, "M", "Ꮍ"), + (0xAB8E, "M", "Ꮎ"), + (0xAB8F, "M", "Ꮏ"), + (0xAB90, "M", "Ꮐ"), + (0xAB91, "M", "Ꮑ"), + (0xAB92, "M", "Ꮒ"), + (0xAB93, "M", "Ꮓ"), + (0xAB94, "M", "Ꮔ"), + (0xAB95, "M", "Ꮕ"), + (0xAB96, "M", "Ꮖ"), + (0xAB97, "M", "Ꮗ"), + (0xAB98, "M", "Ꮘ"), + (0xAB99, "M", "Ꮙ"), + (0xAB9A, "M", "Ꮚ"), + (0xAB9B, "M", "Ꮛ"), + (0xAB9C, "M", "Ꮜ"), + (0xAB9D, "M", "Ꮝ"), + (0xAB9E, "M", "Ꮞ"), + (0xAB9F, "M", "Ꮟ"), + (0xABA0, "M", "Ꮠ"), + (0xABA1, "M", "Ꮡ"), + (0xABA2, "M", "Ꮢ"), + (0xABA3, "M", "Ꮣ"), + (0xABA4, "M", "Ꮤ"), + (0xABA5, "M", "Ꮥ"), + (0xABA6, "M", "Ꮦ"), + (0xABA7, "M", "Ꮧ"), + (0xABA8, "M", "Ꮨ"), + (0xABA9, "M", "Ꮩ"), + (0xABAA, "M", "Ꮪ"), + (0xABAB, "M", "Ꮫ"), + (0xABAC, "M", "Ꮬ"), + (0xABAD, "M", "Ꮭ"), + (0xABAE, "M", "Ꮮ"), + (0xABAF, "M", "Ꮯ"), + (0xABB0, "M", "Ꮰ"), + (0xABB1, "M", "Ꮱ"), + (0xABB2, "M", "Ꮲ"), + (0xABB3, "M", "Ꮳ"), + (0xABB4, "M", "Ꮴ"), + (0xABB5, "M", "Ꮵ"), + (0xABB6, "M", "Ꮶ"), + (0xABB7, "M", "Ꮷ"), + (0xABB8, "M", "Ꮸ"), + (0xABB9, "M", "Ꮹ"), + (0xABBA, "M", "Ꮺ"), + (0xABBB, "M", "Ꮻ"), + (0xABBC, "M", "Ꮼ"), + (0xABBD, "M", "Ꮽ"), + (0xABBE, "M", "Ꮾ"), + (0xABBF, "M", "Ꮿ"), + (0xABC0, "V"), + (0xABEE, "X"), + (0xABF0, "V"), + (0xABFA, "X"), + (0xAC00, "V"), + (0xD7A4, "X"), + (0xD7B0, "V"), + (0xD7C7, "X"), + (0xD7CB, "V"), + (0xD7FC, "X"), + (0xF900, "M", "豈"), + (0xF901, "M", "更"), + (0xF902, "M", "車"), + (0xF903, "M", "賈"), + (0xF904, "M", "滑"), + (0xF905, "M", "串"), + (0xF906, "M", "句"), + (0xF907, "M", "龜"), + (0xF909, "M", "契"), + (0xF90A, "M", "金"), + (0xF90B, "M", "喇"), + (0xF90C, "M", "奈"), + (0xF90D, "M", "懶"), + (0xF90E, "M", "癩"), + (0xF90F, "M", "羅"), + (0xF910, "M", "蘿"), + (0xF911, "M", "螺"), + (0xF912, "M", "裸"), + (0xF913, "M", "邏"), + (0xF914, "M", "樂"), + (0xF915, "M", "洛"), + (0xF916, "M", "烙"), + (0xF917, "M", "珞"), + (0xF918, "M", "落"), + (0xF919, "M", "酪"), + (0xF91A, "M", "駱"), + (0xF91B, "M", "亂"), + (0xF91C, "M", "卵"), + (0xF91D, "M", "欄"), + (0xF91E, "M", "爛"), + (0xF91F, "M", "蘭"), + (0xF920, "M", "鸞"), + (0xF921, "M", "嵐"), + (0xF922, "M", "濫"), + (0xF923, "M", "藍"), + (0xF924, "M", "襤"), + (0xF925, "M", "拉"), + (0xF926, "M", "臘"), + (0xF927, "M", "蠟"), + (0xF928, "M", "廊"), + (0xF929, "M", "朗"), + (0xF92A, "M", "浪"), + (0xF92B, "M", "狼"), + (0xF92C, "M", "郎"), + (0xF92D, "M", "來"), + (0xF92E, "M", "冷"), + (0xF92F, "M", "勞"), + (0xF930, "M", "擄"), + (0xF931, "M", "櫓"), + (0xF932, "M", "爐"), + (0xF933, "M", "盧"), + (0xF934, "M", "老"), + (0xF935, "M", "蘆"), + (0xF936, "M", "虜"), + (0xF937, "M", "路"), + (0xF938, "M", "露"), + (0xF939, "M", "魯"), + (0xF93A, "M", "鷺"), + (0xF93B, "M", "碌"), + (0xF93C, "M", "祿"), + (0xF93D, "M", "綠"), + (0xF93E, "M", "菉"), + (0xF93F, "M", "錄"), + (0xF940, "M", "鹿"), + (0xF941, "M", "論"), + (0xF942, "M", "壟"), + (0xF943, "M", "弄"), + (0xF944, "M", "籠"), + (0xF945, "M", "聾"), + (0xF946, "M", "牢"), + (0xF947, "M", "磊"), + (0xF948, "M", "賂"), + (0xF949, "M", "雷"), + (0xF94A, "M", "壘"), + (0xF94B, "M", "屢"), + (0xF94C, "M", "樓"), + (0xF94D, "M", "淚"), + (0xF94E, "M", "漏"), + (0xF94F, "M", "累"), + (0xF950, "M", "縷"), + (0xF951, "M", "陋"), + (0xF952, "M", "勒"), + (0xF953, "M", "肋"), + (0xF954, "M", "凜"), + (0xF955, "M", "凌"), + (0xF956, "M", "稜"), + (0xF957, "M", "綾"), + (0xF958, "M", "菱"), + (0xF959, "M", "陵"), + (0xF95A, "M", "讀"), + (0xF95B, "M", "拏"), + (0xF95C, "M", "樂"), + (0xF95D, "M", "諾"), + (0xF95E, "M", "丹"), + (0xF95F, "M", "寧"), + (0xF960, "M", "怒"), + (0xF961, "M", "率"), + (0xF962, "M", "異"), + (0xF963, "M", "北"), + (0xF964, "M", "磻"), + (0xF965, "M", "便"), + (0xF966, "M", "復"), + (0xF967, "M", "不"), + (0xF968, "M", "泌"), + (0xF969, "M", "數"), + (0xF96A, "M", "索"), + (0xF96B, "M", "參"), + (0xF96C, "M", "塞"), + (0xF96D, "M", "省"), + (0xF96E, "M", "葉"), + (0xF96F, "M", "說"), + (0xF970, "M", "殺"), + (0xF971, "M", "辰"), + (0xF972, "M", "沈"), + (0xF973, "M", "拾"), + (0xF974, "M", "若"), + (0xF975, "M", "掠"), + (0xF976, "M", "略"), + (0xF977, "M", "亮"), + (0xF978, "M", "兩"), + (0xF979, "M", "凉"), + (0xF97A, "M", "梁"), + (0xF97B, "M", "糧"), + (0xF97C, "M", "良"), + (0xF97D, "M", "諒"), + (0xF97E, "M", "量"), + (0xF97F, "M", "勵"), + (0xF980, "M", "呂"), + (0xF981, "M", "女"), + (0xF982, "M", "廬"), + (0xF983, "M", "旅"), + (0xF984, "M", "濾"), + (0xF985, "M", "礪"), + (0xF986, "M", "閭"), + (0xF987, "M", "驪"), + (0xF988, "M", "麗"), + (0xF989, "M", "黎"), + (0xF98A, "M", "力"), + (0xF98B, "M", "曆"), + (0xF98C, "M", "歷"), + (0xF98D, "M", "轢"), + (0xF98E, "M", "年"), + (0xF98F, "M", "憐"), + (0xF990, "M", "戀"), + (0xF991, "M", "撚"), + (0xF992, "M", "漣"), + (0xF993, "M", "煉"), + (0xF994, "M", "璉"), + (0xF995, "M", "秊"), + (0xF996, "M", "練"), + (0xF997, "M", "聯"), + (0xF998, "M", "輦"), + (0xF999, "M", "蓮"), + (0xF99A, "M", "連"), + (0xF99B, "M", "鍊"), + (0xF99C, "M", "列"), + (0xF99D, "M", "劣"), + (0xF99E, "M", "咽"), + (0xF99F, "M", "烈"), + (0xF9A0, "M", "裂"), + (0xF9A1, "M", "說"), + (0xF9A2, "M", "廉"), + (0xF9A3, "M", "念"), + (0xF9A4, "M", "捻"), + (0xF9A5, "M", "殮"), + (0xF9A6, "M", "簾"), + (0xF9A7, "M", "獵"), + (0xF9A8, "M", "令"), + (0xF9A9, "M", "囹"), + (0xF9AA, "M", "寧"), + (0xF9AB, "M", "嶺"), + (0xF9AC, "M", "怜"), + (0xF9AD, "M", "玲"), + (0xF9AE, "M", "瑩"), + (0xF9AF, "M", "羚"), + (0xF9B0, "M", "聆"), + (0xF9B1, "M", "鈴"), + (0xF9B2, "M", "零"), + (0xF9B3, "M", "靈"), + (0xF9B4, "M", "領"), + (0xF9B5, "M", "例"), + (0xF9B6, "M", "禮"), + (0xF9B7, "M", "醴"), + (0xF9B8, "M", "隸"), + (0xF9B9, "M", "惡"), + (0xF9BA, "M", "了"), + (0xF9BB, "M", "僚"), + (0xF9BC, "M", "寮"), + (0xF9BD, "M", "尿"), + (0xF9BE, "M", "料"), + (0xF9BF, "M", "樂"), + (0xF9C0, "M", "燎"), + (0xF9C1, "M", "療"), + (0xF9C2, "M", "蓼"), + (0xF9C3, "M", "遼"), + (0xF9C4, "M", "龍"), + (0xF9C5, "M", "暈"), + (0xF9C6, "M", "阮"), + (0xF9C7, "M", "劉"), + (0xF9C8, "M", "杻"), + (0xF9C9, "M", "柳"), + (0xF9CA, "M", "流"), + (0xF9CB, "M", "溜"), + (0xF9CC, "M", "琉"), + (0xF9CD, "M", "留"), + (0xF9CE, "M", "硫"), + (0xF9CF, "M", "紐"), + (0xF9D0, "M", "類"), + (0xF9D1, "M", "六"), + (0xF9D2, "M", "戮"), + (0xF9D3, "M", "陸"), + (0xF9D4, "M", "倫"), + (0xF9D5, "M", "崙"), + (0xF9D6, "M", "淪"), + (0xF9D7, "M", "輪"), + (0xF9D8, "M", "律"), + (0xF9D9, "M", "慄"), + (0xF9DA, "M", "栗"), + (0xF9DB, "M", "率"), + (0xF9DC, "M", "隆"), + (0xF9DD, "M", "利"), + (0xF9DE, "M", "吏"), + (0xF9DF, "M", "履"), + (0xF9E0, "M", "易"), + (0xF9E1, "M", "李"), + (0xF9E2, "M", "梨"), + (0xF9E3, "M", "泥"), + (0xF9E4, "M", "理"), + (0xF9E5, "M", "痢"), + (0xF9E6, "M", "罹"), + (0xF9E7, "M", "裏"), + (0xF9E8, "M", "裡"), + (0xF9E9, "M", "里"), + (0xF9EA, "M", "離"), + (0xF9EB, "M", "匿"), + (0xF9EC, "M", "溺"), + (0xF9ED, "M", "吝"), + (0xF9EE, "M", "燐"), + (0xF9EF, "M", "璘"), + (0xF9F0, "M", "藺"), + (0xF9F1, "M", "隣"), + (0xF9F2, "M", "鱗"), + (0xF9F3, "M", "麟"), + (0xF9F4, "M", "林"), + (0xF9F5, "M", "淋"), + (0xF9F6, "M", "臨"), + (0xF9F7, "M", "立"), + (0xF9F8, "M", "笠"), + (0xF9F9, "M", "粒"), + (0xF9FA, "M", "狀"), + (0xF9FB, "M", "炙"), + (0xF9FC, "M", "識"), + (0xF9FD, "M", "什"), + (0xF9FE, "M", "茶"), + (0xF9FF, "M", "刺"), + (0xFA00, "M", "切"), + (0xFA01, "M", "度"), + (0xFA02, "M", "拓"), + (0xFA03, "M", "糖"), + (0xFA04, "M", "宅"), + (0xFA05, "M", "洞"), + (0xFA06, "M", "暴"), + (0xFA07, "M", "輻"), + (0xFA08, "M", "行"), + (0xFA09, "M", "降"), + (0xFA0A, "M", "見"), + (0xFA0B, "M", "廓"), + (0xFA0C, "M", "兀"), + (0xFA0D, "M", "嗀"), + (0xFA0E, "V"), + (0xFA10, "M", "塚"), + (0xFA11, "V"), + (0xFA12, "M", "晴"), + (0xFA13, "V"), + (0xFA15, "M", "凞"), + (0xFA16, "M", "猪"), + (0xFA17, "M", "益"), + (0xFA18, "M", "礼"), + (0xFA19, "M", "神"), + (0xFA1A, "M", "祥"), + (0xFA1B, "M", "福"), + (0xFA1C, "M", "靖"), + (0xFA1D, "M", "精"), + (0xFA1E, "M", "羽"), + (0xFA1F, "V"), + (0xFA20, "M", "蘒"), + (0xFA21, "V"), + (0xFA22, "M", "諸"), + (0xFA23, "V"), + (0xFA25, "M", "逸"), + (0xFA26, "M", "都"), + (0xFA27, "V"), + (0xFA2A, "M", "飯"), + (0xFA2B, "M", "飼"), + (0xFA2C, "M", "館"), + (0xFA2D, "M", "鶴"), + (0xFA2E, "M", "郞"), + (0xFA2F, "M", "隷"), + (0xFA30, "M", "侮"), + (0xFA31, "M", "僧"), + (0xFA32, "M", "免"), + (0xFA33, "M", "勉"), + (0xFA34, "M", "勤"), + (0xFA35, "M", "卑"), + (0xFA36, "M", "喝"), + (0xFA37, "M", "嘆"), + (0xFA38, "M", "器"), + (0xFA39, "M", "塀"), + (0xFA3A, "M", "墨"), + (0xFA3B, "M", "層"), + (0xFA3C, "M", "屮"), + (0xFA3D, "M", "悔"), + (0xFA3E, "M", "慨"), + (0xFA3F, "M", "憎"), + (0xFA40, "M", "懲"), + (0xFA41, "M", "敏"), + (0xFA42, "M", "既"), + (0xFA43, "M", "暑"), + (0xFA44, "M", "梅"), + (0xFA45, "M", "海"), + (0xFA46, "M", "渚"), + (0xFA47, "M", "漢"), + (0xFA48, "M", "煮"), + (0xFA49, "M", "爫"), + (0xFA4A, "M", "琢"), + (0xFA4B, "M", "碑"), + (0xFA4C, "M", "社"), + (0xFA4D, "M", "祉"), + (0xFA4E, "M", "祈"), + (0xFA4F, "M", "祐"), + (0xFA50, "M", "祖"), + (0xFA51, "M", "祝"), + (0xFA52, "M", "禍"), + (0xFA53, "M", "禎"), + (0xFA54, "M", "穀"), + (0xFA55, "M", "突"), + (0xFA56, "M", "節"), + (0xFA57, "M", "練"), + (0xFA58, "M", "縉"), + (0xFA59, "M", "繁"), + (0xFA5A, "M", "署"), + (0xFA5B, "M", "者"), + (0xFA5C, "M", "臭"), + (0xFA5D, "M", "艹"), + (0xFA5F, "M", "著"), + (0xFA60, "M", "褐"), + (0xFA61, "M", "視"), + (0xFA62, "M", "謁"), + (0xFA63, "M", "謹"), + (0xFA64, "M", "賓"), + (0xFA65, "M", "贈"), + (0xFA66, "M", "辶"), + (0xFA67, "M", "逸"), + (0xFA68, "M", "難"), + (0xFA69, "M", "響"), + (0xFA6A, "M", "頻"), + (0xFA6B, "M", "恵"), + (0xFA6C, "M", "𤋮"), + (0xFA6D, "M", "舘"), + (0xFA6E, "X"), + (0xFA70, "M", "並"), + (0xFA71, "M", "况"), + (0xFA72, "M", "全"), + (0xFA73, "M", "侀"), + (0xFA74, "M", "充"), + (0xFA75, "M", "冀"), + (0xFA76, "M", "勇"), + (0xFA77, "M", "勺"), + (0xFA78, "M", "喝"), + (0xFA79, "M", "啕"), + (0xFA7A, "M", "喙"), + (0xFA7B, "M", "嗢"), + (0xFA7C, "M", "塚"), + (0xFA7D, "M", "墳"), + (0xFA7E, "M", "奄"), + (0xFA7F, "M", "奔"), + (0xFA80, "M", "婢"), + (0xFA81, "M", "嬨"), + (0xFA82, "M", "廒"), + (0xFA83, "M", "廙"), + (0xFA84, "M", "彩"), + (0xFA85, "M", "徭"), + (0xFA86, "M", "惘"), + (0xFA87, "M", "慎"), + (0xFA88, "M", "愈"), + (0xFA89, "M", "憎"), + (0xFA8A, "M", "慠"), + (0xFA8B, "M", "懲"), + (0xFA8C, "M", "戴"), + (0xFA8D, "M", "揄"), + (0xFA8E, "M", "搜"), + (0xFA8F, "M", "摒"), + (0xFA90, "M", "敖"), + (0xFA91, "M", "晴"), + (0xFA92, "M", "朗"), + (0xFA93, "M", "望"), + (0xFA94, "M", "杖"), + (0xFA95, "M", "歹"), + (0xFA96, "M", "殺"), + (0xFA97, "M", "流"), + (0xFA98, "M", "滛"), + (0xFA99, "M", "滋"), + (0xFA9A, "M", "漢"), + (0xFA9B, "M", "瀞"), + (0xFA9C, "M", "煮"), + (0xFA9D, "M", "瞧"), + (0xFA9E, "M", "爵"), + (0xFA9F, "M", "犯"), + (0xFAA0, "M", "猪"), + (0xFAA1, "M", "瑱"), + (0xFAA2, "M", "甆"), + (0xFAA3, "M", "画"), + (0xFAA4, "M", "瘝"), + (0xFAA5, "M", "瘟"), + (0xFAA6, "M", "益"), + (0xFAA7, "M", "盛"), + (0xFAA8, "M", "直"), + (0xFAA9, "M", "睊"), + (0xFAAA, "M", "着"), + (0xFAAB, "M", "磌"), + (0xFAAC, "M", "窱"), + (0xFAAD, "M", "節"), + (0xFAAE, "M", "类"), + (0xFAAF, "M", "絛"), + (0xFAB0, "M", "練"), + (0xFAB1, "M", "缾"), + (0xFAB2, "M", "者"), + (0xFAB3, "M", "荒"), + (0xFAB4, "M", "華"), + (0xFAB5, "M", "蝹"), + (0xFAB6, "M", "襁"), + (0xFAB7, "M", "覆"), + (0xFAB8, "M", "視"), + (0xFAB9, "M", "調"), + (0xFABA, "M", "諸"), + (0xFABB, "M", "請"), + (0xFABC, "M", "謁"), + (0xFABD, "M", "諾"), + (0xFABE, "M", "諭"), + (0xFABF, "M", "謹"), + (0xFAC0, "M", "變"), + (0xFAC1, "M", "贈"), + (0xFAC2, "M", "輸"), + (0xFAC3, "M", "遲"), + (0xFAC4, "M", "醙"), + (0xFAC5, "M", "鉶"), + (0xFAC6, "M", "陼"), + (0xFAC7, "M", "難"), + (0xFAC8, "M", "靖"), + (0xFAC9, "M", "韛"), + (0xFACA, "M", "響"), + (0xFACB, "M", "頋"), + (0xFACC, "M", "頻"), + (0xFACD, "M", "鬒"), + (0xFACE, "M", "龜"), + (0xFACF, "M", "𢡊"), + (0xFAD0, "M", "𢡄"), + (0xFAD1, "M", "𣏕"), + (0xFAD2, "M", "㮝"), + (0xFAD3, "M", "䀘"), + (0xFAD4, "M", "䀹"), + (0xFAD5, "M", "𥉉"), + (0xFAD6, "M", "𥳐"), + (0xFAD7, "M", "𧻓"), + (0xFAD8, "M", "齃"), + (0xFAD9, "M", "龎"), + (0xFADA, "X"), + (0xFB00, "M", "ff"), + (0xFB01, "M", "fi"), + (0xFB02, "M", "fl"), + (0xFB03, "M", "ffi"), + (0xFB04, "M", "ffl"), + (0xFB05, "M", "st"), + (0xFB07, "X"), + (0xFB13, "M", "մն"), + (0xFB14, "M", "մե"), + (0xFB15, "M", "մի"), + (0xFB16, "M", "վն"), + (0xFB17, "M", "մխ"), + (0xFB18, "X"), + (0xFB1D, "M", "יִ"), + (0xFB1E, "V"), + (0xFB1F, "M", "ײַ"), + (0xFB20, "M", "ע"), + (0xFB21, "M", "א"), + (0xFB22, "M", "ד"), + (0xFB23, "M", "ה"), + (0xFB24, "M", "כ"), + (0xFB25, "M", "ל"), + (0xFB26, "M", "ם"), + (0xFB27, "M", "ר"), + (0xFB28, "M", "ת"), + (0xFB29, "M", "+"), + (0xFB2A, "M", "שׁ"), + (0xFB2B, "M", "שׂ"), + (0xFB2C, "M", "שּׁ"), + (0xFB2D, "M", "שּׂ"), + (0xFB2E, "M", "אַ"), + (0xFB2F, "M", "אָ"), + (0xFB30, "M", "אּ"), + (0xFB31, "M", "בּ"), + (0xFB32, "M", "גּ"), + (0xFB33, "M", "דּ"), + (0xFB34, "M", "הּ"), + (0xFB35, "M", "וּ"), + (0xFB36, "M", "זּ"), + (0xFB37, "X"), + (0xFB38, "M", "טּ"), + (0xFB39, "M", "יּ"), + (0xFB3A, "M", "ךּ"), + (0xFB3B, "M", "כּ"), + (0xFB3C, "M", "לּ"), + (0xFB3D, "X"), + (0xFB3E, "M", "מּ"), + (0xFB3F, "X"), + (0xFB40, "M", "נּ"), + (0xFB41, "M", "סּ"), + (0xFB42, "X"), + (0xFB43, "M", "ףּ"), + (0xFB44, "M", "פּ"), + (0xFB45, "X"), + (0xFB46, "M", "צּ"), + (0xFB47, "M", "קּ"), + (0xFB48, "M", "רּ"), + (0xFB49, "M", "שּ"), + (0xFB4A, "M", "תּ"), + (0xFB4B, "M", "וֹ"), + (0xFB4C, "M", "בֿ"), + (0xFB4D, "M", "כֿ"), + (0xFB4E, "M", "פֿ"), + (0xFB4F, "M", "אל"), + (0xFB50, "M", "ٱ"), + (0xFB52, "M", "ٻ"), + (0xFB56, "M", "پ"), + (0xFB5A, "M", "ڀ"), + (0xFB5E, "M", "ٺ"), + (0xFB62, "M", "ٿ"), + (0xFB66, "M", "ٹ"), + (0xFB6A, "M", "ڤ"), + (0xFB6E, "M", "ڦ"), + (0xFB72, "M", "ڄ"), + (0xFB76, "M", "ڃ"), + (0xFB7A, "M", "چ"), + (0xFB7E, "M", "ڇ"), + (0xFB82, "M", "ڍ"), + (0xFB84, "M", "ڌ"), + (0xFB86, "M", "ڎ"), + (0xFB88, "M", "ڈ"), + (0xFB8A, "M", "ژ"), + (0xFB8C, "M", "ڑ"), + (0xFB8E, "M", "ک"), + (0xFB92, "M", "گ"), + (0xFB96, "M", "ڳ"), + (0xFB9A, "M", "ڱ"), + (0xFB9E, "M", "ں"), + (0xFBA0, "M", "ڻ"), + (0xFBA4, "M", "ۀ"), + (0xFBA6, "M", "ہ"), + (0xFBAA, "M", "ھ"), + (0xFBAE, "M", "ے"), + (0xFBB0, "M", "ۓ"), + (0xFBB2, "V"), + (0xFBD3, "M", "ڭ"), + (0xFBD7, "M", "ۇ"), + (0xFBD9, "M", "ۆ"), + (0xFBDB, "M", "ۈ"), + (0xFBDD, "M", "ۇٴ"), + (0xFBDE, "M", "ۋ"), + (0xFBE0, "M", "ۅ"), + (0xFBE2, "M", "ۉ"), + (0xFBE4, "M", "ې"), + (0xFBE8, "M", "ى"), + (0xFBEA, "M", "ئا"), + (0xFBEC, "M", "ئە"), + (0xFBEE, "M", "ئو"), + (0xFBF0, "M", "ئۇ"), + (0xFBF2, "M", "ئۆ"), + (0xFBF4, "M", "ئۈ"), + (0xFBF6, "M", "ئې"), + (0xFBF9, "M", "ئى"), + (0xFBFC, "M", "ی"), + (0xFC00, "M", "ئج"), + (0xFC01, "M", "ئح"), + (0xFC02, "M", "ئم"), + (0xFC03, "M", "ئى"), + (0xFC04, "M", "ئي"), + (0xFC05, "M", "بج"), + (0xFC06, "M", "بح"), + (0xFC07, "M", "بخ"), + (0xFC08, "M", "بم"), + (0xFC09, "M", "بى"), + (0xFC0A, "M", "بي"), + (0xFC0B, "M", "تج"), + (0xFC0C, "M", "تح"), + (0xFC0D, "M", "تخ"), + (0xFC0E, "M", "تم"), + (0xFC0F, "M", "تى"), + (0xFC10, "M", "تي"), + (0xFC11, "M", "ثج"), + (0xFC12, "M", "ثم"), + (0xFC13, "M", "ثى"), + (0xFC14, "M", "ثي"), + (0xFC15, "M", "جح"), + (0xFC16, "M", "جم"), + (0xFC17, "M", "حج"), + (0xFC18, "M", "حم"), + (0xFC19, "M", "خج"), + (0xFC1A, "M", "خح"), + (0xFC1B, "M", "خم"), + (0xFC1C, "M", "سج"), + (0xFC1D, "M", "سح"), + (0xFC1E, "M", "سخ"), + (0xFC1F, "M", "سم"), + (0xFC20, "M", "صح"), + (0xFC21, "M", "صم"), + (0xFC22, "M", "ضج"), + (0xFC23, "M", "ضح"), + (0xFC24, "M", "ضخ"), + (0xFC25, "M", "ضم"), + (0xFC26, "M", "طح"), + (0xFC27, "M", "طم"), + (0xFC28, "M", "ظم"), + (0xFC29, "M", "عج"), + (0xFC2A, "M", "عم"), + (0xFC2B, "M", "غج"), + (0xFC2C, "M", "غم"), + (0xFC2D, "M", "فج"), + (0xFC2E, "M", "فح"), + (0xFC2F, "M", "فخ"), + (0xFC30, "M", "فم"), + (0xFC31, "M", "فى"), + (0xFC32, "M", "في"), + (0xFC33, "M", "قح"), + (0xFC34, "M", "قم"), + (0xFC35, "M", "قى"), + (0xFC36, "M", "قي"), + (0xFC37, "M", "كا"), + (0xFC38, "M", "كج"), + (0xFC39, "M", "كح"), + (0xFC3A, "M", "كخ"), + (0xFC3B, "M", "كل"), + (0xFC3C, "M", "كم"), + (0xFC3D, "M", "كى"), + (0xFC3E, "M", "كي"), + (0xFC3F, "M", "لج"), + (0xFC40, "M", "لح"), + (0xFC41, "M", "لخ"), + (0xFC42, "M", "لم"), + (0xFC43, "M", "لى"), + (0xFC44, "M", "لي"), + (0xFC45, "M", "مج"), + (0xFC46, "M", "مح"), + (0xFC47, "M", "مخ"), + (0xFC48, "M", "مم"), + (0xFC49, "M", "مى"), + (0xFC4A, "M", "مي"), + (0xFC4B, "M", "نج"), + (0xFC4C, "M", "نح"), + (0xFC4D, "M", "نخ"), + (0xFC4E, "M", "نم"), + (0xFC4F, "M", "نى"), + (0xFC50, "M", "ني"), + (0xFC51, "M", "هج"), + (0xFC52, "M", "هم"), + (0xFC53, "M", "هى"), + (0xFC54, "M", "هي"), + (0xFC55, "M", "يج"), + (0xFC56, "M", "يح"), + (0xFC57, "M", "يخ"), + (0xFC58, "M", "يم"), + (0xFC59, "M", "يى"), + (0xFC5A, "M", "يي"), + (0xFC5B, "M", "ذٰ"), + (0xFC5C, "M", "رٰ"), + (0xFC5D, "M", "ىٰ"), + (0xFC5E, "M", " ٌّ"), + (0xFC5F, "M", " ٍّ"), + (0xFC60, "M", " َّ"), + (0xFC61, "M", " ُّ"), + (0xFC62, "M", " ِّ"), + (0xFC63, "M", " ّٰ"), + (0xFC64, "M", "ئر"), + (0xFC65, "M", "ئز"), + (0xFC66, "M", "ئم"), + (0xFC67, "M", "ئن"), + (0xFC68, "M", "ئى"), + (0xFC69, "M", "ئي"), + (0xFC6A, "M", "بر"), + (0xFC6B, "M", "بز"), + (0xFC6C, "M", "بم"), + (0xFC6D, "M", "بن"), + (0xFC6E, "M", "بى"), + (0xFC6F, "M", "بي"), + (0xFC70, "M", "تر"), + (0xFC71, "M", "تز"), + (0xFC72, "M", "تم"), + (0xFC73, "M", "تن"), + (0xFC74, "M", "تى"), + (0xFC75, "M", "تي"), + (0xFC76, "M", "ثر"), + (0xFC77, "M", "ثز"), + (0xFC78, "M", "ثم"), + (0xFC79, "M", "ثن"), + (0xFC7A, "M", "ثى"), + (0xFC7B, "M", "ثي"), + (0xFC7C, "M", "فى"), + (0xFC7D, "M", "في"), + (0xFC7E, "M", "قى"), + (0xFC7F, "M", "قي"), + (0xFC80, "M", "كا"), + (0xFC81, "M", "كل"), + (0xFC82, "M", "كم"), + (0xFC83, "M", "كى"), + (0xFC84, "M", "كي"), + (0xFC85, "M", "لم"), + (0xFC86, "M", "لى"), + (0xFC87, "M", "لي"), + (0xFC88, "M", "ما"), + (0xFC89, "M", "مم"), + (0xFC8A, "M", "نر"), + (0xFC8B, "M", "نز"), + (0xFC8C, "M", "نم"), + (0xFC8D, "M", "نن"), + (0xFC8E, "M", "نى"), + (0xFC8F, "M", "ني"), + (0xFC90, "M", "ىٰ"), + (0xFC91, "M", "ير"), + (0xFC92, "M", "يز"), + (0xFC93, "M", "يم"), + (0xFC94, "M", "ين"), + (0xFC95, "M", "يى"), + (0xFC96, "M", "يي"), + (0xFC97, "M", "ئج"), + (0xFC98, "M", "ئح"), + (0xFC99, "M", "ئخ"), + (0xFC9A, "M", "ئم"), + (0xFC9B, "M", "ئه"), + (0xFC9C, "M", "بج"), + (0xFC9D, "M", "بح"), + (0xFC9E, "M", "بخ"), + (0xFC9F, "M", "بم"), + (0xFCA0, "M", "به"), + (0xFCA1, "M", "تج"), + (0xFCA2, "M", "تح"), + (0xFCA3, "M", "تخ"), + (0xFCA4, "M", "تم"), + (0xFCA5, "M", "ته"), + (0xFCA6, "M", "ثم"), + (0xFCA7, "M", "جح"), + (0xFCA8, "M", "جم"), + (0xFCA9, "M", "حج"), + (0xFCAA, "M", "حم"), + (0xFCAB, "M", "خج"), + (0xFCAC, "M", "خم"), + (0xFCAD, "M", "سج"), + (0xFCAE, "M", "سح"), + (0xFCAF, "M", "سخ"), + (0xFCB0, "M", "سم"), + (0xFCB1, "M", "صح"), + (0xFCB2, "M", "صخ"), + (0xFCB3, "M", "صم"), + (0xFCB4, "M", "ضج"), + (0xFCB5, "M", "ضح"), + (0xFCB6, "M", "ضخ"), + (0xFCB7, "M", "ضم"), + (0xFCB8, "M", "طح"), + (0xFCB9, "M", "ظم"), + (0xFCBA, "M", "عج"), + (0xFCBB, "M", "عم"), + (0xFCBC, "M", "غج"), + (0xFCBD, "M", "غم"), + (0xFCBE, "M", "فج"), + (0xFCBF, "M", "فح"), + (0xFCC0, "M", "فخ"), + (0xFCC1, "M", "فم"), + (0xFCC2, "M", "قح"), + (0xFCC3, "M", "قم"), + (0xFCC4, "M", "كج"), + (0xFCC5, "M", "كح"), + (0xFCC6, "M", "كخ"), + (0xFCC7, "M", "كل"), + (0xFCC8, "M", "كم"), + (0xFCC9, "M", "لج"), + (0xFCCA, "M", "لح"), + (0xFCCB, "M", "لخ"), + (0xFCCC, "M", "لم"), + (0xFCCD, "M", "له"), + (0xFCCE, "M", "مج"), + (0xFCCF, "M", "مح"), + (0xFCD0, "M", "مخ"), + (0xFCD1, "M", "مم"), + (0xFCD2, "M", "نج"), + (0xFCD3, "M", "نح"), + (0xFCD4, "M", "نخ"), + (0xFCD5, "M", "نم"), + (0xFCD6, "M", "نه"), + (0xFCD7, "M", "هج"), + (0xFCD8, "M", "هم"), + (0xFCD9, "M", "هٰ"), + (0xFCDA, "M", "يج"), + (0xFCDB, "M", "يح"), + (0xFCDC, "M", "يخ"), + (0xFCDD, "M", "يم"), + (0xFCDE, "M", "يه"), + (0xFCDF, "M", "ئم"), + (0xFCE0, "M", "ئه"), + (0xFCE1, "M", "بم"), + (0xFCE2, "M", "به"), + (0xFCE3, "M", "تم"), + (0xFCE4, "M", "ته"), + (0xFCE5, "M", "ثم"), + (0xFCE6, "M", "ثه"), + (0xFCE7, "M", "سم"), + (0xFCE8, "M", "سه"), + (0xFCE9, "M", "شم"), + (0xFCEA, "M", "شه"), + (0xFCEB, "M", "كل"), + (0xFCEC, "M", "كم"), + (0xFCED, "M", "لم"), + (0xFCEE, "M", "نم"), + (0xFCEF, "M", "نه"), + (0xFCF0, "M", "يم"), + (0xFCF1, "M", "يه"), + (0xFCF2, "M", "ـَّ"), + (0xFCF3, "M", "ـُّ"), + (0xFCF4, "M", "ـِّ"), + (0xFCF5, "M", "طى"), + (0xFCF6, "M", "طي"), + (0xFCF7, "M", "عى"), + (0xFCF8, "M", "عي"), + (0xFCF9, "M", "غى"), + (0xFCFA, "M", "غي"), + (0xFCFB, "M", "سى"), + (0xFCFC, "M", "سي"), + (0xFCFD, "M", "شى"), + (0xFCFE, "M", "شي"), + (0xFCFF, "M", "حى"), + (0xFD00, "M", "حي"), + (0xFD01, "M", "جى"), + (0xFD02, "M", "جي"), + (0xFD03, "M", "خى"), + (0xFD04, "M", "خي"), + (0xFD05, "M", "صى"), + (0xFD06, "M", "صي"), + (0xFD07, "M", "ضى"), + (0xFD08, "M", "ضي"), + (0xFD09, "M", "شج"), + (0xFD0A, "M", "شح"), + (0xFD0B, "M", "شخ"), + (0xFD0C, "M", "شم"), + (0xFD0D, "M", "شر"), + (0xFD0E, "M", "سر"), + (0xFD0F, "M", "صر"), + (0xFD10, "M", "ضر"), + (0xFD11, "M", "طى"), + (0xFD12, "M", "طي"), + (0xFD13, "M", "عى"), + (0xFD14, "M", "عي"), + (0xFD15, "M", "غى"), + (0xFD16, "M", "غي"), + (0xFD17, "M", "سى"), + (0xFD18, "M", "سي"), + (0xFD19, "M", "شى"), + (0xFD1A, "M", "شي"), + (0xFD1B, "M", "حى"), + (0xFD1C, "M", "حي"), + (0xFD1D, "M", "جى"), + (0xFD1E, "M", "جي"), + (0xFD1F, "M", "خى"), + (0xFD20, "M", "خي"), + (0xFD21, "M", "صى"), + (0xFD22, "M", "صي"), + (0xFD23, "M", "ضى"), + (0xFD24, "M", "ضي"), + (0xFD25, "M", "شج"), + (0xFD26, "M", "شح"), + (0xFD27, "M", "شخ"), + (0xFD28, "M", "شم"), + (0xFD29, "M", "شر"), + (0xFD2A, "M", "سر"), + (0xFD2B, "M", "صر"), + (0xFD2C, "M", "ضر"), + (0xFD2D, "M", "شج"), + (0xFD2E, "M", "شح"), + (0xFD2F, "M", "شخ"), + (0xFD30, "M", "شم"), + (0xFD31, "M", "سه"), + (0xFD32, "M", "شه"), + (0xFD33, "M", "طم"), + (0xFD34, "M", "سج"), + (0xFD35, "M", "سح"), + (0xFD36, "M", "سخ"), + (0xFD37, "M", "شج"), + (0xFD38, "M", "شح"), + (0xFD39, "M", "شخ"), + (0xFD3A, "M", "طم"), + (0xFD3B, "M", "ظم"), + (0xFD3C, "M", "اً"), + (0xFD3E, "V"), + (0xFD50, "M", "تجم"), + (0xFD51, "M", "تحج"), + (0xFD53, "M", "تحم"), + (0xFD54, "M", "تخم"), + (0xFD55, "M", "تمج"), + (0xFD56, "M", "تمح"), + (0xFD57, "M", "تمخ"), + (0xFD58, "M", "جمح"), + (0xFD5A, "M", "حمي"), + (0xFD5B, "M", "حمى"), + (0xFD5C, "M", "سحج"), + (0xFD5D, "M", "سجح"), + (0xFD5E, "M", "سجى"), + (0xFD5F, "M", "سمح"), + (0xFD61, "M", "سمج"), + (0xFD62, "M", "سمم"), + (0xFD64, "M", "صحح"), + (0xFD66, "M", "صمم"), + (0xFD67, "M", "شحم"), + (0xFD69, "M", "شجي"), + (0xFD6A, "M", "شمخ"), + (0xFD6C, "M", "شمم"), + (0xFD6E, "M", "ضحى"), + (0xFD6F, "M", "ضخم"), + (0xFD71, "M", "طمح"), + (0xFD73, "M", "طمم"), + (0xFD74, "M", "طمي"), + (0xFD75, "M", "عجم"), + (0xFD76, "M", "عمم"), + (0xFD78, "M", "عمى"), + (0xFD79, "M", "غمم"), + (0xFD7A, "M", "غمي"), + (0xFD7B, "M", "غمى"), + (0xFD7C, "M", "فخم"), + (0xFD7E, "M", "قمح"), + (0xFD7F, "M", "قمم"), + (0xFD80, "M", "لحم"), + (0xFD81, "M", "لحي"), + (0xFD82, "M", "لحى"), + (0xFD83, "M", "لجج"), + (0xFD85, "M", "لخم"), + (0xFD87, "M", "لمح"), + (0xFD89, "M", "محج"), + (0xFD8A, "M", "محم"), + (0xFD8B, "M", "محي"), + (0xFD8C, "M", "مجح"), + (0xFD8D, "M", "مجم"), + (0xFD8E, "M", "مخج"), + (0xFD8F, "M", "مخم"), + (0xFD90, "V"), + (0xFD92, "M", "مجخ"), + (0xFD93, "M", "همج"), + (0xFD94, "M", "همم"), + (0xFD95, "M", "نحم"), + (0xFD96, "M", "نحى"), + (0xFD97, "M", "نجم"), + (0xFD99, "M", "نجى"), + (0xFD9A, "M", "نمي"), + (0xFD9B, "M", "نمى"), + (0xFD9C, "M", "يمم"), + (0xFD9E, "M", "بخي"), + (0xFD9F, "M", "تجي"), + (0xFDA0, "M", "تجى"), + (0xFDA1, "M", "تخي"), + (0xFDA2, "M", "تخى"), + (0xFDA3, "M", "تمي"), + (0xFDA4, "M", "تمى"), + (0xFDA5, "M", "جمي"), + (0xFDA6, "M", "جحى"), + (0xFDA7, "M", "جمى"), + (0xFDA8, "M", "سخى"), + (0xFDA9, "M", "صحي"), + (0xFDAA, "M", "شحي"), + (0xFDAB, "M", "ضحي"), + (0xFDAC, "M", "لجي"), + (0xFDAD, "M", "لمي"), + (0xFDAE, "M", "يحي"), + (0xFDAF, "M", "يجي"), + (0xFDB0, "M", "يمي"), + (0xFDB1, "M", "ممي"), + (0xFDB2, "M", "قمي"), + (0xFDB3, "M", "نحي"), + (0xFDB4, "M", "قمح"), + (0xFDB5, "M", "لحم"), + (0xFDB6, "M", "عمي"), + (0xFDB7, "M", "كمي"), + (0xFDB8, "M", "نجح"), + (0xFDB9, "M", "مخي"), + (0xFDBA, "M", "لجم"), + (0xFDBB, "M", "كمم"), + (0xFDBC, "M", "لجم"), + (0xFDBD, "M", "نجح"), + (0xFDBE, "M", "جحي"), + (0xFDBF, "M", "حجي"), + (0xFDC0, "M", "مجي"), + (0xFDC1, "M", "فمي"), + (0xFDC2, "M", "بحي"), + (0xFDC3, "M", "كمم"), + (0xFDC4, "M", "عجم"), + (0xFDC5, "M", "صمم"), + (0xFDC6, "M", "سخي"), + (0xFDC7, "M", "نجي"), + (0xFDC8, "V"), + (0xFDD0, "X"), + (0xFDF0, "M", "صلے"), + (0xFDF1, "M", "قلے"), + (0xFDF2, "M", "الله"), + (0xFDF3, "M", "اكبر"), + (0xFDF4, "M", "محمد"), + (0xFDF5, "M", "صلعم"), + (0xFDF6, "M", "رسول"), + (0xFDF7, "M", "عليه"), + (0xFDF8, "M", "وسلم"), + (0xFDF9, "M", "صلى"), + (0xFDFA, "M", "صلى الله عليه وسلم"), + (0xFDFB, "M", "جل جلاله"), + (0xFDFC, "M", "ریال"), + (0xFDFD, "V"), + (0xFE00, "I"), + (0xFE10, "M", ","), + (0xFE11, "M", "、"), + (0xFE12, "X"), + (0xFE13, "M", ":"), + (0xFE14, "M", ";"), + (0xFE15, "M", "!"), + (0xFE16, "M", "?"), + (0xFE17, "M", "〖"), + (0xFE18, "M", "〗"), + (0xFE19, "X"), + (0xFE20, "V"), + (0xFE30, "X"), + (0xFE31, "M", "—"), + (0xFE32, "M", "–"), + (0xFE33, "M", "_"), + (0xFE35, "M", "("), + (0xFE36, "M", ")"), + (0xFE37, "M", "{"), + (0xFE38, "M", "}"), + (0xFE39, "M", "〔"), + (0xFE3A, "M", "〕"), + (0xFE3B, "M", "【"), + (0xFE3C, "M", "】"), + (0xFE3D, "M", "《"), + (0xFE3E, "M", "》"), + (0xFE3F, "M", "〈"), + (0xFE40, "M", "〉"), + (0xFE41, "M", "「"), + (0xFE42, "M", "」"), + (0xFE43, "M", "『"), + (0xFE44, "M", "』"), + (0xFE45, "V"), + (0xFE47, "M", "["), + (0xFE48, "M", "]"), + (0xFE49, "M", " ̅"), + (0xFE4D, "M", "_"), + (0xFE50, "M", ","), + (0xFE51, "M", "、"), + (0xFE52, "X"), + (0xFE54, "M", ";"), + (0xFE55, "M", ":"), + (0xFE56, "M", "?"), + (0xFE57, "M", "!"), + (0xFE58, "M", "—"), + (0xFE59, "M", "("), + (0xFE5A, "M", ")"), + (0xFE5B, "M", "{"), + (0xFE5C, "M", "}"), + (0xFE5D, "M", "〔"), + (0xFE5E, "M", "〕"), + (0xFE5F, "M", "#"), + (0xFE60, "M", "&"), + (0xFE61, "M", "*"), + (0xFE62, "M", "+"), + (0xFE63, "M", "-"), + (0xFE64, "M", "<"), + (0xFE65, "M", ">"), + (0xFE66, "M", "="), + (0xFE67, "X"), + (0xFE68, "M", "\\"), + (0xFE69, "M", "$"), + (0xFE6A, "M", "%"), + (0xFE6B, "M", "@"), + (0xFE6C, "X"), + (0xFE70, "M", " ً"), + (0xFE71, "M", "ـً"), + (0xFE72, "M", " ٌ"), + (0xFE73, "V"), + (0xFE74, "M", " ٍ"), + (0xFE75, "X"), + (0xFE76, "M", " َ"), + (0xFE77, "M", "ـَ"), + (0xFE78, "M", " ُ"), + (0xFE79, "M", "ـُ"), + (0xFE7A, "M", " ِ"), + (0xFE7B, "M", "ـِ"), + (0xFE7C, "M", " ّ"), + (0xFE7D, "M", "ـّ"), + (0xFE7E, "M", " ْ"), + (0xFE7F, "M", "ـْ"), + (0xFE80, "M", "ء"), + (0xFE81, "M", "آ"), + (0xFE83, "M", "أ"), + (0xFE85, "M", "ؤ"), + (0xFE87, "M", "إ"), + (0xFE89, "M", "ئ"), + (0xFE8D, "M", "ا"), + (0xFE8F, "M", "ب"), + (0xFE93, "M", "ة"), + (0xFE95, "M", "ت"), + (0xFE99, "M", "ث"), + (0xFE9D, "M", "ج"), + (0xFEA1, "M", "ح"), + (0xFEA5, "M", "خ"), + (0xFEA9, "M", "د"), + (0xFEAB, "M", "ذ"), + (0xFEAD, "M", "ر"), + (0xFEAF, "M", "ز"), + (0xFEB1, "M", "س"), + (0xFEB5, "M", "ش"), + (0xFEB9, "M", "ص"), + (0xFEBD, "M", "ض"), + (0xFEC1, "M", "ط"), + (0xFEC5, "M", "ظ"), + (0xFEC9, "M", "ع"), + (0xFECD, "M", "غ"), + (0xFED1, "M", "ف"), + (0xFED5, "M", "ق"), + (0xFED9, "M", "ك"), + (0xFEDD, "M", "ل"), + (0xFEE1, "M", "م"), + (0xFEE5, "M", "ن"), + (0xFEE9, "M", "ه"), + (0xFEED, "M", "و"), + (0xFEEF, "M", "ى"), + (0xFEF1, "M", "ي"), + (0xFEF5, "M", "لآ"), + (0xFEF7, "M", "لأ"), + (0xFEF9, "M", "لإ"), + (0xFEFB, "M", "لا"), + (0xFEFD, "X"), + (0xFEFF, "I"), + (0xFF00, "X"), + (0xFF01, "M", "!"), + (0xFF02, "M", '"'), + (0xFF03, "M", "#"), + (0xFF04, "M", "$"), + (0xFF05, "M", "%"), + (0xFF06, "M", "&"), + (0xFF07, "M", "'"), + (0xFF08, "M", "("), + (0xFF09, "M", ")"), + (0xFF0A, "M", "*"), + (0xFF0B, "M", "+"), + (0xFF0C, "M", ","), + (0xFF0D, "M", "-"), + (0xFF0E, "M", "."), + (0xFF0F, "M", "/"), + (0xFF10, "M", "0"), + (0xFF11, "M", "1"), + (0xFF12, "M", "2"), + (0xFF13, "M", "3"), + (0xFF14, "M", "4"), + (0xFF15, "M", "5"), + (0xFF16, "M", "6"), + (0xFF17, "M", "7"), + (0xFF18, "M", "8"), + (0xFF19, "M", "9"), + (0xFF1A, "M", ":"), + (0xFF1B, "M", ";"), + (0xFF1C, "M", "<"), + (0xFF1D, "M", "="), + (0xFF1E, "M", ">"), + (0xFF1F, "M", "?"), + (0xFF20, "M", "@"), + (0xFF21, "M", "a"), + (0xFF22, "M", "b"), + (0xFF23, "M", "c"), + (0xFF24, "M", "d"), + (0xFF25, "M", "e"), + (0xFF26, "M", "f"), + (0xFF27, "M", "g"), + (0xFF28, "M", "h"), + (0xFF29, "M", "i"), + (0xFF2A, "M", "j"), + (0xFF2B, "M", "k"), + (0xFF2C, "M", "l"), + (0xFF2D, "M", "m"), + (0xFF2E, "M", "n"), + (0xFF2F, "M", "o"), + (0xFF30, "M", "p"), + (0xFF31, "M", "q"), + (0xFF32, "M", "r"), + (0xFF33, "M", "s"), + (0xFF34, "M", "t"), + (0xFF35, "M", "u"), + (0xFF36, "M", "v"), + (0xFF37, "M", "w"), + (0xFF38, "M", "x"), + (0xFF39, "M", "y"), + (0xFF3A, "M", "z"), + (0xFF3B, "M", "["), + (0xFF3C, "M", "\\"), + (0xFF3D, "M", "]"), + (0xFF3E, "M", "^"), + (0xFF3F, "M", "_"), + (0xFF40, "M", "`"), + (0xFF41, "M", "a"), + (0xFF42, "M", "b"), + (0xFF43, "M", "c"), + (0xFF44, "M", "d"), + (0xFF45, "M", "e"), + (0xFF46, "M", "f"), + (0xFF47, "M", "g"), + (0xFF48, "M", "h"), + (0xFF49, "M", "i"), + (0xFF4A, "M", "j"), + (0xFF4B, "M", "k"), + (0xFF4C, "M", "l"), + (0xFF4D, "M", "m"), + (0xFF4E, "M", "n"), + (0xFF4F, "M", "o"), + (0xFF50, "M", "p"), + (0xFF51, "M", "q"), + (0xFF52, "M", "r"), + (0xFF53, "M", "s"), + (0xFF54, "M", "t"), + (0xFF55, "M", "u"), + (0xFF56, "M", "v"), + (0xFF57, "M", "w"), + (0xFF58, "M", "x"), + (0xFF59, "M", "y"), + (0xFF5A, "M", "z"), + (0xFF5B, "M", "{"), + (0xFF5C, "M", "|"), + (0xFF5D, "M", "}"), + (0xFF5E, "M", "~"), + (0xFF5F, "M", "⦅"), + (0xFF60, "M", "⦆"), + (0xFF61, "M", "."), + (0xFF62, "M", "「"), + (0xFF63, "M", "」"), + (0xFF64, "M", "、"), + (0xFF65, "M", "・"), + (0xFF66, "M", "ヲ"), + (0xFF67, "M", "ァ"), + (0xFF68, "M", "ィ"), + (0xFF69, "M", "ゥ"), + (0xFF6A, "M", "ェ"), + (0xFF6B, "M", "ォ"), + (0xFF6C, "M", "ャ"), + (0xFF6D, "M", "ュ"), + (0xFF6E, "M", "ョ"), + (0xFF6F, "M", "ッ"), + (0xFF70, "M", "ー"), + (0xFF71, "M", "ア"), + (0xFF72, "M", "イ"), + (0xFF73, "M", "ウ"), + (0xFF74, "M", "エ"), + (0xFF75, "M", "オ"), + (0xFF76, "M", "カ"), + (0xFF77, "M", "キ"), + (0xFF78, "M", "ク"), + (0xFF79, "M", "ケ"), + (0xFF7A, "M", "コ"), + (0xFF7B, "M", "サ"), + (0xFF7C, "M", "シ"), + (0xFF7D, "M", "ス"), + (0xFF7E, "M", "セ"), + (0xFF7F, "M", "ソ"), + (0xFF80, "M", "タ"), + (0xFF81, "M", "チ"), + (0xFF82, "M", "ツ"), + (0xFF83, "M", "テ"), + (0xFF84, "M", "ト"), + (0xFF85, "M", "ナ"), + (0xFF86, "M", "ニ"), + (0xFF87, "M", "ヌ"), + (0xFF88, "M", "ネ"), + (0xFF89, "M", "ノ"), + (0xFF8A, "M", "ハ"), + (0xFF8B, "M", "ヒ"), + (0xFF8C, "M", "フ"), + (0xFF8D, "M", "ヘ"), + (0xFF8E, "M", "ホ"), + (0xFF8F, "M", "マ"), + (0xFF90, "M", "ミ"), + (0xFF91, "M", "ム"), + (0xFF92, "M", "メ"), + (0xFF93, "M", "モ"), + (0xFF94, "M", "ヤ"), + (0xFF95, "M", "ユ"), + (0xFF96, "M", "ヨ"), + (0xFF97, "M", "ラ"), + (0xFF98, "M", "リ"), + (0xFF99, "M", "ル"), + (0xFF9A, "M", "レ"), + (0xFF9B, "M", "ロ"), + (0xFF9C, "M", "ワ"), + (0xFF9D, "M", "ン"), + (0xFF9E, "M", "゙"), + (0xFF9F, "M", "゚"), + (0xFFA0, "I"), + (0xFFA1, "M", "ᄀ"), + (0xFFA2, "M", "ᄁ"), + (0xFFA3, "M", "ᆪ"), + (0xFFA4, "M", "ᄂ"), + (0xFFA5, "M", "ᆬ"), + (0xFFA6, "M", "ᆭ"), + (0xFFA7, "M", "ᄃ"), + (0xFFA8, "M", "ᄄ"), + (0xFFA9, "M", "ᄅ"), + (0xFFAA, "M", "ᆰ"), + (0xFFAB, "M", "ᆱ"), + (0xFFAC, "M", "ᆲ"), + (0xFFAD, "M", "ᆳ"), + (0xFFAE, "M", "ᆴ"), + (0xFFAF, "M", "ᆵ"), + (0xFFB0, "M", "ᄚ"), + (0xFFB1, "M", "ᄆ"), + (0xFFB2, "M", "ᄇ"), + (0xFFB3, "M", "ᄈ"), + (0xFFB4, "M", "ᄡ"), + (0xFFB5, "M", "ᄉ"), + (0xFFB6, "M", "ᄊ"), + (0xFFB7, "M", "ᄋ"), + (0xFFB8, "M", "ᄌ"), + (0xFFB9, "M", "ᄍ"), + (0xFFBA, "M", "ᄎ"), + (0xFFBB, "M", "ᄏ"), + (0xFFBC, "M", "ᄐ"), + (0xFFBD, "M", "ᄑ"), + (0xFFBE, "M", "ᄒ"), + (0xFFBF, "X"), + (0xFFC2, "M", "ᅡ"), + (0xFFC3, "M", "ᅢ"), + (0xFFC4, "M", "ᅣ"), + (0xFFC5, "M", "ᅤ"), + (0xFFC6, "M", "ᅥ"), + (0xFFC7, "M", "ᅦ"), + (0xFFC8, "X"), + (0xFFCA, "M", "ᅧ"), + (0xFFCB, "M", "ᅨ"), + (0xFFCC, "M", "ᅩ"), + (0xFFCD, "M", "ᅪ"), + (0xFFCE, "M", "ᅫ"), + (0xFFCF, "M", "ᅬ"), + (0xFFD0, "X"), + (0xFFD2, "M", "ᅭ"), + (0xFFD3, "M", "ᅮ"), + (0xFFD4, "M", "ᅯ"), + (0xFFD5, "M", "ᅰ"), + (0xFFD6, "M", "ᅱ"), + (0xFFD7, "M", "ᅲ"), + (0xFFD8, "X"), + (0xFFDA, "M", "ᅳ"), + (0xFFDB, "M", "ᅴ"), + (0xFFDC, "M", "ᅵ"), + (0xFFDD, "X"), + (0xFFE0, "M", "¢"), + (0xFFE1, "M", "£"), + (0xFFE2, "M", "¬"), + (0xFFE3, "M", " ̄"), + (0xFFE4, "M", "¦"), + (0xFFE5, "M", "¥"), + (0xFFE6, "M", "₩"), + (0xFFE7, "X"), + (0xFFE8, "M", "│"), + (0xFFE9, "M", "←"), + (0xFFEA, "M", "↑"), + (0xFFEB, "M", "→"), + (0xFFEC, "M", "↓"), + (0xFFED, "M", "■"), + (0xFFEE, "M", "○"), + (0xFFEF, "X"), + (0x10000, "V"), + (0x1000C, "X"), + (0x1000D, "V"), + (0x10027, "X"), + (0x10028, "V"), + (0x1003B, "X"), + (0x1003C, "V"), + (0x1003E, "X"), + (0x1003F, "V"), + (0x1004E, "X"), + (0x10050, "V"), + (0x1005E, "X"), + (0x10080, "V"), + (0x100FB, "X"), + (0x10100, "V"), + (0x10103, "X"), + (0x10107, "V"), + (0x10134, "X"), + (0x10137, "V"), + (0x1018F, "X"), + (0x10190, "V"), + (0x1019D, "X"), + (0x101A0, "V"), + (0x101A1, "X"), + (0x101D0, "V"), + (0x101FE, "X"), + (0x10280, "V"), + (0x1029D, "X"), + (0x102A0, "V"), + (0x102D1, "X"), + (0x102E0, "V"), + (0x102FC, "X"), + (0x10300, "V"), + (0x10324, "X"), + (0x1032D, "V"), + (0x1034B, "X"), + (0x10350, "V"), + (0x1037B, "X"), + (0x10380, "V"), + (0x1039E, "X"), + (0x1039F, "V"), + (0x103C4, "X"), + (0x103C8, "V"), + (0x103D6, "X"), + (0x10400, "M", "𐐨"), + (0x10401, "M", "𐐩"), + (0x10402, "M", "𐐪"), + (0x10403, "M", "𐐫"), + (0x10404, "M", "𐐬"), + (0x10405, "M", "𐐭"), + (0x10406, "M", "𐐮"), + (0x10407, "M", "𐐯"), + (0x10408, "M", "𐐰"), + (0x10409, "M", "𐐱"), + (0x1040A, "M", "𐐲"), + (0x1040B, "M", "𐐳"), + (0x1040C, "M", "𐐴"), + (0x1040D, "M", "𐐵"), + (0x1040E, "M", "𐐶"), + (0x1040F, "M", "𐐷"), + (0x10410, "M", "𐐸"), + (0x10411, "M", "𐐹"), + (0x10412, "M", "𐐺"), + (0x10413, "M", "𐐻"), + (0x10414, "M", "𐐼"), + (0x10415, "M", "𐐽"), + (0x10416, "M", "𐐾"), + (0x10417, "M", "𐐿"), + (0x10418, "M", "𐑀"), + (0x10419, "M", "𐑁"), + (0x1041A, "M", "𐑂"), + (0x1041B, "M", "𐑃"), + (0x1041C, "M", "𐑄"), + (0x1041D, "M", "𐑅"), + (0x1041E, "M", "𐑆"), + (0x1041F, "M", "𐑇"), + (0x10420, "M", "𐑈"), + (0x10421, "M", "𐑉"), + (0x10422, "M", "𐑊"), + (0x10423, "M", "𐑋"), + (0x10424, "M", "𐑌"), + (0x10425, "M", "𐑍"), + (0x10426, "M", "𐑎"), + (0x10427, "M", "𐑏"), + (0x10428, "V"), + (0x1049E, "X"), + (0x104A0, "V"), + (0x104AA, "X"), + (0x104B0, "M", "𐓘"), + (0x104B1, "M", "𐓙"), + (0x104B2, "M", "𐓚"), + (0x104B3, "M", "𐓛"), + (0x104B4, "M", "𐓜"), + (0x104B5, "M", "𐓝"), + (0x104B6, "M", "𐓞"), + (0x104B7, "M", "𐓟"), + (0x104B8, "M", "𐓠"), + (0x104B9, "M", "𐓡"), + (0x104BA, "M", "𐓢"), + (0x104BB, "M", "𐓣"), + (0x104BC, "M", "𐓤"), + (0x104BD, "M", "𐓥"), + (0x104BE, "M", "𐓦"), + (0x104BF, "M", "𐓧"), + (0x104C0, "M", "𐓨"), + (0x104C1, "M", "𐓩"), + (0x104C2, "M", "𐓪"), + (0x104C3, "M", "𐓫"), + (0x104C4, "M", "𐓬"), + (0x104C5, "M", "𐓭"), + (0x104C6, "M", "𐓮"), + (0x104C7, "M", "𐓯"), + (0x104C8, "M", "𐓰"), + (0x104C9, "M", "𐓱"), + (0x104CA, "M", "𐓲"), + (0x104CB, "M", "𐓳"), + (0x104CC, "M", "𐓴"), + (0x104CD, "M", "𐓵"), + (0x104CE, "M", "𐓶"), + (0x104CF, "M", "𐓷"), + (0x104D0, "M", "𐓸"), + (0x104D1, "M", "𐓹"), + (0x104D2, "M", "𐓺"), + (0x104D3, "M", "𐓻"), + (0x104D4, "X"), + (0x104D8, "V"), + (0x104FC, "X"), + (0x10500, "V"), + (0x10528, "X"), + (0x10530, "V"), + (0x10564, "X"), + (0x1056F, "V"), + (0x10570, "M", "𐖗"), + (0x10571, "M", "𐖘"), + (0x10572, "M", "𐖙"), + (0x10573, "M", "𐖚"), + (0x10574, "M", "𐖛"), + (0x10575, "M", "𐖜"), + (0x10576, "M", "𐖝"), + (0x10577, "M", "𐖞"), + (0x10578, "M", "𐖟"), + (0x10579, "M", "𐖠"), + (0x1057A, "M", "𐖡"), + (0x1057B, "X"), + (0x1057C, "M", "𐖣"), + (0x1057D, "M", "𐖤"), + (0x1057E, "M", "𐖥"), + (0x1057F, "M", "𐖦"), + (0x10580, "M", "𐖧"), + (0x10581, "M", "𐖨"), + (0x10582, "M", "𐖩"), + (0x10583, "M", "𐖪"), + (0x10584, "M", "𐖫"), + (0x10585, "M", "𐖬"), + (0x10586, "M", "𐖭"), + (0x10587, "M", "𐖮"), + (0x10588, "M", "𐖯"), + (0x10589, "M", "𐖰"), + (0x1058A, "M", "𐖱"), + (0x1058B, "X"), + (0x1058C, "M", "𐖳"), + (0x1058D, "M", "𐖴"), + (0x1058E, "M", "𐖵"), + (0x1058F, "M", "𐖶"), + (0x10590, "M", "𐖷"), + (0x10591, "M", "𐖸"), + (0x10592, "M", "𐖹"), + (0x10593, "X"), + (0x10594, "M", "𐖻"), + (0x10595, "M", "𐖼"), + (0x10596, "X"), + (0x10597, "V"), + (0x105A2, "X"), + (0x105A3, "V"), + (0x105B2, "X"), + (0x105B3, "V"), + (0x105BA, "X"), + (0x105BB, "V"), + (0x105BD, "X"), + (0x105C0, "V"), + (0x105F4, "X"), + (0x10600, "V"), + (0x10737, "X"), + (0x10740, "V"), + (0x10756, "X"), + (0x10760, "V"), + (0x10768, "X"), + (0x10780, "V"), + (0x10781, "M", "ː"), + (0x10782, "M", "ˑ"), + (0x10783, "M", "æ"), + (0x10784, "M", "ʙ"), + (0x10785, "M", "ɓ"), + (0x10786, "X"), + (0x10787, "M", "ʣ"), + (0x10788, "M", "ꭦ"), + (0x10789, "M", "ʥ"), + (0x1078A, "M", "ʤ"), + (0x1078B, "M", "ɖ"), + (0x1078C, "M", "ɗ"), + (0x1078D, "M", "ᶑ"), + (0x1078E, "M", "ɘ"), + (0x1078F, "M", "ɞ"), + (0x10790, "M", "ʩ"), + (0x10791, "M", "ɤ"), + (0x10792, "M", "ɢ"), + (0x10793, "M", "ɠ"), + (0x10794, "M", "ʛ"), + (0x10795, "M", "ħ"), + (0x10796, "M", "ʜ"), + (0x10797, "M", "ɧ"), + (0x10798, "M", "ʄ"), + (0x10799, "M", "ʪ"), + (0x1079A, "M", "ʫ"), + (0x1079B, "M", "ɬ"), + (0x1079C, "M", "𝼄"), + (0x1079D, "M", "ꞎ"), + (0x1079E, "M", "ɮ"), + (0x1079F, "M", "𝼅"), + (0x107A0, "M", "ʎ"), + (0x107A1, "M", "𝼆"), + (0x107A2, "M", "ø"), + (0x107A3, "M", "ɶ"), + (0x107A4, "M", "ɷ"), + (0x107A5, "M", "q"), + (0x107A6, "M", "ɺ"), + (0x107A7, "M", "𝼈"), + (0x107A8, "M", "ɽ"), + (0x107A9, "M", "ɾ"), + (0x107AA, "M", "ʀ"), + (0x107AB, "M", "ʨ"), + (0x107AC, "M", "ʦ"), + (0x107AD, "M", "ꭧ"), + (0x107AE, "M", "ʧ"), + (0x107AF, "M", "ʈ"), + (0x107B0, "M", "ⱱ"), + (0x107B1, "X"), + (0x107B2, "M", "ʏ"), + (0x107B3, "M", "ʡ"), + (0x107B4, "M", "ʢ"), + (0x107B5, "M", "ʘ"), + (0x107B6, "M", "ǀ"), + (0x107B7, "M", "ǁ"), + (0x107B8, "M", "ǂ"), + (0x107B9, "M", "𝼊"), + (0x107BA, "M", "𝼞"), + (0x107BB, "X"), + (0x10800, "V"), + (0x10806, "X"), + (0x10808, "V"), + (0x10809, "X"), + (0x1080A, "V"), + (0x10836, "X"), + (0x10837, "V"), + (0x10839, "X"), + (0x1083C, "V"), + (0x1083D, "X"), + (0x1083F, "V"), + (0x10856, "X"), + (0x10857, "V"), + (0x1089F, "X"), + (0x108A7, "V"), + (0x108B0, "X"), + (0x108E0, "V"), + (0x108F3, "X"), + (0x108F4, "V"), + (0x108F6, "X"), + (0x108FB, "V"), + (0x1091C, "X"), + (0x1091F, "V"), + (0x1093A, "X"), + (0x1093F, "V"), + (0x1095A, "X"), + (0x10980, "V"), + (0x109B8, "X"), + (0x109BC, "V"), + (0x109D0, "X"), + (0x109D2, "V"), + (0x10A04, "X"), + (0x10A05, "V"), + (0x10A07, "X"), + (0x10A0C, "V"), + (0x10A14, "X"), + (0x10A15, "V"), + (0x10A18, "X"), + (0x10A19, "V"), + (0x10A36, "X"), + (0x10A38, "V"), + (0x10A3B, "X"), + (0x10A3F, "V"), + (0x10A49, "X"), + (0x10A50, "V"), + (0x10A59, "X"), + (0x10A60, "V"), + (0x10AA0, "X"), + (0x10AC0, "V"), + (0x10AE7, "X"), + (0x10AEB, "V"), + (0x10AF7, "X"), + (0x10B00, "V"), + (0x10B36, "X"), + (0x10B39, "V"), + (0x10B56, "X"), + (0x10B58, "V"), + (0x10B73, "X"), + (0x10B78, "V"), + (0x10B92, "X"), + (0x10B99, "V"), + (0x10B9D, "X"), + (0x10BA9, "V"), + (0x10BB0, "X"), + (0x10C00, "V"), + (0x10C49, "X"), + (0x10C80, "M", "𐳀"), + (0x10C81, "M", "𐳁"), + (0x10C82, "M", "𐳂"), + (0x10C83, "M", "𐳃"), + (0x10C84, "M", "𐳄"), + (0x10C85, "M", "𐳅"), + (0x10C86, "M", "𐳆"), + (0x10C87, "M", "𐳇"), + (0x10C88, "M", "𐳈"), + (0x10C89, "M", "𐳉"), + (0x10C8A, "M", "𐳊"), + (0x10C8B, "M", "𐳋"), + (0x10C8C, "M", "𐳌"), + (0x10C8D, "M", "𐳍"), + (0x10C8E, "M", "𐳎"), + (0x10C8F, "M", "𐳏"), + (0x10C90, "M", "𐳐"), + (0x10C91, "M", "𐳑"), + (0x10C92, "M", "𐳒"), + (0x10C93, "M", "𐳓"), + (0x10C94, "M", "𐳔"), + (0x10C95, "M", "𐳕"), + (0x10C96, "M", "𐳖"), + (0x10C97, "M", "𐳗"), + (0x10C98, "M", "𐳘"), + (0x10C99, "M", "𐳙"), + (0x10C9A, "M", "𐳚"), + (0x10C9B, "M", "𐳛"), + (0x10C9C, "M", "𐳜"), + (0x10C9D, "M", "𐳝"), + (0x10C9E, "M", "𐳞"), + (0x10C9F, "M", "𐳟"), + (0x10CA0, "M", "𐳠"), + (0x10CA1, "M", "𐳡"), + (0x10CA2, "M", "𐳢"), + (0x10CA3, "M", "𐳣"), + (0x10CA4, "M", "𐳤"), + (0x10CA5, "M", "𐳥"), + (0x10CA6, "M", "𐳦"), + (0x10CA7, "M", "𐳧"), + (0x10CA8, "M", "𐳨"), + (0x10CA9, "M", "𐳩"), + (0x10CAA, "M", "𐳪"), + (0x10CAB, "M", "𐳫"), + (0x10CAC, "M", "𐳬"), + (0x10CAD, "M", "𐳭"), + (0x10CAE, "M", "𐳮"), + (0x10CAF, "M", "𐳯"), + (0x10CB0, "M", "𐳰"), + (0x10CB1, "M", "𐳱"), + (0x10CB2, "M", "𐳲"), + (0x10CB3, "X"), + (0x10CC0, "V"), + (0x10CF3, "X"), + (0x10CFA, "V"), + (0x10D28, "X"), + (0x10D30, "V"), + (0x10D3A, "X"), + (0x10D40, "V"), + (0x10D50, "M", "𐵰"), + (0x10D51, "M", "𐵱"), + (0x10D52, "M", "𐵲"), + (0x10D53, "M", "𐵳"), + (0x10D54, "M", "𐵴"), + (0x10D55, "M", "𐵵"), + (0x10D56, "M", "𐵶"), + (0x10D57, "M", "𐵷"), + (0x10D58, "M", "𐵸"), + (0x10D59, "M", "𐵹"), + (0x10D5A, "M", "𐵺"), + (0x10D5B, "M", "𐵻"), + (0x10D5C, "M", "𐵼"), + (0x10D5D, "M", "𐵽"), + (0x10D5E, "M", "𐵾"), + (0x10D5F, "M", "𐵿"), + (0x10D60, "M", "𐶀"), + (0x10D61, "M", "𐶁"), + (0x10D62, "M", "𐶂"), + (0x10D63, "M", "𐶃"), + (0x10D64, "M", "𐶄"), + (0x10D65, "M", "𐶅"), + (0x10D66, "X"), + (0x10D69, "V"), + (0x10D86, "X"), + (0x10D8E, "V"), + (0x10D90, "X"), + (0x10E60, "V"), + (0x10E7F, "X"), + (0x10E80, "V"), + (0x10EAA, "X"), + (0x10EAB, "V"), + (0x10EAE, "X"), + (0x10EB0, "V"), + (0x10EB2, "X"), + (0x10EC2, "V"), + (0x10EC8, "X"), + (0x10ED0, "V"), + (0x10ED9, "X"), + (0x10EFA, "V"), + (0x10F28, "X"), + (0x10F30, "V"), + (0x10F5A, "X"), + (0x10F70, "V"), + (0x10F8A, "X"), + (0x10FB0, "V"), + (0x10FCC, "X"), + (0x10FE0, "V"), + (0x10FF7, "X"), + (0x11000, "V"), + (0x1104E, "X"), + (0x11052, "V"), + (0x11076, "X"), + (0x1107F, "V"), + (0x110BD, "X"), + (0x110BE, "V"), + (0x110C3, "X"), + (0x110D0, "V"), + (0x110E9, "X"), + (0x110F0, "V"), + (0x110FA, "X"), + (0x11100, "V"), + (0x11135, "X"), + (0x11136, "V"), + (0x11148, "X"), + (0x11150, "V"), + (0x11177, "X"), + (0x11180, "V"), + (0x111E0, "X"), + (0x111E1, "V"), + (0x111F5, "X"), + (0x11200, "V"), + (0x11212, "X"), + (0x11213, "V"), + (0x11242, "X"), + (0x11280, "V"), + (0x11287, "X"), + (0x11288, "V"), + (0x11289, "X"), + (0x1128A, "V"), + (0x1128E, "X"), + (0x1128F, "V"), + (0x1129E, "X"), + (0x1129F, "V"), + (0x112AA, "X"), + (0x112B0, "V"), + (0x112EB, "X"), + (0x112F0, "V"), + (0x112FA, "X"), + (0x11300, "V"), + (0x11304, "X"), + (0x11305, "V"), + (0x1130D, "X"), + (0x1130F, "V"), + (0x11311, "X"), + (0x11313, "V"), + (0x11329, "X"), + (0x1132A, "V"), + (0x11331, "X"), + (0x11332, "V"), + (0x11334, "X"), + (0x11335, "V"), + (0x1133A, "X"), + (0x1133B, "V"), + (0x11345, "X"), + (0x11347, "V"), + (0x11349, "X"), + (0x1134B, "V"), + (0x1134E, "X"), + (0x11350, "V"), + (0x11351, "X"), + (0x11357, "V"), + (0x11358, "X"), + (0x1135D, "V"), + (0x11364, "X"), + (0x11366, "V"), + (0x1136D, "X"), + (0x11370, "V"), + (0x11375, "X"), + (0x11380, "V"), + (0x1138A, "X"), + (0x1138B, "V"), + (0x1138C, "X"), + (0x1138E, "V"), + (0x1138F, "X"), + (0x11390, "V"), + (0x113B6, "X"), + (0x113B7, "V"), + (0x113C1, "X"), + (0x113C2, "V"), + (0x113C3, "X"), + (0x113C5, "V"), + (0x113C6, "X"), + (0x113C7, "V"), + (0x113CB, "X"), + (0x113CC, "V"), + (0x113D6, "X"), + (0x113D7, "V"), + (0x113D9, "X"), + (0x113E1, "V"), + (0x113E3, "X"), + (0x11400, "V"), + (0x1145C, "X"), + (0x1145D, "V"), + (0x11462, "X"), + (0x11480, "V"), + (0x114C8, "X"), + (0x114D0, "V"), + (0x114DA, "X"), + (0x11580, "V"), + (0x115B6, "X"), + (0x115B8, "V"), + (0x115DE, "X"), + (0x11600, "V"), + (0x11645, "X"), + (0x11650, "V"), + (0x1165A, "X"), + (0x11660, "V"), + (0x1166D, "X"), + (0x11680, "V"), + (0x116BA, "X"), + (0x116C0, "V"), + (0x116CA, "X"), + (0x116D0, "V"), + (0x116E4, "X"), + (0x11700, "V"), + (0x1171B, "X"), + (0x1171D, "V"), + (0x1172C, "X"), + (0x11730, "V"), + (0x11747, "X"), + (0x11800, "V"), + (0x1183C, "X"), + (0x118A0, "M", "𑣀"), + (0x118A1, "M", "𑣁"), + (0x118A2, "M", "𑣂"), + (0x118A3, "M", "𑣃"), + (0x118A4, "M", "𑣄"), + (0x118A5, "M", "𑣅"), + (0x118A6, "M", "𑣆"), + (0x118A7, "M", "𑣇"), + (0x118A8, "M", "𑣈"), + (0x118A9, "M", "𑣉"), + (0x118AA, "M", "𑣊"), + (0x118AB, "M", "𑣋"), + (0x118AC, "M", "𑣌"), + (0x118AD, "M", "𑣍"), + (0x118AE, "M", "𑣎"), + (0x118AF, "M", "𑣏"), + (0x118B0, "M", "𑣐"), + (0x118B1, "M", "𑣑"), + (0x118B2, "M", "𑣒"), + (0x118B3, "M", "𑣓"), + (0x118B4, "M", "𑣔"), + (0x118B5, "M", "𑣕"), + (0x118B6, "M", "𑣖"), + (0x118B7, "M", "𑣗"), + (0x118B8, "M", "𑣘"), + (0x118B9, "M", "𑣙"), + (0x118BA, "M", "𑣚"), + (0x118BB, "M", "𑣛"), + (0x118BC, "M", "𑣜"), + (0x118BD, "M", "𑣝"), + (0x118BE, "M", "𑣞"), + (0x118BF, "M", "𑣟"), + (0x118C0, "V"), + (0x118F3, "X"), + (0x118FF, "V"), + (0x11907, "X"), + (0x11909, "V"), + (0x1190A, "X"), + (0x1190C, "V"), + (0x11914, "X"), + (0x11915, "V"), + (0x11917, "X"), + (0x11918, "V"), + (0x11936, "X"), + (0x11937, "V"), + (0x11939, "X"), + (0x1193B, "V"), + (0x11947, "X"), + (0x11950, "V"), + (0x1195A, "X"), + (0x119A0, "V"), + (0x119A8, "X"), + (0x119AA, "V"), + (0x119D8, "X"), + (0x119DA, "V"), + (0x119E5, "X"), + (0x11A00, "V"), + (0x11A48, "X"), + (0x11A50, "V"), + (0x11AA3, "X"), + (0x11AB0, "V"), + (0x11AF9, "X"), + (0x11B00, "V"), + (0x11B0A, "X"), + (0x11B60, "V"), + (0x11B68, "X"), + (0x11BC0, "V"), + (0x11BE2, "X"), + (0x11BF0, "V"), + (0x11BFA, "X"), + (0x11C00, "V"), + (0x11C09, "X"), + (0x11C0A, "V"), + (0x11C37, "X"), + (0x11C38, "V"), + (0x11C46, "X"), + (0x11C50, "V"), + (0x11C6D, "X"), + (0x11C70, "V"), + (0x11C90, "X"), + (0x11C92, "V"), + (0x11CA8, "X"), + (0x11CA9, "V"), + (0x11CB7, "X"), + (0x11D00, "V"), + (0x11D07, "X"), + (0x11D08, "V"), + (0x11D0A, "X"), + (0x11D0B, "V"), + (0x11D37, "X"), + (0x11D3A, "V"), + (0x11D3B, "X"), + (0x11D3C, "V"), + (0x11D3E, "X"), + (0x11D3F, "V"), + (0x11D48, "X"), + (0x11D50, "V"), + (0x11D5A, "X"), + (0x11D60, "V"), + (0x11D66, "X"), + (0x11D67, "V"), + (0x11D69, "X"), + (0x11D6A, "V"), + (0x11D8F, "X"), + (0x11D90, "V"), + (0x11D92, "X"), + (0x11D93, "V"), + (0x11D99, "X"), + (0x11DA0, "V"), + (0x11DAA, "X"), + (0x11DB0, "V"), + (0x11DDC, "X"), + (0x11DE0, "V"), + (0x11DEA, "X"), + (0x11EE0, "V"), + (0x11EF9, "X"), + (0x11F00, "V"), + (0x11F11, "X"), + (0x11F12, "V"), + (0x11F3B, "X"), + (0x11F3E, "V"), + (0x11F5B, "X"), + (0x11FB0, "V"), + (0x11FB1, "X"), + (0x11FC0, "V"), + (0x11FF2, "X"), + (0x11FFF, "V"), + (0x1239A, "X"), + (0x12400, "V"), + (0x1246F, "X"), + (0x12470, "V"), + (0x12475, "X"), + (0x12480, "V"), + (0x12544, "X"), + (0x12F90, "V"), + (0x12FF3, "X"), + (0x13000, "V"), + (0x13430, "X"), + (0x13440, "V"), + (0x13456, "X"), + (0x13460, "V"), + (0x143FB, "X"), + (0x14400, "V"), + (0x14647, "X"), + (0x16100, "V"), + (0x1613A, "X"), + (0x16800, "V"), + (0x16A39, "X"), + (0x16A40, "V"), + (0x16A5F, "X"), + (0x16A60, "V"), + (0x16A6A, "X"), + (0x16A6E, "V"), + (0x16ABF, "X"), + (0x16AC0, "V"), + (0x16ACA, "X"), + (0x16AD0, "V"), + (0x16AEE, "X"), + (0x16AF0, "V"), + (0x16AF6, "X"), + (0x16B00, "V"), + (0x16B46, "X"), + (0x16B50, "V"), + (0x16B5A, "X"), + (0x16B5B, "V"), + (0x16B62, "X"), + (0x16B63, "V"), + (0x16B78, "X"), + (0x16B7D, "V"), + (0x16B90, "X"), + (0x16D40, "V"), + (0x16D7A, "X"), + (0x16E40, "M", "𖹠"), + (0x16E41, "M", "𖹡"), + (0x16E42, "M", "𖹢"), + (0x16E43, "M", "𖹣"), + (0x16E44, "M", "𖹤"), + (0x16E45, "M", "𖹥"), + (0x16E46, "M", "𖹦"), + (0x16E47, "M", "𖹧"), + (0x16E48, "M", "𖹨"), + (0x16E49, "M", "𖹩"), + (0x16E4A, "M", "𖹪"), + (0x16E4B, "M", "𖹫"), + (0x16E4C, "M", "𖹬"), + (0x16E4D, "M", "𖹭"), + (0x16E4E, "M", "𖹮"), + (0x16E4F, "M", "𖹯"), + (0x16E50, "M", "𖹰"), + (0x16E51, "M", "𖹱"), + (0x16E52, "M", "𖹲"), + (0x16E53, "M", "𖹳"), + (0x16E54, "M", "𖹴"), + (0x16E55, "M", "𖹵"), + (0x16E56, "M", "𖹶"), + (0x16E57, "M", "𖹷"), + (0x16E58, "M", "𖹸"), + (0x16E59, "M", "𖹹"), + (0x16E5A, "M", "𖹺"), + (0x16E5B, "M", "𖹻"), + (0x16E5C, "M", "𖹼"), + (0x16E5D, "M", "𖹽"), + (0x16E5E, "M", "𖹾"), + (0x16E5F, "M", "𖹿"), + (0x16E60, "V"), + (0x16E9B, "X"), + (0x16EA0, "M", "𖺻"), + (0x16EA1, "M", "𖺼"), + (0x16EA2, "M", "𖺽"), + (0x16EA3, "M", "𖺾"), + (0x16EA4, "M", "𖺿"), + (0x16EA5, "M", "𖻀"), + (0x16EA6, "M", "𖻁"), + (0x16EA7, "M", "𖻂"), + (0x16EA8, "M", "𖻃"), + (0x16EA9, "M", "𖻄"), + (0x16EAA, "M", "𖻅"), + (0x16EAB, "M", "𖻆"), + (0x16EAC, "M", "𖻇"), + (0x16EAD, "M", "𖻈"), + (0x16EAE, "M", "𖻉"), + (0x16EAF, "M", "𖻊"), + (0x16EB0, "M", "𖻋"), + (0x16EB1, "M", "𖻌"), + (0x16EB2, "M", "𖻍"), + (0x16EB3, "M", "𖻎"), + (0x16EB4, "M", "𖻏"), + (0x16EB5, "M", "𖻐"), + (0x16EB6, "M", "𖻑"), + (0x16EB7, "M", "𖻒"), + (0x16EB8, "M", "𖻓"), + (0x16EB9, "X"), + (0x16EBB, "V"), + (0x16ED4, "X"), + (0x16F00, "V"), + (0x16F4B, "X"), + (0x16F4F, "V"), + (0x16F88, "X"), + (0x16F8F, "V"), + (0x16FA0, "X"), + (0x16FE0, "V"), + (0x16FE5, "X"), + (0x16FF0, "V"), + (0x16FF7, "X"), + (0x17000, "V"), + (0x18CD6, "X"), + (0x18CFF, "V"), + (0x18D1F, "X"), + (0x18D80, "V"), + (0x18DF3, "X"), + (0x1AFF0, "V"), + (0x1AFF4, "X"), + (0x1AFF5, "V"), + (0x1AFFC, "X"), + (0x1AFFD, "V"), + (0x1AFFF, "X"), + (0x1B000, "V"), + (0x1B123, "X"), + (0x1B132, "V"), + (0x1B133, "X"), + (0x1B150, "V"), + (0x1B153, "X"), + (0x1B155, "V"), + (0x1B156, "X"), + (0x1B164, "V"), + (0x1B168, "X"), + (0x1B170, "V"), + (0x1B2FC, "X"), + (0x1BC00, "V"), + (0x1BC6B, "X"), + (0x1BC70, "V"), + (0x1BC7D, "X"), + (0x1BC80, "V"), + (0x1BC89, "X"), + (0x1BC90, "V"), + (0x1BC9A, "X"), + (0x1BC9C, "V"), + (0x1BCA0, "I"), + (0x1BCA4, "X"), + (0x1CC00, "V"), + (0x1CCD6, "M", "a"), + (0x1CCD7, "M", "b"), + (0x1CCD8, "M", "c"), + (0x1CCD9, "M", "d"), + (0x1CCDA, "M", "e"), + (0x1CCDB, "M", "f"), + (0x1CCDC, "M", "g"), + (0x1CCDD, "M", "h"), + (0x1CCDE, "M", "i"), + (0x1CCDF, "M", "j"), + (0x1CCE0, "M", "k"), + (0x1CCE1, "M", "l"), + (0x1CCE2, "M", "m"), + (0x1CCE3, "M", "n"), + (0x1CCE4, "M", "o"), + (0x1CCE5, "M", "p"), + (0x1CCE6, "M", "q"), + (0x1CCE7, "M", "r"), + (0x1CCE8, "M", "s"), + (0x1CCE9, "M", "t"), + (0x1CCEA, "M", "u"), + (0x1CCEB, "M", "v"), + (0x1CCEC, "M", "w"), + (0x1CCED, "M", "x"), + (0x1CCEE, "M", "y"), + (0x1CCEF, "M", "z"), + (0x1CCF0, "M", "0"), + (0x1CCF1, "M", "1"), + (0x1CCF2, "M", "2"), + (0x1CCF3, "M", "3"), + (0x1CCF4, "M", "4"), + (0x1CCF5, "M", "5"), + (0x1CCF6, "M", "6"), + (0x1CCF7, "M", "7"), + (0x1CCF8, "M", "8"), + (0x1CCF9, "M", "9"), + (0x1CCFA, "V"), + (0x1CCFD, "X"), + (0x1CD00, "V"), + (0x1CEB4, "X"), + (0x1CEBA, "V"), + (0x1CED1, "X"), + (0x1CEE0, "V"), + (0x1CEF1, "X"), + (0x1CF00, "V"), + (0x1CF2E, "X"), + (0x1CF30, "V"), + (0x1CF47, "X"), + (0x1CF50, "V"), + (0x1CFC4, "X"), + (0x1D000, "V"), + (0x1D0F6, "X"), + (0x1D100, "V"), + (0x1D127, "X"), + (0x1D129, "V"), + (0x1D15E, "M", "𝅗𝅥"), + (0x1D15F, "M", "𝅘𝅥"), + (0x1D160, "M", "𝅘𝅥𝅮"), + (0x1D161, "M", "𝅘𝅥𝅯"), + (0x1D162, "M", "𝅘𝅥𝅰"), + (0x1D163, "M", "𝅘𝅥𝅱"), + (0x1D164, "M", "𝅘𝅥𝅲"), + (0x1D165, "V"), + (0x1D173, "I"), + (0x1D17B, "V"), + (0x1D1BB, "M", "𝆹𝅥"), + (0x1D1BC, "M", "𝆺𝅥"), + (0x1D1BD, "M", "𝆹𝅥𝅮"), + (0x1D1BE, "M", "𝆺𝅥𝅮"), + (0x1D1BF, "M", "𝆹𝅥𝅯"), + (0x1D1C0, "M", "𝆺𝅥𝅯"), + (0x1D1C1, "V"), + (0x1D1EB, "X"), + (0x1D200, "V"), + (0x1D246, "X"), + (0x1D2C0, "V"), + (0x1D2D4, "X"), + (0x1D2E0, "V"), + (0x1D2F4, "X"), + (0x1D300, "V"), + (0x1D357, "X"), + (0x1D360, "V"), + (0x1D379, "X"), + (0x1D400, "M", "a"), + (0x1D401, "M", "b"), + (0x1D402, "M", "c"), + (0x1D403, "M", "d"), + (0x1D404, "M", "e"), + (0x1D405, "M", "f"), + (0x1D406, "M", "g"), + (0x1D407, "M", "h"), + (0x1D408, "M", "i"), + (0x1D409, "M", "j"), + (0x1D40A, "M", "k"), + (0x1D40B, "M", "l"), + (0x1D40C, "M", "m"), + (0x1D40D, "M", "n"), + (0x1D40E, "M", "o"), + (0x1D40F, "M", "p"), + (0x1D410, "M", "q"), + (0x1D411, "M", "r"), + (0x1D412, "M", "s"), + (0x1D413, "M", "t"), + (0x1D414, "M", "u"), + (0x1D415, "M", "v"), + (0x1D416, "M", "w"), + (0x1D417, "M", "x"), + (0x1D418, "M", "y"), + (0x1D419, "M", "z"), + (0x1D41A, "M", "a"), + (0x1D41B, "M", "b"), + (0x1D41C, "M", "c"), + (0x1D41D, "M", "d"), + (0x1D41E, "M", "e"), + (0x1D41F, "M", "f"), + (0x1D420, "M", "g"), + (0x1D421, "M", "h"), + (0x1D422, "M", "i"), + (0x1D423, "M", "j"), + (0x1D424, "M", "k"), + (0x1D425, "M", "l"), + (0x1D426, "M", "m"), + (0x1D427, "M", "n"), + (0x1D428, "M", "o"), + (0x1D429, "M", "p"), + (0x1D42A, "M", "q"), + (0x1D42B, "M", "r"), + (0x1D42C, "M", "s"), + (0x1D42D, "M", "t"), + (0x1D42E, "M", "u"), + (0x1D42F, "M", "v"), + (0x1D430, "M", "w"), + (0x1D431, "M", "x"), + (0x1D432, "M", "y"), + (0x1D433, "M", "z"), + (0x1D434, "M", "a"), + (0x1D435, "M", "b"), + (0x1D436, "M", "c"), + (0x1D437, "M", "d"), + (0x1D438, "M", "e"), + (0x1D439, "M", "f"), + (0x1D43A, "M", "g"), + (0x1D43B, "M", "h"), + (0x1D43C, "M", "i"), + (0x1D43D, "M", "j"), + (0x1D43E, "M", "k"), + (0x1D43F, "M", "l"), + (0x1D440, "M", "m"), + (0x1D441, "M", "n"), + (0x1D442, "M", "o"), + (0x1D443, "M", "p"), + (0x1D444, "M", "q"), + (0x1D445, "M", "r"), + (0x1D446, "M", "s"), + (0x1D447, "M", "t"), + (0x1D448, "M", "u"), + (0x1D449, "M", "v"), + (0x1D44A, "M", "w"), + (0x1D44B, "M", "x"), + (0x1D44C, "M", "y"), + (0x1D44D, "M", "z"), + (0x1D44E, "M", "a"), + (0x1D44F, "M", "b"), + (0x1D450, "M", "c"), + (0x1D451, "M", "d"), + (0x1D452, "M", "e"), + (0x1D453, "M", "f"), + (0x1D454, "M", "g"), + (0x1D455, "X"), + (0x1D456, "M", "i"), + (0x1D457, "M", "j"), + (0x1D458, "M", "k"), + (0x1D459, "M", "l"), + (0x1D45A, "M", "m"), + (0x1D45B, "M", "n"), + (0x1D45C, "M", "o"), + (0x1D45D, "M", "p"), + (0x1D45E, "M", "q"), + (0x1D45F, "M", "r"), + (0x1D460, "M", "s"), + (0x1D461, "M", "t"), + (0x1D462, "M", "u"), + (0x1D463, "M", "v"), + (0x1D464, "M", "w"), + (0x1D465, "M", "x"), + (0x1D466, "M", "y"), + (0x1D467, "M", "z"), + (0x1D468, "M", "a"), + (0x1D469, "M", "b"), + (0x1D46A, "M", "c"), + (0x1D46B, "M", "d"), + (0x1D46C, "M", "e"), + (0x1D46D, "M", "f"), + (0x1D46E, "M", "g"), + (0x1D46F, "M", "h"), + (0x1D470, "M", "i"), + (0x1D471, "M", "j"), + (0x1D472, "M", "k"), + (0x1D473, "M", "l"), + (0x1D474, "M", "m"), + (0x1D475, "M", "n"), + (0x1D476, "M", "o"), + (0x1D477, "M", "p"), + (0x1D478, "M", "q"), + (0x1D479, "M", "r"), + (0x1D47A, "M", "s"), + (0x1D47B, "M", "t"), + (0x1D47C, "M", "u"), + (0x1D47D, "M", "v"), + (0x1D47E, "M", "w"), + (0x1D47F, "M", "x"), + (0x1D480, "M", "y"), + (0x1D481, "M", "z"), + (0x1D482, "M", "a"), + (0x1D483, "M", "b"), + (0x1D484, "M", "c"), + (0x1D485, "M", "d"), + (0x1D486, "M", "e"), + (0x1D487, "M", "f"), + (0x1D488, "M", "g"), + (0x1D489, "M", "h"), + (0x1D48A, "M", "i"), + (0x1D48B, "M", "j"), + (0x1D48C, "M", "k"), + (0x1D48D, "M", "l"), + (0x1D48E, "M", "m"), + (0x1D48F, "M", "n"), + (0x1D490, "M", "o"), + (0x1D491, "M", "p"), + (0x1D492, "M", "q"), + (0x1D493, "M", "r"), + (0x1D494, "M", "s"), + (0x1D495, "M", "t"), + (0x1D496, "M", "u"), + (0x1D497, "M", "v"), + (0x1D498, "M", "w"), + (0x1D499, "M", "x"), + (0x1D49A, "M", "y"), + (0x1D49B, "M", "z"), + (0x1D49C, "M", "a"), + (0x1D49D, "X"), + (0x1D49E, "M", "c"), + (0x1D49F, "M", "d"), + (0x1D4A0, "X"), + (0x1D4A2, "M", "g"), + (0x1D4A3, "X"), + (0x1D4A5, "M", "j"), + (0x1D4A6, "M", "k"), + (0x1D4A7, "X"), + (0x1D4A9, "M", "n"), + (0x1D4AA, "M", "o"), + (0x1D4AB, "M", "p"), + (0x1D4AC, "M", "q"), + (0x1D4AD, "X"), + (0x1D4AE, "M", "s"), + (0x1D4AF, "M", "t"), + (0x1D4B0, "M", "u"), + (0x1D4B1, "M", "v"), + (0x1D4B2, "M", "w"), + (0x1D4B3, "M", "x"), + (0x1D4B4, "M", "y"), + (0x1D4B5, "M", "z"), + (0x1D4B6, "M", "a"), + (0x1D4B7, "M", "b"), + (0x1D4B8, "M", "c"), + (0x1D4B9, "M", "d"), + (0x1D4BA, "X"), + (0x1D4BB, "M", "f"), + (0x1D4BC, "X"), + (0x1D4BD, "M", "h"), + (0x1D4BE, "M", "i"), + (0x1D4BF, "M", "j"), + (0x1D4C0, "M", "k"), + (0x1D4C1, "M", "l"), + (0x1D4C2, "M", "m"), + (0x1D4C3, "M", "n"), + (0x1D4C4, "X"), + (0x1D4C5, "M", "p"), + (0x1D4C6, "M", "q"), + (0x1D4C7, "M", "r"), + (0x1D4C8, "M", "s"), + (0x1D4C9, "M", "t"), + (0x1D4CA, "M", "u"), + (0x1D4CB, "M", "v"), + (0x1D4CC, "M", "w"), + (0x1D4CD, "M", "x"), + (0x1D4CE, "M", "y"), + (0x1D4CF, "M", "z"), + (0x1D4D0, "M", "a"), + (0x1D4D1, "M", "b"), + (0x1D4D2, "M", "c"), + (0x1D4D3, "M", "d"), + (0x1D4D4, "M", "e"), + (0x1D4D5, "M", "f"), + (0x1D4D6, "M", "g"), + (0x1D4D7, "M", "h"), + (0x1D4D8, "M", "i"), + (0x1D4D9, "M", "j"), + (0x1D4DA, "M", "k"), + (0x1D4DB, "M", "l"), + (0x1D4DC, "M", "m"), + (0x1D4DD, "M", "n"), + (0x1D4DE, "M", "o"), + (0x1D4DF, "M", "p"), + (0x1D4E0, "M", "q"), + (0x1D4E1, "M", "r"), + (0x1D4E2, "M", "s"), + (0x1D4E3, "M", "t"), + (0x1D4E4, "M", "u"), + (0x1D4E5, "M", "v"), + (0x1D4E6, "M", "w"), + (0x1D4E7, "M", "x"), + (0x1D4E8, "M", "y"), + (0x1D4E9, "M", "z"), + (0x1D4EA, "M", "a"), + (0x1D4EB, "M", "b"), + (0x1D4EC, "M", "c"), + (0x1D4ED, "M", "d"), + (0x1D4EE, "M", "e"), + (0x1D4EF, "M", "f"), + (0x1D4F0, "M", "g"), + (0x1D4F1, "M", "h"), + (0x1D4F2, "M", "i"), + (0x1D4F3, "M", "j"), + (0x1D4F4, "M", "k"), + (0x1D4F5, "M", "l"), + (0x1D4F6, "M", "m"), + (0x1D4F7, "M", "n"), + (0x1D4F8, "M", "o"), + (0x1D4F9, "M", "p"), + (0x1D4FA, "M", "q"), + (0x1D4FB, "M", "r"), + (0x1D4FC, "M", "s"), + (0x1D4FD, "M", "t"), + (0x1D4FE, "M", "u"), + (0x1D4FF, "M", "v"), + (0x1D500, "M", "w"), + (0x1D501, "M", "x"), + (0x1D502, "M", "y"), + (0x1D503, "M", "z"), + (0x1D504, "M", "a"), + (0x1D505, "M", "b"), + (0x1D506, "X"), + (0x1D507, "M", "d"), + (0x1D508, "M", "e"), + (0x1D509, "M", "f"), + (0x1D50A, "M", "g"), + (0x1D50B, "X"), + (0x1D50D, "M", "j"), + (0x1D50E, "M", "k"), + (0x1D50F, "M", "l"), + (0x1D510, "M", "m"), + (0x1D511, "M", "n"), + (0x1D512, "M", "o"), + (0x1D513, "M", "p"), + (0x1D514, "M", "q"), + (0x1D515, "X"), + (0x1D516, "M", "s"), + (0x1D517, "M", "t"), + (0x1D518, "M", "u"), + (0x1D519, "M", "v"), + (0x1D51A, "M", "w"), + (0x1D51B, "M", "x"), + (0x1D51C, "M", "y"), + (0x1D51D, "X"), + (0x1D51E, "M", "a"), + (0x1D51F, "M", "b"), + (0x1D520, "M", "c"), + (0x1D521, "M", "d"), + (0x1D522, "M", "e"), + (0x1D523, "M", "f"), + (0x1D524, "M", "g"), + (0x1D525, "M", "h"), + (0x1D526, "M", "i"), + (0x1D527, "M", "j"), + (0x1D528, "M", "k"), + (0x1D529, "M", "l"), + (0x1D52A, "M", "m"), + (0x1D52B, "M", "n"), + (0x1D52C, "M", "o"), + (0x1D52D, "M", "p"), + (0x1D52E, "M", "q"), + (0x1D52F, "M", "r"), + (0x1D530, "M", "s"), + (0x1D531, "M", "t"), + (0x1D532, "M", "u"), + (0x1D533, "M", "v"), + (0x1D534, "M", "w"), + (0x1D535, "M", "x"), + (0x1D536, "M", "y"), + (0x1D537, "M", "z"), + (0x1D538, "M", "a"), + (0x1D539, "M", "b"), + (0x1D53A, "X"), + (0x1D53B, "M", "d"), + (0x1D53C, "M", "e"), + (0x1D53D, "M", "f"), + (0x1D53E, "M", "g"), + (0x1D53F, "X"), + (0x1D540, "M", "i"), + (0x1D541, "M", "j"), + (0x1D542, "M", "k"), + (0x1D543, "M", "l"), + (0x1D544, "M", "m"), + (0x1D545, "X"), + (0x1D546, "M", "o"), + (0x1D547, "X"), + (0x1D54A, "M", "s"), + (0x1D54B, "M", "t"), + (0x1D54C, "M", "u"), + (0x1D54D, "M", "v"), + (0x1D54E, "M", "w"), + (0x1D54F, "M", "x"), + (0x1D550, "M", "y"), + (0x1D551, "X"), + (0x1D552, "M", "a"), + (0x1D553, "M", "b"), + (0x1D554, "M", "c"), + (0x1D555, "M", "d"), + (0x1D556, "M", "e"), + (0x1D557, "M", "f"), + (0x1D558, "M", "g"), + (0x1D559, "M", "h"), + (0x1D55A, "M", "i"), + (0x1D55B, "M", "j"), + (0x1D55C, "M", "k"), + (0x1D55D, "M", "l"), + (0x1D55E, "M", "m"), + (0x1D55F, "M", "n"), + (0x1D560, "M", "o"), + (0x1D561, "M", "p"), + (0x1D562, "M", "q"), + (0x1D563, "M", "r"), + (0x1D564, "M", "s"), + (0x1D565, "M", "t"), + (0x1D566, "M", "u"), + (0x1D567, "M", "v"), + (0x1D568, "M", "w"), + (0x1D569, "M", "x"), + (0x1D56A, "M", "y"), + (0x1D56B, "M", "z"), + (0x1D56C, "M", "a"), + (0x1D56D, "M", "b"), + (0x1D56E, "M", "c"), + (0x1D56F, "M", "d"), + (0x1D570, "M", "e"), + (0x1D571, "M", "f"), + (0x1D572, "M", "g"), + (0x1D573, "M", "h"), + (0x1D574, "M", "i"), + (0x1D575, "M", "j"), + (0x1D576, "M", "k"), + (0x1D577, "M", "l"), + (0x1D578, "M", "m"), + (0x1D579, "M", "n"), + (0x1D57A, "M", "o"), + (0x1D57B, "M", "p"), + (0x1D57C, "M", "q"), + (0x1D57D, "M", "r"), + (0x1D57E, "M", "s"), + (0x1D57F, "M", "t"), + (0x1D580, "M", "u"), + (0x1D581, "M", "v"), + (0x1D582, "M", "w"), + (0x1D583, "M", "x"), + (0x1D584, "M", "y"), + (0x1D585, "M", "z"), + (0x1D586, "M", "a"), + (0x1D587, "M", "b"), + (0x1D588, "M", "c"), + (0x1D589, "M", "d"), + (0x1D58A, "M", "e"), + (0x1D58B, "M", "f"), + (0x1D58C, "M", "g"), + (0x1D58D, "M", "h"), + (0x1D58E, "M", "i"), + (0x1D58F, "M", "j"), + (0x1D590, "M", "k"), + (0x1D591, "M", "l"), + (0x1D592, "M", "m"), + (0x1D593, "M", "n"), + (0x1D594, "M", "o"), + (0x1D595, "M", "p"), + (0x1D596, "M", "q"), + (0x1D597, "M", "r"), + (0x1D598, "M", "s"), + (0x1D599, "M", "t"), + (0x1D59A, "M", "u"), + (0x1D59B, "M", "v"), + (0x1D59C, "M", "w"), + (0x1D59D, "M", "x"), + (0x1D59E, "M", "y"), + (0x1D59F, "M", "z"), + (0x1D5A0, "M", "a"), + (0x1D5A1, "M", "b"), + (0x1D5A2, "M", "c"), + (0x1D5A3, "M", "d"), + (0x1D5A4, "M", "e"), + (0x1D5A5, "M", "f"), + (0x1D5A6, "M", "g"), + (0x1D5A7, "M", "h"), + (0x1D5A8, "M", "i"), + (0x1D5A9, "M", "j"), + (0x1D5AA, "M", "k"), + (0x1D5AB, "M", "l"), + (0x1D5AC, "M", "m"), + (0x1D5AD, "M", "n"), + (0x1D5AE, "M", "o"), + (0x1D5AF, "M", "p"), + (0x1D5B0, "M", "q"), + (0x1D5B1, "M", "r"), + (0x1D5B2, "M", "s"), + (0x1D5B3, "M", "t"), + (0x1D5B4, "M", "u"), + (0x1D5B5, "M", "v"), + (0x1D5B6, "M", "w"), + (0x1D5B7, "M", "x"), + (0x1D5B8, "M", "y"), + (0x1D5B9, "M", "z"), + (0x1D5BA, "M", "a"), + (0x1D5BB, "M", "b"), + (0x1D5BC, "M", "c"), + (0x1D5BD, "M", "d"), + (0x1D5BE, "M", "e"), + (0x1D5BF, "M", "f"), + (0x1D5C0, "M", "g"), + (0x1D5C1, "M", "h"), + (0x1D5C2, "M", "i"), + (0x1D5C3, "M", "j"), + (0x1D5C4, "M", "k"), + (0x1D5C5, "M", "l"), + (0x1D5C6, "M", "m"), + (0x1D5C7, "M", "n"), + (0x1D5C8, "M", "o"), + (0x1D5C9, "M", "p"), + (0x1D5CA, "M", "q"), + (0x1D5CB, "M", "r"), + (0x1D5CC, "M", "s"), + (0x1D5CD, "M", "t"), + (0x1D5CE, "M", "u"), + (0x1D5CF, "M", "v"), + (0x1D5D0, "M", "w"), + (0x1D5D1, "M", "x"), + (0x1D5D2, "M", "y"), + (0x1D5D3, "M", "z"), + (0x1D5D4, "M", "a"), + (0x1D5D5, "M", "b"), + (0x1D5D6, "M", "c"), + (0x1D5D7, "M", "d"), + (0x1D5D8, "M", "e"), + (0x1D5D9, "M", "f"), + (0x1D5DA, "M", "g"), + (0x1D5DB, "M", "h"), + (0x1D5DC, "M", "i"), + (0x1D5DD, "M", "j"), + (0x1D5DE, "M", "k"), + (0x1D5DF, "M", "l"), + (0x1D5E0, "M", "m"), + (0x1D5E1, "M", "n"), + (0x1D5E2, "M", "o"), + (0x1D5E3, "M", "p"), + (0x1D5E4, "M", "q"), + (0x1D5E5, "M", "r"), + (0x1D5E6, "M", "s"), + (0x1D5E7, "M", "t"), + (0x1D5E8, "M", "u"), + (0x1D5E9, "M", "v"), + (0x1D5EA, "M", "w"), + (0x1D5EB, "M", "x"), + (0x1D5EC, "M", "y"), + (0x1D5ED, "M", "z"), + (0x1D5EE, "M", "a"), + (0x1D5EF, "M", "b"), + (0x1D5F0, "M", "c"), + (0x1D5F1, "M", "d"), + (0x1D5F2, "M", "e"), + (0x1D5F3, "M", "f"), + (0x1D5F4, "M", "g"), + (0x1D5F5, "M", "h"), + (0x1D5F6, "M", "i"), + (0x1D5F7, "M", "j"), + (0x1D5F8, "M", "k"), + (0x1D5F9, "M", "l"), + (0x1D5FA, "M", "m"), + (0x1D5FB, "M", "n"), + (0x1D5FC, "M", "o"), + (0x1D5FD, "M", "p"), + (0x1D5FE, "M", "q"), + (0x1D5FF, "M", "r"), + (0x1D600, "M", "s"), + (0x1D601, "M", "t"), + (0x1D602, "M", "u"), + (0x1D603, "M", "v"), + (0x1D604, "M", "w"), + (0x1D605, "M", "x"), + (0x1D606, "M", "y"), + (0x1D607, "M", "z"), + (0x1D608, "M", "a"), + (0x1D609, "M", "b"), + (0x1D60A, "M", "c"), + (0x1D60B, "M", "d"), + (0x1D60C, "M", "e"), + (0x1D60D, "M", "f"), + (0x1D60E, "M", "g"), + (0x1D60F, "M", "h"), + (0x1D610, "M", "i"), + (0x1D611, "M", "j"), + (0x1D612, "M", "k"), + (0x1D613, "M", "l"), + (0x1D614, "M", "m"), + (0x1D615, "M", "n"), + (0x1D616, "M", "o"), + (0x1D617, "M", "p"), + (0x1D618, "M", "q"), + (0x1D619, "M", "r"), + (0x1D61A, "M", "s"), + (0x1D61B, "M", "t"), + (0x1D61C, "M", "u"), + (0x1D61D, "M", "v"), + (0x1D61E, "M", "w"), + (0x1D61F, "M", "x"), + (0x1D620, "M", "y"), + (0x1D621, "M", "z"), + (0x1D622, "M", "a"), + (0x1D623, "M", "b"), + (0x1D624, "M", "c"), + (0x1D625, "M", "d"), + (0x1D626, "M", "e"), + (0x1D627, "M", "f"), + (0x1D628, "M", "g"), + (0x1D629, "M", "h"), + (0x1D62A, "M", "i"), + (0x1D62B, "M", "j"), + (0x1D62C, "M", "k"), + (0x1D62D, "M", "l"), + (0x1D62E, "M", "m"), + (0x1D62F, "M", "n"), + (0x1D630, "M", "o"), + (0x1D631, "M", "p"), + (0x1D632, "M", "q"), + (0x1D633, "M", "r"), + (0x1D634, "M", "s"), + (0x1D635, "M", "t"), + (0x1D636, "M", "u"), + (0x1D637, "M", "v"), + (0x1D638, "M", "w"), + (0x1D639, "M", "x"), + (0x1D63A, "M", "y"), + (0x1D63B, "M", "z"), + (0x1D63C, "M", "a"), + (0x1D63D, "M", "b"), + (0x1D63E, "M", "c"), + (0x1D63F, "M", "d"), + (0x1D640, "M", "e"), + (0x1D641, "M", "f"), + (0x1D642, "M", "g"), + (0x1D643, "M", "h"), + (0x1D644, "M", "i"), + (0x1D645, "M", "j"), + (0x1D646, "M", "k"), + (0x1D647, "M", "l"), + (0x1D648, "M", "m"), + (0x1D649, "M", "n"), + (0x1D64A, "M", "o"), + (0x1D64B, "M", "p"), + (0x1D64C, "M", "q"), + (0x1D64D, "M", "r"), + (0x1D64E, "M", "s"), + (0x1D64F, "M", "t"), + (0x1D650, "M", "u"), + (0x1D651, "M", "v"), + (0x1D652, "M", "w"), + (0x1D653, "M", "x"), + (0x1D654, "M", "y"), + (0x1D655, "M", "z"), + (0x1D656, "M", "a"), + (0x1D657, "M", "b"), + (0x1D658, "M", "c"), + (0x1D659, "M", "d"), + (0x1D65A, "M", "e"), + (0x1D65B, "M", "f"), + (0x1D65C, "M", "g"), + (0x1D65D, "M", "h"), + (0x1D65E, "M", "i"), + (0x1D65F, "M", "j"), + (0x1D660, "M", "k"), + (0x1D661, "M", "l"), + (0x1D662, "M", "m"), + (0x1D663, "M", "n"), + (0x1D664, "M", "o"), + (0x1D665, "M", "p"), + (0x1D666, "M", "q"), + (0x1D667, "M", "r"), + (0x1D668, "M", "s"), + (0x1D669, "M", "t"), + (0x1D66A, "M", "u"), + (0x1D66B, "M", "v"), + (0x1D66C, "M", "w"), + (0x1D66D, "M", "x"), + (0x1D66E, "M", "y"), + (0x1D66F, "M", "z"), + (0x1D670, "M", "a"), + (0x1D671, "M", "b"), + (0x1D672, "M", "c"), + (0x1D673, "M", "d"), + (0x1D674, "M", "e"), + (0x1D675, "M", "f"), + (0x1D676, "M", "g"), + (0x1D677, "M", "h"), + (0x1D678, "M", "i"), + (0x1D679, "M", "j"), + (0x1D67A, "M", "k"), + (0x1D67B, "M", "l"), + (0x1D67C, "M", "m"), + (0x1D67D, "M", "n"), + (0x1D67E, "M", "o"), + (0x1D67F, "M", "p"), + (0x1D680, "M", "q"), + (0x1D681, "M", "r"), + (0x1D682, "M", "s"), + (0x1D683, "M", "t"), + (0x1D684, "M", "u"), + (0x1D685, "M", "v"), + (0x1D686, "M", "w"), + (0x1D687, "M", "x"), + (0x1D688, "M", "y"), + (0x1D689, "M", "z"), + (0x1D68A, "M", "a"), + (0x1D68B, "M", "b"), + (0x1D68C, "M", "c"), + (0x1D68D, "M", "d"), + (0x1D68E, "M", "e"), + (0x1D68F, "M", "f"), + (0x1D690, "M", "g"), + (0x1D691, "M", "h"), + (0x1D692, "M", "i"), + (0x1D693, "M", "j"), + (0x1D694, "M", "k"), + (0x1D695, "M", "l"), + (0x1D696, "M", "m"), + (0x1D697, "M", "n"), + (0x1D698, "M", "o"), + (0x1D699, "M", "p"), + (0x1D69A, "M", "q"), + (0x1D69B, "M", "r"), + (0x1D69C, "M", "s"), + (0x1D69D, "M", "t"), + (0x1D69E, "M", "u"), + (0x1D69F, "M", "v"), + (0x1D6A0, "M", "w"), + (0x1D6A1, "M", "x"), + (0x1D6A2, "M", "y"), + (0x1D6A3, "M", "z"), + (0x1D6A4, "M", "ı"), + (0x1D6A5, "M", "ȷ"), + (0x1D6A6, "X"), + (0x1D6A8, "M", "α"), + (0x1D6A9, "M", "β"), + (0x1D6AA, "M", "γ"), + (0x1D6AB, "M", "δ"), + (0x1D6AC, "M", "ε"), + (0x1D6AD, "M", "ζ"), + (0x1D6AE, "M", "η"), + (0x1D6AF, "M", "θ"), + (0x1D6B0, "M", "ι"), + (0x1D6B1, "M", "κ"), + (0x1D6B2, "M", "λ"), + (0x1D6B3, "M", "μ"), + (0x1D6B4, "M", "ν"), + (0x1D6B5, "M", "ξ"), + (0x1D6B6, "M", "ο"), + (0x1D6B7, "M", "π"), + (0x1D6B8, "M", "ρ"), + (0x1D6B9, "M", "θ"), + (0x1D6BA, "M", "σ"), + (0x1D6BB, "M", "τ"), + (0x1D6BC, "M", "υ"), + (0x1D6BD, "M", "φ"), + (0x1D6BE, "M", "χ"), + (0x1D6BF, "M", "ψ"), + (0x1D6C0, "M", "ω"), + (0x1D6C1, "M", "∇"), + (0x1D6C2, "M", "α"), + (0x1D6C3, "M", "β"), + (0x1D6C4, "M", "γ"), + (0x1D6C5, "M", "δ"), + (0x1D6C6, "M", "ε"), + (0x1D6C7, "M", "ζ"), + (0x1D6C8, "M", "η"), + (0x1D6C9, "M", "θ"), + (0x1D6CA, "M", "ι"), + (0x1D6CB, "M", "κ"), + (0x1D6CC, "M", "λ"), + (0x1D6CD, "M", "μ"), + (0x1D6CE, "M", "ν"), + (0x1D6CF, "M", "ξ"), + (0x1D6D0, "M", "ο"), + (0x1D6D1, "M", "π"), + (0x1D6D2, "M", "ρ"), + (0x1D6D3, "M", "σ"), + (0x1D6D5, "M", "τ"), + (0x1D6D6, "M", "υ"), + (0x1D6D7, "M", "φ"), + (0x1D6D8, "M", "χ"), + (0x1D6D9, "M", "ψ"), + (0x1D6DA, "M", "ω"), + (0x1D6DB, "M", "∂"), + (0x1D6DC, "M", "ε"), + (0x1D6DD, "M", "θ"), + (0x1D6DE, "M", "κ"), + (0x1D6DF, "M", "φ"), + (0x1D6E0, "M", "ρ"), + (0x1D6E1, "M", "π"), + (0x1D6E2, "M", "α"), + (0x1D6E3, "M", "β"), + (0x1D6E4, "M", "γ"), + (0x1D6E5, "M", "δ"), + (0x1D6E6, "M", "ε"), + (0x1D6E7, "M", "ζ"), + (0x1D6E8, "M", "η"), + (0x1D6E9, "M", "θ"), + (0x1D6EA, "M", "ι"), + (0x1D6EB, "M", "κ"), + (0x1D6EC, "M", "λ"), + (0x1D6ED, "M", "μ"), + (0x1D6EE, "M", "ν"), + (0x1D6EF, "M", "ξ"), + (0x1D6F0, "M", "ο"), + (0x1D6F1, "M", "π"), + (0x1D6F2, "M", "ρ"), + (0x1D6F3, "M", "θ"), + (0x1D6F4, "M", "σ"), + (0x1D6F5, "M", "τ"), + (0x1D6F6, "M", "υ"), + (0x1D6F7, "M", "φ"), + (0x1D6F8, "M", "χ"), + (0x1D6F9, "M", "ψ"), + (0x1D6FA, "M", "ω"), + (0x1D6FB, "M", "∇"), + (0x1D6FC, "M", "α"), + (0x1D6FD, "M", "β"), + (0x1D6FE, "M", "γ"), + (0x1D6FF, "M", "δ"), + (0x1D700, "M", "ε"), + (0x1D701, "M", "ζ"), + (0x1D702, "M", "η"), + (0x1D703, "M", "θ"), + (0x1D704, "M", "ι"), + (0x1D705, "M", "κ"), + (0x1D706, "M", "λ"), + (0x1D707, "M", "μ"), + (0x1D708, "M", "ν"), + (0x1D709, "M", "ξ"), + (0x1D70A, "M", "ο"), + (0x1D70B, "M", "π"), + (0x1D70C, "M", "ρ"), + (0x1D70D, "M", "σ"), + (0x1D70F, "M", "τ"), + (0x1D710, "M", "υ"), + (0x1D711, "M", "φ"), + (0x1D712, "M", "χ"), + (0x1D713, "M", "ψ"), + (0x1D714, "M", "ω"), + (0x1D715, "M", "∂"), + (0x1D716, "M", "ε"), + (0x1D717, "M", "θ"), + (0x1D718, "M", "κ"), + (0x1D719, "M", "φ"), + (0x1D71A, "M", "ρ"), + (0x1D71B, "M", "π"), + (0x1D71C, "M", "α"), + (0x1D71D, "M", "β"), + (0x1D71E, "M", "γ"), + (0x1D71F, "M", "δ"), + (0x1D720, "M", "ε"), + (0x1D721, "M", "ζ"), + (0x1D722, "M", "η"), + (0x1D723, "M", "θ"), + (0x1D724, "M", "ι"), + (0x1D725, "M", "κ"), + (0x1D726, "M", "λ"), + (0x1D727, "M", "μ"), + (0x1D728, "M", "ν"), + (0x1D729, "M", "ξ"), + (0x1D72A, "M", "ο"), + (0x1D72B, "M", "π"), + (0x1D72C, "M", "ρ"), + (0x1D72D, "M", "θ"), + (0x1D72E, "M", "σ"), + (0x1D72F, "M", "τ"), + (0x1D730, "M", "υ"), + (0x1D731, "M", "φ"), + (0x1D732, "M", "χ"), + (0x1D733, "M", "ψ"), + (0x1D734, "M", "ω"), + (0x1D735, "M", "∇"), + (0x1D736, "M", "α"), + (0x1D737, "M", "β"), + (0x1D738, "M", "γ"), + (0x1D739, "M", "δ"), + (0x1D73A, "M", "ε"), + (0x1D73B, "M", "ζ"), + (0x1D73C, "M", "η"), + (0x1D73D, "M", "θ"), + (0x1D73E, "M", "ι"), + (0x1D73F, "M", "κ"), + (0x1D740, "M", "λ"), + (0x1D741, "M", "μ"), + (0x1D742, "M", "ν"), + (0x1D743, "M", "ξ"), + (0x1D744, "M", "ο"), + (0x1D745, "M", "π"), + (0x1D746, "M", "ρ"), + (0x1D747, "M", "σ"), + (0x1D749, "M", "τ"), + (0x1D74A, "M", "υ"), + (0x1D74B, "M", "φ"), + (0x1D74C, "M", "χ"), + (0x1D74D, "M", "ψ"), + (0x1D74E, "M", "ω"), + (0x1D74F, "M", "∂"), + (0x1D750, "M", "ε"), + (0x1D751, "M", "θ"), + (0x1D752, "M", "κ"), + (0x1D753, "M", "φ"), + (0x1D754, "M", "ρ"), + (0x1D755, "M", "π"), + (0x1D756, "M", "α"), + (0x1D757, "M", "β"), + (0x1D758, "M", "γ"), + (0x1D759, "M", "δ"), + (0x1D75A, "M", "ε"), + (0x1D75B, "M", "ζ"), + (0x1D75C, "M", "η"), + (0x1D75D, "M", "θ"), + (0x1D75E, "M", "ι"), + (0x1D75F, "M", "κ"), + (0x1D760, "M", "λ"), + (0x1D761, "M", "μ"), + (0x1D762, "M", "ν"), + (0x1D763, "M", "ξ"), + (0x1D764, "M", "ο"), + (0x1D765, "M", "π"), + (0x1D766, "M", "ρ"), + (0x1D767, "M", "θ"), + (0x1D768, "M", "σ"), + (0x1D769, "M", "τ"), + (0x1D76A, "M", "υ"), + (0x1D76B, "M", "φ"), + (0x1D76C, "M", "χ"), + (0x1D76D, "M", "ψ"), + (0x1D76E, "M", "ω"), + (0x1D76F, "M", "∇"), + (0x1D770, "M", "α"), + (0x1D771, "M", "β"), + (0x1D772, "M", "γ"), + (0x1D773, "M", "δ"), + (0x1D774, "M", "ε"), + (0x1D775, "M", "ζ"), + (0x1D776, "M", "η"), + (0x1D777, "M", "θ"), + (0x1D778, "M", "ι"), + (0x1D779, "M", "κ"), + (0x1D77A, "M", "λ"), + (0x1D77B, "M", "μ"), + (0x1D77C, "M", "ν"), + (0x1D77D, "M", "ξ"), + (0x1D77E, "M", "ο"), + (0x1D77F, "M", "π"), + (0x1D780, "M", "ρ"), + (0x1D781, "M", "σ"), + (0x1D783, "M", "τ"), + (0x1D784, "M", "υ"), + (0x1D785, "M", "φ"), + (0x1D786, "M", "χ"), + (0x1D787, "M", "ψ"), + (0x1D788, "M", "ω"), + (0x1D789, "M", "∂"), + (0x1D78A, "M", "ε"), + (0x1D78B, "M", "θ"), + (0x1D78C, "M", "κ"), + (0x1D78D, "M", "φ"), + (0x1D78E, "M", "ρ"), + (0x1D78F, "M", "π"), + (0x1D790, "M", "α"), + (0x1D791, "M", "β"), + (0x1D792, "M", "γ"), + (0x1D793, "M", "δ"), + (0x1D794, "M", "ε"), + (0x1D795, "M", "ζ"), + (0x1D796, "M", "η"), + (0x1D797, "M", "θ"), + (0x1D798, "M", "ι"), + (0x1D799, "M", "κ"), + (0x1D79A, "M", "λ"), + (0x1D79B, "M", "μ"), + (0x1D79C, "M", "ν"), + (0x1D79D, "M", "ξ"), + (0x1D79E, "M", "ο"), + (0x1D79F, "M", "π"), + (0x1D7A0, "M", "ρ"), + (0x1D7A1, "M", "θ"), + (0x1D7A2, "M", "σ"), + (0x1D7A3, "M", "τ"), + (0x1D7A4, "M", "υ"), + (0x1D7A5, "M", "φ"), + (0x1D7A6, "M", "χ"), + (0x1D7A7, "M", "ψ"), + (0x1D7A8, "M", "ω"), + (0x1D7A9, "M", "∇"), + (0x1D7AA, "M", "α"), + (0x1D7AB, "M", "β"), + (0x1D7AC, "M", "γ"), + (0x1D7AD, "M", "δ"), + (0x1D7AE, "M", "ε"), + (0x1D7AF, "M", "ζ"), + (0x1D7B0, "M", "η"), + (0x1D7B1, "M", "θ"), + (0x1D7B2, "M", "ι"), + (0x1D7B3, "M", "κ"), + (0x1D7B4, "M", "λ"), + (0x1D7B5, "M", "μ"), + (0x1D7B6, "M", "ν"), + (0x1D7B7, "M", "ξ"), + (0x1D7B8, "M", "ο"), + (0x1D7B9, "M", "π"), + (0x1D7BA, "M", "ρ"), + (0x1D7BB, "M", "σ"), + (0x1D7BD, "M", "τ"), + (0x1D7BE, "M", "υ"), + (0x1D7BF, "M", "φ"), + (0x1D7C0, "M", "χ"), + (0x1D7C1, "M", "ψ"), + (0x1D7C2, "M", "ω"), + (0x1D7C3, "M", "∂"), + (0x1D7C4, "M", "ε"), + (0x1D7C5, "M", "θ"), + (0x1D7C6, "M", "κ"), + (0x1D7C7, "M", "φ"), + (0x1D7C8, "M", "ρ"), + (0x1D7C9, "M", "π"), + (0x1D7CA, "M", "ϝ"), + (0x1D7CC, "X"), + (0x1D7CE, "M", "0"), + (0x1D7CF, "M", "1"), + (0x1D7D0, "M", "2"), + (0x1D7D1, "M", "3"), + (0x1D7D2, "M", "4"), + (0x1D7D3, "M", "5"), + (0x1D7D4, "M", "6"), + (0x1D7D5, "M", "7"), + (0x1D7D6, "M", "8"), + (0x1D7D7, "M", "9"), + (0x1D7D8, "M", "0"), + (0x1D7D9, "M", "1"), + (0x1D7DA, "M", "2"), + (0x1D7DB, "M", "3"), + (0x1D7DC, "M", "4"), + (0x1D7DD, "M", "5"), + (0x1D7DE, "M", "6"), + (0x1D7DF, "M", "7"), + (0x1D7E0, "M", "8"), + (0x1D7E1, "M", "9"), + (0x1D7E2, "M", "0"), + (0x1D7E3, "M", "1"), + (0x1D7E4, "M", "2"), + (0x1D7E5, "M", "3"), + (0x1D7E6, "M", "4"), + (0x1D7E7, "M", "5"), + (0x1D7E8, "M", "6"), + (0x1D7E9, "M", "7"), + (0x1D7EA, "M", "8"), + (0x1D7EB, "M", "9"), + (0x1D7EC, "M", "0"), + (0x1D7ED, "M", "1"), + (0x1D7EE, "M", "2"), + (0x1D7EF, "M", "3"), + (0x1D7F0, "M", "4"), + (0x1D7F1, "M", "5"), + (0x1D7F2, "M", "6"), + (0x1D7F3, "M", "7"), + (0x1D7F4, "M", "8"), + (0x1D7F5, "M", "9"), + (0x1D7F6, "M", "0"), + (0x1D7F7, "M", "1"), + (0x1D7F8, "M", "2"), + (0x1D7F9, "M", "3"), + (0x1D7FA, "M", "4"), + (0x1D7FB, "M", "5"), + (0x1D7FC, "M", "6"), + (0x1D7FD, "M", "7"), + (0x1D7FE, "M", "8"), + (0x1D7FF, "M", "9"), + (0x1D800, "V"), + (0x1DA8C, "X"), + (0x1DA9B, "V"), + (0x1DAA0, "X"), + (0x1DAA1, "V"), + (0x1DAB0, "X"), + (0x1DF00, "V"), + (0x1DF1F, "X"), + (0x1DF25, "V"), + (0x1DF2B, "X"), + (0x1E000, "V"), + (0x1E007, "X"), + (0x1E008, "V"), + (0x1E019, "X"), + (0x1E01B, "V"), + (0x1E022, "X"), + (0x1E023, "V"), + (0x1E025, "X"), + (0x1E026, "V"), + (0x1E02B, "X"), + (0x1E030, "M", "а"), + (0x1E031, "M", "б"), + (0x1E032, "M", "в"), + (0x1E033, "M", "г"), + (0x1E034, "M", "д"), + (0x1E035, "M", "е"), + (0x1E036, "M", "ж"), + (0x1E037, "M", "з"), + (0x1E038, "M", "и"), + (0x1E039, "M", "к"), + (0x1E03A, "M", "л"), + (0x1E03B, "M", "м"), + (0x1E03C, "M", "о"), + (0x1E03D, "M", "п"), + (0x1E03E, "M", "р"), + (0x1E03F, "M", "с"), + (0x1E040, "M", "т"), + (0x1E041, "M", "у"), + (0x1E042, "M", "ф"), + (0x1E043, "M", "х"), + (0x1E044, "M", "ц"), + (0x1E045, "M", "ч"), + (0x1E046, "M", "ш"), + (0x1E047, "M", "ы"), + (0x1E048, "M", "э"), + (0x1E049, "M", "ю"), + (0x1E04A, "M", "ꚉ"), + (0x1E04B, "M", "ә"), + (0x1E04C, "M", "і"), + (0x1E04D, "M", "ј"), + (0x1E04E, "M", "ө"), + (0x1E04F, "M", "ү"), + (0x1E050, "M", "ӏ"), + (0x1E051, "M", "а"), + (0x1E052, "M", "б"), + (0x1E053, "M", "в"), + (0x1E054, "M", "г"), + (0x1E055, "M", "д"), + (0x1E056, "M", "е"), + (0x1E057, "M", "ж"), + (0x1E058, "M", "з"), + (0x1E059, "M", "и"), + (0x1E05A, "M", "к"), + (0x1E05B, "M", "л"), + (0x1E05C, "M", "о"), + (0x1E05D, "M", "п"), + (0x1E05E, "M", "с"), + (0x1E05F, "M", "у"), + (0x1E060, "M", "ф"), + (0x1E061, "M", "х"), + (0x1E062, "M", "ц"), + (0x1E063, "M", "ч"), + (0x1E064, "M", "ш"), + (0x1E065, "M", "ъ"), + (0x1E066, "M", "ы"), + (0x1E067, "M", "ґ"), + (0x1E068, "M", "і"), + (0x1E069, "M", "ѕ"), + (0x1E06A, "M", "џ"), + (0x1E06B, "M", "ҫ"), + (0x1E06C, "M", "ꙑ"), + (0x1E06D, "M", "ұ"), + (0x1E06E, "X"), + (0x1E08F, "V"), + (0x1E090, "X"), + (0x1E100, "V"), + (0x1E12D, "X"), + (0x1E130, "V"), + (0x1E13E, "X"), + (0x1E140, "V"), + (0x1E14A, "X"), + (0x1E14E, "V"), + (0x1E150, "X"), + (0x1E290, "V"), + (0x1E2AF, "X"), + (0x1E2C0, "V"), + (0x1E2FA, "X"), + (0x1E2FF, "V"), + (0x1E300, "X"), + (0x1E4D0, "V"), + (0x1E4FA, "X"), + (0x1E5D0, "V"), + (0x1E5FB, "X"), + (0x1E5FF, "V"), + (0x1E600, "X"), + (0x1E6C0, "V"), + (0x1E6DF, "X"), + (0x1E6E0, "V"), + (0x1E6F6, "X"), + (0x1E6FE, "V"), + (0x1E700, "X"), + (0x1E7E0, "V"), + (0x1E7E7, "X"), + (0x1E7E8, "V"), + (0x1E7EC, "X"), + (0x1E7ED, "V"), + (0x1E7EF, "X"), + (0x1E7F0, "V"), + (0x1E7FF, "X"), + (0x1E800, "V"), + (0x1E8C5, "X"), + (0x1E8C7, "V"), + (0x1E8D7, "X"), + (0x1E900, "M", "𞤢"), + (0x1E901, "M", "𞤣"), + (0x1E902, "M", "𞤤"), + (0x1E903, "M", "𞤥"), + (0x1E904, "M", "𞤦"), + (0x1E905, "M", "𞤧"), + (0x1E906, "M", "𞤨"), + (0x1E907, "M", "𞤩"), + (0x1E908, "M", "𞤪"), + (0x1E909, "M", "𞤫"), + (0x1E90A, "M", "𞤬"), + (0x1E90B, "M", "𞤭"), + (0x1E90C, "M", "𞤮"), + (0x1E90D, "M", "𞤯"), + (0x1E90E, "M", "𞤰"), + (0x1E90F, "M", "𞤱"), + (0x1E910, "M", "𞤲"), + (0x1E911, "M", "𞤳"), + (0x1E912, "M", "𞤴"), + (0x1E913, "M", "𞤵"), + (0x1E914, "M", "𞤶"), + (0x1E915, "M", "𞤷"), + (0x1E916, "M", "𞤸"), + (0x1E917, "M", "𞤹"), + (0x1E918, "M", "𞤺"), + (0x1E919, "M", "𞤻"), + (0x1E91A, "M", "𞤼"), + (0x1E91B, "M", "𞤽"), + (0x1E91C, "M", "𞤾"), + (0x1E91D, "M", "𞤿"), + (0x1E91E, "M", "𞥀"), + (0x1E91F, "M", "𞥁"), + (0x1E920, "M", "𞥂"), + (0x1E921, "M", "𞥃"), + (0x1E922, "V"), + (0x1E94C, "X"), + (0x1E950, "V"), + (0x1E95A, "X"), + (0x1E95E, "V"), + (0x1E960, "X"), + (0x1EC71, "V"), + (0x1ECB5, "X"), + (0x1ED01, "V"), + (0x1ED3E, "X"), + (0x1EE00, "M", "ا"), + (0x1EE01, "M", "ب"), + (0x1EE02, "M", "ج"), + (0x1EE03, "M", "د"), + (0x1EE04, "X"), + (0x1EE05, "M", "و"), + (0x1EE06, "M", "ز"), + (0x1EE07, "M", "ح"), + (0x1EE08, "M", "ط"), + (0x1EE09, "M", "ي"), + (0x1EE0A, "M", "ك"), + (0x1EE0B, "M", "ل"), + (0x1EE0C, "M", "م"), + (0x1EE0D, "M", "ن"), + (0x1EE0E, "M", "س"), + (0x1EE0F, "M", "ع"), + (0x1EE10, "M", "ف"), + (0x1EE11, "M", "ص"), + (0x1EE12, "M", "ق"), + (0x1EE13, "M", "ر"), + (0x1EE14, "M", "ش"), + (0x1EE15, "M", "ت"), + (0x1EE16, "M", "ث"), + (0x1EE17, "M", "خ"), + (0x1EE18, "M", "ذ"), + (0x1EE19, "M", "ض"), + (0x1EE1A, "M", "ظ"), + (0x1EE1B, "M", "غ"), + (0x1EE1C, "M", "ٮ"), + (0x1EE1D, "M", "ں"), + (0x1EE1E, "M", "ڡ"), + (0x1EE1F, "M", "ٯ"), + (0x1EE20, "X"), + (0x1EE21, "M", "ب"), + (0x1EE22, "M", "ج"), + (0x1EE23, "X"), + (0x1EE24, "M", "ه"), + (0x1EE25, "X"), + (0x1EE27, "M", "ح"), + (0x1EE28, "X"), + (0x1EE29, "M", "ي"), + (0x1EE2A, "M", "ك"), + (0x1EE2B, "M", "ل"), + (0x1EE2C, "M", "م"), + (0x1EE2D, "M", "ن"), + (0x1EE2E, "M", "س"), + (0x1EE2F, "M", "ع"), + (0x1EE30, "M", "ف"), + (0x1EE31, "M", "ص"), + (0x1EE32, "M", "ق"), + (0x1EE33, "X"), + (0x1EE34, "M", "ش"), + (0x1EE35, "M", "ت"), + (0x1EE36, "M", "ث"), + (0x1EE37, "M", "خ"), + (0x1EE38, "X"), + (0x1EE39, "M", "ض"), + (0x1EE3A, "X"), + (0x1EE3B, "M", "غ"), + (0x1EE3C, "X"), + (0x1EE42, "M", "ج"), + (0x1EE43, "X"), + (0x1EE47, "M", "ح"), + (0x1EE48, "X"), + (0x1EE49, "M", "ي"), + (0x1EE4A, "X"), + (0x1EE4B, "M", "ل"), + (0x1EE4C, "X"), + (0x1EE4D, "M", "ن"), + (0x1EE4E, "M", "س"), + (0x1EE4F, "M", "ع"), + (0x1EE50, "X"), + (0x1EE51, "M", "ص"), + (0x1EE52, "M", "ق"), + (0x1EE53, "X"), + (0x1EE54, "M", "ش"), + (0x1EE55, "X"), + (0x1EE57, "M", "خ"), + (0x1EE58, "X"), + (0x1EE59, "M", "ض"), + (0x1EE5A, "X"), + (0x1EE5B, "M", "غ"), + (0x1EE5C, "X"), + (0x1EE5D, "M", "ں"), + (0x1EE5E, "X"), + (0x1EE5F, "M", "ٯ"), + (0x1EE60, "X"), + (0x1EE61, "M", "ب"), + (0x1EE62, "M", "ج"), + (0x1EE63, "X"), + (0x1EE64, "M", "ه"), + (0x1EE65, "X"), + (0x1EE67, "M", "ح"), + (0x1EE68, "M", "ط"), + (0x1EE69, "M", "ي"), + (0x1EE6A, "M", "ك"), + (0x1EE6B, "X"), + (0x1EE6C, "M", "م"), + (0x1EE6D, "M", "ن"), + (0x1EE6E, "M", "س"), + (0x1EE6F, "M", "ع"), + (0x1EE70, "M", "ف"), + (0x1EE71, "M", "ص"), + (0x1EE72, "M", "ق"), + (0x1EE73, "X"), + (0x1EE74, "M", "ش"), + (0x1EE75, "M", "ت"), + (0x1EE76, "M", "ث"), + (0x1EE77, "M", "خ"), + (0x1EE78, "X"), + (0x1EE79, "M", "ض"), + (0x1EE7A, "M", "ظ"), + (0x1EE7B, "M", "غ"), + (0x1EE7C, "M", "ٮ"), + (0x1EE7D, "X"), + (0x1EE7E, "M", "ڡ"), + (0x1EE7F, "X"), + (0x1EE80, "M", "ا"), + (0x1EE81, "M", "ب"), + (0x1EE82, "M", "ج"), + (0x1EE83, "M", "د"), + (0x1EE84, "M", "ه"), + (0x1EE85, "M", "و"), + (0x1EE86, "M", "ز"), + (0x1EE87, "M", "ح"), + (0x1EE88, "M", "ط"), + (0x1EE89, "M", "ي"), + (0x1EE8A, "X"), + (0x1EE8B, "M", "ل"), + (0x1EE8C, "M", "م"), + (0x1EE8D, "M", "ن"), + (0x1EE8E, "M", "س"), + (0x1EE8F, "M", "ع"), + (0x1EE90, "M", "ف"), + (0x1EE91, "M", "ص"), + (0x1EE92, "M", "ق"), + (0x1EE93, "M", "ر"), + (0x1EE94, "M", "ش"), + (0x1EE95, "M", "ت"), + (0x1EE96, "M", "ث"), + (0x1EE97, "M", "خ"), + (0x1EE98, "M", "ذ"), + (0x1EE99, "M", "ض"), + (0x1EE9A, "M", "ظ"), + (0x1EE9B, "M", "غ"), + (0x1EE9C, "X"), + (0x1EEA1, "M", "ب"), + (0x1EEA2, "M", "ج"), + (0x1EEA3, "M", "د"), + (0x1EEA4, "X"), + (0x1EEA5, "M", "و"), + (0x1EEA6, "M", "ز"), + (0x1EEA7, "M", "ح"), + (0x1EEA8, "M", "ط"), + (0x1EEA9, "M", "ي"), + (0x1EEAA, "X"), + (0x1EEAB, "M", "ل"), + (0x1EEAC, "M", "م"), + (0x1EEAD, "M", "ن"), + (0x1EEAE, "M", "س"), + (0x1EEAF, "M", "ع"), + (0x1EEB0, "M", "ف"), + (0x1EEB1, "M", "ص"), + (0x1EEB2, "M", "ق"), + (0x1EEB3, "M", "ر"), + (0x1EEB4, "M", "ش"), + (0x1EEB5, "M", "ت"), + (0x1EEB6, "M", "ث"), + (0x1EEB7, "M", "خ"), + (0x1EEB8, "M", "ذ"), + (0x1EEB9, "M", "ض"), + (0x1EEBA, "M", "ظ"), + (0x1EEBB, "M", "غ"), + (0x1EEBC, "X"), + (0x1EEF0, "V"), + (0x1EEF2, "X"), + (0x1F000, "V"), + (0x1F02C, "X"), + (0x1F030, "V"), + (0x1F094, "X"), + (0x1F0A0, "V"), + (0x1F0AF, "X"), + (0x1F0B1, "V"), + (0x1F0C0, "X"), + (0x1F0C1, "V"), + (0x1F0D0, "X"), + (0x1F0D1, "V"), + (0x1F0F6, "X"), + (0x1F101, "M", "0,"), + (0x1F102, "M", "1,"), + (0x1F103, "M", "2,"), + (0x1F104, "M", "3,"), + (0x1F105, "M", "4,"), + (0x1F106, "M", "5,"), + (0x1F107, "M", "6,"), + (0x1F108, "M", "7,"), + (0x1F109, "M", "8,"), + (0x1F10A, "M", "9,"), + (0x1F10B, "V"), + (0x1F110, "M", "(a)"), + (0x1F111, "M", "(b)"), + (0x1F112, "M", "(c)"), + (0x1F113, "M", "(d)"), + (0x1F114, "M", "(e)"), + (0x1F115, "M", "(f)"), + (0x1F116, "M", "(g)"), + (0x1F117, "M", "(h)"), + (0x1F118, "M", "(i)"), + (0x1F119, "M", "(j)"), + (0x1F11A, "M", "(k)"), + (0x1F11B, "M", "(l)"), + (0x1F11C, "M", "(m)"), + (0x1F11D, "M", "(n)"), + (0x1F11E, "M", "(o)"), + (0x1F11F, "M", "(p)"), + (0x1F120, "M", "(q)"), + (0x1F121, "M", "(r)"), + (0x1F122, "M", "(s)"), + (0x1F123, "M", "(t)"), + (0x1F124, "M", "(u)"), + (0x1F125, "M", "(v)"), + (0x1F126, "M", "(w)"), + (0x1F127, "M", "(x)"), + (0x1F128, "M", "(y)"), + (0x1F129, "M", "(z)"), + (0x1F12A, "M", "〔s〕"), + (0x1F12B, "M", "c"), + (0x1F12C, "M", "r"), + (0x1F12D, "M", "cd"), + (0x1F12E, "M", "wz"), + (0x1F12F, "V"), + (0x1F130, "M", "a"), + (0x1F131, "M", "b"), + (0x1F132, "M", "c"), + (0x1F133, "M", "d"), + (0x1F134, "M", "e"), + (0x1F135, "M", "f"), + (0x1F136, "M", "g"), + (0x1F137, "M", "h"), + (0x1F138, "M", "i"), + (0x1F139, "M", "j"), + (0x1F13A, "M", "k"), + (0x1F13B, "M", "l"), + (0x1F13C, "M", "m"), + (0x1F13D, "M", "n"), + (0x1F13E, "M", "o"), + (0x1F13F, "M", "p"), + (0x1F140, "M", "q"), + (0x1F141, "M", "r"), + (0x1F142, "M", "s"), + (0x1F143, "M", "t"), + (0x1F144, "M", "u"), + (0x1F145, "M", "v"), + (0x1F146, "M", "w"), + (0x1F147, "M", "x"), + (0x1F148, "M", "y"), + (0x1F149, "M", "z"), + (0x1F14A, "M", "hv"), + (0x1F14B, "M", "mv"), + (0x1F14C, "M", "sd"), + (0x1F14D, "M", "ss"), + (0x1F14E, "M", "ppv"), + (0x1F14F, "M", "wc"), + (0x1F150, "V"), + (0x1F16A, "M", "mc"), + (0x1F16B, "M", "md"), + (0x1F16C, "M", "mr"), + (0x1F16D, "V"), + (0x1F190, "M", "dj"), + (0x1F191, "V"), + (0x1F1AE, "X"), + (0x1F1E6, "V"), + (0x1F200, "M", "ほか"), + (0x1F201, "M", "ココ"), + (0x1F202, "M", "サ"), + (0x1F203, "X"), + (0x1F210, "M", "手"), + (0x1F211, "M", "字"), + (0x1F212, "M", "双"), + (0x1F213, "M", "デ"), + (0x1F214, "M", "二"), + (0x1F215, "M", "多"), + (0x1F216, "M", "解"), + (0x1F217, "M", "天"), + (0x1F218, "M", "交"), + (0x1F219, "M", "映"), + (0x1F21A, "M", "無"), + (0x1F21B, "M", "料"), + (0x1F21C, "M", "前"), + (0x1F21D, "M", "後"), + (0x1F21E, "M", "再"), + (0x1F21F, "M", "新"), + (0x1F220, "M", "初"), + (0x1F221, "M", "終"), + (0x1F222, "M", "生"), + (0x1F223, "M", "販"), + (0x1F224, "M", "声"), + (0x1F225, "M", "吹"), + (0x1F226, "M", "演"), + (0x1F227, "M", "投"), + (0x1F228, "M", "捕"), + (0x1F229, "M", "一"), + (0x1F22A, "M", "三"), + (0x1F22B, "M", "遊"), + (0x1F22C, "M", "左"), + (0x1F22D, "M", "中"), + (0x1F22E, "M", "右"), + (0x1F22F, "M", "指"), + (0x1F230, "M", "走"), + (0x1F231, "M", "打"), + (0x1F232, "M", "禁"), + (0x1F233, "M", "空"), + (0x1F234, "M", "合"), + (0x1F235, "M", "満"), + (0x1F236, "M", "有"), + (0x1F237, "M", "月"), + (0x1F238, "M", "申"), + (0x1F239, "M", "割"), + (0x1F23A, "M", "営"), + (0x1F23B, "M", "配"), + (0x1F23C, "X"), + (0x1F240, "M", "〔本〕"), + (0x1F241, "M", "〔三〕"), + (0x1F242, "M", "〔二〕"), + (0x1F243, "M", "〔安〕"), + (0x1F244, "M", "〔点〕"), + (0x1F245, "M", "〔打〕"), + (0x1F246, "M", "〔盗〕"), + (0x1F247, "M", "〔勝〕"), + (0x1F248, "M", "〔敗〕"), + (0x1F249, "X"), + (0x1F250, "M", "得"), + (0x1F251, "M", "可"), + (0x1F252, "X"), + (0x1F260, "V"), + (0x1F266, "X"), + (0x1F300, "V"), + (0x1F6D9, "X"), + (0x1F6DC, "V"), + (0x1F6ED, "X"), + (0x1F6F0, "V"), + (0x1F6FD, "X"), + (0x1F700, "V"), + (0x1F7DA, "X"), + (0x1F7E0, "V"), + (0x1F7EC, "X"), + (0x1F7F0, "V"), + (0x1F7F1, "X"), + (0x1F800, "V"), + (0x1F80C, "X"), + (0x1F810, "V"), + (0x1F848, "X"), + (0x1F850, "V"), + (0x1F85A, "X"), + (0x1F860, "V"), + (0x1F888, "X"), + (0x1F890, "V"), + (0x1F8AE, "X"), + (0x1F8B0, "V"), + (0x1F8BC, "X"), + (0x1F8C0, "V"), + (0x1F8C2, "X"), + (0x1F8D0, "V"), + (0x1F8D9, "X"), + (0x1F900, "V"), + (0x1FA58, "X"), + (0x1FA60, "V"), + (0x1FA6E, "X"), + (0x1FA70, "V"), + (0x1FA7D, "X"), + (0x1FA80, "V"), + (0x1FA8B, "X"), + (0x1FA8E, "V"), + (0x1FAC7, "X"), + (0x1FAC8, "V"), + (0x1FAC9, "X"), + (0x1FACD, "V"), + (0x1FADD, "X"), + (0x1FADF, "V"), + (0x1FAEB, "X"), + (0x1FAEF, "V"), + (0x1FAF9, "X"), + (0x1FB00, "V"), + (0x1FB93, "X"), + (0x1FB94, "V"), + (0x1FBF0, "M", "0"), + (0x1FBF1, "M", "1"), + (0x1FBF2, "M", "2"), + (0x1FBF3, "M", "3"), + (0x1FBF4, "M", "4"), + (0x1FBF5, "M", "5"), + (0x1FBF6, "M", "6"), + (0x1FBF7, "M", "7"), + (0x1FBF8, "M", "8"), + (0x1FBF9, "M", "9"), + (0x1FBFA, "V"), + (0x1FBFB, "X"), + (0x20000, "V"), + (0x2A6E0, "X"), + (0x2A700, "V"), + (0x2B81E, "X"), + (0x2B820, "V"), + (0x2CEAE, "X"), + (0x2CEB0, "V"), + (0x2EBE1, "X"), + (0x2EBF0, "V"), + (0x2EE5E, "X"), + (0x2F800, "M", "丽"), + (0x2F801, "M", "丸"), + (0x2F802, "M", "乁"), + (0x2F803, "M", "𠄢"), + (0x2F804, "M", "你"), + (0x2F805, "M", "侮"), + (0x2F806, "M", "侻"), + (0x2F807, "M", "倂"), + (0x2F808, "M", "偺"), + (0x2F809, "M", "備"), + (0x2F80A, "M", "僧"), + (0x2F80B, "M", "像"), + (0x2F80C, "M", "㒞"), + (0x2F80D, "M", "𠘺"), + (0x2F80E, "M", "免"), + (0x2F80F, "M", "兔"), + (0x2F810, "M", "兤"), + (0x2F811, "M", "具"), + (0x2F812, "M", "𠔜"), + (0x2F813, "M", "㒹"), + (0x2F814, "M", "內"), + (0x2F815, "M", "再"), + (0x2F816, "M", "𠕋"), + (0x2F817, "M", "冗"), + (0x2F818, "M", "冤"), + (0x2F819, "M", "仌"), + (0x2F81A, "M", "冬"), + (0x2F81B, "M", "况"), + (0x2F81C, "M", "𩇟"), + (0x2F81D, "M", "凵"), + (0x2F81E, "M", "刃"), + (0x2F81F, "M", "㓟"), + (0x2F820, "M", "刻"), + (0x2F821, "M", "剆"), + (0x2F822, "M", "割"), + (0x2F823, "M", "剷"), + (0x2F824, "M", "㔕"), + (0x2F825, "M", "勇"), + (0x2F826, "M", "勉"), + (0x2F827, "M", "勤"), + (0x2F828, "M", "勺"), + (0x2F829, "M", "包"), + (0x2F82A, "M", "匆"), + (0x2F82B, "M", "北"), + (0x2F82C, "M", "卉"), + (0x2F82D, "M", "卑"), + (0x2F82E, "M", "博"), + (0x2F82F, "M", "即"), + (0x2F830, "M", "卽"), + (0x2F831, "M", "卿"), + (0x2F834, "M", "𠨬"), + (0x2F835, "M", "灰"), + (0x2F836, "M", "及"), + (0x2F837, "M", "叟"), + (0x2F838, "M", "𠭣"), + (0x2F839, "M", "叫"), + (0x2F83A, "M", "叱"), + (0x2F83B, "M", "吆"), + (0x2F83C, "M", "咞"), + (0x2F83D, "M", "吸"), + (0x2F83E, "M", "呈"), + (0x2F83F, "M", "周"), + (0x2F840, "M", "咢"), + (0x2F841, "M", "哶"), + (0x2F842, "M", "唐"), + (0x2F843, "M", "啓"), + (0x2F844, "M", "啣"), + (0x2F845, "M", "善"), + (0x2F847, "M", "喙"), + (0x2F848, "M", "喫"), + (0x2F849, "M", "喳"), + (0x2F84A, "M", "嗂"), + (0x2F84B, "M", "圖"), + (0x2F84C, "M", "嘆"), + (0x2F84D, "M", "圗"), + (0x2F84E, "M", "噑"), + (0x2F84F, "M", "噴"), + (0x2F850, "M", "切"), + (0x2F851, "M", "壮"), + (0x2F852, "M", "城"), + (0x2F853, "M", "埴"), + (0x2F854, "M", "堍"), + (0x2F855, "M", "型"), + (0x2F856, "M", "堲"), + (0x2F857, "M", "報"), + (0x2F858, "M", "墬"), + (0x2F859, "M", "𡓤"), + (0x2F85A, "M", "売"), + (0x2F85B, "M", "壷"), + (0x2F85C, "M", "夆"), + (0x2F85D, "M", "多"), + (0x2F85E, "M", "夢"), + (0x2F85F, "M", "奢"), + (0x2F860, "M", "𡚨"), + (0x2F861, "M", "𡛪"), + (0x2F862, "M", "姬"), + (0x2F863, "M", "娛"), + (0x2F864, "M", "娧"), + (0x2F865, "M", "姘"), + (0x2F866, "M", "婦"), + (0x2F867, "M", "㛮"), + (0x2F868, "M", "㛼"), + (0x2F869, "M", "嬈"), + (0x2F86A, "M", "嬾"), + (0x2F86C, "M", "𡧈"), + (0x2F86D, "M", "寃"), + (0x2F86E, "M", "寘"), + (0x2F86F, "M", "寧"), + (0x2F870, "M", "寳"), + (0x2F871, "M", "𡬘"), + (0x2F872, "M", "寿"), + (0x2F873, "M", "将"), + (0x2F874, "M", "当"), + (0x2F875, "M", "尢"), + (0x2F876, "M", "㞁"), + (0x2F877, "M", "屠"), + (0x2F878, "M", "屮"), + (0x2F879, "M", "峀"), + (0x2F87A, "M", "岍"), + (0x2F87B, "M", "𡷤"), + (0x2F87C, "M", "嵃"), + (0x2F87D, "M", "𡷦"), + (0x2F87E, "M", "嵮"), + (0x2F87F, "M", "嵫"), + (0x2F880, "M", "嵼"), + (0x2F881, "M", "巡"), + (0x2F882, "M", "巢"), + (0x2F883, "M", "㠯"), + (0x2F884, "M", "巽"), + (0x2F885, "M", "帨"), + (0x2F886, "M", "帽"), + (0x2F887, "M", "幩"), + (0x2F888, "M", "㡢"), + (0x2F889, "M", "𢆃"), + (0x2F88A, "M", "㡼"), + (0x2F88B, "M", "庰"), + (0x2F88C, "M", "庳"), + (0x2F88D, "M", "庶"), + (0x2F88E, "M", "廊"), + (0x2F88F, "M", "𪎒"), + (0x2F890, "M", "廾"), + (0x2F891, "M", "𢌱"), + (0x2F893, "M", "舁"), + (0x2F894, "M", "弢"), + (0x2F896, "M", "㣇"), + (0x2F897, "M", "𣊸"), + (0x2F898, "M", "𦇚"), + (0x2F899, "M", "形"), + (0x2F89A, "M", "彫"), + (0x2F89B, "M", "㣣"), + (0x2F89C, "M", "徚"), + (0x2F89D, "M", "忍"), + (0x2F89E, "M", "志"), + (0x2F89F, "M", "忹"), + (0x2F8A0, "M", "悁"), + (0x2F8A1, "M", "㤺"), + (0x2F8A2, "M", "㤜"), + (0x2F8A3, "M", "悔"), + (0x2F8A4, "M", "𢛔"), + (0x2F8A5, "M", "惇"), + (0x2F8A6, "M", "慈"), + (0x2F8A7, "M", "慌"), + (0x2F8A8, "M", "慎"), + (0x2F8A9, "M", "慌"), + (0x2F8AA, "M", "慺"), + (0x2F8AB, "M", "憎"), + (0x2F8AC, "M", "憲"), + (0x2F8AD, "M", "憤"), + (0x2F8AE, "M", "憯"), + (0x2F8AF, "M", "懞"), + (0x2F8B0, "M", "懲"), + (0x2F8B1, "M", "懶"), + (0x2F8B2, "M", "成"), + (0x2F8B3, "M", "戛"), + (0x2F8B4, "M", "扝"), + (0x2F8B5, "M", "抱"), + (0x2F8B6, "M", "拔"), + (0x2F8B7, "M", "捐"), + (0x2F8B8, "M", "𢬌"), + (0x2F8B9, "M", "挽"), + (0x2F8BA, "M", "拼"), + (0x2F8BB, "M", "捨"), + (0x2F8BC, "M", "掃"), + (0x2F8BD, "M", "揤"), + (0x2F8BE, "M", "𢯱"), + (0x2F8BF, "M", "搢"), + (0x2F8C0, "M", "揅"), + (0x2F8C1, "M", "掩"), + (0x2F8C2, "M", "㨮"), + (0x2F8C3, "M", "摩"), + (0x2F8C4, "M", "摾"), + (0x2F8C5, "M", "撝"), + (0x2F8C6, "M", "摷"), + (0x2F8C7, "M", "㩬"), + (0x2F8C8, "M", "敏"), + (0x2F8C9, "M", "敬"), + (0x2F8CA, "M", "𣀊"), + (0x2F8CB, "M", "旣"), + (0x2F8CC, "M", "書"), + (0x2F8CD, "M", "晉"), + (0x2F8CE, "M", "㬙"), + (0x2F8CF, "M", "暑"), + (0x2F8D0, "M", "㬈"), + (0x2F8D1, "M", "㫤"), + (0x2F8D2, "M", "冒"), + (0x2F8D3, "M", "冕"), + (0x2F8D4, "M", "最"), + (0x2F8D5, "M", "暜"), + (0x2F8D6, "M", "肭"), + (0x2F8D7, "M", "䏙"), + (0x2F8D8, "M", "朗"), + (0x2F8D9, "M", "望"), + (0x2F8DA, "M", "朡"), + (0x2F8DB, "M", "杞"), + (0x2F8DC, "M", "杓"), + (0x2F8DD, "M", "𣏃"), + (0x2F8DE, "M", "㭉"), + (0x2F8DF, "M", "柺"), + (0x2F8E0, "M", "枅"), + (0x2F8E1, "M", "桒"), + (0x2F8E2, "M", "梅"), + (0x2F8E3, "M", "𣑭"), + (0x2F8E4, "M", "梎"), + (0x2F8E5, "M", "栟"), + (0x2F8E6, "M", "椔"), + (0x2F8E7, "M", "㮝"), + (0x2F8E8, "M", "楂"), + (0x2F8E9, "M", "榣"), + (0x2F8EA, "M", "槪"), + (0x2F8EB, "M", "檨"), + (0x2F8EC, "M", "𣚣"), + (0x2F8ED, "M", "櫛"), + (0x2F8EE, "M", "㰘"), + (0x2F8EF, "M", "次"), + (0x2F8F0, "M", "𣢧"), + (0x2F8F1, "M", "歔"), + (0x2F8F2, "M", "㱎"), + (0x2F8F3, "M", "歲"), + (0x2F8F4, "M", "殟"), + (0x2F8F5, "M", "殺"), + (0x2F8F6, "M", "殻"), + (0x2F8F7, "M", "𣪍"), + (0x2F8F8, "M", "𡴋"), + (0x2F8F9, "M", "𣫺"), + (0x2F8FA, "M", "汎"), + (0x2F8FB, "M", "𣲼"), + (0x2F8FC, "M", "沿"), + (0x2F8FD, "M", "泍"), + (0x2F8FE, "M", "汧"), + (0x2F8FF, "M", "洖"), + (0x2F900, "M", "派"), + (0x2F901, "M", "海"), + (0x2F902, "M", "流"), + (0x2F903, "M", "浩"), + (0x2F904, "M", "浸"), + (0x2F905, "M", "涅"), + (0x2F906, "M", "𣴞"), + (0x2F907, "M", "洴"), + (0x2F908, "M", "港"), + (0x2F909, "M", "湮"), + (0x2F90A, "M", "㴳"), + (0x2F90B, "M", "滋"), + (0x2F90C, "M", "滇"), + (0x2F90D, "M", "𣻑"), + (0x2F90E, "M", "淹"), + (0x2F90F, "M", "潮"), + (0x2F910, "M", "𣽞"), + (0x2F911, "M", "𣾎"), + (0x2F912, "M", "濆"), + (0x2F913, "M", "瀹"), + (0x2F914, "M", "瀞"), + (0x2F915, "M", "瀛"), + (0x2F916, "M", "㶖"), + (0x2F917, "M", "灊"), + (0x2F918, "M", "災"), + (0x2F919, "M", "灷"), + (0x2F91A, "M", "炭"), + (0x2F91B, "M", "𠔥"), + (0x2F91C, "M", "煅"), + (0x2F91D, "M", "𤉣"), + (0x2F91E, "M", "熜"), + (0x2F91F, "M", "𤎫"), + (0x2F920, "M", "爨"), + (0x2F921, "M", "爵"), + (0x2F922, "M", "牐"), + (0x2F923, "M", "𤘈"), + (0x2F924, "M", "犀"), + (0x2F925, "M", "犕"), + (0x2F926, "M", "𤜵"), + (0x2F927, "M", "𤠔"), + (0x2F928, "M", "獺"), + (0x2F929, "M", "王"), + (0x2F92A, "M", "㺬"), + (0x2F92B, "M", "玥"), + (0x2F92C, "M", "㺸"), + (0x2F92E, "M", "瑇"), + (0x2F92F, "M", "瑜"), + (0x2F930, "M", "瑱"), + (0x2F931, "M", "璅"), + (0x2F932, "M", "瓊"), + (0x2F933, "M", "㼛"), + (0x2F934, "M", "甤"), + (0x2F935, "M", "𤰶"), + (0x2F936, "M", "甾"), + (0x2F937, "M", "𤲒"), + (0x2F938, "M", "異"), + (0x2F939, "M", "𢆟"), + (0x2F93A, "M", "瘐"), + (0x2F93B, "M", "𤾡"), + (0x2F93C, "M", "𤾸"), + (0x2F93D, "M", "𥁄"), + (0x2F93E, "M", "㿼"), + (0x2F93F, "M", "䀈"), + (0x2F940, "M", "直"), + (0x2F941, "M", "𥃳"), + (0x2F942, "M", "𥃲"), + (0x2F943, "M", "𥄙"), + (0x2F944, "M", "𥄳"), + (0x2F945, "M", "眞"), + (0x2F946, "M", "真"), + (0x2F948, "M", "睊"), + (0x2F949, "M", "䀹"), + (0x2F94A, "M", "瞋"), + (0x2F94B, "M", "䁆"), + (0x2F94C, "M", "䂖"), + (0x2F94D, "M", "𥐝"), + (0x2F94E, "M", "硎"), + (0x2F94F, "M", "碌"), + (0x2F950, "M", "磌"), + (0x2F951, "M", "䃣"), + (0x2F952, "M", "𥘦"), + (0x2F953, "M", "祖"), + (0x2F954, "M", "𥚚"), + (0x2F955, "M", "𥛅"), + (0x2F956, "M", "福"), + (0x2F957, "M", "秫"), + (0x2F958, "M", "䄯"), + (0x2F959, "M", "穀"), + (0x2F95A, "M", "穊"), + (0x2F95B, "M", "穏"), + (0x2F95C, "M", "𥥼"), + (0x2F95D, "M", "𥪧"), + (0x2F95F, "M", "竮"), + (0x2F960, "M", "䈂"), + (0x2F961, "M", "𥮫"), + (0x2F962, "M", "篆"), + (0x2F963, "M", "築"), + (0x2F964, "M", "䈧"), + (0x2F965, "M", "𥲀"), + (0x2F966, "M", "糒"), + (0x2F967, "M", "䊠"), + (0x2F968, "M", "糨"), + (0x2F969, "M", "糣"), + (0x2F96A, "M", "紀"), + (0x2F96B, "M", "𥾆"), + (0x2F96C, "M", "絣"), + (0x2F96D, "M", "䌁"), + (0x2F96E, "M", "緇"), + (0x2F96F, "M", "縂"), + (0x2F970, "M", "繅"), + (0x2F971, "M", "䌴"), + (0x2F972, "M", "𦈨"), + (0x2F973, "M", "𦉇"), + (0x2F974, "M", "䍙"), + (0x2F975, "M", "𦋙"), + (0x2F976, "M", "罺"), + (0x2F977, "M", "𦌾"), + (0x2F978, "M", "羕"), + (0x2F979, "M", "翺"), + (0x2F97A, "M", "者"), + (0x2F97B, "M", "𦓚"), + (0x2F97C, "M", "𦔣"), + (0x2F97D, "M", "聠"), + (0x2F97E, "M", "𦖨"), + (0x2F97F, "M", "聰"), + (0x2F980, "M", "𣍟"), + (0x2F981, "M", "䏕"), + (0x2F982, "M", "育"), + (0x2F983, "M", "脃"), + (0x2F984, "M", "䐋"), + (0x2F985, "M", "脾"), + (0x2F986, "M", "媵"), + (0x2F987, "M", "𦞧"), + (0x2F988, "M", "𦞵"), + (0x2F989, "M", "𣎓"), + (0x2F98A, "M", "𣎜"), + (0x2F98B, "M", "舁"), + (0x2F98C, "M", "舄"), + (0x2F98D, "M", "辞"), + (0x2F98E, "M", "䑫"), + (0x2F98F, "M", "芑"), + (0x2F990, "M", "芋"), + (0x2F991, "M", "芝"), + (0x2F992, "M", "劳"), + (0x2F993, "M", "花"), + (0x2F994, "M", "芳"), + (0x2F995, "M", "芽"), + (0x2F996, "M", "苦"), + (0x2F997, "M", "𦬼"), + (0x2F998, "M", "若"), + (0x2F999, "M", "茝"), + (0x2F99A, "M", "荣"), + (0x2F99B, "M", "莭"), + (0x2F99C, "M", "茣"), + (0x2F99D, "M", "莽"), + (0x2F99E, "M", "菧"), + (0x2F99F, "M", "著"), + (0x2F9A0, "M", "荓"), + (0x2F9A1, "M", "菊"), + (0x2F9A2, "M", "菌"), + (0x2F9A3, "M", "菜"), + (0x2F9A4, "M", "𦰶"), + (0x2F9A5, "M", "𦵫"), + (0x2F9A6, "M", "𦳕"), + (0x2F9A7, "M", "䔫"), + (0x2F9A8, "M", "蓱"), + (0x2F9A9, "M", "蓳"), + (0x2F9AA, "M", "蔖"), + (0x2F9AB, "M", "𧏊"), + (0x2F9AC, "M", "蕤"), + (0x2F9AD, "M", "𦼬"), + (0x2F9AE, "M", "䕝"), + (0x2F9AF, "M", "䕡"), + (0x2F9B0, "M", "𦾱"), + (0x2F9B1, "M", "𧃒"), + (0x2F9B2, "M", "䕫"), + (0x2F9B3, "M", "虐"), + (0x2F9B4, "M", "虜"), + (0x2F9B5, "M", "虧"), + (0x2F9B6, "M", "虩"), + (0x2F9B7, "M", "蚩"), + (0x2F9B8, "M", "蚈"), + (0x2F9B9, "M", "蜎"), + (0x2F9BA, "M", "蛢"), + (0x2F9BB, "M", "蝹"), + (0x2F9BC, "M", "蜨"), + (0x2F9BD, "M", "蝫"), + (0x2F9BE, "M", "螆"), + (0x2F9BF, "M", "䗗"), + (0x2F9C0, "M", "蟡"), + (0x2F9C1, "M", "蠁"), + (0x2F9C2, "M", "䗹"), + (0x2F9C3, "M", "衠"), + (0x2F9C4, "M", "衣"), + (0x2F9C5, "M", "𧙧"), + (0x2F9C6, "M", "裗"), + (0x2F9C7, "M", "裞"), + (0x2F9C8, "M", "䘵"), + (0x2F9C9, "M", "裺"), + (0x2F9CA, "M", "㒻"), + (0x2F9CB, "M", "𧢮"), + (0x2F9CC, "M", "𧥦"), + (0x2F9CD, "M", "䚾"), + (0x2F9CE, "M", "䛇"), + (0x2F9CF, "M", "誠"), + (0x2F9D0, "M", "諭"), + (0x2F9D1, "M", "變"), + (0x2F9D2, "M", "豕"), + (0x2F9D3, "M", "𧲨"), + (0x2F9D4, "M", "貫"), + (0x2F9D5, "M", "賁"), + (0x2F9D6, "M", "贛"), + (0x2F9D7, "M", "起"), + (0x2F9D8, "M", "𧼯"), + (0x2F9D9, "M", "𠠄"), + (0x2F9DA, "M", "跋"), + (0x2F9DB, "M", "趼"), + (0x2F9DC, "M", "跰"), + (0x2F9DD, "M", "𠣞"), + (0x2F9DE, "M", "軔"), + (0x2F9DF, "M", "輸"), + (0x2F9E0, "M", "𨗒"), + (0x2F9E1, "M", "𨗭"), + (0x2F9E2, "M", "邔"), + (0x2F9E3, "M", "郱"), + (0x2F9E4, "M", "鄑"), + (0x2F9E5, "M", "𨜮"), + (0x2F9E6, "M", "鄛"), + (0x2F9E7, "M", "鈸"), + (0x2F9E8, "M", "鋗"), + (0x2F9E9, "M", "鋘"), + (0x2F9EA, "M", "鉼"), + (0x2F9EB, "M", "鏹"), + (0x2F9EC, "M", "鐕"), + (0x2F9ED, "M", "𨯺"), + (0x2F9EE, "M", "開"), + (0x2F9EF, "M", "䦕"), + (0x2F9F0, "M", "閷"), + (0x2F9F1, "M", "𨵷"), + (0x2F9F2, "M", "䧦"), + (0x2F9F3, "M", "雃"), + (0x2F9F4, "M", "嶲"), + (0x2F9F5, "M", "霣"), + (0x2F9F6, "M", "𩅅"), + (0x2F9F7, "M", "𩈚"), + (0x2F9F8, "M", "䩮"), + (0x2F9F9, "M", "䩶"), + (0x2F9FA, "M", "韠"), + (0x2F9FB, "M", "𩐊"), + (0x2F9FC, "M", "䪲"), + (0x2F9FD, "M", "𩒖"), + (0x2F9FE, "M", "頋"), + (0x2FA00, "M", "頩"), + (0x2FA01, "M", "𩖶"), + (0x2FA02, "M", "飢"), + (0x2FA03, "M", "䬳"), + (0x2FA04, "M", "餩"), + (0x2FA05, "M", "馧"), + (0x2FA06, "M", "駂"), + (0x2FA07, "M", "駾"), + (0x2FA08, "M", "䯎"), + (0x2FA09, "M", "𩬰"), + (0x2FA0A, "M", "鬒"), + (0x2FA0B, "M", "鱀"), + (0x2FA0C, "M", "鳽"), + (0x2FA0D, "M", "䳎"), + (0x2FA0E, "M", "䳭"), + (0x2FA0F, "M", "鵧"), + (0x2FA10, "M", "𪃎"), + (0x2FA11, "M", "䳸"), + (0x2FA12, "M", "𪄅"), + (0x2FA13, "M", "𪈎"), + (0x2FA14, "M", "𪊑"), + (0x2FA15, "M", "麻"), + (0x2FA16, "M", "䵖"), + (0x2FA17, "M", "黹"), + (0x2FA18, "M", "黾"), + (0x2FA19, "M", "鼅"), + (0x2FA1A, "M", "鼏"), + (0x2FA1B, "M", "鼖"), + (0x2FA1C, "M", "鼻"), + (0x2FA1D, "M", "𪘀"), + (0x2FA1E, "X"), + (0x30000, "V"), + (0x3134B, "X"), + (0x31350, "V"), + (0x3347A, "X"), + (0xE0100, "I"), + (0xE01F0, "X"), +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..9d894b433dc0e27e53d3be160edb861358db99fd --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/METADATA @@ -0,0 +1,133 @@ +Metadata-Version: 2.4 +Name: importlib_metadata +Version: 8.7.1 +Summary: Read metadata from Python packages +Author-email: "Jason R. Coombs" +License-Expression: Apache-2.0 +Project-URL: Source, https://github.com/python/importlib_metadata +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: zipp>=3.20 +Provides-Extra: test +Requires-Dist: pytest!=8.1.*,>=6; extra == "test" +Requires-Dist: packaging; extra == "test" +Requires-Dist: pyfakefs; extra == "test" +Requires-Dist: flufl.flake8; extra == "test" +Requires-Dist: pytest-perf>=0.9.2; extra == "test" +Requires-Dist: jaraco.test>=5.4; extra == "test" +Provides-Extra: doc +Requires-Dist: sphinx>=3.5; extra == "doc" +Requires-Dist: jaraco.packaging>=9.3; extra == "doc" +Requires-Dist: rst.linker>=1.9; extra == "doc" +Requires-Dist: furo; extra == "doc" +Requires-Dist: sphinx-lint; extra == "doc" +Requires-Dist: jaraco.tidelift>=1.4; extra == "doc" +Provides-Extra: perf +Requires-Dist: ipython; extra == "perf" +Provides-Extra: check +Requires-Dist: pytest-checkdocs>=2.4; extra == "check" +Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check" +Provides-Extra: cover +Requires-Dist: pytest-cov; extra == "cover" +Provides-Extra: enabler +Requires-Dist: pytest-enabler>=3.4; extra == "enabler" +Provides-Extra: type +Requires-Dist: pytest-mypy>=1.0.1; extra == "type" +Requires-Dist: mypy<1.19; platform_python_implementation == "PyPy" and extra == "type" +Dynamic: license-file + +.. image:: https://img.shields.io/pypi/v/importlib_metadata.svg + :target: https://pypi.org/project/importlib_metadata + +.. image:: https://img.shields.io/pypi/pyversions/importlib_metadata.svg + +.. image:: https://github.com/python/importlib_metadata/actions/workflows/main.yml/badge.svg + :target: https://github.com/python/importlib_metadata/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. image:: https://readthedocs.org/projects/importlib-metadata/badge/?version=latest + :target: https://importlib-metadata.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2025-informational + :target: https://blog.jaraco.com/skeleton + +.. image:: https://tidelift.com/badges/package/pypi/importlib-metadata + :target: https://tidelift.com/subscription/pkg/pypi-importlib-metadata?utm_source=pypi-importlib-metadata&utm_medium=readme + +Library to access the metadata for a Python package. + +This package supplies third-party access to the functionality of +`importlib.metadata `_ +including improvements added to subsequent Python versions. + + +Compatibility +============= + +New features are introduced in this third-party library and later merged +into CPython. The following table indicates which versions of this library +were contributed to different versions in the standard library: + +.. list-table:: + :header-rows: 1 + + * - importlib_metadata + - stdlib + * - 7.0 + - 3.13 + * - 6.5 + - 3.12 + * - 4.13 + - 3.11 + * - 4.6 + - 3.10 + * - 1.4 + - 3.8 + + +Usage +===== + +See the `online documentation `_ +for usage details. + +`Finder authors +`_ can +also add support for custom package installers. See the above documentation +for details. + + +Caveats +======= + +This project primarily supports third-party packages installed by PyPA +tools (or other conforming packages). It does not support: + +- Packages in the stdlib. +- Packages installed without metadata. + +Project details +=============== + + * Project home: https://github.com/python/importlib_metadata + * Report bugs at: https://github.com/python/importlib_metadata/issues + * Code hosting: https://github.com/python/importlib_metadata + * Documentation: https://importlib-metadata.readthedocs.io/ + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..1ab479c4230665e355ded6c92e07b1984993b308 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/RECORD @@ -0,0 +1,33 @@ +importlib_metadata-8.7.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +importlib_metadata-8.7.1.dist-info/METADATA,sha256=o-OLnuQyYonUhkcE8w4pnudp4jCc6fSnXw3hpQrQo1Y,4670 +importlib_metadata-8.7.1.dist-info/RECORD,, +importlib_metadata-8.7.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +importlib_metadata-8.7.1.dist-info/licenses/LICENSE,sha256=RYUC4S2Xu_ZEOGBqIARKqF6wX7CoqAe7NdvsJT_R_AQ,10278 +importlib_metadata-8.7.1.dist-info/top_level.txt,sha256=CO3fD9yylANiXkrMo4qHLV_mqXL2sC5JFKgt1yWAT-A,19 +importlib_metadata/__init__.py,sha256=u7Ew4-UkpzNY-ka6k-WRkDhQZS1akkLMfWs2eEnUmGo,37734 +importlib_metadata/__pycache__/__init__.cpython-311.pyc,, +importlib_metadata/__pycache__/_adapters.cpython-311.pyc,, +importlib_metadata/__pycache__/_collections.cpython-311.pyc,, +importlib_metadata/__pycache__/_compat.cpython-311.pyc,, +importlib_metadata/__pycache__/_functools.cpython-311.pyc,, +importlib_metadata/__pycache__/_itertools.cpython-311.pyc,, +importlib_metadata/__pycache__/_meta.cpython-311.pyc,, +importlib_metadata/__pycache__/_text.cpython-311.pyc,, +importlib_metadata/__pycache__/_typing.cpython-311.pyc,, +importlib_metadata/__pycache__/diagnose.cpython-311.pyc,, +importlib_metadata/_adapters.py,sha256=r5i8XLrKT6xmrpoREZhZrfczOYDmrVZeJBW5u0HzIGU,3797 +importlib_metadata/_collections.py,sha256=CxAhzlF3g1rwu_fMiB53JtRQiUFh0RgiMpoOvmK_ocg,760 +importlib_metadata/_compat.py,sha256=VC5ZDLlT-BcshauCShdFJvMNLntJJfZzNK1meGa-enw,1313 +importlib_metadata/_functools.py,sha256=0pA2OoiVK6wnsGq8HvVIzgdkvLiZ0nfnfw7IsndjoHk,3510 +importlib_metadata/_itertools.py,sha256=nMvp9SfHAQ_JYwK4L2i64lr3GRXGlYlikGTVzWbys_E,5351 +importlib_metadata/_meta.py,sha256=EtHyiJ5kGzWFDfKyQ2XQp6Vu113CeadKW1Vf6aGc1B4,1765 +importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166 +importlib_metadata/_typing.py,sha256=EQKhhsEgz_Sa-FnePI-faC72rNOOQwopjA1i5pG8FDU,367 +importlib_metadata/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_metadata/compat/__pycache__/__init__.cpython-311.pyc,, +importlib_metadata/compat/__pycache__/py311.cpython-311.pyc,, +importlib_metadata/compat/__pycache__/py39.cpython-311.pyc,, +importlib_metadata/compat/py311.py,sha256=uqm-K-uohyj1042TH4a9Er_I5o7667DvulcD-gC_fSA,608 +importlib_metadata/compat/py39.py,sha256=J3W7PUVRPNYMmcvT12RF8ndBU9e8_T0Ac4U87Bsrq70,1187 +importlib_metadata/diagnose.py,sha256=nkSRMiowlmkhLYhKhvCg9glmt_11Cox-EmLzEbqYTa8,379 +importlib_metadata/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..bbb07547a19c30031d13c45cf01cba61dc434e47 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata-8.7.1.dist-info/top_level.txt @@ -0,0 +1 @@ +importlib_metadata diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..508b02e4fce3fa9463b7466138cca7414db0e9b9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/__init__.py @@ -0,0 +1,1191 @@ +""" +APIs exposing metadata from third-party Python packages. + +This codebase is shared between importlib.metadata in the stdlib +and importlib_metadata in PyPI. See +https://github.com/python/importlib_metadata/wiki/Development-Methodology +for more detail. +""" + +from __future__ import annotations + +import abc +import collections +import email +import functools +import itertools +import operator +import os +import pathlib +import posixpath +import re +import sys +import textwrap +import types +from collections.abc import Iterable, Mapping +from contextlib import suppress +from importlib import import_module +from importlib.abc import MetaPathFinder +from itertools import starmap +from typing import Any + +from . import _meta +from ._collections import FreezableDefaultDict, Pair +from ._compat import ( + NullFinder, + install, +) +from ._functools import method_cache, noop, pass_none, passthrough +from ._itertools import always_iterable, bucket, unique_everseen +from ._meta import PackageMetadata, SimplePath +from ._typing import md_none +from .compat import py39, py311 + +__all__ = [ + 'Distribution', + 'DistributionFinder', + 'PackageMetadata', + 'PackageNotFoundError', + 'SimplePath', + 'distribution', + 'distributions', + 'entry_points', + 'files', + 'metadata', + 'packages_distributions', + 'requires', + 'version', +] + + +class PackageNotFoundError(ModuleNotFoundError): + """The package was not found.""" + + def __str__(self) -> str: + return f"No package metadata was found for {self.name}" + + @property + def name(self) -> str: # type: ignore[override] # make readonly + (name,) = self.args + return name + + +class Sectioned: + """ + A simple entry point config parser for performance + + >>> for item in Sectioned.read(Sectioned._sample): + ... print(item) + Pair(name='sec1', value='# comments ignored') + Pair(name='sec1', value='a = 1') + Pair(name='sec1', value='b = 2') + Pair(name='sec2', value='a = 2') + + >>> res = Sectioned.section_pairs(Sectioned._sample) + >>> item = next(res) + >>> item.name + 'sec1' + >>> item.value + Pair(name='a', value='1') + >>> item = next(res) + >>> item.value + Pair(name='b', value='2') + >>> item = next(res) + >>> item.name + 'sec2' + >>> item.value + Pair(name='a', value='2') + >>> list(res) + [] + """ + + _sample = textwrap.dedent( + """ + [sec1] + # comments ignored + a = 1 + b = 2 + + [sec2] + a = 2 + """ + ).lstrip() + + @classmethod + def section_pairs(cls, text): + return ( + section._replace(value=Pair.parse(section.value)) + for section in cls.read(text, filter_=cls.valid) + if section.name is not None + ) + + @staticmethod + def read(text, filter_=None): + lines = filter(filter_, map(str.strip, text.splitlines())) + name = None + for value in lines: + section_match = value.startswith('[') and value.endswith(']') + if section_match: + name = value.strip('[]') + continue + yield Pair(name, value) + + @staticmethod + def valid(line: str): + return line and not line.startswith('#') + + +class _EntryPointMatch(types.SimpleNamespace): + module: str + attr: str + extras: str + + +class EntryPoint: + """An entry point as defined by Python packaging conventions. + + See `the packaging docs on entry points + `_ + for more information. + + >>> ep = EntryPoint( + ... name=None, group=None, value='package.module:attr [extra1, extra2]') + >>> ep.module + 'package.module' + >>> ep.attr + 'attr' + >>> ep.extras + ['extra1', 'extra2'] + + If the value package or module are not valid identifiers, a + ValueError is raised on access. + + >>> EntryPoint(name=None, group=None, value='invalid-name').module + Traceback (most recent call last): + ... + ValueError: ('Invalid object reference...invalid-name... + >>> EntryPoint(name=None, group=None, value='invalid-name').attr + Traceback (most recent call last): + ... + ValueError: ('Invalid object reference...invalid-name... + >>> EntryPoint(name=None, group=None, value='invalid-name').extras + Traceback (most recent call last): + ... + ValueError: ('Invalid object reference...invalid-name... + + The same thing happens on construction. + + >>> EntryPoint(name=None, group=None, value='invalid-name') + Traceback (most recent call last): + ... + ValueError: ('Invalid object reference...invalid-name... + + """ + + pattern = re.compile( + r'(?P[\w.]+)\s*' + r'(:\s*(?P[\w.]+)\s*)?' + r'((?P\[.*\])\s*)?$' + ) + """ + A regular expression describing the syntax for an entry point, + which might look like: + + - module + - package.module + - package.module:attribute + - package.module:object.attribute + - package.module:attr [extra1, extra2] + + Other combinations are possible as well. + + The expression is lenient about whitespace around the ':', + following the attr, and following any extras. + """ + + name: str + value: str + group: str + + dist: Distribution | None = None + + def __init__(self, name: str, value: str, group: str) -> None: + vars(self).update(name=name, value=value, group=group) + self.module + + def load(self) -> Any: + """Load the entry point from its definition. If only a module + is indicated by the value, return that module. Otherwise, + return the named object. + """ + module = import_module(self.module) + attrs = filter(None, (self.attr or '').split('.')) + return functools.reduce(getattr, attrs, module) + + @property + def module(self) -> str: + return self._match.module + + @property + def attr(self) -> str: + return self._match.attr + + @property + def extras(self) -> list[str]: + return re.findall(r'\w+', self._match.extras or '') + + @functools.cached_property + def _match(self) -> _EntryPointMatch: + match = self.pattern.match(self.value) + if not match: + raise ValueError( + 'Invalid object reference. ' + 'See https://packaging.python.org' + '/en/latest/specifications/entry-points/#data-model', + self.value, + ) + return _EntryPointMatch(**match.groupdict()) + + def _for(self, dist): + vars(self).update(dist=dist) + return self + + def matches(self, **params): + """ + EntryPoint matches the given parameters. + + >>> ep = EntryPoint(group='foo', name='bar', value='bing:bong [extra1, extra2]') + >>> ep.matches(group='foo') + True + >>> ep.matches(name='bar', value='bing:bong [extra1, extra2]') + True + >>> ep.matches(group='foo', name='other') + False + >>> ep.matches() + True + >>> ep.matches(extras=['extra1', 'extra2']) + True + >>> ep.matches(module='bing') + True + >>> ep.matches(attr='bong') + True + """ + self._disallow_dist(params) + attrs = (getattr(self, param) for param in params) + return all(map(operator.eq, params.values(), attrs)) + + @staticmethod + def _disallow_dist(params): + """ + Querying by dist is not allowed (dist objects are not comparable). + >>> EntryPoint(name='fan', value='fav', group='fag').matches(dist='foo') + Traceback (most recent call last): + ... + ValueError: "dist" is not suitable for matching... + """ + if "dist" in params: + raise ValueError( + '"dist" is not suitable for matching. ' + "Instead, use Distribution.entry_points.select() on a " + "located distribution." + ) + + def _key(self): + return self.name, self.value, self.group + + def __lt__(self, other): + return self._key() < other._key() + + def __eq__(self, other): + return self._key() == other._key() + + def __setattr__(self, name, value): + raise AttributeError("EntryPoint objects are immutable.") + + def __repr__(self): + return ( + f'EntryPoint(name={self.name!r}, value={self.value!r}, ' + f'group={self.group!r})' + ) + + def __hash__(self) -> int: + return hash(self._key()) + + +class EntryPoints(tuple): + """ + An immutable collection of selectable EntryPoint objects. + """ + + __slots__ = () + + def __getitem__(self, name: str) -> EntryPoint: # type: ignore[override] # Work with str instead of int + """ + Get the EntryPoint in self matching name. + """ + try: + return next(iter(self.select(name=name))) + except StopIteration: + raise KeyError(name) + + def __repr__(self): + """ + Repr with classname and tuple constructor to + signal that we deviate from regular tuple behavior. + """ + return '%s(%r)' % (self.__class__.__name__, tuple(self)) + + def select(self, **params) -> EntryPoints: + """ + Select entry points from self that match the + given parameters (typically group and/or name). + """ + return EntryPoints(ep for ep in self if py39.ep_matches(ep, **params)) + + @property + def names(self) -> set[str]: + """ + Return the set of all names of all entry points. + """ + return {ep.name for ep in self} + + @property + def groups(self) -> set[str]: + """ + Return the set of all groups of all entry points. + """ + return {ep.group for ep in self} + + @classmethod + def _from_text_for(cls, text, dist): + return cls(ep._for(dist) for ep in cls._from_text(text)) + + @staticmethod + def _from_text(text): + return ( + EntryPoint(name=item.value.name, value=item.value.value, group=item.name) + for item in Sectioned.section_pairs(text or '') + ) + + +class PackagePath(pathlib.PurePosixPath): + """A reference to a path in a package""" + + hash: FileHash | None + size: int + dist: Distribution + + def read_text(self, encoding: str = 'utf-8') -> str: + return self.locate().read_text(encoding=encoding) + + def read_binary(self) -> bytes: + return self.locate().read_bytes() + + def locate(self) -> SimplePath: + """Return a path-like object for this path""" + return self.dist.locate_file(self) + + +class FileHash: + def __init__(self, spec: str) -> None: + self.mode, _, self.value = spec.partition('=') + + def __repr__(self) -> str: + return f'' + + +class Distribution(metaclass=abc.ABCMeta): + """ + An abstract Python distribution package. + + Custom providers may derive from this class and define + the abstract methods to provide a concrete implementation + for their environment. Some providers may opt to override + the default implementation of some properties to bypass + the file-reading mechanism. + """ + + @abc.abstractmethod + def read_text(self, filename) -> str | None: + """Attempt to load metadata file given by the name. + + Python distribution metadata is organized by blobs of text + typically represented as "files" in the metadata directory + (e.g. package-1.0.dist-info). These files include things + like: + + - METADATA: The distribution metadata including fields + like Name and Version and Description. + - entry_points.txt: A series of entry points as defined in + `the entry points spec `_. + - RECORD: A record of files according to + `this recording spec `_. + + A package may provide any set of files, including those + not listed here or none at all. + + :param filename: The name of the file in the distribution info. + :return: The text if found, otherwise None. + """ + + @abc.abstractmethod + def locate_file(self, path: str | os.PathLike[str]) -> SimplePath: + """ + Given a path to a file in this distribution, return a SimplePath + to it. + + This method is used by callers of ``Distribution.files()`` to + locate files within the distribution. If it's possible for a + Distribution to represent files in the distribution as + ``SimplePath`` objects, it should implement this method + to resolve such objects. + + Some Distribution providers may elect not to resolve SimplePath + objects within the distribution by raising a + NotImplementedError, but consumers of such a Distribution would + be unable to invoke ``Distribution.files()``. + """ + + @classmethod + def from_name(cls, name: str) -> Distribution: + """Return the Distribution for the given package name. + + :param name: The name of the distribution package to search for. + :return: The Distribution instance (or subclass thereof) for the named + package, if found. + :raises PackageNotFoundError: When the named package's distribution + metadata cannot be found. + :raises ValueError: When an invalid value is supplied for name. + """ + if not name: + raise ValueError("A distribution name is required.") + try: + return next(iter(cls._prefer_valid(cls.discover(name=name)))) + except StopIteration: + raise PackageNotFoundError(name) + + @classmethod + def discover( + cls, *, context: DistributionFinder.Context | None = None, **kwargs + ) -> Iterable[Distribution]: + """Return an iterable of Distribution objects for all packages. + + Pass a ``context`` or pass keyword arguments for constructing + a context. + + :context: A ``DistributionFinder.Context`` object. + :return: Iterable of Distribution objects for packages matching + the context. + """ + if context and kwargs: + raise ValueError("cannot accept context and kwargs") + context = context or DistributionFinder.Context(**kwargs) + return itertools.chain.from_iterable( + resolver(context) for resolver in cls._discover_resolvers() + ) + + @staticmethod + def _prefer_valid(dists: Iterable[Distribution]) -> Iterable[Distribution]: + """ + Prefer (move to the front) distributions that have metadata. + + Ref python/importlib_resources#489. + """ + buckets = bucket(dists, lambda dist: bool(dist.metadata)) + return itertools.chain(buckets[True], buckets[False]) + + @staticmethod + def at(path: str | os.PathLike[str]) -> Distribution: + """Return a Distribution for the indicated metadata path. + + :param path: a string or path-like object + :return: a concrete Distribution instance for the path + """ + return PathDistribution(pathlib.Path(path)) + + @staticmethod + def _discover_resolvers(): + """Search the meta_path for resolvers (MetadataPathFinders).""" + declared = ( + getattr(finder, 'find_distributions', None) for finder in sys.meta_path + ) + return filter(None, declared) + + @property + def metadata(self) -> _meta.PackageMetadata | None: + """Return the parsed metadata for this Distribution. + + The returned object will have keys that name the various bits of + metadata per the + `Core metadata specifications `_. + + Custom providers may provide the METADATA file or override this + property. + """ + + text = ( + self.read_text('METADATA') + or self.read_text('PKG-INFO') + # This last clause is here to support old egg-info files. Its + # effect is to just end up using the PathDistribution's self._path + # (which points to the egg-info file) attribute unchanged. + or self.read_text('') + ) + return self._assemble_message(text) + + @staticmethod + @pass_none + def _assemble_message(text: str) -> _meta.PackageMetadata: + # deferred for performance (python/cpython#109829) + from . import _adapters + + return _adapters.Message(email.message_from_string(text)) + + @property + def name(self) -> str: + """Return the 'Name' metadata for the distribution package.""" + return md_none(self.metadata)['Name'] + + @property + def _normalized_name(self): + """Return a normalized version of the name.""" + return Prepared.normalize(self.name) + + @property + def version(self) -> str: + """Return the 'Version' metadata for the distribution package.""" + return md_none(self.metadata)['Version'] + + @property + def entry_points(self) -> EntryPoints: + """ + Return EntryPoints for this distribution. + + Custom providers may provide the ``entry_points.txt`` file + or override this property. + """ + return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self) + + @property + def files(self) -> list[PackagePath] | None: + """Files in this distribution. + + :return: List of PackagePath for this distribution or None + + Result is `None` if the metadata file that enumerates files + (i.e. RECORD for dist-info, or installed-files.txt or + SOURCES.txt for egg-info) is missing. + Result may be empty if the metadata exists but is empty. + + Custom providers are recommended to provide a "RECORD" file (in + ``read_text``) or override this property to allow for callers to be + able to resolve filenames provided by the package. + """ + + def make_file(name, hash=None, size_str=None): + result = PackagePath(name) + result.hash = FileHash(hash) if hash else None + result.size = int(size_str) if size_str else None + result.dist = self + return result + + @pass_none + def make_files(lines): + # Delay csv import, since Distribution.files is not as widely used + # as other parts of importlib.metadata + import csv + + return starmap(make_file, csv.reader(lines)) + + @pass_none + def skip_missing_files(package_paths): + return list(filter(lambda path: path.locate().exists(), package_paths)) + + return skip_missing_files( + make_files( + self._read_files_distinfo() + or self._read_files_egginfo_installed() + or self._read_files_egginfo_sources() + ) + ) + + def _read_files_distinfo(self): + """ + Read the lines of RECORD. + """ + text = self.read_text('RECORD') + return text and text.splitlines() + + def _read_files_egginfo_installed(self): + """ + Read installed-files.txt and return lines in a similar + CSV-parsable format as RECORD: each file must be placed + relative to the site-packages directory and must also be + quoted (since file names can contain literal commas). + + This file is written when the package is installed by pip, + but it might not be written for other installation methods. + Assume the file is accurate if it exists. + """ + text = self.read_text('installed-files.txt') + # Prepend the .egg-info/ subdir to the lines in this file. + # But this subdir is only available from PathDistribution's + # self._path. + subdir = getattr(self, '_path', None) + if not text or not subdir: + return + + paths = ( + py311 + .relative_fix((subdir / name).resolve()) + .relative_to(self.locate_file('').resolve(), walk_up=True) + .as_posix() + for name in text.splitlines() + ) + return map('"{}"'.format, paths) + + def _read_files_egginfo_sources(self): + """ + Read SOURCES.txt and return lines in a similar CSV-parsable + format as RECORD: each file name must be quoted (since it + might contain literal commas). + + Note that SOURCES.txt is not a reliable source for what + files are installed by a package. This file is generated + for a source archive, and the files that are present + there (e.g. setup.py) may not correctly reflect the files + that are present after the package has been installed. + """ + text = self.read_text('SOURCES.txt') + return text and map('"{}"'.format, text.splitlines()) + + @property + def requires(self) -> list[str] | None: + """Generated requirements specified for this Distribution""" + reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs() + return reqs and list(reqs) + + def _read_dist_info_reqs(self): + return self.metadata.get_all('Requires-Dist') + + def _read_egg_info_reqs(self): + source = self.read_text('requires.txt') + return pass_none(self._deps_from_requires_text)(source) + + @classmethod + def _deps_from_requires_text(cls, source): + return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source)) + + @staticmethod + def _convert_egg_info_reqs_to_simple_reqs(sections): + """ + Historically, setuptools would solicit and store 'extra' + requirements, including those with environment markers, + in separate sections. More modern tools expect each + dependency to be defined separately, with any relevant + extras and environment markers attached directly to that + requirement. This method converts the former to the + latter. See _test_deps_from_requires_text for an example. + """ + + def make_condition(name): + return name and f'extra == "{name}"' + + def quoted_marker(section): + section = section or '' + extra, sep, markers = section.partition(':') + if extra and markers: + markers = f'({markers})' + conditions = list(filter(None, [markers, make_condition(extra)])) + return '; ' + ' and '.join(conditions) if conditions else '' + + def url_req_space(req): + """ + PEP 508 requires a space between the url_spec and the quoted_marker. + Ref python/importlib_metadata#357. + """ + # '@' is uniquely indicative of a url_req. + return ' ' * ('@' in req) + + for section in sections: + space = url_req_space(section.value) + yield section.value + space + quoted_marker(section.name) + + @property + def origin(self): + return self._load_json('direct_url.json') + + def _load_json(self, filename): + # Deferred for performance (python/importlib_metadata#503) + import json + + return pass_none(json.loads)( + self.read_text(filename), + object_hook=lambda data: types.SimpleNamespace(**data), + ) + + +class DistributionFinder(MetaPathFinder): + """ + A MetaPathFinder capable of discovering installed distributions. + + Custom providers should implement this interface in order to + supply metadata. + """ + + class Context: + """ + Keyword arguments presented by the caller to + ``distributions()`` or ``Distribution.discover()`` + to narrow the scope of a search for distributions + in all DistributionFinders. + + Each DistributionFinder may expect any parameters + and should attempt to honor the canonical + parameters defined below when appropriate. + + This mechanism gives a custom provider a means to + solicit additional details from the caller beyond + "name" and "path" when searching distributions. + For example, imagine a provider that exposes suites + of packages in either a "public" or "private" ``realm``. + A caller may wish to query only for distributions in + a particular realm and could call + ``distributions(realm="private")`` to signal to the + custom provider to only include distributions from that + realm. + """ + + name = None + """ + Specific name for which a distribution finder should match. + A name of ``None`` matches all distributions. + """ + + def __init__(self, **kwargs): + vars(self).update(kwargs) + + @property + def path(self) -> list[str]: + """ + The sequence of directory path that a distribution finder + should search. + + Typically refers to Python installed package paths such as + "site-packages" directories and defaults to ``sys.path``. + """ + return vars(self).get('path', sys.path) + + @abc.abstractmethod + def find_distributions(self, context=Context()) -> Iterable[Distribution]: + """ + Find distributions. + + Return an iterable of all Distribution instances capable of + loading the metadata for packages matching the ``context``, + a DistributionFinder.Context instance. + """ + + +@passthrough +def _clear_after_fork(cached): + """Ensure ``func`` clears cached state after ``fork`` when supported. + + ``FastPath`` caches zip-backed ``pathlib.Path`` objects that retain a + reference to the parent's open ``ZipFile`` handle. Re-using a cached + instance in a forked child can therefore resurrect invalid file pointers + and trigger ``BadZipFile``/``OSError`` failures (python/importlib_metadata#520). + Registering ``cache_clear`` with ``os.register_at_fork`` keeps each process + on its own cache. + """ + getattr(os, 'register_at_fork', noop)(after_in_child=cached.cache_clear) + + +class FastPath: + """ + Micro-optimized class for searching a root for children. + + Root is a path on the file system that may contain metadata + directories either as natural directories or within a zip file. + + >>> FastPath('').children() + ['...'] + + FastPath objects are cached and recycled for any given root. + + >>> FastPath('foobar') is FastPath('foobar') + True + """ + + @_clear_after_fork # type: ignore[misc] + @functools.lru_cache() + def __new__(cls, root): + return super().__new__(cls) + + def __init__(self, root): + self.root = root + + def joinpath(self, child): + return pathlib.Path(self.root, child) + + def children(self): + with suppress(Exception): + return os.listdir(self.root or '.') + with suppress(Exception): + return self.zip_children() + return [] + + def zip_children(self): + # deferred for performance (python/importlib_metadata#502) + from zipp.compat.overlay import zipfile + + zip_path = zipfile.Path(self.root) + names = zip_path.root.namelist() + self.joinpath = zip_path.joinpath + + return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names) + + def search(self, name): + return self.lookup(self.mtime).search(name) + + @property + def mtime(self): + with suppress(OSError): + return os.stat(self.root).st_mtime + self.lookup.cache_clear() + + @method_cache + def lookup(self, mtime): + return Lookup(self) + + +class Lookup: + """ + A micro-optimized class for searching a (fast) path for metadata. + """ + + def __init__(self, path: FastPath): + """ + Calculate all of the children representing metadata. + + From the children in the path, calculate early all of the + children that appear to represent metadata (infos) or legacy + metadata (eggs). + """ + + base = os.path.basename(path.root).lower() + base_is_egg = base.endswith(".egg") + self.infos = FreezableDefaultDict(list) + self.eggs = FreezableDefaultDict(list) + + for child in path.children(): + low = child.lower() + if low.endswith((".dist-info", ".egg-info")): + # rpartition is faster than splitext and suitable for this purpose. + name = low.rpartition(".")[0].partition("-")[0] + normalized = Prepared.normalize(name) + self.infos[normalized].append(path.joinpath(child)) + elif base_is_egg and low == "egg-info": + name = base.rpartition(".")[0].partition("-")[0] + legacy_normalized = Prepared.legacy_normalize(name) + self.eggs[legacy_normalized].append(path.joinpath(child)) + + self.infos.freeze() + self.eggs.freeze() + + def search(self, prepared: Prepared): + """ + Yield all infos and eggs matching the Prepared query. + """ + infos = ( + self.infos[prepared.normalized] + if prepared + else itertools.chain.from_iterable(self.infos.values()) + ) + eggs = ( + self.eggs[prepared.legacy_normalized] + if prepared + else itertools.chain.from_iterable(self.eggs.values()) + ) + return itertools.chain(infos, eggs) + + +class Prepared: + """ + A prepared search query for metadata on a possibly-named package. + + Pre-calculates the normalization to prevent repeated operations. + + >>> none = Prepared(None) + >>> none.normalized + >>> none.legacy_normalized + >>> bool(none) + False + >>> sample = Prepared('Sample__Pkg-name.foo') + >>> sample.normalized + 'sample_pkg_name_foo' + >>> sample.legacy_normalized + 'sample__pkg_name.foo' + >>> bool(sample) + True + """ + + normalized = None + legacy_normalized = None + + def __init__(self, name: str | None): + self.name = name + if name is None: + return + self.normalized = self.normalize(name) + self.legacy_normalized = self.legacy_normalize(name) + + @staticmethod + def normalize(name): + """ + PEP 503 normalization plus dashes as underscores. + """ + return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_') + + @staticmethod + def legacy_normalize(name): + """ + Normalize the package name as found in the convention in + older packaging tools versions and specs. + """ + return name.lower().replace('-', '_') + + def __bool__(self): + return bool(self.name) + + +@install +class MetadataPathFinder(NullFinder, DistributionFinder): + """A degenerate finder for distribution packages on the file system. + + This finder supplies only a find_distributions() method for versions + of Python that do not have a PathFinder find_distributions(). + """ + + @classmethod + def find_distributions( + cls, context=DistributionFinder.Context() + ) -> Iterable[PathDistribution]: + """ + Find distributions. + + Return an iterable of all Distribution instances capable of + loading the metadata for packages matching ``context.name`` + (or all names if ``None`` indicated) along the paths in the list + of directories ``context.path``. + """ + found = cls._search_paths(context.name, context.path) + return map(PathDistribution, found) + + @classmethod + def _search_paths(cls, name, paths): + """Find metadata directories in paths heuristically.""" + prepared = Prepared(name) + return itertools.chain.from_iterable( + path.search(prepared) for path in map(FastPath, paths) + ) + + @classmethod + def invalidate_caches(cls) -> None: + FastPath.__new__.cache_clear() + + +class PathDistribution(Distribution): + def __init__(self, path: SimplePath) -> None: + """Construct a distribution. + + :param path: SimplePath indicating the metadata directory. + """ + self._path = path + + def read_text(self, filename: str | os.PathLike[str]) -> str | None: + with suppress( + FileNotFoundError, + IsADirectoryError, + KeyError, + NotADirectoryError, + PermissionError, + ): + return self._path.joinpath(filename).read_text(encoding='utf-8') + + return None + + read_text.__doc__ = Distribution.read_text.__doc__ + + def locate_file(self, path: str | os.PathLike[str]) -> SimplePath: + return self._path.parent / path + + @property + def _normalized_name(self): + """ + Performance optimization: where possible, resolve the + normalized name from the file system path. + """ + stem = os.path.basename(str(self._path)) + return ( + pass_none(Prepared.normalize)(self._name_from_stem(stem)) + or super()._normalized_name + ) + + @staticmethod + def _name_from_stem(stem): + """ + >>> PathDistribution._name_from_stem('foo-3.0.egg-info') + 'foo' + >>> PathDistribution._name_from_stem('CherryPy-3.0.dist-info') + 'CherryPy' + >>> PathDistribution._name_from_stem('face.egg-info') + 'face' + >>> PathDistribution._name_from_stem('foo.bar') + """ + filename, ext = os.path.splitext(stem) + if ext not in ('.dist-info', '.egg-info'): + return + name, sep, rest = filename.partition('-') + return name + + +def distribution(distribution_name: str) -> Distribution: + """Get the ``Distribution`` instance for the named package. + + :param distribution_name: The name of the distribution package as a string. + :return: A ``Distribution`` instance (or subclass thereof). + """ + return Distribution.from_name(distribution_name) + + +def distributions(**kwargs) -> Iterable[Distribution]: + """Get all ``Distribution`` instances in the current environment. + + :return: An iterable of ``Distribution`` instances. + """ + return Distribution.discover(**kwargs) + + +def metadata(distribution_name: str) -> _meta.PackageMetadata | None: + """Get the metadata for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: A PackageMetadata containing the parsed metadata. + """ + return Distribution.from_name(distribution_name).metadata + + +def version(distribution_name: str) -> str: + """Get the version string for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: The version string for the package as defined in the package's + "Version" metadata key. + """ + return distribution(distribution_name).version + + +_unique = functools.partial( + unique_everseen, + key=py39.normalized_name, +) +""" +Wrapper for ``distributions`` to return unique distributions by name. +""" + + +def entry_points(**params) -> EntryPoints: + """Return EntryPoint objects for all installed packages. + + Pass selection parameters (group or name) to filter the + result to entry points matching those properties (see + EntryPoints.select()). + + :return: EntryPoints for all installed packages. + """ + eps = itertools.chain.from_iterable( + dist.entry_points for dist in _unique(distributions()) + ) + return EntryPoints(eps).select(**params) + + +def files(distribution_name: str) -> list[PackagePath] | None: + """Return a list of files for the named package. + + :param distribution_name: The name of the distribution package to query. + :return: List of files composing the distribution. + """ + return distribution(distribution_name).files + + +def requires(distribution_name: str) -> list[str] | None: + """ + Return a list of requirements for the named package. + + :return: An iterable of requirements, suitable for + packaging.requirement.Requirement. + """ + return distribution(distribution_name).requires + + +def packages_distributions() -> Mapping[str, list[str]]: + """ + Return a mapping of top-level packages to their + distributions. + + >>> import collections.abc + >>> pkgs = packages_distributions() + >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values()) + True + """ + pkg_to_dist = collections.defaultdict(list) + for dist in distributions(): + for pkg in _top_level_declared(dist) or _top_level_inferred(dist): + pkg_to_dist[pkg].append(md_none(dist.metadata)['Name']) + return dict(pkg_to_dist) + + +def _top_level_declared(dist): + return (dist.read_text('top_level.txt') or '').split() + + +def _topmost(name: PackagePath) -> str | None: + """ + Return the top-most parent as long as there is a parent. + """ + top, *rest = name.parts + return top if rest else None + + +def _get_toplevel_name(name: PackagePath) -> str: + """ + Infer a possibly importable module name from a name presumed on + sys.path. + + >>> _get_toplevel_name(PackagePath('foo.py')) + 'foo' + >>> _get_toplevel_name(PackagePath('foo')) + 'foo' + >>> _get_toplevel_name(PackagePath('foo.pyc')) + 'foo' + >>> _get_toplevel_name(PackagePath('foo/__init__.py')) + 'foo' + >>> _get_toplevel_name(PackagePath('foo.pth')) + 'foo.pth' + >>> _get_toplevel_name(PackagePath('foo.dist-info')) + 'foo.dist-info' + """ + # Defer import of inspect for performance (python/cpython#118761) + import inspect + + return _topmost(name) or inspect.getmodulename(name) or str(name) + + +def _top_level_inferred(dist): + opt_names = set(map(_get_toplevel_name, always_iterable(dist.files))) + + def importable_name(name): + return '.' not in name + + return filter(importable_name, opt_names) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_adapters.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..dede395d79a38bab322d56a66d916703af84f77b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_adapters.py @@ -0,0 +1,136 @@ +import email.message +import email.policy +import re +import textwrap + +from ._text import FoldedCase + + +class RawPolicy(email.policy.EmailPolicy): + def fold(self, name, value): + folded = self.linesep.join( + textwrap + .indent(value, prefix=' ' * 8, predicate=lambda line: True) + .lstrip() + .splitlines() + ) + return f'{name}: {folded}{self.linesep}' + + +class Message(email.message.Message): + r""" + Specialized Message subclass to handle metadata naturally. + + Reads values that may have newlines in them and converts the + payload to the Description. + + >>> msg_text = textwrap.dedent(''' + ... Name: Foo + ... Version: 3.0 + ... License: blah + ... de-blah + ... + ... First line of description. + ... Second line of description. + ... + ... Fourth line! + ... ''').lstrip().replace('', '') + >>> msg = Message(email.message_from_string(msg_text)) + >>> msg['Description'] + 'First line of description.\nSecond line of description.\n\nFourth line!\n' + + Message should render even if values contain newlines. + + >>> print(msg) + Name: Foo + Version: 3.0 + License: blah + de-blah + Description: First line of description. + Second line of description. + + Fourth line! + + + """ + + multiple_use_keys = set( + map( + FoldedCase, + [ + 'Classifier', + 'Obsoletes-Dist', + 'Platform', + 'Project-URL', + 'Provides-Dist', + 'Provides-Extra', + 'Requires-Dist', + 'Requires-External', + 'Supported-Platform', + 'Dynamic', + ], + ) + ) + """ + Keys that may be indicated multiple times per PEP 566. + """ + + def __new__(cls, orig: email.message.Message): + res = super().__new__(cls) + vars(res).update(vars(orig)) + return res + + def __init__(self, *args, **kwargs): + self._headers = self._repair_headers() + + # suppress spurious error from mypy + def __iter__(self): + return super().__iter__() + + def __getitem__(self, item): + """ + Override parent behavior to typical dict behavior. + + ``email.message.Message`` will emit None values for missing + keys. Typical mappings, including this ``Message``, will raise + a key error for missing keys. + + Ref python/importlib_metadata#371. + """ + res = super().__getitem__(item) + if res is None: + raise KeyError(item) + return res + + def _repair_headers(self): + def redent(value): + "Correct for RFC822 indentation" + indent = ' ' * 8 + if not value or '\n' + indent not in value: + return value + return textwrap.dedent(indent + value) + + headers = [(key, redent(value)) for key, value in vars(self)['_headers']] + if self._payload: + headers.append(('Description', self.get_payload())) + self.set_payload('') + return headers + + def as_string(self): + return super().as_string(policy=RawPolicy()) + + @property + def json(self): + """ + Convert PackageMetadata to a JSON-compatible format + per PEP 0566. + """ + + def transform(key): + value = self.get_all(key) if key in self.multiple_use_keys else self[key] + if key == 'Keywords': + value = re.split(r'\s+', value) + tk = key.lower().replace('-', '_') + return tk, value + + return dict(map(transform, map(FoldedCase, self))) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_collections.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..fc5045d36be57251000393b32baba7baa9cd8c4f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_collections.py @@ -0,0 +1,34 @@ +import collections +import typing + + +# from jaraco.collections 3.3 +class FreezableDefaultDict(collections.defaultdict): + """ + Often it is desirable to prevent the mutation of + a default dict after its initial construction, such + as to prevent mutation during iteration. + + >>> dd = FreezableDefaultDict(list) + >>> dd[0].append('1') + >>> dd.freeze() + >>> dd[1] + [] + >>> len(dd) + 1 + """ + + def __missing__(self, key): + return getattr(self, '_frozen', super().__missing__)(key) + + def freeze(self): + self._frozen = lambda key: self.default_factory() + + +class Pair(typing.NamedTuple): + name: str + value: str + + @classmethod + def parse(cls, text): + return cls(*map(str.strip, text.split("=", 1))) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_compat.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..01356d69b97c95a6d41818e5c2c50a299146bef4 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_compat.py @@ -0,0 +1,56 @@ +import platform +import sys + +__all__ = ['install', 'NullFinder'] + + +def install(cls): + """ + Class decorator for installation on sys.meta_path. + + Adds the backport DistributionFinder to sys.meta_path and + attempts to disable the finder functionality of the stdlib + DistributionFinder. + """ + sys.meta_path.append(cls()) + disable_stdlib_finder() + return cls + + +def disable_stdlib_finder(): + """ + Give the backport primacy for discovering path-based distributions + by monkey-patching the stdlib O_O. + + See #91 for more background for rationale on this sketchy + behavior. + """ + + def matches(finder): + return getattr( + finder, '__module__', None + ) == '_frozen_importlib_external' and hasattr(finder, 'find_distributions') + + for finder in filter(matches, sys.meta_path): # pragma: nocover + del finder.find_distributions + + +class NullFinder: + """ + A "Finder" (aka "MetaPathFinder") that never finds any modules, + but may find distributions. + """ + + @staticmethod + def find_spec(*args, **kwargs): + return None + + +def pypy_partial(val): + """ + Adjust for variable stacklevel on partial under PyPy. + + Workaround for #327. + """ + is_pypy = platform.python_implementation() == 'PyPy' + return val + is_pypy diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_functools.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_functools.py new file mode 100644 index 0000000000000000000000000000000000000000..b1fd04a84ab4c129b19f71a13f7489c37d1a9e9e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_functools.py @@ -0,0 +1,135 @@ +import functools +import types +from typing import Callable, TypeVar + + +# from jaraco.functools 3.3 +def method_cache(method, cache_wrapper=None): + """ + Wrap lru_cache to support storing the cache data in the object instances. + + Abstracts the common paradigm where the method explicitly saves an + underscore-prefixed protected property on first call and returns that + subsequently. + + >>> class MyClass: + ... calls = 0 + ... + ... @method_cache + ... def method(self, value): + ... self.calls += 1 + ... return value + + >>> a = MyClass() + >>> a.method(3) + 3 + >>> for x in range(75): + ... res = a.method(x) + >>> a.calls + 75 + + Note that the apparent behavior will be exactly like that of lru_cache + except that the cache is stored on each instance, so values in one + instance will not flush values from another, and when an instance is + deleted, so are the cached values for that instance. + + >>> b = MyClass() + >>> for x in range(35): + ... res = b.method(x) + >>> b.calls + 35 + >>> a.method(0) + 0 + >>> a.calls + 75 + + Note that if method had been decorated with ``functools.lru_cache()``, + a.calls would have been 76 (due to the cached value of 0 having been + flushed by the 'b' instance). + + Clear the cache with ``.cache_clear()`` + + >>> a.method.cache_clear() + + Same for a method that hasn't yet been called. + + >>> c = MyClass() + >>> c.method.cache_clear() + + Another cache wrapper may be supplied: + + >>> cache = functools.lru_cache(maxsize=2) + >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache) + >>> a = MyClass() + >>> a.method2() + 3 + + Caution - do not subsequently wrap the method with another decorator, such + as ``@property``, which changes the semantics of the function. + + See also + http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/ + for another implementation and additional justification. + """ + cache_wrapper = cache_wrapper or functools.lru_cache() + + def wrapper(self, *args, **kwargs): + # it's the first call, replace the method with a cached, bound method + bound_method = types.MethodType(method, self) + cached_method = cache_wrapper(bound_method) + setattr(self, method.__name__, cached_method) + return cached_method(*args, **kwargs) + + # Support cache clear even before cache has been created. + wrapper.cache_clear = lambda: None + + return wrapper + + +# From jaraco.functools 3.3 +def pass_none(func): + """ + Wrap func so it's not called if its first param is None + + >>> print_text = pass_none(print) + >>> print_text('text') + text + >>> print_text(None) + """ + + @functools.wraps(func) + def wrapper(param, *args, **kwargs): + if param is not None: + return func(param, *args, **kwargs) + + return wrapper + + +# From jaraco.functools 4.4 +def noop(*args, **kwargs): + """ + A no-operation function that does nothing. + + >>> noop(1, 2, three=3) + """ + + +_T = TypeVar('_T') + + +# From jaraco.functools 4.4 +def passthrough(func: Callable[..., object]) -> Callable[[_T], _T]: + """ + Wrap the function to always return the first parameter. + + >>> passthrough(print)('3') + 3 + '3' + """ + + @functools.wraps(func) + def wrapper(first: _T, *args, **kwargs) -> _T: + func(first, *args, **kwargs) + return first + + return wrapper # type: ignore[return-value] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_itertools.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..79d37198ce7aff317873f6e4e84cd904a46a69de --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_itertools.py @@ -0,0 +1,171 @@ +from collections import defaultdict, deque +from itertools import filterfalse + + +def unique_everseen(iterable, key=None): + "List unique elements, preserving order. Remember all elements ever seen." + # unique_everseen('AAAABBBCCDAABBB') --> A B C D + # unique_everseen('ABBCcAD', str.lower) --> A B C D + seen = set() + seen_add = seen.add + if key is None: + for element in filterfalse(seen.__contains__, iterable): + seen_add(element) + yield element + else: + for element in iterable: + k = key(element) + if k not in seen: + seen_add(k) + yield element + + +# copied from more_itertools 8.8 +def always_iterable(obj, base_type=(str, bytes)): + """If *obj* is iterable, return an iterator over its items:: + + >>> obj = (1, 2, 3) + >>> list(always_iterable(obj)) + [1, 2, 3] + + If *obj* is not iterable, return a one-item iterable containing *obj*:: + + >>> obj = 1 + >>> list(always_iterable(obj)) + [1] + + If *obj* is ``None``, return an empty iterable: + + >>> obj = None + >>> list(always_iterable(None)) + [] + + By default, binary and text strings are not considered iterable:: + + >>> obj = 'foo' + >>> list(always_iterable(obj)) + ['foo'] + + If *base_type* is set, objects for which ``isinstance(obj, base_type)`` + returns ``True`` won't be considered iterable. + + >>> obj = {'a': 1} + >>> list(always_iterable(obj)) # Iterate over the dict's keys + ['a'] + >>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit + [{'a': 1}] + + Set *base_type* to ``None`` to avoid any special handling and treat objects + Python considers iterable as iterable: + + >>> obj = 'foo' + >>> list(always_iterable(obj, base_type=None)) + ['f', 'o', 'o'] + """ + if obj is None: + return iter(()) + + if (base_type is not None) and isinstance(obj, base_type): + return iter((obj,)) + + try: + return iter(obj) + except TypeError: + return iter((obj,)) + + +# Copied from more_itertools 10.3 +class bucket: + """Wrap *iterable* and return an object that buckets the iterable into + child iterables based on a *key* function. + + >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3'] + >>> s = bucket(iterable, key=lambda x: x[0]) # Bucket by 1st character + >>> sorted(list(s)) # Get the keys + ['a', 'b', 'c'] + >>> a_iterable = s['a'] + >>> next(a_iterable) + 'a1' + >>> next(a_iterable) + 'a2' + >>> list(s['b']) + ['b1', 'b2', 'b3'] + + The original iterable will be advanced and its items will be cached until + they are used by the child iterables. This may require significant storage. + + By default, attempting to select a bucket to which no items belong will + exhaust the iterable and cache all values. + If you specify a *validator* function, selected buckets will instead be + checked against it. + + >>> from itertools import count + >>> it = count(1, 2) # Infinite sequence of odd numbers + >>> key = lambda x: x % 10 # Bucket by last digit + >>> validator = lambda x: x in {1, 3, 5, 7, 9} # Odd digits only + >>> s = bucket(it, key=key, validator=validator) + >>> 2 in s + False + >>> list(s[2]) + [] + + """ + + def __init__(self, iterable, key, validator=None): + self._it = iter(iterable) + self._key = key + self._cache = defaultdict(deque) + self._validator = validator or (lambda x: True) + + def __contains__(self, value): + if not self._validator(value): + return False + + try: + item = next(self[value]) + except StopIteration: + return False + else: + self._cache[value].appendleft(item) + + return True + + def _get_values(self, value): + """ + Helper to yield items from the parent iterator that match *value*. + Items that don't match are stored in the local cache as they + are encountered. + """ + while True: + # If we've cached some items that match the target value, emit + # the first one and evict it from the cache. + if self._cache[value]: + yield self._cache[value].popleft() + # Otherwise we need to advance the parent iterator to search for + # a matching item, caching the rest. + else: + while True: + try: + item = next(self._it) + except StopIteration: + return + item_value = self._key(item) + if item_value == value: + yield item + break + elif self._validator(item_value): + self._cache[item_value].append(item) + + def __iter__(self): + for item in self._it: + item_value = self._key(item) + if self._validator(item_value): + self._cache[item_value].append(item) + + yield from self._cache.keys() + + def __getitem__(self, value): + if not self._validator(value): + return iter(()) + + return self._get_values(value) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_meta.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_meta.py new file mode 100644 index 0000000000000000000000000000000000000000..0c20eff3da75223a5ca76a1743b7c5b8fa1dc1f6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_meta.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +import os +from collections.abc import Iterator +from typing import ( + Any, + Protocol, + TypeVar, + overload, +) + +_T = TypeVar("_T") + + +class PackageMetadata(Protocol): + def __len__(self) -> int: ... # pragma: no cover + + def __contains__(self, item: str) -> bool: ... # pragma: no cover + + def __getitem__(self, key: str) -> str: ... # pragma: no cover + + def __iter__(self) -> Iterator[str]: ... # pragma: no cover + + @overload + def get( + self, name: str, failobj: None = None + ) -> str | None: ... # pragma: no cover + + @overload + def get(self, name: str, failobj: _T) -> str | _T: ... # pragma: no cover + + # overload per python/importlib_metadata#435 + @overload + def get_all( + self, name: str, failobj: None = None + ) -> list[Any] | None: ... # pragma: no cover + + @overload + def get_all(self, name: str, failobj: _T) -> list[Any] | _T: + """ + Return all values associated with a possibly multi-valued key. + """ + + @property + def json(self) -> dict[str, str | list[str]]: + """ + A JSON-compatible form of the metadata. + """ + + +class SimplePath(Protocol): + """ + A minimal subset of pathlib.Path required by Distribution. + """ + + def joinpath( + self, other: str | os.PathLike[str] + ) -> SimplePath: ... # pragma: no cover + + def __truediv__( + self, other: str | os.PathLike[str] + ) -> SimplePath: ... # pragma: no cover + + @property + def parent(self) -> SimplePath: ... # pragma: no cover + + def read_text(self, encoding=None) -> str: ... # pragma: no cover + + def read_bytes(self) -> bytes: ... # pragma: no cover + + def exists(self) -> bool: ... # pragma: no cover diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_text.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_text.py new file mode 100644 index 0000000000000000000000000000000000000000..c88cfbb2349c6401336bc5ba6623f51afd1eb59d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_text.py @@ -0,0 +1,99 @@ +import re + +from ._functools import method_cache + + +# from jaraco.text 3.5 +class FoldedCase(str): + """ + A case insensitive string class; behaves just like str + except compares equal when the only variation is case. + + >>> s = FoldedCase('hello world') + + >>> s == 'Hello World' + True + + >>> 'Hello World' == s + True + + >>> s != 'Hello World' + False + + >>> s.index('O') + 4 + + >>> s.split('O') + ['hell', ' w', 'rld'] + + >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta'])) + ['alpha', 'Beta', 'GAMMA'] + + Sequence membership is straightforward. + + >>> "Hello World" in [s] + True + >>> s in ["Hello World"] + True + + You may test for set inclusion, but candidate and elements + must both be folded. + + >>> FoldedCase("Hello World") in {s} + True + >>> s in {FoldedCase("Hello World")} + True + + String inclusion works as long as the FoldedCase object + is on the right. + + >>> "hello" in FoldedCase("Hello World") + True + + But not if the FoldedCase object is on the left: + + >>> FoldedCase('hello') in 'Hello World' + False + + In that case, use in_: + + >>> FoldedCase('hello').in_('Hello World') + True + + >>> FoldedCase('hello') > FoldedCase('Hello') + False + """ + + def __lt__(self, other): + return self.lower() < other.lower() + + def __gt__(self, other): + return self.lower() > other.lower() + + def __eq__(self, other): + return self.lower() == other.lower() + + def __ne__(self, other): + return self.lower() != other.lower() + + def __hash__(self): + return hash(self.lower()) + + def __contains__(self, other): + return super().lower().__contains__(other.lower()) + + def in_(self, other): + "Does self appear in other?" + return self in FoldedCase(other) + + # cache lower since it's likely to be called frequently. + @method_cache + def lower(self): + return super().lower() + + def index(self, sub): + return self.lower().index(sub.lower()) + + def split(self, splitter=' ', maxsplit=0): + pattern = re.compile(re.escape(splitter), re.I) + return pattern.split(self, maxsplit) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_typing.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..32b1d2b98ac987e8361f60362b8bdabcdc6fb1c8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/_typing.py @@ -0,0 +1,15 @@ +import functools +import typing + +from ._meta import PackageMetadata + +md_none = functools.partial(typing.cast, PackageMetadata) +""" +Suppress type errors for optional metadata. + +Although Distribution.metadata can return None when metadata is corrupt +and thus None, allow callers to assume it's not None and crash if +that's the case. + +# python/importlib_metadata#493 +""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/diagnose.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/diagnose.py new file mode 100644 index 0000000000000000000000000000000000000000..e405471ac4d94371b1ee9b1622227ff76b337180 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/diagnose.py @@ -0,0 +1,21 @@ +import sys + +from . import Distribution + + +def inspect(path): + print("Inspecting", path) + dists = list(Distribution.discover(path=[path])) + if not dists: + return + print("Found", len(dists), "packages:", end=' ') + print(', '.join(dist.name for dist in dists)) + + +def run(): + for path in sys.path: + inspect(path) + + +if __name__ == '__main__': + run() diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_metadata/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..fea7349dde117292c7507f4dadd772518c0ef1d8 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/METADATA @@ -0,0 +1,104 @@ +Metadata-Version: 2.4 +Name: importlib_resources +Version: 7.1.0 +Summary: Read resources from Python packages +Author-email: Barry Warsaw +Maintainer-email: "Jason R. Coombs" +License-Expression: Apache-2.0 +Project-URL: Source, https://github.com/python/importlib_resources +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Requires-Python: >=3.10 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: zipp>=3.1.0; python_version < "3.10" +Provides-Extra: test +Requires-Dist: pytest!=8.1.*,>=6; extra == "test" +Requires-Dist: zipp>=3.17; extra == "test" +Requires-Dist: jaraco.test>=5.4; extra == "test" +Provides-Extra: doc +Requires-Dist: sphinx>=3.5; extra == "doc" +Requires-Dist: jaraco.packaging>=9.3; extra == "doc" +Requires-Dist: rst.linker>=1.9; extra == "doc" +Requires-Dist: furo; extra == "doc" +Requires-Dist: sphinx-lint; extra == "doc" +Requires-Dist: jaraco.tidelift>=1.4; extra == "doc" +Provides-Extra: check +Requires-Dist: pytest-checkdocs>=2.14; extra == "check" +Requires-Dist: pytest-ruff>=0.2.1; sys_platform != "cygwin" and extra == "check" +Provides-Extra: cover +Requires-Dist: pytest-cov; extra == "cover" +Provides-Extra: enabler +Requires-Dist: pytest-enabler>=3.4; extra == "enabler" +Provides-Extra: type +Requires-Dist: pytest-mypy>=1.0.1; platform_python_implementation != "PyPy" and extra == "type" +Dynamic: license-file + +.. image:: https://img.shields.io/pypi/v/importlib_resources.svg + :target: https://pypi.org/project/importlib_resources + +.. image:: https://img.shields.io/pypi/pyversions/importlib_resources.svg + +.. image:: https://github.com/python/importlib_resources/actions/workflows/main.yml/badge.svg + :target: https://github.com/python/importlib_resources/actions?query=workflow%3A%22tests%22 + :alt: tests + +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Ruff + +.. image:: https://readthedocs.org/projects/importlib-resources/badge/?version=latest + :target: https://importlib-resources.readthedocs.io/en/latest/?badge=latest + +.. image:: https://img.shields.io/badge/skeleton-2025-informational + :target: https://blog.jaraco.com/skeleton + +.. image:: https://tidelift.com/badges/package/pypi/importlib-resources + :target: https://tidelift.com/subscription/pkg/pypi-importlib-resources?utm_source=pypi-importlib-resources&utm_medium=readme + +``importlib_resources`` is a backport of Python standard library +`importlib.resources +`_ +module for older Pythons. + +The key goal of this module is to replace parts of `pkg_resources +`_ with a +solution in Python's stdlib that relies on well-defined APIs. This makes +reading resources included in packages easier, with more stable and consistent +semantics. + +Compatibility +============= + +New features are introduced in this third-party library and later merged +into CPython. The following table indicates which versions of this library +were contributed to different versions in the standard library: + +.. list-table:: + :header-rows: 1 + + * - importlib_resources + - stdlib + * - 6.0 + - 3.13 + * - 5.12 + - 3.12 + * - 5.7 + - 3.11 + * - 5.0 + - 3.10 + * - 1.3 + - 3.9 + * - 0.5 (?) + - 3.7 + +For Enterprise +============== + +Available as part of the Tidelift Subscription. + +This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use. + +`Learn more `_. diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..c3efaf968c030f5caf48c30a31f088103508a316 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/RECORD @@ -0,0 +1,67 @@ +importlib_resources-7.1.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +importlib_resources-7.1.0.dist-info/METADATA,sha256=q0fMmH8UBUwTiLUYBlbSH-n_IaLc2Nejm9dQPA5m1kI,3987 +importlib_resources-7.1.0.dist-info/RECORD,, +importlib_resources-7.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91 +importlib_resources-7.1.0.dist-info/licenses/LICENSE,sha256=4ve7BVfno4FJnxW6p8HXdtg9ZhZZkXnXHTEJuOOfeyU,10278 +importlib_resources-7.1.0.dist-info/top_level.txt,sha256=fHIjHU1GZwAjvcydpmUnUrTnbvdiWjG4OEVZK8by0TQ,20 +importlib_resources/__init__.py,sha256=F6SOMZILiez96lK3h9duE_c5kRTEydzHvI6D7TRcOJE,700 +importlib_resources/__pycache__/__init__.cpython-311.pyc,, +importlib_resources/__pycache__/_adapters.cpython-311.pyc,, +importlib_resources/__pycache__/_common.cpython-311.pyc,, +importlib_resources/__pycache__/_functional.cpython-311.pyc,, +importlib_resources/__pycache__/_itertools.cpython-311.pyc,, +importlib_resources/__pycache__/abc.cpython-311.pyc,, +importlib_resources/__pycache__/readers.cpython-311.pyc,, +importlib_resources/__pycache__/simple.cpython-311.pyc,, +importlib_resources/_adapters.py,sha256=vprJGbUeHbajX6XCuMP6J3lMrqCi-P_MTlziJUR7jfk,4482 +importlib_resources/_common.py,sha256=_RxoOvtqCPulSmK_2gVD6__guE85JDg8EEUZQwv1VLE,5178 +importlib_resources/_functional.py,sha256=nMop9Zc7g1Yhiyk5oqr9ukvfJcOx4vnvqD7nh24hV7Y,2743 +importlib_resources/_itertools.py,sha256=eDisV6RqiNZOogLSXf6LOGHOYc79FGgPrKNLzFLmCrU,1277 +importlib_resources/abc.py,sha256=kQb57_sqzkfduUn1EGqrwrhlrfvgr7vnq2-fkYF3Bo4,5531 +importlib_resources/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_resources/compat/__pycache__/__init__.cpython-311.pyc,, +importlib_resources/compat/__pycache__/py39.cpython-311.pyc,, +importlib_resources/compat/py39.py,sha256=gx5NE25XH1pQrTRJDY7QJUngZpD7OotsK9F6pZy5KjM,151 +importlib_resources/future/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_resources/future/__pycache__/__init__.cpython-311.pyc,, +importlib_resources/future/__pycache__/adapters.cpython-311.pyc,, +importlib_resources/future/adapters.py,sha256=UFIMxEuLo4PqcVbtoV3e_k9BcxCS-mmG22f8U2Vtkx4,3285 +importlib_resources/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_resources/readers.py,sha256=uHf9X-smA3CtxdB9IHWH0z-O53379wlcEMmzA2UXzqE,6250 +importlib_resources/simple.py,sha256=twuYiz7U18iqoFC-49ogFDniaDGA2BG4HJ9x60cLguM,2584 +importlib_resources/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_resources/tests/__pycache__/__init__.cpython-311.pyc,, +importlib_resources/tests/__pycache__/_path.cpython-311.pyc,, +importlib_resources/tests/__pycache__/test_compatibilty_files.cpython-311.pyc,, +importlib_resources/tests/__pycache__/test_contents.cpython-311.pyc,, +importlib_resources/tests/__pycache__/test_custom.cpython-311.pyc,, +importlib_resources/tests/__pycache__/test_files.cpython-311.pyc,, +importlib_resources/tests/__pycache__/test_functional.cpython-311.pyc,, +importlib_resources/tests/__pycache__/test_open.cpython-311.pyc,, +importlib_resources/tests/__pycache__/test_path.cpython-311.pyc,, +importlib_resources/tests/__pycache__/test_read.cpython-311.pyc,, +importlib_resources/tests/__pycache__/test_reader.cpython-311.pyc,, +importlib_resources/tests/__pycache__/test_resource.cpython-311.pyc,, +importlib_resources/tests/__pycache__/test_util.cpython-311.pyc,, +importlib_resources/tests/__pycache__/util.cpython-311.pyc,, +importlib_resources/tests/__pycache__/zip.cpython-311.pyc,, +importlib_resources/tests/_path.py,sha256=ph8DOLJEvvWBe3eWMgE3tqg27wgOa2g0AbMAVFQKGaY,2227 +importlib_resources/tests/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +importlib_resources/tests/compat/__pycache__/__init__.cpython-311.pyc,, +importlib_resources/tests/compat/__pycache__/py312.cpython-311.pyc,, +importlib_resources/tests/compat/__pycache__/py39.cpython-311.pyc,, +importlib_resources/tests/compat/py312.py,sha256=qcWjpZhQo2oEsdwIlRRQHrsMGDltkFTnETeG7fLdUS8,364 +importlib_resources/tests/compat/py39.py,sha256=nOjut4CZDtRgZEblX9hWhupo9vli_CA1270_JwdQzRo,441 +importlib_resources/tests/test_compatibilty_files.py,sha256=niKlQ7-bqC37EeLpUQmuf_zpBVm-gMjtTXMndItilYQ,3081 +importlib_resources/tests/test_contents.py,sha256=r8kVH1k7DHrco2JVTUMCbsWK0JvvjKt0zgrmH56c4Vg,838 +importlib_resources/tests/test_custom.py,sha256=ep5mGT6uT6O1gPdM-b3mXo9HWDnCLD90uc4H1bU68oI,1222 +importlib_resources/tests/test_files.py,sha256=YzmwkxC8Qgdf8jNj9Q5Rgp5gmJUxFTHEBf2NNpRJuxM,5471 +importlib_resources/tests/test_functional.py,sha256=xFKw0VzJWaLNklbl2PwYurIvIl4O3Av4V0bZNd6iusA,8989 +importlib_resources/tests/test_open.py,sha256=ceMNlQZKNGtl1Sc-mr32ecvOLFLyDfeX4QRqDq6teKY,2635 +importlib_resources/tests/test_path.py,sha256=HnZqYaRds6V6znDwWlmFZkgGaVXbzCbjTlgnx6HiUx4,1963 +importlib_resources/tests/test_read.py,sha256=5MB7JNG1bMUXqMAwsBbPH8vLAeHOxTp9BLCyaDvmdgc,3002 +importlib_resources/tests/test_reader.py,sha256=di6Yury4x6Y4fatM6qNlpWIYy6CdNXHInLahtqSFvkI,4380 +importlib_resources/tests/test_resource.py,sha256=x6eeB-S4ZSolz0DqaCl2WVvjQTFpfVlQ1-6TSBYQtpI,7983 +importlib_resources/tests/test_util.py,sha256=VotLNbngOyFg03FKVTzIZKd4Gz4UO-dMEr0G-vHMiuI,1105 +importlib_resources/tests/util.py,sha256=NaGtI-csCx6rBA67UOpDchPlL6MrVuQkO_PEPv7u9l0,9786 +importlib_resources/tests/zip.py,sha256=nG9D6u_4nu67NrEUFfMt7vzba0qO_-QPyAAWc6W4gP4,577 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..14a883f292bc96b20c2b76a3081991f2676523a9 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (82.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/top_level.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..58ad1bd333593cb544d1a6516e8e2849f094d09b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources-7.1.0.dist-info/top_level.txt @@ -0,0 +1 @@ +importlib_resources diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..27d6c7f89307efe0eb4aa5dcca2b0f32c45fca96 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/__init__.py @@ -0,0 +1,40 @@ +""" +Read resources contained within a package. + +This codebase is shared between importlib.resources in the stdlib +and importlib_resources in PyPI. See +https://github.com/python/importlib_metadata/wiki/Development-Methodology +for more detail. +""" + +from ._common import ( + Anchor, + Package, + as_file, + files, +) +from ._functional import ( + contents, + is_resource, + open_binary, + open_text, + path, + read_binary, + read_text, +) +from .abc import ResourceReader + +__all__ = [ + 'Package', + 'Anchor', + 'ResourceReader', + 'as_file', + 'files', + 'contents', + 'is_resource', + 'open_binary', + 'open_text', + 'path', + 'read_binary', + 'read_text', +] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/_adapters.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..50688fbb666658c5b0569a363a4ea5b75f2fc00d --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/_adapters.py @@ -0,0 +1,168 @@ +from contextlib import suppress +from io import TextIOWrapper + +from . import abc + + +class SpecLoaderAdapter: + """ + Adapt a package spec to adapt the underlying loader. + """ + + def __init__(self, spec, adapter=lambda spec: spec.loader): + self.spec = spec + self.loader = adapter(spec) + + def __getattr__(self, name): + return getattr(self.spec, name) + + +class TraversableResourcesLoader: + """ + Adapt a loader to provide TraversableResources. + """ + + def __init__(self, spec): + self.spec = spec + + def get_resource_reader(self, name): + return CompatibilityFiles(self.spec)._native() + + +def _io_wrapper(file, mode='r', *args, **kwargs): + if mode == 'r': + return TextIOWrapper(file, *args, **kwargs) + elif mode == 'rb': + return file + raise ValueError(f"Invalid mode value '{mode}', only 'r' and 'rb' are supported") + + +class CompatibilityFiles: + """ + Adapter for an existing or non-existent resource reader + to provide a compatibility .files(). + """ + + class SpecPath(abc.Traversable): + """ + Path tied to a module spec. + Can be read and exposes the resource reader children. + """ + + def __init__(self, spec, reader): + self._spec = spec + self._reader = reader + + def iterdir(self): + if not self._reader: + return iter(()) + return iter( + CompatibilityFiles.ChildPath(self._reader, path) + for path in self._reader.contents() + ) + + def is_file(self): + return False + + is_dir = is_file + + def joinpath(self, other): + if not self._reader: + return CompatibilityFiles.OrphanPath(other) + return CompatibilityFiles.ChildPath(self._reader, other) + + @property + def name(self): + return self._spec.name + + def open(self, mode='r', *args, **kwargs): + return _io_wrapper(self._reader.open_resource(None), mode, *args, **kwargs) + + class ChildPath(abc.Traversable): + """ + Path tied to a resource reader child. + Can be read but doesn't expose any meaningful children. + """ + + def __init__(self, reader, name): + self._reader = reader + self._name = name + + def iterdir(self): + return iter(()) + + def is_file(self): + return self._reader.is_resource(self.name) + + def is_dir(self): + return not self.is_file() + + def joinpath(self, other): + return CompatibilityFiles.OrphanPath(self.name, other) + + @property + def name(self): + return self._name + + def open(self, mode='r', *args, **kwargs): + return _io_wrapper( + self._reader.open_resource(self.name), mode, *args, **kwargs + ) + + class OrphanPath(abc.Traversable): + """ + Orphan path, not tied to a module spec or resource reader. + Can't be read and doesn't expose any meaningful children. + """ + + def __init__(self, *path_parts): + if len(path_parts) < 1: + raise ValueError('Need at least one path part to construct a path') + self._path = path_parts + + def iterdir(self): + return iter(()) + + def is_file(self): + return False + + is_dir = is_file + + def joinpath(self, other): + return CompatibilityFiles.OrphanPath(*self._path, other) + + @property + def name(self): + return self._path[-1] + + def open(self, mode='r', *args, **kwargs): + raise FileNotFoundError("Can't open orphan path") + + def __init__(self, spec): + self.spec = spec + + @property + def _reader(self): + with suppress(AttributeError): + return self.spec.loader.get_resource_reader(self.spec.name) + + def _native(self): + """ + Return the native reader if it supports files(). + """ + reader = self._reader + return reader if hasattr(reader, 'files') else self + + def __getattr__(self, attr): + return getattr(self._reader, attr) + + def files(self): + return CompatibilityFiles.SpecPath(self.spec, self._reader) + + +def wrap_spec(package): + """ + Construct a package spec with traversable compatibility + on the spec/loader/reader. + """ + return SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/_common.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/_common.py new file mode 100644 index 0000000000000000000000000000000000000000..4e7c9137481f41e0b7e5e4efb77d5eeaface18e5 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/_common.py @@ -0,0 +1,191 @@ +import contextlib +import functools +import importlib +import inspect +import itertools +import os +import pathlib +import tempfile +import types +from typing import Optional, cast + +from .abc import ResourceReader, Traversable + +Package = types.ModuleType | str +Anchor = Package + + +def files(anchor: Optional[Anchor] = None) -> Traversable: + """ + Get a Traversable resource for an anchor. + """ + return from_package(resolve(anchor)) + + +def get_resource_reader(package: types.ModuleType) -> Optional[ResourceReader]: + """ + Return the package's loader if it's a ResourceReader. + """ + # We can't use + # a issubclass() check here because apparently abc.'s __subclasscheck__() + # hook wants to create a weak reference to the object, but + # zipimport.zipimporter does not support weak references, resulting in a + # TypeError. That seems terrible. + spec = package.__spec__ + reader = getattr(spec.loader, 'get_resource_reader', None) # type: ignore[union-attr] + if reader is None: + return None + return reader(spec.name) # type: ignore[union-attr] + + +@functools.singledispatch +def resolve(cand: Optional[Anchor]) -> types.ModuleType: + return cast(types.ModuleType, cand) + + +@resolve.register +def _(cand: str) -> types.ModuleType: + return importlib.import_module(cand) + + +@resolve.register +def _(cand: None) -> types.ModuleType: + return resolve(_infer_caller().f_globals['__name__']) + + +def _infer_caller(): + """ + Walk the stack and find the frame of the first caller not in this module. + """ + + def is_this_file(frame_info): + return frame_info.filename == stack[0].filename + + def is_wrapper(frame_info): + return frame_info.function == 'wrapper' + + stack = inspect.stack() + not_this_file = itertools.filterfalse(is_this_file, stack) + # also exclude 'wrapper' due to singledispatch in the call stack + callers = itertools.filterfalse(is_wrapper, not_this_file) + return next(callers).frame + + +def _assert_spec(package: types.ModuleType) -> None: + """ + Provide a nicer error message when package is ``__main__`` + and its ``__spec__`` is ``None`` + (https://docs.python.org/3/reference/import.html#main-spec). + """ + if package.__spec__ is None: + raise TypeError( + f"Cannot access resources for '{package.__name__}' " + "as it does not appear to correspond to an importable module (its __spec__ is None)." + ) + + +def from_package(package: types.ModuleType): + """ + Return a Traversable object for the given package. + + """ + # deferred for performance (python/cpython#109829) + from .future.adapters import wrap_spec + + _assert_spec(package) + spec = wrap_spec(package) + reader = spec.loader.get_resource_reader(spec.name) + return reader.files() + + +@contextlib.contextmanager +def _tempfile( + reader, + suffix='', + # gh-93353: Keep a reference to call os.remove() in late Python + # finalization. + *, + _os_remove=os.remove, +): + # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try' + # blocks due to the need to close the temporary file to work on Windows + # properly. + fd, raw_path = tempfile.mkstemp(suffix=suffix) + try: + try: + os.write(fd, reader()) + finally: + os.close(fd) + del reader + yield pathlib.Path(raw_path) + finally: + try: + _os_remove(raw_path) + except FileNotFoundError: + pass + + +def _temp_file(path): + return _tempfile(path.read_bytes, suffix=path.name) + + +def _is_present_dir(path: Traversable) -> bool: + """ + Some Traversables implement ``is_dir()`` to raise an + exception (i.e. ``FileNotFoundError``) when the + directory doesn't exist. This function wraps that call + to always return a boolean and only return True + if there's a dir and it exists. + """ + with contextlib.suppress(FileNotFoundError): + return path.is_dir() + return False + + +@functools.singledispatch +def as_file(path): + """ + Given a Traversable object, return that object as a + path on the local file system in a context manager. + """ + return _temp_dir(path) if _is_present_dir(path) else _temp_file(path) + + +@as_file.register(pathlib.Path) +@contextlib.contextmanager +def _(path): + """ + Degenerate behavior for pathlib.Path objects. + """ + yield path + + +@contextlib.contextmanager +def _temp_path(dir: tempfile.TemporaryDirectory): + """ + Wrap tempfile.TemporaryDirectory to return a pathlib object. + """ + with dir as result: + yield pathlib.Path(result) + + +@contextlib.contextmanager +def _temp_dir(path): + """ + Given a traversable dir, recursively replicate the whole tree + to the file system in a context manager. + """ + assert path.is_dir() + with _temp_path(tempfile.TemporaryDirectory()) as temp_dir: + yield _write_contents(temp_dir, path) + + +def _write_contents(target, source): + child = target.joinpath(source.name) + if source.is_dir(): + child.mkdir() + for item in source.iterdir(): + _write_contents(child, item) + else: + child.write_bytes(source.read_bytes()) + return child diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/_functional.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/_functional.py new file mode 100644 index 0000000000000000000000000000000000000000..b08a5c6efe22a234914ed33bdaa1ee0e2432e478 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/_functional.py @@ -0,0 +1,84 @@ +"""Simplified function-based API for importlib.resources""" + +import warnings + +from ._common import as_file, files +from .abc import TraversalError + +_MISSING = object() + + +def open_binary(anchor, *path_names): + """Open for binary reading the *resource* within *package*.""" + return _get_resource(anchor, path_names).open('rb') + + +def open_text(anchor, *path_names, encoding=_MISSING, errors='strict'): + """Open for text reading the *resource* within *package*.""" + encoding = _get_encoding_arg(path_names, encoding) + resource = _get_resource(anchor, path_names) + return resource.open('r', encoding=encoding, errors=errors) + + +def read_binary(anchor, *path_names): + """Read and return contents of *resource* within *package* as bytes.""" + return _get_resource(anchor, path_names).read_bytes() + + +def read_text(anchor, *path_names, encoding=_MISSING, errors='strict'): + """Read and return contents of *resource* within *package* as str.""" + encoding = _get_encoding_arg(path_names, encoding) + resource = _get_resource(anchor, path_names) + return resource.read_text(encoding=encoding, errors=errors) + + +def path(anchor, *path_names): + """Return the path to the *resource* as an actual file system path.""" + return as_file(_get_resource(anchor, path_names)) + + +def is_resource(anchor, *path_names): + """Return ``True`` if there is a resource named *name* in the package, + + Otherwise returns ``False``. + """ + try: + return _get_resource(anchor, path_names).is_file() + except TraversalError: + return False + + +def contents(anchor, *path_names): + """Return an iterable over the named resources within the package. + + The iterable returns :class:`str` resources (e.g. files). + The iterable does not recurse into subdirectories. + """ + warnings.warn( + "importlib.resources.contents is deprecated. " + "Use files(anchor).iterdir() instead.", + DeprecationWarning, + stacklevel=1, + ) + return (resource.name for resource in _get_resource(anchor, path_names).iterdir()) + + +def _get_encoding_arg(path_names, encoding): + # For compatibility with versions where *encoding* was a positional + # argument, it needs to be given explicitly when there are multiple + # *path_names*. + # This limitation can be removed in Python 3.15. + if encoding is _MISSING: + if len(path_names) > 1: + raise TypeError( + "'encoding' argument required with multiple path names", + ) + else: + return 'utf-8' + return encoding + + +def _get_resource(anchor, path_names): + if anchor is None: + raise TypeError("anchor must be module or string, got None") + return files(anchor).joinpath(*path_names) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/_itertools.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/_itertools.py new file mode 100644 index 0000000000000000000000000000000000000000..7b775ef5ae893f2b8061c5f996dc0a15a4c72adb --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/_itertools.py @@ -0,0 +1,38 @@ +# from more_itertools 9.0 +def only(iterable, default=None, too_long=None): + """If *iterable* has only one item, return it. + If it has zero items, return *default*. + If it has more than one item, raise the exception given by *too_long*, + which is ``ValueError`` by default. + >>> only([], default='missing') + 'missing' + >>> only([1]) + 1 + >>> only([1, 2]) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + ValueError: Expected exactly one item in iterable, but got 1, 2, + and perhaps more.' + >>> only([1, 2], too_long=TypeError) # doctest: +IGNORE_EXCEPTION_DETAIL + Traceback (most recent call last): + ... + TypeError + Note that :func:`only` attempts to advance *iterable* twice to ensure there + is only one item. See :func:`spy` or :func:`peekable` to check + iterable contents less destructively. + """ + it = iter(iterable) + first_value = next(it, default) + + try: + second_value = next(it) + except StopIteration: + pass + else: + msg = ( + 'Expected exactly one item in iterable, but got {!r}, {!r}, ' + 'and perhaps more.'.format(first_value, second_value) + ) + raise too_long or ValueError(msg) + + return first_value diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/abc.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..0b5fdee80e87964dede5913189af4d023d9134f6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/abc.py @@ -0,0 +1,189 @@ +import abc +import itertools +import os +import pathlib +from collections.abc import Iterable, Iterator +from typing import ( + Any, + BinaryIO, + Literal, + NoReturn, + Optional, + Protocol, + Text, + TextIO, + overload, + runtime_checkable, +) + +StrPath = str | os.PathLike[str] + +__all__ = ["ResourceReader", "Traversable", "TraversableResources"] + + +class ResourceReader(metaclass=abc.ABCMeta): + """Abstract base class for loaders to provide resource reading support.""" + + @abc.abstractmethod + def open_resource(self, resource: Text) -> BinaryIO: + """Return an opened, file-like object for binary reading. + + The 'resource' argument is expected to represent only a file name. + If the resource cannot be found, FileNotFoundError is raised. + """ + # This deliberately raises FileNotFoundError instead of + # NotImplementedError so that if this method is accidentally called, + # it'll still do the right thing. + raise FileNotFoundError + + @abc.abstractmethod + def resource_path(self, resource: Text) -> Text: + """Return the file system path to the specified resource. + + The 'resource' argument is expected to represent only a file name. + If the resource does not exist on the file system, raise + FileNotFoundError. + """ + # This deliberately raises FileNotFoundError instead of + # NotImplementedError so that if this method is accidentally called, + # it'll still do the right thing. + raise FileNotFoundError + + @abc.abstractmethod + def is_resource(self, path: Text) -> bool: + """Return True if the named 'path' is a resource. + + Files are resources, directories are not. + """ + raise FileNotFoundError + + @abc.abstractmethod + def contents(self) -> Iterable[str]: + """Return an iterable of entries in `package`.""" + raise FileNotFoundError + + +class TraversalError(Exception): + pass + + +@runtime_checkable +class Traversable(Protocol): + """ + An object with a subset of pathlib.Path methods suitable for + traversing directories and opening files. + + Any exceptions that occur when accessing the backing resource + may propagate unaltered. + """ + + @abc.abstractmethod + def iterdir(self) -> Iterator["Traversable"]: + """ + Yield Traversable objects in self + """ + + def read_bytes(self) -> bytes: + """ + Read contents of self as bytes + """ + with self.open('rb') as strm: + return strm.read() + + def read_text( + self, encoding: Optional[str] = None, errors: Optional[str] = None + ) -> str: + """ + Read contents of self as text + """ + with self.open(encoding=encoding, errors=errors) as strm: + return strm.read() + + @abc.abstractmethod + def is_dir(self) -> bool: + """ + Return True if self is a directory + """ + + @abc.abstractmethod + def is_file(self) -> bool: + """ + Return True if self is a file + """ + + def joinpath(self, *descendants: StrPath) -> "Traversable": + """ + Return Traversable resolved with any descendants applied. + + Each descendant should be a path segment relative to self + and each may contain multiple levels separated by + ``posixpath.sep`` (``/``). + """ + if not descendants: + return self + names = itertools.chain.from_iterable( + path.parts for path in map(pathlib.PurePosixPath, descendants) + ) + target = next(names) + matches = ( + traversable for traversable in self.iterdir() if traversable.name == target + ) + try: + match = next(matches) + except StopIteration: + raise TraversalError( + "Target not found during traversal.", target, list(names) + ) + return match.joinpath(*names) + + def __truediv__(self, child: StrPath) -> "Traversable": + """ + Return Traversable child in self + """ + return self.joinpath(child) + + @overload + def open(self, mode: Literal['r'] = 'r', *args: Any, **kwargs: Any) -> TextIO: ... + + @overload + def open(self, mode: Literal['rb'], *args: Any, **kwargs: Any) -> BinaryIO: ... + + @abc.abstractmethod + def open(self, mode: str = 'r', *args: Any, **kwargs: Any) -> TextIO | BinaryIO: + """ + mode may be 'r' or 'rb' to open as text or binary. Return a handle + suitable for reading (same as pathlib.Path.open). + + When opening as text, accepts encoding parameters such as those + accepted by io.TextIOWrapper. + """ + + @property + @abc.abstractmethod + def name(self) -> str: + """ + The base name of this object without any parent references. + """ + + +class TraversableResources(ResourceReader): + """ + The required interface for providing traversable + resources. + """ + + @abc.abstractmethod + def files(self) -> "Traversable": + """Return a Traversable object for the loaded package.""" + + def open_resource(self, resource: StrPath) -> BinaryIO: + return self.files().joinpath(resource).open('rb') + + def resource_path(self, resource: Any) -> NoReturn: + raise FileNotFoundError(resource) + + def is_resource(self, path: StrPath) -> bool: + return self.files().joinpath(path).is_file() + + def contents(self) -> Iterator[str]: + return (item.name for item in self.files().iterdir()) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/py.typed b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/readers.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/readers.py new file mode 100644 index 0000000000000000000000000000000000000000..99884b6af93adcac5e91679f30fd4cf082451ada --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/readers.py @@ -0,0 +1,202 @@ +from __future__ import annotations + +import collections +import contextlib +import itertools +import operator +import pathlib +import re +import warnings +from collections.abc import Iterator + +from . import abc +from ._itertools import only +from .compat.py39 import ZipPath + + +def remove_duplicates(items): + return iter(collections.OrderedDict.fromkeys(items)) + + +class FileReader(abc.TraversableResources): + def __init__(self, loader): + self.path = pathlib.Path(loader.path).parent + + def resource_path(self, resource): + """ + Return the file system path to prevent + `resources.path()` from creating a temporary + copy. + """ + return str(self.path.joinpath(resource)) + + def files(self): + return self.path + + +class ZipReader(abc.TraversableResources): + def __init__(self, loader, module): + self.prefix = loader.prefix.replace('\\', '/') + if loader.is_package(module): + _, _, name = module.rpartition('.') + self.prefix += name + '/' + self.archive = loader.archive + + def open_resource(self, resource): + try: + return super().open_resource(resource) + except KeyError as exc: + raise FileNotFoundError(exc.args[0]) + + def is_resource(self, path): + """ + Workaround for `zipfile.Path.is_file` returning true + for non-existent paths. + """ + target = self.files().joinpath(path) + return target.is_file() and target.exists() + + def files(self): + return ZipPath(self.archive, self.prefix) + + +class MultiplexedPath(abc.Traversable): + """ + Given a series of Traversable objects, implement a merged + version of the interface across all objects. Useful for + namespace packages which may be multihomed at a single + name. + """ + + def __init__(self, *paths): + self._paths = list(map(_ensure_traversable, remove_duplicates(paths))) + if not self._paths: + message = 'MultiplexedPath must contain at least one path' + raise FileNotFoundError(message) + if not all(path.is_dir() for path in self._paths): + raise NotADirectoryError('MultiplexedPath only supports directories') + + def iterdir(self): + children = (child for path in self._paths for child in path.iterdir()) + by_name = operator.attrgetter('name') + groups = itertools.groupby(sorted(children, key=by_name), key=by_name) + return map(self._follow, (locs for name, locs in groups)) + + def read_bytes(self): + raise FileNotFoundError(f'{self} is not a file') + + def read_text(self, *args, **kwargs): + raise FileNotFoundError(f'{self} is not a file') + + def is_dir(self): + return True + + def is_file(self): + return False + + def joinpath(self, *descendants): + try: + return super().joinpath(*descendants) + except abc.TraversalError: + # One of the paths did not resolve (a directory does not exist). + # Just return something that will not exist. + return self._paths[0].joinpath(*descendants) + + @classmethod + def _follow(cls, children): + """ + Construct a MultiplexedPath if needed. + + If children contains a sole element, return it. + Otherwise, return a MultiplexedPath of the items. + Unless one of the items is not a Directory, then return the first. + """ + subdirs, one_dir, one_file = itertools.tee(children, 3) + + try: + return only(one_dir) + except ValueError: + try: + return cls(*subdirs) + except NotADirectoryError: + return next(one_file) + + def open(self, *args, **kwargs): + raise FileNotFoundError(f'{self} is not a file') + + @property + def name(self): + return self._paths[0].name + + def __repr__(self): + paths = ', '.join(f"'{path}'" for path in self._paths) + return f'MultiplexedPath({paths})' + + +class NamespaceReader(abc.TraversableResources): + def __init__(self, namespace_path): + if 'NamespacePath' not in str(namespace_path): + raise ValueError('Invalid path') + self.path = MultiplexedPath(*filter(bool, map(self._resolve, namespace_path))) + + @classmethod + def _resolve(cls, path_str) -> abc.Traversable | None: + r""" + Given an item from a namespace path, resolve it to a Traversable. + + path_str might be a directory on the filesystem or a path to a + zipfile plus the path within the zipfile, e.g. ``/foo/bar`` or + ``/foo/baz.zip/inner_dir`` or ``foo\baz.zip\inner_dir\sub``. + + path_str might also be a sentinel used by editable packages to + trigger other behaviors (see python/importlib_resources#311). + In that case, return None. + """ + dirs = (cand for cand in cls._candidate_paths(path_str) if cand.is_dir()) + return next(dirs, None) + + @classmethod + def _candidate_paths(cls, path_str: str) -> Iterator[abc.Traversable]: + yield pathlib.Path(path_str) + yield from cls._resolve_zip_path(path_str) + + @staticmethod + def _resolve_zip_path(path_str: str): + for match in reversed(list(re.finditer(r'[\\/]', path_str))): + with contextlib.suppress( + FileNotFoundError, + IsADirectoryError, + NotADirectoryError, + PermissionError, + ): + inner = path_str[match.end() :].replace('\\', '/') + '/' + yield ZipPath(path_str[: match.start()], inner.lstrip('/')) + + def resource_path(self, resource): + """ + Return the file system path to prevent + `resources.path()` from creating a temporary + copy. + """ + return str(self.path.joinpath(resource)) + + def files(self): + return self.path + + +def _ensure_traversable(path): + """ + Convert deprecated string arguments to traversables (pathlib.Path). + + Remove with Python 3.15. + """ + if not isinstance(path, str): + return path + + warnings.warn( + "String arguments are deprecated. Pass a Traversable instead.", + DeprecationWarning, + stacklevel=3, + ) + + return pathlib.Path(path) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/simple.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/simple.py new file mode 100644 index 0000000000000000000000000000000000000000..5e182d12607c45ebb369f604d227e3aaa62f433b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/importlib_resources/simple.py @@ -0,0 +1,106 @@ +""" +Interface adapters for low-level readers. +""" + +import abc +import io +import itertools +from typing import BinaryIO + +from .abc import Traversable, TraversableResources + + +class SimpleReader(abc.ABC): + """ + The minimum, low-level interface required from a resource + provider. + """ + + @property + @abc.abstractmethod + def package(self) -> str: + """ + The name of the package for which this reader loads resources. + """ + + @abc.abstractmethod + def children(self) -> list['SimpleReader']: + """ + Obtain an iterable of SimpleReader for available + child containers (e.g. directories). + """ + + @abc.abstractmethod + def resources(self) -> list[str]: + """ + Obtain available named resources for this virtual package. + """ + + @abc.abstractmethod + def open_binary(self, resource: str) -> BinaryIO: + """ + Obtain a File-like for a named resource. + """ + + @property + def name(self): + return self.package.split('.')[-1] + + +class ResourceContainer(Traversable): + """ + Traversable container for a package's resources via its reader. + """ + + def __init__(self, reader: SimpleReader): + self.reader = reader + + def is_dir(self): + return True + + def is_file(self): + return False + + def iterdir(self): + files = (ResourceHandle(self, name) for name in self.reader.resources) + dirs = map(ResourceContainer, self.reader.children()) + return itertools.chain(files, dirs) + + def open(self, *args, **kwargs): + raise IsADirectoryError() + + +class ResourceHandle(Traversable): + """ + Handle to a named resource in a ResourceReader. + """ + + def __init__(self, parent: ResourceContainer, name: str): + self.parent = parent + self.name = name # type: ignore[misc] + + def is_file(self): + return True + + def is_dir(self): + return False + + def open(self, mode='r', *args, **kwargs): + stream = self.parent.reader.open_binary(self.name) + if 'b' not in mode: + stream = io.TextIOWrapper(stream, *args, **kwargs) + return stream + + def joinpath(self, name): + raise RuntimeError("Cannot traverse into a resource") + + +class TraversableReader(TraversableResources, SimpleReader): + """ + A TraversableResources based on SimpleReader. Resource providers + may derive from this class to provide the TraversableResources + interface by supplying the SimpleReader interface. + """ + + def files(self): + return ResourceContainer(self) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/INSTALLER b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/METADATA b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..ffef2ff3bfa0c42b6e6e3eefda700391d181c9a0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/METADATA @@ -0,0 +1,84 @@ +Metadata-Version: 2.4 +Name: Jinja2 +Version: 3.1.6 +Summary: A very fast and expressive template engine. +Maintainer-email: Pallets +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Web Environment +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: BSD License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content +Classifier: Topic :: Text Processing :: Markup :: HTML +Classifier: Typing :: Typed +License-File: LICENSE.txt +Requires-Dist: MarkupSafe>=2.0 +Requires-Dist: Babel>=2.7 ; extra == "i18n" +Project-URL: Changes, https://jinja.palletsprojects.com/changes/ +Project-URL: Chat, https://discord.gg/pallets +Project-URL: Documentation, https://jinja.palletsprojects.com/ +Project-URL: Donate, https://palletsprojects.com/donate +Project-URL: Source, https://github.com/pallets/jinja/ +Provides-Extra: i18n + +# Jinja + +Jinja is a fast, expressive, extensible templating engine. Special +placeholders in the template allow writing code similar to Python +syntax. Then the template is passed data to render the final document. + +It includes: + +- Template inheritance and inclusion. +- Define and import macros within templates. +- HTML templates can use autoescaping to prevent XSS from untrusted + user input. +- A sandboxed environment can safely render untrusted templates. +- AsyncIO support for generating templates and calling async + functions. +- I18N support with Babel. +- Templates are compiled to optimized Python code just-in-time and + cached, or can be compiled ahead-of-time. +- Exceptions point to the correct line in templates to make debugging + easier. +- Extensible filters, tests, functions, and even syntax. + +Jinja's philosophy is that while application logic belongs in Python if +possible, it shouldn't make the template designer's job difficult by +restricting functionality too much. + + +## In A Nutshell + +```jinja +{% extends "base.html" %} +{% block title %}Members{% endblock %} +{% block content %} + +{% endblock %} +``` + +## Donate + +The Pallets organization develops and supports Jinja and other popular +packages. In order to grow the community of contributors and users, and +allow the maintainers to devote more time to the projects, [please +donate today][]. + +[please donate today]: https://palletsprojects.com/donate + +## Contributing + +See our [detailed contributing documentation][contrib] for many ways to +contribute, including reporting issues, requesting features, asking or answering +questions, and making PRs. + +[contrib]: https://palletsprojects.com/contributing/ + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/RECORD b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..4b48b91fa45686b153737ec87eeddd846c2f56c6 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/RECORD @@ -0,0 +1,57 @@ +jinja2-3.1.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +jinja2-3.1.6.dist-info/METADATA,sha256=aMVUj7Z8QTKhOJjZsx7FDGvqKr3ZFdkh8hQ1XDpkmcg,2871 +jinja2-3.1.6.dist-info/RECORD,, +jinja2-3.1.6.dist-info/WHEEL,sha256=_2ozNFCLWc93bK4WKHCO-eDUENDlo-dgc9cU3qokYO4,82 +jinja2-3.1.6.dist-info/entry_points.txt,sha256=OL85gYU1eD8cuPlikifFngXpeBjaxl6rIJ8KkC_3r-I,58 +jinja2-3.1.6.dist-info/licenses/LICENSE.txt,sha256=O0nc7kEF6ze6wQ-vG-JgQI_oXSUrjp3y4JefweCUQ3s,1475 +jinja2/__init__.py,sha256=xxepO9i7DHsqkQrgBEduLtfoz2QCuT6_gbL4XSN1hbU,1928 +jinja2/__pycache__/__init__.cpython-311.pyc,, +jinja2/__pycache__/_identifier.cpython-311.pyc,, +jinja2/__pycache__/async_utils.cpython-311.pyc,, +jinja2/__pycache__/bccache.cpython-311.pyc,, +jinja2/__pycache__/compiler.cpython-311.pyc,, +jinja2/__pycache__/constants.cpython-311.pyc,, +jinja2/__pycache__/debug.cpython-311.pyc,, +jinja2/__pycache__/defaults.cpython-311.pyc,, +jinja2/__pycache__/environment.cpython-311.pyc,, +jinja2/__pycache__/exceptions.cpython-311.pyc,, +jinja2/__pycache__/ext.cpython-311.pyc,, +jinja2/__pycache__/filters.cpython-311.pyc,, +jinja2/__pycache__/idtracking.cpython-311.pyc,, +jinja2/__pycache__/lexer.cpython-311.pyc,, +jinja2/__pycache__/loaders.cpython-311.pyc,, +jinja2/__pycache__/meta.cpython-311.pyc,, +jinja2/__pycache__/nativetypes.cpython-311.pyc,, +jinja2/__pycache__/nodes.cpython-311.pyc,, +jinja2/__pycache__/optimizer.cpython-311.pyc,, +jinja2/__pycache__/parser.cpython-311.pyc,, +jinja2/__pycache__/runtime.cpython-311.pyc,, +jinja2/__pycache__/sandbox.cpython-311.pyc,, +jinja2/__pycache__/tests.cpython-311.pyc,, +jinja2/__pycache__/utils.cpython-311.pyc,, +jinja2/__pycache__/visitor.cpython-311.pyc,, +jinja2/_identifier.py,sha256=_zYctNKzRqlk_murTNlzrju1FFJL7Va_Ijqqd7ii2lU,1958 +jinja2/async_utils.py,sha256=vK-PdsuorOMnWSnEkT3iUJRIkTnYgO2T6MnGxDgHI5o,2834 +jinja2/bccache.py,sha256=gh0qs9rulnXo0PhX5jTJy2UHzI8wFnQ63o_vw7nhzRg,14061 +jinja2/compiler.py,sha256=9RpCQl5X88BHllJiPsHPh295Hh0uApvwFJNQuutULeM,74131 +jinja2/constants.py,sha256=GMoFydBF_kdpaRKPoM5cl5MviquVRLVyZtfp5-16jg0,1433 +jinja2/debug.py,sha256=CnHqCDHd-BVGvti_8ZsTolnXNhA3ECsY-6n_2pwU8Hw,6297 +jinja2/defaults.py,sha256=boBcSw78h-lp20YbaXSJsqkAI2uN_mD_TtCydpeq5wU,1267 +jinja2/environment.py,sha256=9nhrP7Ch-NbGX00wvyr4yy-uhNHq2OCc60ggGrni_fk,61513 +jinja2/exceptions.py,sha256=ioHeHrWwCWNaXX1inHmHVblvc4haO7AXsjCp3GfWvx0,5071 +jinja2/ext.py,sha256=5PF5eHfh8mXAIxXHHRB2xXbXohi8pE3nHSOxa66uS7E,31875 +jinja2/filters.py,sha256=PQ_Egd9n9jSgtnGQYyF4K5j2nYwhUIulhPnyimkdr-k,55212 +jinja2/idtracking.py,sha256=-ll5lIp73pML3ErUYiIJj7tdmWxcH_IlDv3yA_hiZYo,10555 +jinja2/lexer.py,sha256=LYiYio6br-Tep9nPcupWXsPEtjluw3p1mU-lNBVRUfk,29786 +jinja2/loaders.py,sha256=wIrnxjvcbqh5VwW28NSkfotiDq8qNCxIOSFbGUiSLB4,24055 +jinja2/meta.py,sha256=OTDPkaFvU2Hgvx-6akz7154F8BIWaRmvJcBFvwopHww,4397 +jinja2/nativetypes.py,sha256=7GIGALVJgdyL80oZJdQUaUfwSt5q2lSSZbXt0dNf_M4,4210 +jinja2/nodes.py,sha256=m1Duzcr6qhZI8JQ6VyJgUNinjAf5bQzijSmDnMsvUx8,34579 +jinja2/optimizer.py,sha256=rJnCRlQ7pZsEEmMhsQDgC_pKyDHxP5TPS6zVPGsgcu8,1651 +jinja2/parser.py,sha256=lLOFy3sEmHc5IaEHRiH1sQVnId2moUQzhyeJZTtdY30,40383 +jinja2/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +jinja2/runtime.py,sha256=gDk-GvdriJXqgsGbHgrcKTP0Yp6zPXzhzrIpCFH3jAU,34249 +jinja2/sandbox.py,sha256=Mw2aitlY2I8la7FYhcX2YG9BtUYcLnD0Gh3d29cDWrY,15009 +jinja2/tests.py,sha256=VLsBhVFnWg-PxSBz1MhRnNWgP1ovXk3neO1FLQMeC9Q,5926 +jinja2/utils.py,sha256=rRp3o9e7ZKS4fyrWRbELyLcpuGVTFcnooaOa1qx_FIk,24129 +jinja2/visitor.py,sha256=EcnL1PIwf_4RVCOMxsRNuR8AXHbS1qfAdMOE2ngKJz4,3557 diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/WHEEL b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..23d2d7e9a5d381ef8a375db09f82052144d1fd96 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.11.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/entry_points.txt b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..abc3eae3b3bc573957cf7401711948799b3465c0 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2-3.1.6.dist-info/entry_points.txt @@ -0,0 +1,3 @@ +[babel.extractors] +jinja2=jinja2.ext:babel_extract[i18n] + diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1a423a3eac16ac550e8e4008d7f5d79401b50e0f --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/__init__.py @@ -0,0 +1,38 @@ +"""Jinja is a template engine written in pure Python. It provides a +non-XML syntax that supports inline expressions and an optional +sandboxed environment. +""" + +from .bccache import BytecodeCache as BytecodeCache +from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache +from .bccache import MemcachedBytecodeCache as MemcachedBytecodeCache +from .environment import Environment as Environment +from .environment import Template as Template +from .exceptions import TemplateAssertionError as TemplateAssertionError +from .exceptions import TemplateError as TemplateError +from .exceptions import TemplateNotFound as TemplateNotFound +from .exceptions import TemplateRuntimeError as TemplateRuntimeError +from .exceptions import TemplatesNotFound as TemplatesNotFound +from .exceptions import TemplateSyntaxError as TemplateSyntaxError +from .exceptions import UndefinedError as UndefinedError +from .loaders import BaseLoader as BaseLoader +from .loaders import ChoiceLoader as ChoiceLoader +from .loaders import DictLoader as DictLoader +from .loaders import FileSystemLoader as FileSystemLoader +from .loaders import FunctionLoader as FunctionLoader +from .loaders import ModuleLoader as ModuleLoader +from .loaders import PackageLoader as PackageLoader +from .loaders import PrefixLoader as PrefixLoader +from .runtime import ChainableUndefined as ChainableUndefined +from .runtime import DebugUndefined as DebugUndefined +from .runtime import make_logging_undefined as make_logging_undefined +from .runtime import StrictUndefined as StrictUndefined +from .runtime import Undefined as Undefined +from .utils import clear_caches as clear_caches +from .utils import is_undefined as is_undefined +from .utils import pass_context as pass_context +from .utils import pass_environment as pass_environment +from .utils import pass_eval_context as pass_eval_context +from .utils import select_autoescape as select_autoescape + +__version__ = "3.1.6" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/_identifier.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/_identifier.py new file mode 100644 index 0000000000000000000000000000000000000000..928c1503c7d414a8a86bbf5a82c68d42cb089bd2 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/_identifier.py @@ -0,0 +1,6 @@ +import re + +# generated by scripts/generate_identifier_pattern.py +pattern = re.compile( + r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣ৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఄా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꣿꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𐴤-𐽆𐴧-𐽐𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑄴𑅅𑅆𑅳𑆀-𑆂𑆳-𑇀𑇉-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌻𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑑞𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑠬-𑠺𑨁-𑨊𑨳-𑨹𑨻-𑨾𑩇𑩑-𑩛𑪊-𑪙𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𑴱-𑴶𑴺𑴼𑴽𑴿-𑵅𑵇𑶊-𑶎𑶐𑶑𑶓-𑶗𑻳-𑻶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯]+" # noqa: B950 +) diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/async_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/async_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f0c140205c50a3df9863ce1ab610b0c62a483f1b --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/async_utils.py @@ -0,0 +1,99 @@ +import inspect +import typing as t +from functools import WRAPPER_ASSIGNMENTS +from functools import wraps + +from .utils import _PassArg +from .utils import pass_eval_context + +if t.TYPE_CHECKING: + import typing_extensions as te + +V = t.TypeVar("V") + + +def async_variant(normal_func): # type: ignore + def decorator(async_func): # type: ignore + pass_arg = _PassArg.from_obj(normal_func) + need_eval_context = pass_arg is None + + if pass_arg is _PassArg.environment: + + def is_async(args: t.Any) -> bool: + return t.cast(bool, args[0].is_async) + + else: + + def is_async(args: t.Any) -> bool: + return t.cast(bool, args[0].environment.is_async) + + # Take the doc and annotations from the sync function, but the + # name from the async function. Pallets-Sphinx-Themes + # build_function_directive expects __wrapped__ to point to the + # sync function. + async_func_attrs = ("__module__", "__name__", "__qualname__") + normal_func_attrs = tuple(set(WRAPPER_ASSIGNMENTS).difference(async_func_attrs)) + + @wraps(normal_func, assigned=normal_func_attrs) + @wraps(async_func, assigned=async_func_attrs, updated=()) + def wrapper(*args, **kwargs): # type: ignore + b = is_async(args) + + if need_eval_context: + args = args[1:] + + if b: + return async_func(*args, **kwargs) + + return normal_func(*args, **kwargs) + + if need_eval_context: + wrapper = pass_eval_context(wrapper) + + wrapper.jinja_async_variant = True # type: ignore[attr-defined] + return wrapper + + return decorator + + +_common_primitives = {int, float, bool, str, list, dict, tuple, type(None)} + + +async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V": + # Avoid a costly call to isawaitable + if type(value) in _common_primitives: + return t.cast("V", value) + + if inspect.isawaitable(value): + return await t.cast("t.Awaitable[V]", value) + + return value + + +class _IteratorToAsyncIterator(t.Generic[V]): + def __init__(self, iterator: "t.Iterator[V]"): + self._iterator = iterator + + def __aiter__(self) -> "te.Self": + return self + + async def __anext__(self) -> V: + try: + return next(self._iterator) + except StopIteration as e: + raise StopAsyncIteration(e.value) from e + + +def auto_aiter( + iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", +) -> "t.AsyncIterator[V]": + if hasattr(iterable, "__aiter__"): + return iterable.__aiter__() + else: + return _IteratorToAsyncIterator(iter(iterable)) + + +async def auto_to_list( + value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]", +) -> t.List["V"]: + return [x async for x in auto_aiter(value)] diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/bccache.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/bccache.py new file mode 100644 index 0000000000000000000000000000000000000000..ada8b099ff251ea9c6da4c42e1383f37e359f06a --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/bccache.py @@ -0,0 +1,408 @@ +"""The optional bytecode cache system. This is useful if you have very +complex template situations and the compilation of all those templates +slows down your application too much. + +Situations where this is useful are often forking web applications that +are initialized on the first request. +""" + +import errno +import fnmatch +import marshal +import os +import pickle +import stat +import sys +import tempfile +import typing as t +from hashlib import sha1 +from io import BytesIO +from types import CodeType + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .environment import Environment + + class _MemcachedClient(te.Protocol): + def get(self, key: str) -> bytes: ... + + def set( + self, key: str, value: bytes, timeout: t.Optional[int] = None + ) -> None: ... + + +bc_version = 5 +# Magic bytes to identify Jinja bytecode cache files. Contains the +# Python major and minor version to avoid loading incompatible bytecode +# if a project upgrades its Python version. +bc_magic = ( + b"j2" + + pickle.dumps(bc_version, 2) + + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1], 2) +) + + +class Bucket: + """Buckets are used to store the bytecode for one template. It's created + and initialized by the bytecode cache and passed to the loading functions. + + The buckets get an internal checksum from the cache assigned and use this + to automatically reject outdated cache material. Individual bytecode + cache subclasses don't have to care about cache invalidation. + """ + + def __init__(self, environment: "Environment", key: str, checksum: str) -> None: + self.environment = environment + self.key = key + self.checksum = checksum + self.reset() + + def reset(self) -> None: + """Resets the bucket (unloads the bytecode).""" + self.code: t.Optional[CodeType] = None + + def load_bytecode(self, f: t.BinaryIO) -> None: + """Loads bytecode from a file or file like object.""" + # make sure the magic header is correct + magic = f.read(len(bc_magic)) + if magic != bc_magic: + self.reset() + return + # the source code of the file changed, we need to reload + checksum = pickle.load(f) + if self.checksum != checksum: + self.reset() + return + # if marshal_load fails then we need to reload + try: + self.code = marshal.load(f) + except (EOFError, ValueError, TypeError): + self.reset() + return + + def write_bytecode(self, f: t.IO[bytes]) -> None: + """Dump the bytecode into the file or file like object passed.""" + if self.code is None: + raise TypeError("can't write empty bucket") + f.write(bc_magic) + pickle.dump(self.checksum, f, 2) + marshal.dump(self.code, f) + + def bytecode_from_string(self, string: bytes) -> None: + """Load bytecode from bytes.""" + self.load_bytecode(BytesIO(string)) + + def bytecode_to_string(self) -> bytes: + """Return the bytecode as bytes.""" + out = BytesIO() + self.write_bytecode(out) + return out.getvalue() + + +class BytecodeCache: + """To implement your own bytecode cache you have to subclass this class + and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of + these methods are passed a :class:`~jinja2.bccache.Bucket`. + + A very basic bytecode cache that saves the bytecode on the file system:: + + from os import path + + class MyCache(BytecodeCache): + + def __init__(self, directory): + self.directory = directory + + def load_bytecode(self, bucket): + filename = path.join(self.directory, bucket.key) + if path.exists(filename): + with open(filename, 'rb') as f: + bucket.load_bytecode(f) + + def dump_bytecode(self, bucket): + filename = path.join(self.directory, bucket.key) + with open(filename, 'wb') as f: + bucket.write_bytecode(f) + + A more advanced version of a filesystem based bytecode cache is part of + Jinja. + """ + + def load_bytecode(self, bucket: Bucket) -> None: + """Subclasses have to override this method to load bytecode into a + bucket. If they are not able to find code in the cache for the + bucket, it must not do anything. + """ + raise NotImplementedError() + + def dump_bytecode(self, bucket: Bucket) -> None: + """Subclasses have to override this method to write the bytecode + from a bucket back to the cache. If it unable to do so it must not + fail silently but raise an exception. + """ + raise NotImplementedError() + + def clear(self) -> None: + """Clears the cache. This method is not used by Jinja but should be + implemented to allow applications to clear the bytecode cache used + by a particular environment. + """ + + def get_cache_key( + self, name: str, filename: t.Optional[t.Union[str]] = None + ) -> str: + """Returns the unique hash key for this template name.""" + hash = sha1(name.encode("utf-8")) + + if filename is not None: + hash.update(f"|{filename}".encode()) + + return hash.hexdigest() + + def get_source_checksum(self, source: str) -> str: + """Returns a checksum for the source.""" + return sha1(source.encode("utf-8")).hexdigest() + + def get_bucket( + self, + environment: "Environment", + name: str, + filename: t.Optional[str], + source: str, + ) -> Bucket: + """Return a cache bucket for the given template. All arguments are + mandatory but filename may be `None`. + """ + key = self.get_cache_key(name, filename) + checksum = self.get_source_checksum(source) + bucket = Bucket(environment, key, checksum) + self.load_bytecode(bucket) + return bucket + + def set_bucket(self, bucket: Bucket) -> None: + """Put the bucket into the cache.""" + self.dump_bytecode(bucket) + + +class FileSystemBytecodeCache(BytecodeCache): + """A bytecode cache that stores bytecode on the filesystem. It accepts + two arguments: The directory where the cache items are stored and a + pattern string that is used to build the filename. + + If no directory is specified a default cache directory is selected. On + Windows the user's temp directory is used, on UNIX systems a directory + is created for the user in the system temp directory. + + The pattern can be used to have multiple separate caches operate on the + same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s`` + is replaced with the cache key. + + >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache') + + This bytecode cache supports clearing of the cache using the clear method. + """ + + def __init__( + self, directory: t.Optional[str] = None, pattern: str = "__jinja2_%s.cache" + ) -> None: + if directory is None: + directory = self._get_default_cache_dir() + self.directory = directory + self.pattern = pattern + + def _get_default_cache_dir(self) -> str: + def _unsafe_dir() -> "te.NoReturn": + raise RuntimeError( + "Cannot determine safe temp directory. You " + "need to explicitly provide one." + ) + + tmpdir = tempfile.gettempdir() + + # On windows the temporary directory is used specific unless + # explicitly forced otherwise. We can just use that. + if os.name == "nt": + return tmpdir + if not hasattr(os, "getuid"): + _unsafe_dir() + + dirname = f"_jinja2-cache-{os.getuid()}" + actual_dir = os.path.join(tmpdir, dirname) + + try: + os.mkdir(actual_dir, stat.S_IRWXU) + except OSError as e: + if e.errno != errno.EEXIST: + raise + try: + os.chmod(actual_dir, stat.S_IRWXU) + actual_dir_stat = os.lstat(actual_dir) + if ( + actual_dir_stat.st_uid != os.getuid() + or not stat.S_ISDIR(actual_dir_stat.st_mode) + or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU + ): + _unsafe_dir() + except OSError as e: + if e.errno != errno.EEXIST: + raise + + actual_dir_stat = os.lstat(actual_dir) + if ( + actual_dir_stat.st_uid != os.getuid() + or not stat.S_ISDIR(actual_dir_stat.st_mode) + or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU + ): + _unsafe_dir() + + return actual_dir + + def _get_cache_filename(self, bucket: Bucket) -> str: + return os.path.join(self.directory, self.pattern % (bucket.key,)) + + def load_bytecode(self, bucket: Bucket) -> None: + filename = self._get_cache_filename(bucket) + + # Don't test for existence before opening the file, since the + # file could disappear after the test before the open. + try: + f = open(filename, "rb") + except (FileNotFoundError, IsADirectoryError, PermissionError): + # PermissionError can occur on Windows when an operation is + # in progress, such as calling clear(). + return + + with f: + bucket.load_bytecode(f) + + def dump_bytecode(self, bucket: Bucket) -> None: + # Write to a temporary file, then rename to the real name after + # writing. This avoids another process reading the file before + # it is fully written. + name = self._get_cache_filename(bucket) + f = tempfile.NamedTemporaryFile( + mode="wb", + dir=os.path.dirname(name), + prefix=os.path.basename(name), + suffix=".tmp", + delete=False, + ) + + def remove_silent() -> None: + try: + os.remove(f.name) + except OSError: + # Another process may have called clear(). On Windows, + # another program may be holding the file open. + pass + + try: + with f: + bucket.write_bytecode(f) + except BaseException: + remove_silent() + raise + + try: + os.replace(f.name, name) + except OSError: + # Another process may have called clear(). On Windows, + # another program may be holding the file open. + remove_silent() + except BaseException: + remove_silent() + raise + + def clear(self) -> None: + # imported lazily here because google app-engine doesn't support + # write access on the file system and the function does not exist + # normally. + from os import remove + + files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",)) + for filename in files: + try: + remove(os.path.join(self.directory, filename)) + except OSError: + pass + + +class MemcachedBytecodeCache(BytecodeCache): + """This class implements a bytecode cache that uses a memcache cache for + storing the information. It does not enforce a specific memcache library + (tummy's memcache or cmemcache) but will accept any class that provides + the minimal interface required. + + Libraries compatible with this class: + + - `cachelib `_ + - `python-memcached `_ + + (Unfortunately the django cache interface is not compatible because it + does not support storing binary data, only text. You can however pass + the underlying cache client to the bytecode cache which is available + as `django.core.cache.cache._client`.) + + The minimal interface for the client passed to the constructor is this: + + .. class:: MinimalClientInterface + + .. method:: set(key, value[, timeout]) + + Stores the bytecode in the cache. `value` is a string and + `timeout` the timeout of the key. If timeout is not provided + a default timeout or no timeout should be assumed, if it's + provided it's an integer with the number of seconds the cache + item should exist. + + .. method:: get(key) + + Returns the value for the cache key. If the item does not + exist in the cache the return value must be `None`. + + The other arguments to the constructor are the prefix for all keys that + is added before the actual cache key and the timeout for the bytecode in + the cache system. We recommend a high (or no) timeout. + + This bytecode cache does not support clearing of used items in the cache. + The clear method is a no-operation function. + + .. versionadded:: 2.7 + Added support for ignoring memcache errors through the + `ignore_memcache_errors` parameter. + """ + + def __init__( + self, + client: "_MemcachedClient", + prefix: str = "jinja2/bytecode/", + timeout: t.Optional[int] = None, + ignore_memcache_errors: bool = True, + ): + self.client = client + self.prefix = prefix + self.timeout = timeout + self.ignore_memcache_errors = ignore_memcache_errors + + def load_bytecode(self, bucket: Bucket) -> None: + try: + code = self.client.get(self.prefix + bucket.key) + except Exception: + if not self.ignore_memcache_errors: + raise + else: + bucket.bytecode_from_string(code) + + def dump_bytecode(self, bucket: Bucket) -> None: + key = self.prefix + bucket.key + value = bucket.bytecode_to_string() + + try: + if self.timeout is not None: + self.client.set(key, value, self.timeout) + else: + self.client.set(key, value) + except Exception: + if not self.ignore_memcache_errors: + raise diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/compiler.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ff6a1b11af3e1a868d1a74c48d842390259b43 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/compiler.py @@ -0,0 +1,1998 @@ +"""Compiles nodes from the parser into Python code.""" + +import typing as t +from contextlib import contextmanager +from functools import update_wrapper +from io import StringIO +from itertools import chain +from keyword import iskeyword as is_python_keyword + +from markupsafe import escape +from markupsafe import Markup + +from . import nodes +from .exceptions import TemplateAssertionError +from .idtracking import Symbols +from .idtracking import VAR_LOAD_ALIAS +from .idtracking import VAR_LOAD_PARAMETER +from .idtracking import VAR_LOAD_RESOLVE +from .idtracking import VAR_LOAD_UNDEFINED +from .nodes import EvalContext +from .optimizer import Optimizer +from .utils import _PassArg +from .utils import concat +from .visitor import NodeVisitor + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .environment import Environment + +F = t.TypeVar("F", bound=t.Callable[..., t.Any]) + +operators = { + "eq": "==", + "ne": "!=", + "gt": ">", + "gteq": ">=", + "lt": "<", + "lteq": "<=", + "in": "in", + "notin": "not in", +} + + +def optimizeconst(f: F) -> F: + def new_func( + self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any + ) -> t.Any: + # Only optimize if the frame is not volatile + if self.optimizer is not None and not frame.eval_ctx.volatile: + new_node = self.optimizer.visit(node, frame.eval_ctx) + + if new_node != node: + return self.visit(new_node, frame) + + return f(self, node, frame, **kwargs) + + return update_wrapper(new_func, f) # type: ignore[return-value] + + +def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]: + @optimizeconst + def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None: + if ( + self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignore + ): + self.write(f"environment.call_binop(context, {op!r}, ") + self.visit(node.left, frame) + self.write(", ") + self.visit(node.right, frame) + else: + self.write("(") + self.visit(node.left, frame) + self.write(f" {op} ") + self.visit(node.right, frame) + + self.write(")") + + return visitor + + +def _make_unop( + op: str, +) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]: + @optimizeconst + def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None: + if ( + self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignore + ): + self.write(f"environment.call_unop(context, {op!r}, ") + self.visit(node.node, frame) + else: + self.write("(" + op) + self.visit(node.node, frame) + + self.write(")") + + return visitor + + +def generate( + node: nodes.Template, + environment: "Environment", + name: t.Optional[str], + filename: t.Optional[str], + stream: t.Optional[t.TextIO] = None, + defer_init: bool = False, + optimized: bool = True, +) -> t.Optional[str]: + """Generate the python source for a node tree.""" + if not isinstance(node, nodes.Template): + raise TypeError("Can't compile non template nodes") + + generator = environment.code_generator_class( + environment, name, filename, stream, defer_init, optimized + ) + generator.visit(node) + + if stream is None: + return generator.stream.getvalue() # type: ignore + + return None + + +def has_safe_repr(value: t.Any) -> bool: + """Does the node have a safe representation?""" + if value is None or value is NotImplemented or value is Ellipsis: + return True + + if type(value) in {bool, int, float, complex, range, str, Markup}: + return True + + if type(value) in {tuple, list, set, frozenset}: + return all(has_safe_repr(v) for v in value) + + if type(value) is dict: # noqa E721 + return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items()) + + return False + + +def find_undeclared( + nodes: t.Iterable[nodes.Node], names: t.Iterable[str] +) -> t.Set[str]: + """Check if the names passed are accessed undeclared. The return value + is a set of all the undeclared names from the sequence of names found. + """ + visitor = UndeclaredNameVisitor(names) + try: + for node in nodes: + visitor.visit(node) + except VisitorExit: + pass + return visitor.undeclared + + +class MacroRef: + def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None: + self.node = node + self.accesses_caller = False + self.accesses_kwargs = False + self.accesses_varargs = False + + +class Frame: + """Holds compile time information for us.""" + + def __init__( + self, + eval_ctx: EvalContext, + parent: t.Optional["Frame"] = None, + level: t.Optional[int] = None, + ) -> None: + self.eval_ctx = eval_ctx + + # the parent of this frame + self.parent = parent + + if parent is None: + self.symbols = Symbols(level=level) + + # in some dynamic inheritance situations the compiler needs to add + # write tests around output statements. + self.require_output_check = False + + # inside some tags we are using a buffer rather than yield statements. + # this for example affects {% filter %} or {% macro %}. If a frame + # is buffered this variable points to the name of the list used as + # buffer. + self.buffer: t.Optional[str] = None + + # the name of the block we're in, otherwise None. + self.block: t.Optional[str] = None + + else: + self.symbols = Symbols(parent.symbols, level=level) + self.require_output_check = parent.require_output_check + self.buffer = parent.buffer + self.block = parent.block + + # a toplevel frame is the root + soft frames such as if conditions. + self.toplevel = False + + # the root frame is basically just the outermost frame, so no if + # conditions. This information is used to optimize inheritance + # situations. + self.rootlevel = False + + # variables set inside of loops and blocks should not affect outer frames, + # but they still needs to be kept track of as part of the active context. + self.loop_frame = False + self.block_frame = False + + # track whether the frame is being used in an if-statement or conditional + # expression as it determines which errors should be raised during runtime + # or compile time. + self.soft_frame = False + + def copy(self) -> "te.Self": + """Create a copy of the current one.""" + rv = object.__new__(self.__class__) + rv.__dict__.update(self.__dict__) + rv.symbols = self.symbols.copy() + return rv + + def inner(self, isolated: bool = False) -> "Frame": + """Return an inner frame.""" + if isolated: + return Frame(self.eval_ctx, level=self.symbols.level + 1) + return Frame(self.eval_ctx, self) + + def soft(self) -> "te.Self": + """Return a soft frame. A soft frame may not be modified as + standalone thing as it shares the resources with the frame it + was created of, but it's not a rootlevel frame any longer. + + This is only used to implement if-statements and conditional + expressions. + """ + rv = self.copy() + rv.rootlevel = False + rv.soft_frame = True + return rv + + __copy__ = copy + + +class VisitorExit(RuntimeError): + """Exception used by the `UndeclaredNameVisitor` to signal a stop.""" + + +class DependencyFinderVisitor(NodeVisitor): + """A visitor that collects filter and test calls.""" + + def __init__(self) -> None: + self.filters: t.Set[str] = set() + self.tests: t.Set[str] = set() + + def visit_Filter(self, node: nodes.Filter) -> None: + self.generic_visit(node) + self.filters.add(node.name) + + def visit_Test(self, node: nodes.Test) -> None: + self.generic_visit(node) + self.tests.add(node.name) + + def visit_Block(self, node: nodes.Block) -> None: + """Stop visiting at blocks.""" + + +class UndeclaredNameVisitor(NodeVisitor): + """A visitor that checks if a name is accessed without being + declared. This is different from the frame visitor as it will + not stop at closure frames. + """ + + def __init__(self, names: t.Iterable[str]) -> None: + self.names = set(names) + self.undeclared: t.Set[str] = set() + + def visit_Name(self, node: nodes.Name) -> None: + if node.ctx == "load" and node.name in self.names: + self.undeclared.add(node.name) + if self.undeclared == self.names: + raise VisitorExit() + else: + self.names.discard(node.name) + + def visit_Block(self, node: nodes.Block) -> None: + """Stop visiting a blocks.""" + + +class CompilerExit(Exception): + """Raised if the compiler encountered a situation where it just + doesn't make sense to further process the code. Any block that + raises such an exception is not further processed. + """ + + +class CodeGenerator(NodeVisitor): + def __init__( + self, + environment: "Environment", + name: t.Optional[str], + filename: t.Optional[str], + stream: t.Optional[t.TextIO] = None, + defer_init: bool = False, + optimized: bool = True, + ) -> None: + if stream is None: + stream = StringIO() + self.environment = environment + self.name = name + self.filename = filename + self.stream = stream + self.created_block_context = False + self.defer_init = defer_init + self.optimizer: t.Optional[Optimizer] = None + + if optimized: + self.optimizer = Optimizer(environment) + + # aliases for imports + self.import_aliases: t.Dict[str, str] = {} + + # a registry for all blocks. Because blocks are moved out + # into the global python scope they are registered here + self.blocks: t.Dict[str, nodes.Block] = {} + + # the number of extends statements so far + self.extends_so_far = 0 + + # some templates have a rootlevel extends. In this case we + # can safely assume that we're a child template and do some + # more optimizations. + self.has_known_extends = False + + # the current line number + self.code_lineno = 1 + + # registry of all filters and tests (global, not block local) + self.tests: t.Dict[str, str] = {} + self.filters: t.Dict[str, str] = {} + + # the debug information + self.debug_info: t.List[t.Tuple[int, int]] = [] + self._write_debug_info: t.Optional[int] = None + + # the number of new lines before the next write() + self._new_lines = 0 + + # the line number of the last written statement + self._last_line = 0 + + # true if nothing was written so far. + self._first_write = True + + # used by the `temporary_identifier` method to get new + # unique, temporary identifier + self._last_identifier = 0 + + # the current indentation + self._indentation = 0 + + # Tracks toplevel assignments + self._assign_stack: t.List[t.Set[str]] = [] + + # Tracks parameter definition blocks + self._param_def_block: t.List[t.Set[str]] = [] + + # Tracks the current context. + self._context_reference_stack = ["context"] + + @property + def optimized(self) -> bool: + return self.optimizer is not None + + # -- Various compilation helpers + + def fail(self, msg: str, lineno: int) -> "te.NoReturn": + """Fail with a :exc:`TemplateAssertionError`.""" + raise TemplateAssertionError(msg, lineno, self.name, self.filename) + + def temporary_identifier(self) -> str: + """Get a new unique identifier.""" + self._last_identifier += 1 + return f"t_{self._last_identifier}" + + def buffer(self, frame: Frame) -> None: + """Enable buffering for the frame from that point onwards.""" + frame.buffer = self.temporary_identifier() + self.writeline(f"{frame.buffer} = []") + + def return_buffer_contents( + self, frame: Frame, force_unescaped: bool = False + ) -> None: + """Return the buffer contents of the frame.""" + if not force_unescaped: + if frame.eval_ctx.volatile: + self.writeline("if context.eval_ctx.autoescape:") + self.indent() + self.writeline(f"return Markup(concat({frame.buffer}))") + self.outdent() + self.writeline("else:") + self.indent() + self.writeline(f"return concat({frame.buffer})") + self.outdent() + return + elif frame.eval_ctx.autoescape: + self.writeline(f"return Markup(concat({frame.buffer}))") + return + self.writeline(f"return concat({frame.buffer})") + + def indent(self) -> None: + """Indent by one.""" + self._indentation += 1 + + def outdent(self, step: int = 1) -> None: + """Outdent by step.""" + self._indentation -= step + + def start_write(self, frame: Frame, node: t.Optional[nodes.Node] = None) -> None: + """Yield or write into the frame buffer.""" + if frame.buffer is None: + self.writeline("yield ", node) + else: + self.writeline(f"{frame.buffer}.append(", node) + + def end_write(self, frame: Frame) -> None: + """End the writing process started by `start_write`.""" + if frame.buffer is not None: + self.write(")") + + def simple_write( + self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None + ) -> None: + """Simple shortcut for start_write + write + end_write.""" + self.start_write(frame, node) + self.write(s) + self.end_write(frame) + + def blockvisit(self, nodes: t.Iterable[nodes.Node], frame: Frame) -> None: + """Visit a list of nodes as block in a frame. If the current frame + is no buffer a dummy ``if 0: yield None`` is written automatically. + """ + try: + self.writeline("pass") + for node in nodes: + self.visit(node, frame) + except CompilerExit: + pass + + def write(self, x: str) -> None: + """Write a string into the output stream.""" + if self._new_lines: + if not self._first_write: + self.stream.write("\n" * self._new_lines) + self.code_lineno += self._new_lines + if self._write_debug_info is not None: + self.debug_info.append((self._write_debug_info, self.code_lineno)) + self._write_debug_info = None + self._first_write = False + self.stream.write(" " * self._indentation) + self._new_lines = 0 + self.stream.write(x) + + def writeline( + self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0 + ) -> None: + """Combination of newline and write.""" + self.newline(node, extra) + self.write(x) + + def newline(self, node: t.Optional[nodes.Node] = None, extra: int = 0) -> None: + """Add one or more newlines before the next write.""" + self._new_lines = max(self._new_lines, 1 + extra) + if node is not None and node.lineno != self._last_line: + self._write_debug_info = node.lineno + self._last_line = node.lineno + + def signature( + self, + node: t.Union[nodes.Call, nodes.Filter, nodes.Test], + frame: Frame, + extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + ) -> None: + """Writes a function call to the stream for the current node. + A leading comma is added automatically. The extra keyword + arguments may not include python keywords otherwise a syntax + error could occur. The extra keyword arguments should be given + as python dict. + """ + # if any of the given keyword arguments is a python keyword + # we have to make sure that no invalid call is created. + kwarg_workaround = any( + is_python_keyword(t.cast(str, k)) + for k in chain((x.key for x in node.kwargs), extra_kwargs or ()) + ) + + for arg in node.args: + self.write(", ") + self.visit(arg, frame) + + if not kwarg_workaround: + for kwarg in node.kwargs: + self.write(", ") + self.visit(kwarg, frame) + if extra_kwargs is not None: + for key, value in extra_kwargs.items(): + self.write(f", {key}={value}") + if node.dyn_args: + self.write(", *") + self.visit(node.dyn_args, frame) + + if kwarg_workaround: + if node.dyn_kwargs is not None: + self.write(", **dict({") + else: + self.write(", **{") + for kwarg in node.kwargs: + self.write(f"{kwarg.key!r}: ") + self.visit(kwarg.value, frame) + self.write(", ") + if extra_kwargs is not None: + for key, value in extra_kwargs.items(): + self.write(f"{key!r}: {value}, ") + if node.dyn_kwargs is not None: + self.write("}, **") + self.visit(node.dyn_kwargs, frame) + self.write(")") + else: + self.write("}") + + elif node.dyn_kwargs is not None: + self.write(", **") + self.visit(node.dyn_kwargs, frame) + + def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None: + """Find all filter and test names used in the template and + assign them to variables in the compiled namespace. Checking + that the names are registered with the environment is done when + compiling the Filter and Test nodes. If the node is in an If or + CondExpr node, the check is done at runtime instead. + + .. versionchanged:: 3.0 + Filters and tests in If and CondExpr nodes are checked at + runtime instead of compile time. + """ + visitor = DependencyFinderVisitor() + + for node in nodes: + visitor.visit(node) + + for id_map, names, dependency in ( + (self.filters, visitor.filters, "filters"), + ( + self.tests, + visitor.tests, + "tests", + ), + ): + for name in sorted(names): + if name not in id_map: + id_map[name] = self.temporary_identifier() + + # add check during runtime that dependencies used inside of executed + # blocks are defined, as this step may be skipped during compile time + self.writeline("try:") + self.indent() + self.writeline(f"{id_map[name]} = environment.{dependency}[{name!r}]") + self.outdent() + self.writeline("except KeyError:") + self.indent() + self.writeline("@internalcode") + self.writeline(f"def {id_map[name]}(*unused):") + self.indent() + self.writeline( + f'raise TemplateRuntimeError("No {dependency[:-1]}' + f' named {name!r} found.")' + ) + self.outdent() + self.outdent() + + def enter_frame(self, frame: Frame) -> None: + undefs = [] + for target, (action, param) in frame.symbols.loads.items(): + if action == VAR_LOAD_PARAMETER: + pass + elif action == VAR_LOAD_RESOLVE: + self.writeline(f"{target} = {self.get_resolve_func()}({param!r})") + elif action == VAR_LOAD_ALIAS: + self.writeline(f"{target} = {param}") + elif action == VAR_LOAD_UNDEFINED: + undefs.append(target) + else: + raise NotImplementedError("unknown load instruction") + if undefs: + self.writeline(f"{' = '.join(undefs)} = missing") + + def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None: + if not with_python_scope: + undefs = [] + for target in frame.symbols.loads: + undefs.append(target) + if undefs: + self.writeline(f"{' = '.join(undefs)} = missing") + + def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str: + return async_value if self.environment.is_async else sync_value + + def func(self, name: str) -> str: + return f"{self.choose_async()}def {name}" + + def macro_body( + self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame + ) -> t.Tuple[Frame, MacroRef]: + """Dump the function def of a macro or call block.""" + frame = frame.inner() + frame.symbols.analyze_node(node) + macro_ref = MacroRef(node) + + explicit_caller = None + skip_special_params = set() + args = [] + + for idx, arg in enumerate(node.args): + if arg.name == "caller": + explicit_caller = idx + if arg.name in ("kwargs", "varargs"): + skip_special_params.add(arg.name) + args.append(frame.symbols.ref(arg.name)) + + undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs")) + + if "caller" in undeclared: + # In older Jinja versions there was a bug that allowed caller + # to retain the special behavior even if it was mentioned in + # the argument list. However thankfully this was only really + # working if it was the last argument. So we are explicitly + # checking this now and error out if it is anywhere else in + # the argument list. + if explicit_caller is not None: + try: + node.defaults[explicit_caller - len(node.args)] + except IndexError: + self.fail( + "When defining macros or call blocks the " + 'special "caller" argument must be omitted ' + "or be given a default.", + node.lineno, + ) + else: + args.append(frame.symbols.declare_parameter("caller")) + macro_ref.accesses_caller = True + if "kwargs" in undeclared and "kwargs" not in skip_special_params: + args.append(frame.symbols.declare_parameter("kwargs")) + macro_ref.accesses_kwargs = True + if "varargs" in undeclared and "varargs" not in skip_special_params: + args.append(frame.symbols.declare_parameter("varargs")) + macro_ref.accesses_varargs = True + + # macros are delayed, they never require output checks + frame.require_output_check = False + frame.symbols.analyze_node(node) + self.writeline(f"{self.func('macro')}({', '.join(args)}):", node) + self.indent() + + self.buffer(frame) + self.enter_frame(frame) + + self.push_parameter_definitions(frame) + for idx, arg in enumerate(node.args): + ref = frame.symbols.ref(arg.name) + self.writeline(f"if {ref} is missing:") + self.indent() + try: + default = node.defaults[idx - len(node.args)] + except IndexError: + self.writeline( + f'{ref} = undefined("parameter {arg.name!r} was not provided",' + f" name={arg.name!r})" + ) + else: + self.writeline(f"{ref} = ") + self.visit(default, frame) + self.mark_parameter_stored(ref) + self.outdent() + self.pop_parameter_definitions() + + self.blockvisit(node.body, frame) + self.return_buffer_contents(frame, force_unescaped=True) + self.leave_frame(frame, with_python_scope=True) + self.outdent() + + return frame, macro_ref + + def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None: + """Dump the macro definition for the def created by macro_body.""" + arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args) + name = getattr(macro_ref.node, "name", None) + if len(macro_ref.node.args) == 1: + arg_tuple += "," + self.write( + f"Macro(environment, macro, {name!r}, ({arg_tuple})," + f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r}," + f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)" + ) + + def position(self, node: nodes.Node) -> str: + """Return a human readable position for the node.""" + rv = f"line {node.lineno}" + if self.name is not None: + rv = f"{rv} in {self.name!r}" + return rv + + def dump_local_context(self, frame: Frame) -> str: + items_kv = ", ".join( + f"{name!r}: {target}" + for name, target in frame.symbols.dump_stores().items() + ) + return f"{{{items_kv}}}" + + def write_commons(self) -> None: + """Writes a common preamble that is used by root and block functions. + Primarily this sets up common local helpers and enforces a generator + through a dead branch. + """ + self.writeline("resolve = context.resolve_or_missing") + self.writeline("undefined = environment.undefined") + self.writeline("concat = environment.concat") + # always use the standard Undefined class for the implicit else of + # conditional expressions + self.writeline("cond_expr_undefined = Undefined") + self.writeline("if 0: yield None") + + def push_parameter_definitions(self, frame: Frame) -> None: + """Pushes all parameter targets from the given frame into a local + stack that permits tracking of yet to be assigned parameters. In + particular this enables the optimization from `visit_Name` to skip + undefined expressions for parameters in macros as macros can reference + otherwise unbound parameters. + """ + self._param_def_block.append(frame.symbols.dump_param_targets()) + + def pop_parameter_definitions(self) -> None: + """Pops the current parameter definitions set.""" + self._param_def_block.pop() + + def mark_parameter_stored(self, target: str) -> None: + """Marks a parameter in the current parameter definitions as stored. + This will skip the enforced undefined checks. + """ + if self._param_def_block: + self._param_def_block[-1].discard(target) + + def push_context_reference(self, target: str) -> None: + self._context_reference_stack.append(target) + + def pop_context_reference(self) -> None: + self._context_reference_stack.pop() + + def get_context_ref(self) -> str: + return self._context_reference_stack[-1] + + def get_resolve_func(self) -> str: + target = self._context_reference_stack[-1] + if target == "context": + return "resolve" + return f"{target}.resolve" + + def derive_context(self, frame: Frame) -> str: + return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})" + + def parameter_is_undeclared(self, target: str) -> bool: + """Checks if a given target is an undeclared parameter.""" + if not self._param_def_block: + return False + return target in self._param_def_block[-1] + + def push_assign_tracking(self) -> None: + """Pushes a new layer for assignment tracking.""" + self._assign_stack.append(set()) + + def pop_assign_tracking(self, frame: Frame) -> None: + """Pops the topmost level for assignment tracking and updates the + context variables if necessary. + """ + vars = self._assign_stack.pop() + if ( + not frame.block_frame + and not frame.loop_frame + and not frame.toplevel + or not vars + ): + return + public_names = [x for x in vars if x[:1] != "_"] + if len(vars) == 1: + name = next(iter(vars)) + ref = frame.symbols.ref(name) + if frame.loop_frame: + self.writeline(f"_loop_vars[{name!r}] = {ref}") + return + if frame.block_frame: + self.writeline(f"_block_vars[{name!r}] = {ref}") + return + self.writeline(f"context.vars[{name!r}] = {ref}") + else: + if frame.loop_frame: + self.writeline("_loop_vars.update({") + elif frame.block_frame: + self.writeline("_block_vars.update({") + else: + self.writeline("context.vars.update({") + for idx, name in enumerate(sorted(vars)): + if idx: + self.write(", ") + ref = frame.symbols.ref(name) + self.write(f"{name!r}: {ref}") + self.write("})") + if not frame.block_frame and not frame.loop_frame and public_names: + if len(public_names) == 1: + self.writeline(f"context.exported_vars.add({public_names[0]!r})") + else: + names_str = ", ".join(map(repr, sorted(public_names))) + self.writeline(f"context.exported_vars.update(({names_str}))") + + # -- Statement Visitors + + def visit_Template( + self, node: nodes.Template, frame: t.Optional[Frame] = None + ) -> None: + assert frame is None, "no root frame allowed" + eval_ctx = EvalContext(self.environment, self.name) + + from .runtime import async_exported + from .runtime import exported + + if self.environment.is_async: + exported_names = sorted(exported + async_exported) + else: + exported_names = sorted(exported) + + self.writeline("from jinja2.runtime import " + ", ".join(exported_names)) + + # if we want a deferred initialization we cannot move the + # environment into a local name + envenv = "" if self.defer_init else ", environment=environment" + + # do we have an extends tag at all? If not, we can save some + # overhead by just not processing any inheritance code. + have_extends = node.find(nodes.Extends) is not None + + # find all blocks + for block in node.find_all(nodes.Block): + if block.name in self.blocks: + self.fail(f"block {block.name!r} defined twice", block.lineno) + self.blocks[block.name] = block + + # find all imports and import them + for import_ in node.find_all(nodes.ImportedName): + if import_.importname not in self.import_aliases: + imp = import_.importname + self.import_aliases[imp] = alias = self.temporary_identifier() + if "." in imp: + module, obj = imp.rsplit(".", 1) + self.writeline(f"from {module} import {obj} as {alias}") + else: + self.writeline(f"import {imp} as {alias}") + + # add the load name + self.writeline(f"name = {self.name!r}") + + # generate the root render function. + self.writeline( + f"{self.func('root')}(context, missing=missing{envenv}):", extra=1 + ) + self.indent() + self.write_commons() + + # process the root + frame = Frame(eval_ctx) + if "self" in find_undeclared(node.body, ("self",)): + ref = frame.symbols.declare_parameter("self") + self.writeline(f"{ref} = TemplateReference(context)") + frame.symbols.analyze_node(node) + frame.toplevel = frame.rootlevel = True + frame.require_output_check = have_extends and not self.has_known_extends + if have_extends: + self.writeline("parent_template = None") + self.enter_frame(frame) + self.pull_dependencies(node.body) + self.blockvisit(node.body, frame) + self.leave_frame(frame, with_python_scope=True) + self.outdent() + + # make sure that the parent root is called. + if have_extends: + if not self.has_known_extends: + self.indent() + self.writeline("if parent_template is not None:") + self.indent() + if not self.environment.is_async: + self.writeline("yield from parent_template.root_render_func(context)") + else: + self.writeline("agen = parent_template.root_render_func(context)") + self.writeline("try:") + self.indent() + self.writeline("async for event in agen:") + self.indent() + self.writeline("yield event") + self.outdent() + self.outdent() + self.writeline("finally: await agen.aclose()") + self.outdent(1 + (not self.has_known_extends)) + + # at this point we now have the blocks collected and can visit them too. + for name, block in self.blocks.items(): + self.writeline( + f"{self.func('block_' + name)}(context, missing=missing{envenv}):", + block, + 1, + ) + self.indent() + self.write_commons() + # It's important that we do not make this frame a child of the + # toplevel template. This would cause a variety of + # interesting issues with identifier tracking. + block_frame = Frame(eval_ctx) + block_frame.block_frame = True + undeclared = find_undeclared(block.body, ("self", "super")) + if "self" in undeclared: + ref = block_frame.symbols.declare_parameter("self") + self.writeline(f"{ref} = TemplateReference(context)") + if "super" in undeclared: + ref = block_frame.symbols.declare_parameter("super") + self.writeline(f"{ref} = context.super({name!r}, block_{name})") + block_frame.symbols.analyze_node(block) + block_frame.block = name + self.writeline("_block_vars = {}") + self.enter_frame(block_frame) + self.pull_dependencies(block.body) + self.blockvisit(block.body, block_frame) + self.leave_frame(block_frame, with_python_scope=True) + self.outdent() + + blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks) + self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1) + debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info) + self.writeline(f"debug_info = {debug_kv_str!r}") + + def visit_Block(self, node: nodes.Block, frame: Frame) -> None: + """Call a block and register it for the template.""" + level = 0 + if frame.toplevel: + # if we know that we are a child template, there is no need to + # check if we are one + if self.has_known_extends: + return + if self.extends_so_far > 0: + self.writeline("if parent_template is None:") + self.indent() + level += 1 + + if node.scoped: + context = self.derive_context(frame) + else: + context = self.get_context_ref() + + if node.required: + self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node) + self.indent() + self.writeline( + f'raise TemplateRuntimeError("Required block {node.name!r} not found")', + node, + ) + self.outdent() + + if not self.environment.is_async and frame.buffer is None: + self.writeline( + f"yield from context.blocks[{node.name!r}][0]({context})", node + ) + else: + self.writeline(f"gen = context.blocks[{node.name!r}][0]({context})") + self.writeline("try:") + self.indent() + self.writeline( + f"{self.choose_async()}for event in gen:", + node, + ) + self.indent() + self.simple_write("event", frame) + self.outdent() + self.outdent() + self.writeline( + f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}" + ) + + self.outdent(level) + + def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None: + """Calls the extender.""" + if not frame.toplevel: + self.fail("cannot use extend from a non top-level scope", node.lineno) + + # if the number of extends statements in general is zero so + # far, we don't have to add a check if something extended + # the template before this one. + if self.extends_so_far > 0: + # if we have a known extends we just add a template runtime + # error into the generated code. We could catch that at compile + # time too, but i welcome it not to confuse users by throwing the + # same error at different times just "because we can". + if not self.has_known_extends: + self.writeline("if parent_template is not None:") + self.indent() + self.writeline('raise TemplateRuntimeError("extended multiple times")') + + # if we have a known extends already we don't need that code here + # as we know that the template execution will end here. + if self.has_known_extends: + raise CompilerExit() + else: + self.outdent() + + self.writeline("parent_template = environment.get_template(", node) + self.visit(node.template, frame) + self.write(f", {self.name!r})") + self.writeline("for name, parent_block in parent_template.blocks.items():") + self.indent() + self.writeline("context.blocks.setdefault(name, []).append(parent_block)") + self.outdent() + + # if this extends statement was in the root level we can take + # advantage of that information and simplify the generated code + # in the top level from this point onwards + if frame.rootlevel: + self.has_known_extends = True + + # and now we have one more + self.extends_so_far += 1 + + def visit_Include(self, node: nodes.Include, frame: Frame) -> None: + """Handles includes.""" + if node.ignore_missing: + self.writeline("try:") + self.indent() + + func_name = "get_or_select_template" + if isinstance(node.template, nodes.Const): + if isinstance(node.template.value, str): + func_name = "get_template" + elif isinstance(node.template.value, (tuple, list)): + func_name = "select_template" + elif isinstance(node.template, (nodes.Tuple, nodes.List)): + func_name = "select_template" + + self.writeline(f"template = environment.{func_name}(", node) + self.visit(node.template, frame) + self.write(f", {self.name!r})") + if node.ignore_missing: + self.outdent() + self.writeline("except TemplateNotFound:") + self.indent() + self.writeline("pass") + self.outdent() + self.writeline("else:") + self.indent() + + def loop_body() -> None: + self.indent() + self.simple_write("event", frame) + self.outdent() + + if node.with_context: + self.writeline( + f"gen = template.root_render_func(" + "template.new_context(context.get_all(), True," + f" {self.dump_local_context(frame)}))" + ) + self.writeline("try:") + self.indent() + self.writeline(f"{self.choose_async()}for event in gen:") + loop_body() + self.outdent() + self.writeline( + f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}" + ) + elif self.environment.is_async: + self.writeline( + "for event in (await template._get_default_module_async())" + "._body_stream:" + ) + loop_body() + else: + self.writeline("yield from template._get_default_module()._body_stream") + + if node.ignore_missing: + self.outdent() + + def _import_common( + self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame + ) -> None: + self.write(f"{self.choose_async('await ')}environment.get_template(") + self.visit(node.template, frame) + self.write(f", {self.name!r}).") + + if node.with_context: + f_name = f"make_module{self.choose_async('_async')}" + self.write( + f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})" + ) + else: + self.write(f"_get_default_module{self.choose_async('_async')}(context)") + + def visit_Import(self, node: nodes.Import, frame: Frame) -> None: + """Visit regular imports.""" + self.writeline(f"{frame.symbols.ref(node.target)} = ", node) + if frame.toplevel: + self.write(f"context.vars[{node.target!r}] = ") + + self._import_common(node, frame) + + if frame.toplevel and not node.target.startswith("_"): + self.writeline(f"context.exported_vars.discard({node.target!r})") + + def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None: + """Visit named imports.""" + self.newline(node) + self.write("included_template = ") + self._import_common(node, frame) + var_names = [] + discarded_names = [] + for name in node.names: + if isinstance(name, tuple): + name, alias = name + else: + alias = name + self.writeline( + f"{frame.symbols.ref(alias)} =" + f" getattr(included_template, {name!r}, missing)" + ) + self.writeline(f"if {frame.symbols.ref(alias)} is missing:") + self.indent() + # The position will contain the template name, and will be formatted + # into a string that will be compiled into an f-string. Curly braces + # in the name must be replaced with escapes so that they will not be + # executed as part of the f-string. + position = self.position(node).replace("{", "{{").replace("}", "}}") + message = ( + "the template {included_template.__name__!r}" + f" (imported on {position})" + f" does not export the requested name {name!r}" + ) + self.writeline( + f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})" + ) + self.outdent() + if frame.toplevel: + var_names.append(alias) + if not alias.startswith("_"): + discarded_names.append(alias) + + if var_names: + if len(var_names) == 1: + name = var_names[0] + self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}") + else: + names_kv = ", ".join( + f"{name!r}: {frame.symbols.ref(name)}" for name in var_names + ) + self.writeline(f"context.vars.update({{{names_kv}}})") + if discarded_names: + if len(discarded_names) == 1: + self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})") + else: + names_str = ", ".join(map(repr, discarded_names)) + self.writeline( + f"context.exported_vars.difference_update(({names_str}))" + ) + + def visit_For(self, node: nodes.For, frame: Frame) -> None: + loop_frame = frame.inner() + loop_frame.loop_frame = True + test_frame = frame.inner() + else_frame = frame.inner() + + # try to figure out if we have an extended loop. An extended loop + # is necessary if the loop is in recursive mode if the special loop + # variable is accessed in the body if the body is a scoped block. + extended_loop = ( + node.recursive + or "loop" + in find_undeclared(node.iter_child_nodes(only=("body",)), ("loop",)) + or any(block.scoped for block in node.find_all(nodes.Block)) + ) + + loop_ref = None + if extended_loop: + loop_ref = loop_frame.symbols.declare_parameter("loop") + + loop_frame.symbols.analyze_node(node, for_branch="body") + if node.else_: + else_frame.symbols.analyze_node(node, for_branch="else") + + if node.test: + loop_filter_func = self.temporary_identifier() + test_frame.symbols.analyze_node(node, for_branch="test") + self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test) + self.indent() + self.enter_frame(test_frame) + self.writeline(self.choose_async("async for ", "for ")) + self.visit(node.target, loop_frame) + self.write(" in ") + self.write(self.choose_async("auto_aiter(fiter)", "fiter")) + self.write(":") + self.indent() + self.writeline("if ", node.test) + self.visit(node.test, test_frame) + self.write(":") + self.indent() + self.writeline("yield ") + self.visit(node.target, loop_frame) + self.outdent(3) + self.leave_frame(test_frame, with_python_scope=True) + + # if we don't have an recursive loop we have to find the shadowed + # variables at that point. Because loops can be nested but the loop + # variable is a special one we have to enforce aliasing for it. + if node.recursive: + self.writeline( + f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node + ) + self.indent() + self.buffer(loop_frame) + + # Use the same buffer for the else frame + else_frame.buffer = loop_frame.buffer + + # make sure the loop variable is a special one and raise a template + # assertion error if a loop tries to write to loop + if extended_loop: + self.writeline(f"{loop_ref} = missing") + + for name in node.find_all(nodes.Name): + if name.ctx == "store" and name.name == "loop": + self.fail( + "Can't assign to special loop variable in for-loop target", + name.lineno, + ) + + if node.else_: + iteration_indicator = self.temporary_identifier() + self.writeline(f"{iteration_indicator} = 1") + + self.writeline(self.choose_async("async for ", "for "), node) + self.visit(node.target, loop_frame) + if extended_loop: + self.write(f", {loop_ref} in {self.choose_async('Async')}LoopContext(") + else: + self.write(" in ") + + if node.test: + self.write(f"{loop_filter_func}(") + if node.recursive: + self.write("reciter") + else: + if self.environment.is_async and not extended_loop: + self.write("auto_aiter(") + self.visit(node.iter, frame) + if self.environment.is_async and not extended_loop: + self.write(")") + if node.test: + self.write(")") + + if node.recursive: + self.write(", undefined, loop_render_func, depth):") + else: + self.write(", undefined):" if extended_loop else ":") + + self.indent() + self.enter_frame(loop_frame) + + self.writeline("_loop_vars = {}") + self.blockvisit(node.body, loop_frame) + if node.else_: + self.writeline(f"{iteration_indicator} = 0") + self.outdent() + self.leave_frame( + loop_frame, with_python_scope=node.recursive and not node.else_ + ) + + if node.else_: + self.writeline(f"if {iteration_indicator}:") + self.indent() + self.enter_frame(else_frame) + self.blockvisit(node.else_, else_frame) + self.leave_frame(else_frame) + self.outdent() + + # if the node was recursive we have to return the buffer contents + # and start the iteration code + if node.recursive: + self.return_buffer_contents(loop_frame) + self.outdent() + self.start_write(frame, node) + self.write(f"{self.choose_async('await ')}loop(") + if self.environment.is_async: + self.write("auto_aiter(") + self.visit(node.iter, frame) + if self.environment.is_async: + self.write(")") + self.write(", loop)") + self.end_write(frame) + + # at the end of the iteration, clear any assignments made in the + # loop from the top level + if self._assign_stack: + self._assign_stack[-1].difference_update(loop_frame.symbols.stores) + + def visit_If(self, node: nodes.If, frame: Frame) -> None: + if_frame = frame.soft() + self.writeline("if ", node) + self.visit(node.test, if_frame) + self.write(":") + self.indent() + self.blockvisit(node.body, if_frame) + self.outdent() + for elif_ in node.elif_: + self.writeline("elif ", elif_) + self.visit(elif_.test, if_frame) + self.write(":") + self.indent() + self.blockvisit(elif_.body, if_frame) + self.outdent() + if node.else_: + self.writeline("else:") + self.indent() + self.blockvisit(node.else_, if_frame) + self.outdent() + + def visit_Macro(self, node: nodes.Macro, frame: Frame) -> None: + macro_frame, macro_ref = self.macro_body(node, frame) + self.newline() + if frame.toplevel: + if not node.name.startswith("_"): + self.write(f"context.exported_vars.add({node.name!r})") + self.writeline(f"context.vars[{node.name!r}] = ") + self.write(f"{frame.symbols.ref(node.name)} = ") + self.macro_def(macro_ref, macro_frame) + + def visit_CallBlock(self, node: nodes.CallBlock, frame: Frame) -> None: + call_frame, macro_ref = self.macro_body(node, frame) + self.writeline("caller = ") + self.macro_def(macro_ref, call_frame) + self.start_write(frame, node) + self.visit_Call(node.call, frame, forward_caller=True) + self.end_write(frame) + + def visit_FilterBlock(self, node: nodes.FilterBlock, frame: Frame) -> None: + filter_frame = frame.inner() + filter_frame.symbols.analyze_node(node) + self.enter_frame(filter_frame) + self.buffer(filter_frame) + self.blockvisit(node.body, filter_frame) + self.start_write(frame, node) + self.visit_Filter(node.filter, filter_frame) + self.end_write(frame) + self.leave_frame(filter_frame) + + def visit_With(self, node: nodes.With, frame: Frame) -> None: + with_frame = frame.inner() + with_frame.symbols.analyze_node(node) + self.enter_frame(with_frame) + for target, expr in zip(node.targets, node.values): + self.newline() + self.visit(target, with_frame) + self.write(" = ") + self.visit(expr, frame) + self.blockvisit(node.body, with_frame) + self.leave_frame(with_frame) + + def visit_ExprStmt(self, node: nodes.ExprStmt, frame: Frame) -> None: + self.newline(node) + self.visit(node.node, frame) + + class _FinalizeInfo(t.NamedTuple): + const: t.Optional[t.Callable[..., str]] + src: t.Optional[str] + + @staticmethod + def _default_finalize(value: t.Any) -> t.Any: + """The default finalize function if the environment isn't + configured with one. Or, if the environment has one, this is + called on that function's output for constants. + """ + return str(value) + + _finalize: t.Optional[_FinalizeInfo] = None + + def _make_finalize(self) -> _FinalizeInfo: + """Build the finalize function to be used on constants and at + runtime. Cached so it's only created once for all output nodes. + + Returns a ``namedtuple`` with the following attributes: + + ``const`` + A function to finalize constant data at compile time. + + ``src`` + Source code to output around nodes to be evaluated at + runtime. + """ + if self._finalize is not None: + return self._finalize + + finalize: t.Optional[t.Callable[..., t.Any]] + finalize = default = self._default_finalize + src = None + + if self.environment.finalize: + src = "environment.finalize(" + env_finalize = self.environment.finalize + pass_arg = { + _PassArg.context: "context", + _PassArg.eval_context: "context.eval_ctx", + _PassArg.environment: "environment", + }.get( + _PassArg.from_obj(env_finalize) # type: ignore + ) + finalize = None + + if pass_arg is None: + + def finalize(value: t.Any) -> t.Any: # noqa: F811 + return default(env_finalize(value)) + + else: + src = f"{src}{pass_arg}, " + + if pass_arg == "environment": + + def finalize(value: t.Any) -> t.Any: # noqa: F811 + return default(env_finalize(self.environment, value)) + + self._finalize = self._FinalizeInfo(finalize, src) + return self._finalize + + def _output_const_repr(self, group: t.Iterable[t.Any]) -> str: + """Given a group of constant values converted from ``Output`` + child nodes, produce a string to write to the template module + source. + """ + return repr(concat(group)) + + def _output_child_to_const( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> str: + """Try to optimize a child of an ``Output`` node by trying to + convert it to constant, finalized data at compile time. + + If :exc:`Impossible` is raised, the node is not constant and + will be evaluated at runtime. Any other exception will also be + evaluated at runtime for easier debugging. + """ + const = node.as_const(frame.eval_ctx) + + if frame.eval_ctx.autoescape: + const = escape(const) + + # Template data doesn't go through finalize. + if isinstance(node, nodes.TemplateData): + return str(const) + + return finalize.const(const) # type: ignore + + def _output_child_pre( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> None: + """Output extra source code before visiting a child of an + ``Output`` node. + """ + if frame.eval_ctx.volatile: + self.write("(escape if context.eval_ctx.autoescape else str)(") + elif frame.eval_ctx.autoescape: + self.write("escape(") + else: + self.write("str(") + + if finalize.src is not None: + self.write(finalize.src) + + def _output_child_post( + self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo + ) -> None: + """Output extra source code after visiting a child of an + ``Output`` node. + """ + self.write(")") + + if finalize.src is not None: + self.write(")") + + def visit_Output(self, node: nodes.Output, frame: Frame) -> None: + # If an extends is active, don't render outside a block. + if frame.require_output_check: + # A top-level extends is known to exist at compile time. + if self.has_known_extends: + return + + self.writeline("if parent_template is None:") + self.indent() + + finalize = self._make_finalize() + body: t.List[t.Union[t.List[t.Any], nodes.Expr]] = [] + + # Evaluate constants at compile time if possible. Each item in + # body will be either a list of static data or a node to be + # evaluated at runtime. + for child in node.nodes: + try: + if not ( + # If the finalize function requires runtime context, + # constants can't be evaluated at compile time. + finalize.const + # Unless it's basic template data that won't be + # finalized anyway. + or isinstance(child, nodes.TemplateData) + ): + raise nodes.Impossible() + + const = self._output_child_to_const(child, frame, finalize) + except (nodes.Impossible, Exception): + # The node was not constant and needs to be evaluated at + # runtime. Or another error was raised, which is easier + # to debug at runtime. + body.append(child) + continue + + if body and isinstance(body[-1], list): + body[-1].append(const) + else: + body.append([const]) + + if frame.buffer is not None: + if len(body) == 1: + self.writeline(f"{frame.buffer}.append(") + else: + self.writeline(f"{frame.buffer}.extend((") + + self.indent() + + for item in body: + if isinstance(item, list): + # A group of constant data to join and output. + val = self._output_const_repr(item) + + if frame.buffer is None: + self.writeline("yield " + val) + else: + self.writeline(val + ",") + else: + if frame.buffer is None: + self.writeline("yield ", item) + else: + self.newline(item) + + # A node to be evaluated at runtime. + self._output_child_pre(item, frame, finalize) + self.visit(item, frame) + self._output_child_post(item, frame, finalize) + + if frame.buffer is not None: + self.write(",") + + if frame.buffer is not None: + self.outdent() + self.writeline(")" if len(body) == 1 else "))") + + if frame.require_output_check: + self.outdent() + + def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None: + self.push_assign_tracking() + + # ``a.b`` is allowed for assignment, and is parsed as an NSRef. However, + # it is only valid if it references a Namespace object. Emit a check for + # that for each ref here, before assignment code is emitted. This can't + # be done in visit_NSRef as the ref could be in the middle of a tuple. + seen_refs: t.Set[str] = set() + + for nsref in node.find_all(nodes.NSRef): + if nsref.name in seen_refs: + # Only emit the check for each reference once, in case the same + # ref is used multiple times in a tuple, `ns.a, ns.b = c, d`. + continue + + seen_refs.add(nsref.name) + ref = frame.symbols.ref(nsref.name) + self.writeline(f"if not isinstance({ref}, Namespace):") + self.indent() + self.writeline( + "raise TemplateRuntimeError" + '("cannot assign attribute on non-namespace object")' + ) + self.outdent() + + self.newline(node) + self.visit(node.target, frame) + self.write(" = ") + self.visit(node.node, frame) + self.pop_assign_tracking(frame) + + def visit_AssignBlock(self, node: nodes.AssignBlock, frame: Frame) -> None: + self.push_assign_tracking() + block_frame = frame.inner() + # This is a special case. Since a set block always captures we + # will disable output checks. This way one can use set blocks + # toplevel even in extended templates. + block_frame.require_output_check = False + block_frame.symbols.analyze_node(node) + self.enter_frame(block_frame) + self.buffer(block_frame) + self.blockvisit(node.body, block_frame) + self.newline(node) + self.visit(node.target, frame) + self.write(" = (Markup if context.eval_ctx.autoescape else identity)(") + if node.filter is not None: + self.visit_Filter(node.filter, block_frame) + else: + self.write(f"concat({block_frame.buffer})") + self.write(")") + self.pop_assign_tracking(frame) + self.leave_frame(block_frame) + + # -- Expression Visitors + + def visit_Name(self, node: nodes.Name, frame: Frame) -> None: + if node.ctx == "store" and ( + frame.toplevel or frame.loop_frame or frame.block_frame + ): + if self._assign_stack: + self._assign_stack[-1].add(node.name) + ref = frame.symbols.ref(node.name) + + # If we are looking up a variable we might have to deal with the + # case where it's undefined. We can skip that case if the load + # instruction indicates a parameter which are always defined. + if node.ctx == "load": + load = frame.symbols.find_load(ref) + if not ( + load is not None + and load[0] == VAR_LOAD_PARAMETER + and not self.parameter_is_undeclared(ref) + ): + self.write( + f"(undefined(name={node.name!r}) if {ref} is missing else {ref})" + ) + return + + self.write(ref) + + def visit_NSRef(self, node: nodes.NSRef, frame: Frame) -> None: + # NSRef is a dotted assignment target a.b=c, but uses a[b]=c internally. + # visit_Assign emits code to validate that each ref is to a Namespace + # object only. That can't be emitted here as the ref could be in the + # middle of a tuple assignment. + ref = frame.symbols.ref(node.name) + self.writeline(f"{ref}[{node.attr!r}]") + + def visit_Const(self, node: nodes.Const, frame: Frame) -> None: + val = node.as_const(frame.eval_ctx) + if isinstance(val, float): + self.write(str(val)) + else: + self.write(repr(val)) + + def visit_TemplateData(self, node: nodes.TemplateData, frame: Frame) -> None: + try: + self.write(repr(node.as_const(frame.eval_ctx))) + except nodes.Impossible: + self.write( + f"(Markup if context.eval_ctx.autoescape else identity)({node.data!r})" + ) + + def visit_Tuple(self, node: nodes.Tuple, frame: Frame) -> None: + self.write("(") + idx = -1 + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item, frame) + self.write(",)" if idx == 0 else ")") + + def visit_List(self, node: nodes.List, frame: Frame) -> None: + self.write("[") + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item, frame) + self.write("]") + + def visit_Dict(self, node: nodes.Dict, frame: Frame) -> None: + self.write("{") + for idx, item in enumerate(node.items): + if idx: + self.write(", ") + self.visit(item.key, frame) + self.write(": ") + self.visit(item.value, frame) + self.write("}") + + visit_Add = _make_binop("+") + visit_Sub = _make_binop("-") + visit_Mul = _make_binop("*") + visit_Div = _make_binop("/") + visit_FloorDiv = _make_binop("//") + visit_Pow = _make_binop("**") + visit_Mod = _make_binop("%") + visit_And = _make_binop("and") + visit_Or = _make_binop("or") + visit_Pos = _make_unop("+") + visit_Neg = _make_unop("-") + visit_Not = _make_unop("not ") + + @optimizeconst + def visit_Concat(self, node: nodes.Concat, frame: Frame) -> None: + if frame.eval_ctx.volatile: + func_name = "(markup_join if context.eval_ctx.volatile else str_join)" + elif frame.eval_ctx.autoescape: + func_name = "markup_join" + else: + func_name = "str_join" + self.write(f"{func_name}((") + for arg in node.nodes: + self.visit(arg, frame) + self.write(", ") + self.write("))") + + @optimizeconst + def visit_Compare(self, node: nodes.Compare, frame: Frame) -> None: + self.write("(") + self.visit(node.expr, frame) + for op in node.ops: + self.visit(op, frame) + self.write(")") + + def visit_Operand(self, node: nodes.Operand, frame: Frame) -> None: + self.write(f" {operators[node.op]} ") + self.visit(node.expr, frame) + + @optimizeconst + def visit_Getattr(self, node: nodes.Getattr, frame: Frame) -> None: + if self.environment.is_async: + self.write("(await auto_await(") + + self.write("environment.getattr(") + self.visit(node.node, frame) + self.write(f", {node.attr!r})") + + if self.environment.is_async: + self.write("))") + + @optimizeconst + def visit_Getitem(self, node: nodes.Getitem, frame: Frame) -> None: + # slices bypass the environment getitem method. + if isinstance(node.arg, nodes.Slice): + self.visit(node.node, frame) + self.write("[") + self.visit(node.arg, frame) + self.write("]") + else: + if self.environment.is_async: + self.write("(await auto_await(") + + self.write("environment.getitem(") + self.visit(node.node, frame) + self.write(", ") + self.visit(node.arg, frame) + self.write(")") + + if self.environment.is_async: + self.write("))") + + def visit_Slice(self, node: nodes.Slice, frame: Frame) -> None: + if node.start is not None: + self.visit(node.start, frame) + self.write(":") + if node.stop is not None: + self.visit(node.stop, frame) + if node.step is not None: + self.write(":") + self.visit(node.step, frame) + + @contextmanager + def _filter_test_common( + self, node: t.Union[nodes.Filter, nodes.Test], frame: Frame, is_filter: bool + ) -> t.Iterator[None]: + if self.environment.is_async: + self.write("(await auto_await(") + + if is_filter: + self.write(f"{self.filters[node.name]}(") + func = self.environment.filters.get(node.name) + else: + self.write(f"{self.tests[node.name]}(") + func = self.environment.tests.get(node.name) + + # When inside an If or CondExpr frame, allow the filter to be + # undefined at compile time and only raise an error if it's + # actually called at runtime. See pull_dependencies. + if func is None and not frame.soft_frame: + type_name = "filter" if is_filter else "test" + self.fail(f"No {type_name} named {node.name!r}.", node.lineno) + + pass_arg = { + _PassArg.context: "context", + _PassArg.eval_context: "context.eval_ctx", + _PassArg.environment: "environment", + }.get( + _PassArg.from_obj(func) # type: ignore + ) + + if pass_arg is not None: + self.write(f"{pass_arg}, ") + + # Back to the visitor function to handle visiting the target of + # the filter or test. + yield + + self.signature(node, frame) + self.write(")") + + if self.environment.is_async: + self.write("))") + + @optimizeconst + def visit_Filter(self, node: nodes.Filter, frame: Frame) -> None: + with self._filter_test_common(node, frame, True): + # if the filter node is None we are inside a filter block + # and want to write to the current buffer + if node.node is not None: + self.visit(node.node, frame) + elif frame.eval_ctx.volatile: + self.write( + f"(Markup(concat({frame.buffer}))" + f" if context.eval_ctx.autoescape else concat({frame.buffer}))" + ) + elif frame.eval_ctx.autoescape: + self.write(f"Markup(concat({frame.buffer}))") + else: + self.write(f"concat({frame.buffer})") + + @optimizeconst + def visit_Test(self, node: nodes.Test, frame: Frame) -> None: + with self._filter_test_common(node, frame, False): + self.visit(node.node, frame) + + @optimizeconst + def visit_CondExpr(self, node: nodes.CondExpr, frame: Frame) -> None: + frame = frame.soft() + + def write_expr2() -> None: + if node.expr2 is not None: + self.visit(node.expr2, frame) + return + + self.write( + f'cond_expr_undefined("the inline if-expression on' + f" {self.position(node)} evaluated to false and no else" + f' section was defined.")' + ) + + self.write("(") + self.visit(node.expr1, frame) + self.write(" if ") + self.visit(node.test, frame) + self.write(" else ") + write_expr2() + self.write(")") + + @optimizeconst + def visit_Call( + self, node: nodes.Call, frame: Frame, forward_caller: bool = False + ) -> None: + if self.environment.is_async: + self.write("(await auto_await(") + if self.environment.sandboxed: + self.write("environment.call(context, ") + else: + self.write("context.call(") + self.visit(node.node, frame) + extra_kwargs = {"caller": "caller"} if forward_caller else None + loop_kwargs = {"_loop_vars": "_loop_vars"} if frame.loop_frame else {} + block_kwargs = {"_block_vars": "_block_vars"} if frame.block_frame else {} + if extra_kwargs: + extra_kwargs.update(loop_kwargs, **block_kwargs) + elif loop_kwargs or block_kwargs: + extra_kwargs = dict(loop_kwargs, **block_kwargs) + self.signature(node, frame, extra_kwargs) + self.write(")") + if self.environment.is_async: + self.write("))") + + def visit_Keyword(self, node: nodes.Keyword, frame: Frame) -> None: + self.write(node.key + "=") + self.visit(node.value, frame) + + # -- Unused nodes for extensions + + def visit_MarkSafe(self, node: nodes.MarkSafe, frame: Frame) -> None: + self.write("Markup(") + self.visit(node.expr, frame) + self.write(")") + + def visit_MarkSafeIfAutoescape( + self, node: nodes.MarkSafeIfAutoescape, frame: Frame + ) -> None: + self.write("(Markup if context.eval_ctx.autoescape else identity)(") + self.visit(node.expr, frame) + self.write(")") + + def visit_EnvironmentAttribute( + self, node: nodes.EnvironmentAttribute, frame: Frame + ) -> None: + self.write("environment." + node.name) + + def visit_ExtensionAttribute( + self, node: nodes.ExtensionAttribute, frame: Frame + ) -> None: + self.write(f"environment.extensions[{node.identifier!r}].{node.name}") + + def visit_ImportedName(self, node: nodes.ImportedName, frame: Frame) -> None: + self.write(self.import_aliases[node.importname]) + + def visit_InternalName(self, node: nodes.InternalName, frame: Frame) -> None: + self.write(node.name) + + def visit_ContextReference( + self, node: nodes.ContextReference, frame: Frame + ) -> None: + self.write("context") + + def visit_DerivedContextReference( + self, node: nodes.DerivedContextReference, frame: Frame + ) -> None: + self.write(self.derive_context(frame)) + + def visit_Continue(self, node: nodes.Continue, frame: Frame) -> None: + self.writeline("continue", node) + + def visit_Break(self, node: nodes.Break, frame: Frame) -> None: + self.writeline("break", node) + + def visit_Scope(self, node: nodes.Scope, frame: Frame) -> None: + scope_frame = frame.inner() + scope_frame.symbols.analyze_node(node) + self.enter_frame(scope_frame) + self.blockvisit(node.body, scope_frame) + self.leave_frame(scope_frame) + + def visit_OverlayScope(self, node: nodes.OverlayScope, frame: Frame) -> None: + ctx = self.temporary_identifier() + self.writeline(f"{ctx} = {self.derive_context(frame)}") + self.writeline(f"{ctx}.vars = ") + self.visit(node.context, frame) + self.push_context_reference(ctx) + + scope_frame = frame.inner(isolated=True) + scope_frame.symbols.analyze_node(node) + self.enter_frame(scope_frame) + self.blockvisit(node.body, scope_frame) + self.leave_frame(scope_frame) + self.pop_context_reference() + + def visit_EvalContextModifier( + self, node: nodes.EvalContextModifier, frame: Frame + ) -> None: + for keyword in node.options: + self.writeline(f"context.eval_ctx.{keyword.key} = ") + self.visit(keyword.value, frame) + try: + val = keyword.value.as_const(frame.eval_ctx) + except nodes.Impossible: + frame.eval_ctx.volatile = True + else: + setattr(frame.eval_ctx, keyword.key, val) + + def visit_ScopedEvalContextModifier( + self, node: nodes.ScopedEvalContextModifier, frame: Frame + ) -> None: + old_ctx_name = self.temporary_identifier() + saved_ctx = frame.eval_ctx.save() + self.writeline(f"{old_ctx_name} = context.eval_ctx.save()") + self.visit_EvalContextModifier(node, frame) + for child in node.body: + self.visit(child, frame) + frame.eval_ctx.revert(saved_ctx) + self.writeline(f"context.eval_ctx.revert({old_ctx_name})") diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/constants.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..41a1c23b0a7fe134b1f662545876eb65b31b071e --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/constants.py @@ -0,0 +1,20 @@ +#: list of lorem ipsum words used by the lipsum() helper function +LOREM_IPSUM_WORDS = """\ +a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at +auctor augue bibendum blandit class commodo condimentum congue consectetuer +consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus +diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend +elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames +faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac +hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum +justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem +luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie +mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non +nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque +penatibus per pharetra phasellus placerat platea porta porttitor posuere +potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus +ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit +sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor +tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices +ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus +viverra volutpat vulputate""" diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/debug.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..eeeeee78b620f5d0745133b4629647973cd7af87 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/debug.py @@ -0,0 +1,191 @@ +import sys +import typing as t +from types import CodeType +from types import TracebackType + +from .exceptions import TemplateSyntaxError +from .utils import internal_code +from .utils import missing + +if t.TYPE_CHECKING: + from .runtime import Context + + +def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException: + """Rewrite the current exception to replace any tracebacks from + within compiled template code with tracebacks that look like they + came from the template source. + + This must be called within an ``except`` block. + + :param source: For ``TemplateSyntaxError``, the original source if + known. + :return: The original exception with the rewritten traceback. + """ + _, exc_value, tb = sys.exc_info() + exc_value = t.cast(BaseException, exc_value) + tb = t.cast(TracebackType, tb) + + if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated: + exc_value.translated = True + exc_value.source = source + # Remove the old traceback, otherwise the frames from the + # compiler still show up. + exc_value.with_traceback(None) + # Outside of runtime, so the frame isn't executing template + # code, but it still needs to point at the template. + tb = fake_traceback( + exc_value, None, exc_value.filename or "", exc_value.lineno + ) + else: + # Skip the frame for the render function. + tb = tb.tb_next + + stack = [] + + # Build the stack of traceback object, replacing any in template + # code with the source file and line information. + while tb is not None: + # Skip frames decorated with @internalcode. These are internal + # calls that aren't useful in template debugging output. + if tb.tb_frame.f_code in internal_code: + tb = tb.tb_next + continue + + template = tb.tb_frame.f_globals.get("__jinja_template__") + + if template is not None: + lineno = template.get_corresponding_lineno(tb.tb_lineno) + fake_tb = fake_traceback(exc_value, tb, template.filename, lineno) + stack.append(fake_tb) + else: + stack.append(tb) + + tb = tb.tb_next + + tb_next = None + + # Assign tb_next in reverse to avoid circular references. + for tb in reversed(stack): + tb.tb_next = tb_next + tb_next = tb + + return exc_value.with_traceback(tb_next) + + +def fake_traceback( # type: ignore + exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int +) -> TracebackType: + """Produce a new traceback object that looks like it came from the + template source instead of the compiled code. The filename, line + number, and location name will point to the template, and the local + variables will be the current template context. + + :param exc_value: The original exception to be re-raised to create + the new traceback. + :param tb: The original traceback to get the local variables and + code info from. + :param filename: The template filename. + :param lineno: The line number in the template source. + """ + if tb is not None: + # Replace the real locals with the context that would be + # available at that point in the template. + locals = get_template_locals(tb.tb_frame.f_locals) + locals.pop("__jinja_exception__", None) + else: + locals = {} + + globals = { + "__name__": filename, + "__file__": filename, + "__jinja_exception__": exc_value, + } + # Raise an exception at the correct line number. + code: CodeType = compile( + "\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec" + ) + + # Build a new code object that points to the template file and + # replaces the location with a block name. + location = "template" + + if tb is not None: + function = tb.tb_frame.f_code.co_name + + if function == "root": + location = "top-level template code" + elif function.startswith("block_"): + location = f"block {function[6:]!r}" + + if sys.version_info >= (3, 8): + code = code.replace(co_name=location) + else: + code = CodeType( + code.co_argcount, + code.co_kwonlyargcount, + code.co_nlocals, + code.co_stacksize, + code.co_flags, + code.co_code, + code.co_consts, + code.co_names, + code.co_varnames, + code.co_filename, + location, + code.co_firstlineno, + code.co_lnotab, + code.co_freevars, + code.co_cellvars, + ) + + # Execute the new code, which is guaranteed to raise, and return + # the new traceback without this frame. + try: + exec(code, globals, locals) + except BaseException: + return sys.exc_info()[2].tb_next # type: ignore + + +def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]: + """Based on the runtime locals, get the context that would be + available at that point in the template. + """ + # Start with the current template context. + ctx: t.Optional[Context] = real_locals.get("context") + + if ctx is not None: + data: t.Dict[str, t.Any] = ctx.get_all().copy() + else: + data = {} + + # Might be in a derived context that only sets local variables + # rather than pushing a context. Local variables follow the scheme + # l_depth_name. Find the highest-depth local that has a value for + # each name. + local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {} + + for name, value in real_locals.items(): + if not name.startswith("l_") or value is missing: + # Not a template variable, or no longer relevant. + continue + + try: + _, depth_str, name = name.split("_", 2) + depth = int(depth_str) + except ValueError: + continue + + cur_depth = local_overrides.get(name, (-1,))[0] + + if cur_depth < depth: + local_overrides[name] = (depth, value) + + # Modify the context with any derived context. + for name, (_, value) in local_overrides.items(): + if value is missing: + data.pop(name, None) + else: + data[name] = value + + return data diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/defaults.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/defaults.py new file mode 100644 index 0000000000000000000000000000000000000000..638cad3d2d8907330bde56e2b76c9b185c523b45 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/defaults.py @@ -0,0 +1,48 @@ +import typing as t + +from .filters import FILTERS as DEFAULT_FILTERS # noqa: F401 +from .tests import TESTS as DEFAULT_TESTS # noqa: F401 +from .utils import Cycler +from .utils import generate_lorem_ipsum +from .utils import Joiner +from .utils import Namespace + +if t.TYPE_CHECKING: + import typing_extensions as te + +# defaults for the parser / lexer +BLOCK_START_STRING = "{%" +BLOCK_END_STRING = "%}" +VARIABLE_START_STRING = "{{" +VARIABLE_END_STRING = "}}" +COMMENT_START_STRING = "{#" +COMMENT_END_STRING = "#}" +LINE_STATEMENT_PREFIX: t.Optional[str] = None +LINE_COMMENT_PREFIX: t.Optional[str] = None +TRIM_BLOCKS = False +LSTRIP_BLOCKS = False +NEWLINE_SEQUENCE: "te.Literal['\\n', '\\r\\n', '\\r']" = "\n" +KEEP_TRAILING_NEWLINE = False + +# default filters, tests and namespace + +DEFAULT_NAMESPACE = { + "range": range, + "dict": dict, + "lipsum": generate_lorem_ipsum, + "cycler": Cycler, + "joiner": Joiner, + "namespace": Namespace, +} + +# default policies +DEFAULT_POLICIES: t.Dict[str, t.Any] = { + "compiler.ascii_str": True, + "urlize.rel": "noopener", + "urlize.target": None, + "urlize.extra_schemes": None, + "truncate.leeway": 5, + "json.dumps_function": None, + "json.dumps_kwargs": {"sort_keys": True}, + "ext.i18n.trimmed": False, +} diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/environment.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..0fc6e5be87ab8273f6056ddfede07e1be28f1495 --- /dev/null +++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/jinja2/environment.py @@ -0,0 +1,1672 @@ +"""Classes for managing templates and their runtime and compile time +options. +""" + +import os +import typing +import typing as t +import weakref +from collections import ChainMap +from functools import lru_cache +from functools import partial +from functools import reduce +from types import CodeType + +from markupsafe import Markup + +from . import nodes +from .compiler import CodeGenerator +from .compiler import generate +from .defaults import BLOCK_END_STRING +from .defaults import BLOCK_START_STRING +from .defaults import COMMENT_END_STRING +from .defaults import COMMENT_START_STRING +from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined] +from .defaults import DEFAULT_NAMESPACE +from .defaults import DEFAULT_POLICIES +from .defaults import DEFAULT_TESTS # type: ignore[attr-defined] +from .defaults import KEEP_TRAILING_NEWLINE +from .defaults import LINE_COMMENT_PREFIX +from .defaults import LINE_STATEMENT_PREFIX +from .defaults import LSTRIP_BLOCKS +from .defaults import NEWLINE_SEQUENCE +from .defaults import TRIM_BLOCKS +from .defaults import VARIABLE_END_STRING +from .defaults import VARIABLE_START_STRING +from .exceptions import TemplateNotFound +from .exceptions import TemplateRuntimeError +from .exceptions import TemplatesNotFound +from .exceptions import TemplateSyntaxError +from .exceptions import UndefinedError +from .lexer import get_lexer +from .lexer import Lexer +from .lexer import TokenStream +from .nodes import EvalContext +from .parser import Parser +from .runtime import Context +from .runtime import new_context +from .runtime import Undefined +from .utils import _PassArg +from .utils import concat +from .utils import consume +from .utils import import_string +from .utils import internalcode +from .utils import LRUCache +from .utils import missing + +if t.TYPE_CHECKING: + import typing_extensions as te + + from .bccache import BytecodeCache + from .ext import Extension + from .loaders import BaseLoader + +_env_bound = t.TypeVar("_env_bound", bound="Environment") + + +# for direct template usage we have up to ten living environments +@lru_cache(maxsize=10) +def get_spontaneous_environment(cls: t.Type[_env_bound], *args: t.Any) -> _env_bound: + """Return a new spontaneous environment. A spontaneous environment + is used for templates created directly rather than through an + existing environment. + + :param cls: Environment class to create. + :param args: Positional arguments passed to environment. + """ + env = cls(*args) + env.shared = True + return env + + +def create_cache( + size: int, +) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]: + """Return the cache class for the given size.""" + if size == 0: + return None + + if size < 0: + return {} + + return LRUCache(size) # type: ignore + + +def copy_cache( + cache: t.Optional[t.MutableMapping[t.Any, t.Any]], +) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]: + """Create an empty copy of the given cache.""" + if cache is None: + return None + + if type(cache) is dict: # noqa E721 + return {} + + return LRUCache(cache.capacity) # type: ignore + + +def load_extensions( + environment: "Environment", + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]], +) -> t.Dict[str, "Extension"]: + """Load the extensions from the list and bind it to the environment. + Returns a dict of instantiated extensions. + """ + result = {} + + for extension in extensions: + if isinstance(extension, str): + extension = t.cast(t.Type["Extension"], import_string(extension)) + + result[extension.identifier] = extension(environment) + + return result + + +def _environment_config_check(environment: _env_bound) -> _env_bound: + """Perform a sanity check on the environment.""" + assert issubclass( + environment.undefined, Undefined + ), "'undefined' must be a subclass of 'jinja2.Undefined'." + assert ( + environment.block_start_string + != environment.variable_start_string + != environment.comment_start_string + ), "block, variable and comment start strings must be different." + assert environment.newline_sequence in { + "\r", + "\r\n", + "\n", + }, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'." + return environment + + +class Environment: + r"""The core component of Jinja is the `Environment`. It contains + important shared variables like configuration, filters, tests, + globals and others. Instances of this class may be modified if + they are not shared and if no template was loaded so far. + Modifications on environments after the first template was loaded + will lead to surprising effects and undefined behavior. + + Here are the possible initialization parameters: + + `block_start_string` + The string marking the beginning of a block. Defaults to ``'{%'``. + + `block_end_string` + The string marking the end of a block. Defaults to ``'%}'``. + + `variable_start_string` + The string marking the beginning of a print statement. + Defaults to ``'{{'``. + + `variable_end_string` + The string marking the end of a print statement. Defaults to + ``'}}'``. + + `comment_start_string` + The string marking the beginning of a comment. Defaults to ``'{#'``. + + `comment_end_string` + The string marking the end of a comment. Defaults to ``'#}'``. + + `line_statement_prefix` + If given and a string, this will be used as prefix for line based + statements. See also :ref:`line-statements`. + + `line_comment_prefix` + If given and a string, this will be used as prefix for line based + comments. See also :ref:`line-statements`. + + .. versionadded:: 2.2 + + `trim_blocks` + If this is set to ``True`` the first newline after a block is + removed (block, not variable tag!). Defaults to `False`. + + `lstrip_blocks` + If this is set to ``True`` leading spaces and tabs are stripped + from the start of a line to a block. Defaults to `False`. + + `newline_sequence` + The sequence that starts a newline. Must be one of ``'\r'``, + ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a + useful default for Linux and OS X systems as well as web + applications. + + `keep_trailing_newline` + Preserve the trailing newline when rendering templates. + The default is ``False``, which causes a single newline, + if present, to be stripped from the end of the template. + + .. versionadded:: 2.7 + + `extensions` + List of Jinja extensions to use. This can either be import paths + as strings or extension classes. For more information have a + look at :ref:`the extensions documentation `. + + `optimized` + should the optimizer be enabled? Default is ``True``. + + `undefined` + :class:`Undefined` or a subclass of it that is used to represent + undefined values in the template. + + `finalize` + A callable that can be used to process the result of a variable + expression before it is output. For example one can convert + ``None`` implicitly into an empty string here. + + `autoescape` + If set to ``True`` the XML/HTML autoescaping feature is enabled by + default. For more details about autoescaping see + :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also + be a callable that is passed the template name and has to + return ``True`` or ``False`` depending on autoescape should be + enabled by default. + + .. versionchanged:: 2.4 + `autoescape` can now be a function + + `loader` + The template loader for this environment. + + `cache_size` + The size of the cache. Per default this is ``400`` which means + that if more than 400 templates are loaded the loader will clean + out the least recently used template. If the cache size is set to + ``0`` templates are recompiled all the time, if the cache size is + ``-1`` the cache will not be cleaned. + + .. versionchanged:: 2.8 + The cache size was increased to 400 from a low 50. + + `auto_reload` + Some loaders load templates from locations where the template + sources may change (ie: file system or database). If + ``auto_reload`` is set to ``True`` (default) every time a template is + requested the loader checks if the source changed and if yes, it + will reload the template. For higher performance it's possible to + disable that. + + `bytecode_cache` + If set to a bytecode cache object, this object will provide a + cache for the internal Jinja bytecode so that templates don't + have to be parsed if they were not changed. + + See :ref:`bytecode-cache` for more information. + + `enable_async` + If set to true this enables async template execution which + allows using async functions and generators. + """ + + #: if this environment is sandboxed. Modifying this variable won't make + #: the environment sandboxed though. For a real sandboxed environment + #: have a look at jinja2.sandbox. This flag alone controls the code + #: generation by the compiler. + sandboxed = False + + #: True if the environment is just an overlay + overlayed = False + + #: the environment this environment is linked to if it is an overlay + linked_to: t.Optional["Environment"] = None + + #: shared environments have this set to `True`. A shared environment + #: must not be modified + shared = False + + #: the class that is used for code generation. See + #: :class:`~jinja2.compiler.CodeGenerator` for more information. + code_generator_class: t.Type["CodeGenerator"] = CodeGenerator + + concat = "".join + + #: the context class that is used for templates. See + #: :class:`~jinja2.runtime.Context` for more information. + context_class: t.Type[Context] = Context + + template_class: t.Type["Template"] + + def __init__( + self, + block_start_string: str = BLOCK_START_STRING, + block_end_string: str = BLOCK_END_STRING, + variable_start_string: str = VARIABLE_START_STRING, + variable_end_string: str = VARIABLE_END_STRING, + comment_start_string: str = COMMENT_START_STRING, + comment_end_string: str = COMMENT_END_STRING, + line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX, + line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX, + trim_blocks: bool = TRIM_BLOCKS, + lstrip_blocks: bool = LSTRIP_BLOCKS, + newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE, + keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE, + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (), + optimized: bool = True, + undefined: t.Type[Undefined] = Undefined, + finalize: t.Optional[t.Callable[..., t.Any]] = None, + autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False, + loader: t.Optional["BaseLoader"] = None, + cache_size: int = 400, + auto_reload: bool = True, + bytecode_cache: t.Optional["BytecodeCache"] = None, + enable_async: bool = False, + ): + # !!Important notice!! + # The constructor accepts quite a few arguments that should be + # passed by keyword rather than position. However it's important to + # not change the order of arguments because it's used at least + # internally in those cases: + # - spontaneous environments (i18n extension and Template) + # - unittests + # If parameter changes are required only add parameters at the end + # and don't change the arguments (or the defaults!) of the arguments + # existing already. + + # lexer / parser information + self.block_start_string = block_start_string + self.block_end_string = block_end_string + self.variable_start_string = variable_start_string + self.variable_end_string = variable_end_string + self.comment_start_string = comment_start_string + self.comment_end_string = comment_end_string + self.line_statement_prefix = line_statement_prefix + self.line_comment_prefix = line_comment_prefix + self.trim_blocks = trim_blocks + self.lstrip_blocks = lstrip_blocks + self.newline_sequence = newline_sequence + self.keep_trailing_newline = keep_trailing_newline + + # runtime information + self.undefined: t.Type[Undefined] = undefined + self.optimized = optimized + self.finalize = finalize + self.autoescape = autoescape + + # defaults + self.filters = DEFAULT_FILTERS.copy() + self.tests = DEFAULT_TESTS.copy() + self.globals = DEFAULT_NAMESPACE.copy() + + # set the loader provided + self.loader = loader + self.cache = create_cache(cache_size) + self.bytecode_cache = bytecode_cache + self.auto_reload = auto_reload + + # configurable policies + self.policies = DEFAULT_POLICIES.copy() + + # load extensions + self.extensions = load_extensions(self, extensions) + + self.is_async = enable_async + _environment_config_check(self) + + def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None: + """Adds an extension after the environment was created. + + .. versionadded:: 2.5 + """ + self.extensions.update(load_extensions(self, [extension])) + + def extend(self, **attributes: t.Any) -> None: + """Add the items to the instance of the environment if they do not exist + yet. This is used by :ref:`extensions ` to register + callbacks and configuration values without breaking inheritance. + """ + for key, value in attributes.items(): + if not hasattr(self, key): + setattr(self, key, value) + + def overlay( + self, + block_start_string: str = missing, + block_end_string: str = missing, + variable_start_string: str = missing, + variable_end_string: str = missing, + comment_start_string: str = missing, + comment_end_string: str = missing, + line_statement_prefix: t.Optional[str] = missing, + line_comment_prefix: t.Optional[str] = missing, + trim_blocks: bool = missing, + lstrip_blocks: bool = missing, + newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing, + keep_trailing_newline: bool = missing, + extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing, + optimized: bool = missing, + undefined: t.Type[Undefined] = missing, + finalize: t.Optional[t.Callable[..., t.Any]] = missing, + autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing, + loader: t.Optional["BaseLoader"] = missing, + cache_size: int = missing, + auto_reload: bool = missing, + bytecode_cache: t.Optional["BytecodeCache"] = missing, + enable_async: bool = missing, + ) -> "te.Self": + """Create a new overlay environment that shares all the data with the + current environment except for cache and the overridden attributes. + Extensions cannot be removed for an overlayed environment. An overlayed + environment automatically gets all the extensions of the environment it + is linked to plus optional extra extensions. + + Creating overlays should happen after the initial environment was set + up completely. Not all attributes are truly linked, some are just + copied over so modifications on the original environment may not shine + through. + + .. versionchanged:: 3.1.5 + ``enable_async`` is applied correctly. + + .. versionchanged:: 3.1.2 + Added the ``newline_sequence``, ``keep_trailing_newline``, + and ``enable_async`` parameters to match ``__init__``. + """ + args = dict(locals()) + del args["self"], args["cache_size"], args["extensions"], args["enable_async"] + + rv = object.__new__(self.__class__) + rv.__dict__.update(self.__dict__) + rv.overlayed = True + rv.linked_to = self + + for key, value in args.items(): + if value is not missing: + setattr(rv, key, value) + + if cache_size is not missing: + rv.cache = create_cache(cache_size) + else: + rv.cache = copy_cache(self.cache) + + rv.extensions = {} + for key, value in self.extensions.items(): + rv.extensions[key] = value.bind(rv) + if extensions is not missing: + rv.extensions.update(load_extensions(rv, extensions)) + + if enable_async is not missing: + rv.is_async = enable_async + + return _environment_config_check(rv) + + @property + def lexer(self) -> Lexer: + """The lexer for this environment.""" + return get_lexer(self) + + def iter_extensions(self) -> t.Iterator["Extension"]: + """Iterates over the extensions by priority.""" + return iter(sorted(self.extensions.values(), key=lambda x: x.priority)) + + def getitem( + self, obj: t.Any, argument: t.Union[str, t.Any] + ) -> t.Union[t.Any, Undefined]: + """Get an item or attribute of an object but prefer the item.""" + try: + return obj[argument] + except (AttributeError, TypeError, LookupError): + if isinstance(argument, str): + try: + attr = str(argument) + except Exception: + pass + else: + try: + return getattr(obj, attr) + except AttributeError: + pass + return self.undefined(obj=obj, name=argument) + + def getattr(self, obj: t.Any, attribute: str) -> t.Any: + """Get an item or attribute of an object but prefer the attribute. + Unlike :meth:`getitem` the attribute *must* be a string. + """ + try: + return getattr(obj, attribute) + except AttributeError: + pass + try: + return obj[attribute] + except (TypeError, LookupError, AttributeError): + return self.undefined(obj=obj, name=attribute) + + def _filter_test_common( + self, + name: t.Union[str, Undefined], + value: t.Any, + args: t.Optional[t.Sequence[t.Any]], + kwargs: t.Optional[t.Mapping[str, t.Any]], + context: t.Optional[Context], + eval_ctx: t.Optional[EvalContext], + is_filter: bool, + ) -> t.Any: + if is_filter: + env_map = self.filters + type_name = "filter" + else: + env_map = self.tests + type_name = "test" + + func = env_map.get(name) # type: ignore + + if func is None: + msg = f"No {type_name} named {name!r}." + + if isinstance(name, Undefined): + try: + name._fail_with_undefined_error() + except Exception as e: + msg = f"{msg} ({e}; did you forget to quote the callable name?)" + + raise TemplateRuntimeError(msg) + + args = [value, *(args if args is not None else ())] + kwargs = kwargs if kwargs is not None else {} + pass_arg = _PassArg.from_obj(func) + + if pass_arg is _PassArg.context: + if context is None: + raise TemplateRuntimeError( + f"Attempted to invoke a context {type_name} without context." + ) + + args.insert(0, context) + elif pass_arg is _PassArg.eval_context: + if eval_ctx is None: + if context is not None: + eval_ctx = context.eval_ctx + else: + eval_ctx = EvalContext(self) + + args.insert(0, eval_ctx) + elif pass_arg is _PassArg.environment: + args.insert(0, self) + + return func(*args, **kwargs) + + def call_filter( + self, + name: str, + value: t.Any, + args: t.Optional[t.Sequence[t.Any]] = None, + kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + context: t.Optional[Context] = None, + eval_ctx: t.Optional[EvalContext] = None, + ) -> t.Any: + """Invoke a filter on a value the same way the compiler does. + + This might return a coroutine if the filter is running from an + environment in async mode and the filter supports async + execution. It's your responsibility to await this if needed. + + .. versionadded:: 2.7 + """ + return self._filter_test_common( + name, value, args, kwargs, context, eval_ctx, True + ) + + def call_test( + self, + name: str, + value: t.Any, + args: t.Optional[t.Sequence[t.Any]] = None, + kwargs: t.Optional[t.Mapping[str, t.Any]] = None, + context: t.Optional[Context] = None, + eval_ctx: t.Optional[EvalContext] = None, + ) -> t.Any: + """Invoke a test on a value the same way the compiler does. + + This might return a coroutine if the test is running from an + environment in async mode and the test supports async execution. + It's your responsibility to await this if needed. + + .. versionchanged:: 3.0 + Tests support ``@pass_context``, etc. decorators. Added + the ``context`` and ``eval_ctx`` parameters. + + .. versionadded:: 2.7 + """ + return self._filter_test_common( + name, value, args, kwargs, context, eval_ctx, False + ) + + @internalcode + def parse( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> nodes.Template: + """Parse the sourcecode and return the abstract syntax tree. This + tree of nodes is used by the compiler to convert the template into + executable source- or bytecode. This is useful for debugging or to + extract information from templates. + + If you are :ref:`developing Jinja extensions ` + this gives you a good overview of the node tree generated. + """ + try: + return self._parse(source, name, filename) + except TemplateSyntaxError: + self.handle_exception(source=source) + + def _parse( + self, source: str, name: t.Optional[str], filename: t.Optional[str] + ) -> nodes.Template: + """Internal parsing function used by `parse` and `compile`.""" + return Parser(self, source, name, filename).parse() + + def lex( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> t.Iterator[t.Tuple[int, str, str]]: + """Lex the given sourcecode and return a generator that yields + tokens as tuples in the form ``(lineno, token_type, value)``. + This can be useful for :ref:`extension development ` + and debugging templates. + + This does not perform preprocessing. If you want the preprocessing + of the extensions to be applied you have to filter source through + the :meth:`preprocess` method. + """ + source = str(source) + try: + return self.lexer.tokeniter(source, name, filename) + except TemplateSyntaxError: + self.handle_exception(source=source) + + def preprocess( + self, + source: str, + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + ) -> str: + """Preprocesses the source with all extensions. This is automatically + called for all parsing and compiling methods but *not* for :meth:`lex` + because there you usually only want the actual source tokenized. + """ + return reduce( + lambda s, e: e.preprocess(s, name, filename), + self.iter_extensions(), + str(source), + ) + + def _tokenize( + self, + source: str, + name: t.Optional[str], + filename: t.Optional[str] = None, + state: t.Optional[str] = None, + ) -> TokenStream: + """Called by the parser to do the preprocessing and filtering + for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. + """ + source = self.preprocess(source, name, filename) + stream = self.lexer.tokenize(source, name, filename, state) + + for ext in self.iter_extensions(): + stream = ext.filter_stream(stream) # type: ignore + + if not isinstance(stream, TokenStream): + stream = TokenStream(stream, name, filename) + + return stream + + def _generate( + self, + source: nodes.Template, + name: t.Optional[str], + filename: t.Optional[str], + defer_init: bool = False, + ) -> str: + """Internal hook that can be overridden to hook a different generate + method in. + + .. versionadded:: 2.5 + """ + return generate( # type: ignore + source, + self, + name, + filename, + defer_init=defer_init, + optimized=self.optimized, + ) + + def _compile(self, source: str, filename: str) -> CodeType: + """Internal hook that can be overridden to hook a different compile + method in. + + .. versionadded:: 2.5 + """ + return compile(source, filename, "exec") + + @typing.overload + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: "te.Literal[False]" = False, + defer_init: bool = False, + ) -> CodeType: ... + + @typing.overload + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: "te.Literal[True]" = ..., + defer_init: bool = False, + ) -> str: ... + + @internalcode + def compile( + self, + source: t.Union[str, nodes.Template], + name: t.Optional[str] = None, + filename: t.Optional[str] = None, + raw: bool = False, + defer_init: bool = False, + ) -> t.Union[str, CodeType]: + """Compile a node or template source code. The `name` parameter is + the load name of the template after it was joined using + :meth:`join_path` if necessary, not the filename on the file system. + the `filename` parameter is the estimated filename of the template on + the file system. If the template came from a database or memory this + can be omitted. + + The return value of this method is a python code object. If the `raw` + parameter is `True` the return value will be a string with python + code equivalent to the bytecode returned otherwise. This method is + mainly used internally. + + `defer_init` is use internally to aid the module code generator. This + causes the generated code to be able to import without the global + environment variable to be set. + + .. versionadded:: 2.4 + `defer_init` parameter added. + """ + source_hint = None + try: + if isinstance(source, str): + source_hint = source + source = self._parse(source, name, filename) + source = self._generate(source, name, filename, defer_init=defer_init) + if raw: + return source + if filename is None: + filename = "